1 import * as Bluebird from 'bluebird'
2 import { map, maxBy, truncate } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
6 import * as Sequelize from 'sequelize'
7 import { VideoPrivacy, VideoResolution } from '../../../shared'
8 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects/video-torrent-object'
11 generateImageFromVideoFile,
14 isVideoDescriptionValid,
27 } from '../../helpers'
28 import { activityPubCollection } from '../../helpers/activitypub'
29 import { isVideoUrlValid } from '../../helpers/custom-validators/videos'
42 } from '../../initializers'
43 import { sendDeleteVideo } from '../../lib/index'
45 import { addMethodsToModel, getSort } from '../utils'
47 import { TagInstance } from './tag-interface'
48 import { VideoFileInstance, VideoFileModel } from './video-file-interface'
49 import { VideoAttributes, VideoInstance, VideoMethods } from './video-interface'
51 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
52 let getOriginalFile: VideoMethods.GetOriginalFile
53 let getVideoFilename: VideoMethods.GetVideoFilename
54 let getThumbnailName: VideoMethods.GetThumbnailName
55 let getThumbnailPath: VideoMethods.GetThumbnailPath
56 let getPreviewName: VideoMethods.GetPreviewName
57 let getPreviewPath: VideoMethods.GetPreviewPath
58 let getTorrentFileName: VideoMethods.GetTorrentFileName
59 let isOwned: VideoMethods.IsOwned
60 let toFormattedJSON: VideoMethods.ToFormattedJSON
61 let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON
62 let toActivityPubObject: VideoMethods.ToActivityPubObject
63 let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile
64 let transcodeOriginalVideofile: VideoMethods.TranscodeOriginalVideofile
65 let createPreview: VideoMethods.CreatePreview
66 let createThumbnail: VideoMethods.CreateThumbnail
67 let getVideoFilePath: VideoMethods.GetVideoFilePath
68 let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash
69 let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight
70 let getEmbedPath: VideoMethods.GetEmbedPath
71 let getDescriptionPath: VideoMethods.GetDescriptionPath
72 let getTruncatedDescription: VideoMethods.GetTruncatedDescription
73 let getCategoryLabel: VideoMethods.GetCategoryLabel
74 let getLicenceLabel: VideoMethods.GetLicenceLabel
75 let getLanguageLabel: VideoMethods.GetLanguageLabel
77 let list: VideoMethods.List
78 let listForApi: VideoMethods.ListForApi
79 let listAllAndSharedByAccountForOutbox: VideoMethods.ListAllAndSharedByAccountForOutbox
80 let listUserVideosForApi: VideoMethods.ListUserVideosForApi
81 let load: VideoMethods.Load
82 let loadByUrlAndPopulateAccount: VideoMethods.LoadByUrlAndPopulateAccount
83 let loadByUUID: VideoMethods.LoadByUUID
84 let loadByUUIDOrURL: VideoMethods.LoadByUUIDOrURL
85 let loadAndPopulateAccountAndServerAndTags: VideoMethods.LoadAndPopulateAccountAndServerAndTags
86 let loadByUUIDAndPopulateAccountAndServerAndTags: VideoMethods.LoadByUUIDAndPopulateAccountAndServerAndTags
87 let searchAndPopulateAccountAndServerAndTags: VideoMethods.SearchAndPopulateAccountAndServerAndTags
88 let removeThumbnail: VideoMethods.RemoveThumbnail
89 let removePreview: VideoMethods.RemovePreview
90 let removeFile: VideoMethods.RemoveFile
91 let removeTorrent: VideoMethods.RemoveTorrent
93 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
94 Video = sequelize.define<VideoInstance, VideoAttributes>('Video',
98 defaultValue: DataTypes.UUIDV4,
105 type: DataTypes.STRING,
108 nameValid: value => {
109 const res = isVideoNameValid(value)
110 if (res === false) throw new Error('Video name is not valid.')
115 type: DataTypes.INTEGER,
118 categoryValid: value => {
119 const res = isVideoCategoryValid(value)
120 if (res === false) throw new Error('Video category is not valid.')
125 type: DataTypes.INTEGER,
129 licenceValid: value => {
130 const res = isVideoLicenceValid(value)
131 if (res === false) throw new Error('Video licence is not valid.')
136 type: DataTypes.INTEGER,
139 languageValid: value => {
140 const res = isVideoLanguageValid(value)
141 if (res === false) throw new Error('Video language is not valid.')
146 type: DataTypes.INTEGER,
149 privacyValid: value => {
150 const res = isVideoPrivacyValid(value)
151 if (res === false) throw new Error('Video privacy is not valid.')
156 type: DataTypes.BOOLEAN,
159 nsfwValid: value => {
160 const res = isVideoNSFWValid(value)
161 if (res === false) throw new Error('Video nsfw attribute is not valid.')
166 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max),
169 descriptionValid: value => {
170 const res = isVideoDescriptionValid(value)
171 if (res === false) throw new Error('Video description is not valid.')
176 type: DataTypes.INTEGER,
179 durationValid: value => {
180 const res = isVideoDurationValid(value)
181 if (res === false) throw new Error('Video duration is not valid.')
186 type: DataTypes.INTEGER,
195 type: DataTypes.INTEGER,
204 type: DataTypes.INTEGER,
213 type: DataTypes.BOOLEAN,
218 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max),
222 const res = isVideoUrlValid(value)
223 if (res === false) throw new Error('Video URL is not valid.')
234 fields: [ 'createdAt' ]
237 fields: [ 'duration' ]
249 fields: [ 'channelId' ]
258 const classMethods = [
262 listAllAndSharedByAccountForOutbox,
264 listUserVideosForApi,
266 loadByUrlAndPopulateAccount,
267 loadAndPopulateAccountAndServerAndTags,
270 loadByUUIDAndPopulateAccountAndServerAndTags,
271 searchAndPopulateAccountAndServerAndTags
273 const instanceMethods = [
276 createTorrentAndSetInfoHash,
292 toFormattedDetailsJSON,
293 optimizeOriginalVideofile,
294 transcodeOriginalVideofile,
295 getOriginalFileHeight,
297 getTruncatedDescription,
303 addMethodsToModel(Video, classMethods, instanceMethods)
308 // ------------------------------ METHODS ------------------------------
310 function associate (models) {
311 Video.belongsTo(models.VideoChannel, {
319 Video.belongsToMany(models.Tag, {
320 foreignKey: 'videoId',
321 through: models.VideoTag,
325 Video.hasMany(models.VideoAbuse, {
333 Video.hasMany(models.VideoFile, {
341 Video.hasMany(models.VideoShare, {
349 Video.hasMany(models.AccountVideoRate, {
358 function afterDestroy (video: VideoInstance) {
362 video.removeThumbnail()
365 if (video.isOwned()) {
367 video.removePreview(),
368 sendDeleteVideo(video, undefined)
371 // Remove physical files and torrents
372 video.VideoFiles.forEach(file => {
373 tasks.push(video.removeFile(file))
374 tasks.push(video.removeTorrent(file))
378 return Promise.all(tasks)
380 logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err)
384 getOriginalFile = function (this: VideoInstance) {
385 if (Array.isArray(this.VideoFiles) === false) return undefined
387 // The original file is the file that have the higher resolution
388 return maxBy(this.VideoFiles, file => file.resolution)
391 getVideoFilename = function (this: VideoInstance, videoFile: VideoFileInstance) {
392 return this.uuid + '-' + videoFile.resolution + videoFile.extname
395 getThumbnailName = function (this: VideoInstance) {
396 // We always have a copy of the thumbnail
397 const extension = '.jpg'
398 return this.uuid + extension
401 getPreviewName = function (this: VideoInstance) {
402 const extension = '.jpg'
403 return this.uuid + extension
406 getTorrentFileName = function (this: VideoInstance, videoFile: VideoFileInstance) {
407 const extension = '.torrent'
408 return this.uuid + '-' + videoFile.resolution + extension
411 isOwned = function (this: VideoInstance) {
412 return this.remote === false
415 createPreview = function (this: VideoInstance, videoFile: VideoFileInstance) {
416 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
418 return generateImageFromVideoFile(
419 this.getVideoFilePath(videoFile),
420 CONFIG.STORAGE.PREVIEWS_DIR,
421 this.getPreviewName(),
426 createThumbnail = function (this: VideoInstance, videoFile: VideoFileInstance) {
427 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
429 return generateImageFromVideoFile(
430 this.getVideoFilePath(videoFile),
431 CONFIG.STORAGE.THUMBNAILS_DIR,
432 this.getThumbnailName(),
437 getVideoFilePath = function (this: VideoInstance, videoFile: VideoFileInstance) {
438 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
441 createTorrentAndSetInfoHash = async function (this: VideoInstance, videoFile: VideoFileInstance) {
444 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
447 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
451 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
453 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
454 logger.info('Creating torrent %s.', filePath)
456 await writeFilePromise(filePath, torrent)
458 const parsedTorrent = parseTorrent(torrent)
459 videoFile.infoHash = parsedTorrent.infoHash
462 getEmbedPath = function (this: VideoInstance) {
463 return '/videos/embed/' + this.uuid
466 getThumbnailPath = function (this: VideoInstance) {
467 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
470 getPreviewPath = function (this: VideoInstance) {
471 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
474 toFormattedJSON = function (this: VideoInstance) {
477 if (this.VideoChannel.Account.Server) {
478 serverHost = this.VideoChannel.Account.Server.host
480 // It means it's our video
481 serverHost = CONFIG.WEBSERVER.HOST
488 category: this.category,
489 categoryLabel: this.getCategoryLabel(),
490 licence: this.licence,
491 licenceLabel: this.getLicenceLabel(),
492 language: this.language,
493 languageLabel: this.getLanguageLabel(),
495 description: this.getTruncatedDescription(),
497 isLocal: this.isOwned(),
498 account: this.VideoChannel.Account.name,
499 duration: this.duration,
502 dislikes: this.dislikes,
503 tags: map<TagInstance, string>(this.Tags, 'name'),
504 thumbnailPath: this.getThumbnailPath(),
505 previewPath: this.getPreviewPath(),
506 embedPath: this.getEmbedPath(),
507 createdAt: this.createdAt,
508 updatedAt: this.updatedAt
514 toFormattedDetailsJSON = function (this: VideoInstance) {
515 const formattedJson = this.toFormattedJSON()
517 // Maybe our server is not up to date and there are new privacy settings since our version
518 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
519 if (!privacyLabel) privacyLabel = 'Unknown'
521 const detailsJson = {
523 privacy: this.privacy,
524 descriptionPath: this.getDescriptionPath(),
525 channel: this.VideoChannel.toFormattedJSON(),
529 // Format and sort video files
530 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
531 detailsJson.files = this.VideoFiles
533 let resolutionLabel = videoFile.resolution + 'p'
535 const videoFileJson = {
536 resolution: videoFile.resolution,
538 magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs),
539 size: videoFile.size,
540 torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp),
541 fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp)
547 if (a.resolution < b.resolution) return 1
548 if (a.resolution === b.resolution) return 0
552 return Object.assign(formattedJson, detailsJson)
555 toActivityPubObject = function (this: VideoInstance) {
556 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
557 if (!this.Tags) this.Tags = []
559 const tag = this.Tags.map(t => ({
560 type: 'Hashtag' as 'Hashtag',
567 identifier: this.language + '',
568 name: this.getLanguageLabel()
575 if (Array.isArray(this.AccountVideoRates)) {
576 const likes: string[] = []
577 const dislikes: string[] = []
579 for (const rate of this.AccountVideoRates) {
580 if (rate.type === 'like') {
581 likes.push(rate.Account.url)
582 } else if (rate.type === 'dislike') {
583 dislikes.push(rate.Account.url)
587 likesObject = activityPubCollection(likes)
588 dislikesObject = activityPubCollection(dislikes)
592 for (const file of this.VideoFiles) {
595 mimeType: 'video/' + file.extname.replace('.', ''),
596 url: getVideoFileUrl(this, file, baseUrlHttp),
597 width: file.resolution,
603 mimeType: 'application/x-bittorrent',
604 url: getTorrentUrl(this, file, baseUrlHttp),
605 width: file.resolution
610 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
611 url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs),
612 width: file.resolution
616 const videoObject: VideoTorrentObject = {
617 type: 'Video' as 'Video',
620 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
621 duration: 'PT' + this.duration + 'S',
625 identifier: this.category + '',
626 name: this.getCategoryLabel()
629 identifier: this.licence + '',
630 name: this.getLicenceLabel()
635 published: this.createdAt.toISOString(),
636 updated: this.updatedAt.toISOString(),
637 mediaType: 'text/markdown',
638 content: this.getTruncatedDescription(),
641 url: getThumbnailUrl(this, baseUrlHttp),
642 mediaType: 'image/jpeg',
643 width: THUMBNAILS_SIZE.width,
644 height: THUMBNAILS_SIZE.height
648 dislikes: dislikesObject
654 getTruncatedDescription = function (this: VideoInstance) {
656 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
659 return truncate(this.description, options)
662 optimizeOriginalVideofile = async function (this: VideoInstance) {
663 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
664 const newExtname = '.mp4'
665 const inputVideoFile = this.getOriginalFile()
666 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
667 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
669 const transcodeOptions = {
670 inputPath: videoInputPath,
671 outputPath: videoOutputPath
675 // Could be very long!
676 await transcode(transcodeOptions)
678 await unlinkPromise(videoInputPath)
680 // Important to do this before getVideoFilename() to take in account the new file extension
681 inputVideoFile.set('extname', newExtname)
683 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
684 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
686 inputVideoFile.set('size', stats.size)
688 await this.createTorrentAndSetInfoHash(inputVideoFile)
689 await inputVideoFile.save()
692 // Auto destruction...
693 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
699 transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) {
700 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
701 const extname = '.mp4'
703 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
704 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
706 const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({
712 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
714 const transcodeOptions = {
715 inputPath: videoInputPath,
716 outputPath: videoOutputPath,
720 await transcode(transcodeOptions)
722 const stats = await statPromise(videoOutputPath)
724 newVideoFile.set('size', stats.size)
726 await this.createTorrentAndSetInfoHash(newVideoFile)
728 await newVideoFile.save()
730 this.VideoFiles.push(newVideoFile)
733 getOriginalFileHeight = function (this: VideoInstance) {
734 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
736 return getVideoFileHeight(originalFilePath)
739 getDescriptionPath = function (this: VideoInstance) {
740 return `/api/${API_VERSION}/videos/${this.uuid}/description`
743 getCategoryLabel = function (this: VideoInstance) {
744 let categoryLabel = VIDEO_CATEGORIES[this.category]
746 // Maybe our server is not up to date and there are new categories since our version
747 if (!categoryLabel) categoryLabel = 'Misc'
752 getLicenceLabel = function (this: VideoInstance) {
753 let licenceLabel = VIDEO_LICENCES[this.licence]
755 // Maybe our server is not up to date and there are new licences since our version
756 if (!licenceLabel) licenceLabel = 'Unknown'
761 getLanguageLabel = function (this: VideoInstance) {
762 // Language is an optional attribute
763 let languageLabel = VIDEO_LANGUAGES[this.language]
764 if (!languageLabel) languageLabel = 'Unknown'
769 removeThumbnail = function (this: VideoInstance) {
770 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
771 return unlinkPromise(thumbnailPath)
774 removePreview = function (this: VideoInstance) {
775 // Same name than video thumbnail
776 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
779 removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) {
780 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
781 return unlinkPromise(filePath)
784 removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) {
785 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
786 return unlinkPromise(torrentPath)
789 // ------------------------------ STATICS ------------------------------
793 include: [ Video['sequelize'].models.VideoFile ]
796 return Video.findAll(query)
799 listAllAndSharedByAccountForOutbox = function (accountId: number, start: number, count: number) {
800 function getRawQuery (select: string) {
801 const queryVideo = 'SELECT ' + select + ' FROM "Videos" AS "Video" ' +
802 'INNER JOIN "VideoChannels" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
803 'WHERE "VideoChannel"."accountId" = ' + accountId
804 const queryVideoShare = 'SELECT ' + select + ' FROM "VideoShares" AS "VideoShare" ' +
805 'INNER JOIN "Videos" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
806 'WHERE "VideoShare"."accountId" = ' + accountId
808 let rawQuery = `(${queryVideo}) UNION (${queryVideoShare})`
813 const rawQuery = getRawQuery('"Video"."id"')
814 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
820 order: [ getSort('createdAt'), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
823 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
828 model: Video['sequelize'].models.VideoShare,
831 [Sequelize.Op.and]: [
834 [Sequelize.Op.not]: null
844 model: Video['sequelize'].models.VideoChannel,
848 model: Video['sequelize'].models.Account,
854 model: Video['sequelize'].models.AccountVideoRate,
855 include: [ Video['sequelize'].models.Account ]
857 Video['sequelize'].models.VideoFile,
858 Video['sequelize'].models.Tag
862 return Bluebird.all([
863 Video.findAll(query),
864 Video['sequelize'].query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
865 ]).then(([ rows, totals ]) => {
866 // totals: totalVideos + totalVideoShares
868 let totalVideoShares = 0
869 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
870 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
872 const total = totalVideos + totalVideoShares
880 listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) {
885 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
888 model: Video['sequelize'].models.VideoChannel,
892 model: Video['sequelize'].models.Account,
900 Video['sequelize'].models.Tag
904 return Video.findAndCountAll(query).then(({ rows, count }) => {
912 listForApi = function (start: number, count: number, sort: string) {
917 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
920 model: Video['sequelize'].models.VideoChannel,
924 model: Video['sequelize'].models.Account,
928 model: Video['sequelize'].models.Server,
935 Video['sequelize'].models.Tag
937 where: createBaseVideosWhere()
940 return Video.findAndCountAll(query).then(({ rows, count }) => {
948 load = function (id: number) {
949 return Video.findById(id)
952 loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
953 const query: Sequelize.FindOptions<VideoAttributes> = {
957 include: [ Video['sequelize'].models.VideoFile ]
960 if (t !== undefined) query.transaction = t
962 return Video.findOne(query)
965 loadByUrlAndPopulateAccount = function (url: string, t?: Sequelize.Transaction) {
966 const query: Sequelize.FindOptions<VideoAttributes> = {
971 Video['sequelize'].models.VideoFile,
973 model: Video['sequelize'].models.VideoChannel,
974 include: [ Video['sequelize'].models.Account ]
979 if (t !== undefined) query.transaction = t
981 return Video.findOne(query)
984 loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) {
985 const query: Sequelize.FindOptions<VideoAttributes> = {
992 include: [ Video['sequelize'].models.VideoFile ]
995 if (t !== undefined) query.transaction = t
997 return Video.findOne(query)
1000 loadAndPopulateAccountAndServerAndTags = function (id: number) {
1004 model: Video['sequelize'].models.VideoChannel,
1007 model: Video['sequelize'].models.Account,
1008 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1013 model: Video['sequelize'].models.AccountVideoRate,
1014 include: [ Video['sequelize'].models.Account ]
1016 Video['sequelize'].models.Tag,
1017 Video['sequelize'].models.VideoFile
1021 return Video.findById(id, options)
1024 loadByUUIDAndPopulateAccountAndServerAndTags = function (uuid: string) {
1031 model: Video['sequelize'].models.VideoChannel,
1034 model: Video['sequelize'].models.Account,
1035 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1040 model: Video['sequelize'].models.AccountVideoRate,
1041 include: [ Video['sequelize'].models.Account ]
1043 Video['sequelize'].models.Tag,
1044 Video['sequelize'].models.VideoFile
1048 return Video.findOne(options)
1051 searchAndPopulateAccountAndServerAndTags = function (value: string, field: string, start: number, count: number, sort: string) {
1052 const serverInclude: Sequelize.IncludeOptions = {
1053 model: Video['sequelize'].models.Server,
1057 const accountInclude: Sequelize.IncludeOptions = {
1058 model: Video['sequelize'].models.Account,
1059 include: [ serverInclude ]
1062 const videoChannelInclude: Sequelize.IncludeOptions = {
1063 model: Video['sequelize'].models.VideoChannel,
1064 include: [ accountInclude ],
1068 const tagInclude: Sequelize.IncludeOptions = {
1069 model: Video['sequelize'].models.Tag
1072 const query: Sequelize.FindOptions<VideoAttributes> = {
1074 where: createBaseVideosWhere(),
1077 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
1080 if (field === 'tags') {
1081 const escapedValue = Video['sequelize'].escape('%' + value + '%')
1082 query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
1083 `(SELECT "VideoTags"."videoId"
1085 INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
1086 WHERE name ILIKE ${escapedValue}
1089 } else if (field === 'host') {
1090 // FIXME: Include our server? (not stored in the database)
1091 serverInclude.where = {
1093 [Sequelize.Op.iLike]: '%' + value + '%'
1096 serverInclude.required = true
1097 } else if (field === 'account') {
1098 accountInclude.where = {
1100 [Sequelize.Op.iLike]: '%' + value + '%'
1104 query.where[field] = {
1105 [Sequelize.Op.iLike]: '%' + value + '%'
1110 videoChannelInclude, tagInclude
1113 return Video.findAndCountAll(query).then(({ rows, count }) => {
1121 // ---------------------------------------------------------------------------
1123 function createBaseVideosWhere () {
1126 [Sequelize.Op.notIn]: Video['sequelize'].literal(
1127 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
1130 privacy: VideoPrivacy.PUBLIC
1134 function getBaseUrls (video: VideoInstance) {
1138 if (video.isOwned()) {
1139 baseUrlHttp = CONFIG.WEBSERVER.URL
1140 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1142 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host
1143 baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host
1146 return { baseUrlHttp, baseUrlWs }
1149 function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) {
1150 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName()
1153 function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1154 return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile)
1157 function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1158 return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile)
1161 function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) {
1162 const xs = getTorrentUrl(video, videoFile, baseUrlHttp)
1163 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1164 const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ]
1166 const magnetHash = {
1170 infoHash: videoFile.infoHash,
1174 return magnetUtil.encode(magnetHash)