1 import { map, maxBy, truncate } from 'lodash'
2 import * as magnetUtil from 'magnet-uri'
3 import * as parseTorrent from 'parse-torrent'
4 import { join } from 'path'
5 import * as safeBuffer from 'safe-buffer'
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,
15 isVideoDescriptionValid,
28 } from '../../helpers'
29 import { isVideoUrlValid } from '../../helpers/custom-validators/videos'
42 } from '../../initializers'
43 import { sendDeleteVideo } from '../../lib/activitypub/send-request'
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 const Buffer = safeBuffer.Buffer
53 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
54 let getOriginalFile: VideoMethods.GetOriginalFile
55 let getVideoFilename: VideoMethods.GetVideoFilename
56 let getThumbnailName: VideoMethods.GetThumbnailName
57 let getThumbnailPath: VideoMethods.GetThumbnailPath
58 let getPreviewName: VideoMethods.GetPreviewName
59 let getPreviewPath: VideoMethods.GetPreviewPath
60 let getTorrentFileName: VideoMethods.GetTorrentFileName
61 let isOwned: VideoMethods.IsOwned
62 let toFormattedJSON: VideoMethods.ToFormattedJSON
63 let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON
64 let toActivityPubObject: VideoMethods.ToActivityPubObject
65 let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile
66 let transcodeOriginalVideofile: VideoMethods.TranscodeOriginalVideofile
67 let createPreview: VideoMethods.CreatePreview
68 let createThumbnail: VideoMethods.CreateThumbnail
69 let getVideoFilePath: VideoMethods.GetVideoFilePath
70 let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash
71 let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight
72 let getEmbedPath: VideoMethods.GetEmbedPath
73 let getDescriptionPath: VideoMethods.GetDescriptionPath
74 let getTruncatedDescription: VideoMethods.GetTruncatedDescription
75 let getCategoryLabel: VideoMethods.GetCategoryLabel
76 let getLicenceLabel: VideoMethods.GetLicenceLabel
77 let getLanguageLabel: VideoMethods.GetLanguageLabel
79 let generateThumbnailFromData: VideoMethods.GenerateThumbnailFromData
80 let list: VideoMethods.List
81 let listForApi: VideoMethods.ListForApi
82 let listUserVideosForApi: VideoMethods.ListUserVideosForApi
83 let loadByHostAndUUID: VideoMethods.LoadByHostAndUUID
84 let listOwnedAndPopulateAccountAndTags: VideoMethods.ListOwnedAndPopulateAccountAndTags
85 let listOwnedByAccount: VideoMethods.ListOwnedByAccount
86 let load: VideoMethods.Load
87 let loadByUrlAndPopulateAccount: VideoMethods.LoadByUrlAndPopulateAccount
88 let loadByUUID: VideoMethods.LoadByUUID
89 let loadByUUIDOrURL: VideoMethods.LoadByUUIDOrURL
90 let loadLocalVideoByUUID: VideoMethods.LoadLocalVideoByUUID
91 let loadAndPopulateAccount: VideoMethods.LoadAndPopulateAccount
92 let loadAndPopulateAccountAndServerAndTags: VideoMethods.LoadAndPopulateAccountAndServerAndTags
93 let loadByUUIDAndPopulateAccountAndServerAndTags: VideoMethods.LoadByUUIDAndPopulateAccountAndServerAndTags
94 let searchAndPopulateAccountAndServerAndTags: VideoMethods.SearchAndPopulateAccountAndServerAndTags
95 let removeThumbnail: VideoMethods.RemoveThumbnail
96 let removePreview: VideoMethods.RemovePreview
97 let removeFile: VideoMethods.RemoveFile
98 let removeTorrent: VideoMethods.RemoveTorrent
100 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
101 Video = sequelize.define<VideoInstance, VideoAttributes>('Video',
104 type: DataTypes.UUID,
105 defaultValue: DataTypes.UUIDV4,
112 type: DataTypes.STRING,
115 nameValid: value => {
116 const res = isVideoNameValid(value)
117 if (res === false) throw new Error('Video name is not valid.')
122 type: DataTypes.INTEGER,
125 categoryValid: value => {
126 const res = isVideoCategoryValid(value)
127 if (res === false) throw new Error('Video category is not valid.')
132 type: DataTypes.INTEGER,
136 licenceValid: value => {
137 const res = isVideoLicenceValid(value)
138 if (res === false) throw new Error('Video licence is not valid.')
143 type: DataTypes.INTEGER,
146 languageValid: value => {
147 const res = isVideoLanguageValid(value)
148 if (res === false) throw new Error('Video language is not valid.')
153 type: DataTypes.INTEGER,
156 privacyValid: value => {
157 const res = isVideoPrivacyValid(value)
158 if (res === false) throw new Error('Video privacy is not valid.')
163 type: DataTypes.BOOLEAN,
166 nsfwValid: value => {
167 const res = isVideoNSFWValid(value)
168 if (res === false) throw new Error('Video nsfw attribute is not valid.')
173 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max),
176 descriptionValid: value => {
177 const res = isVideoDescriptionValid(value)
178 if (res === false) throw new Error('Video description is not valid.')
183 type: DataTypes.INTEGER,
186 durationValid: value => {
187 const res = isVideoDurationValid(value)
188 if (res === false) throw new Error('Video duration is not valid.')
193 type: DataTypes.INTEGER,
202 type: DataTypes.INTEGER,
211 type: DataTypes.INTEGER,
220 type: DataTypes.BOOLEAN,
225 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max),
229 const res = isVideoUrlValid(value)
230 if (res === false) throw new Error('Video URL is not valid.')
241 fields: [ 'createdAt' ]
244 fields: [ 'duration' ]
256 fields: [ 'channelId' ]
265 const classMethods = [
268 generateThumbnailFromData,
271 listUserVideosForApi,
272 listOwnedAndPopulateAccountAndTags,
275 loadByUrlAndPopulateAccount,
276 loadAndPopulateAccount,
277 loadAndPopulateAccountAndServerAndTags,
281 loadLocalVideoByUUID,
282 loadByUUIDAndPopulateAccountAndServerAndTags,
283 searchAndPopulateAccountAndServerAndTags
285 const instanceMethods = [
288 createTorrentAndSetInfoHash,
304 toFormattedDetailsJSON,
305 optimizeOriginalVideofile,
306 transcodeOriginalVideofile,
307 getOriginalFileHeight,
309 getTruncatedDescription,
315 addMethodsToModel(Video, classMethods, instanceMethods)
320 // ------------------------------ METHODS ------------------------------
322 function associate (models) {
323 Video.belongsTo(models.VideoChannel, {
331 Video.belongsToMany(models.Tag, {
332 foreignKey: 'videoId',
333 through: models.VideoTag,
337 Video.hasMany(models.VideoAbuse, {
345 Video.hasMany(models.VideoFile, {
354 function afterDestroy (video: VideoInstance) {
358 video.removeThumbnail()
361 if (video.isOwned()) {
363 video.removePreview(),
364 sendDeleteVideo(video, undefined)
367 // Remove physical files and torrents
368 video.VideoFiles.forEach(file => {
369 tasks.push(video.removeFile(file))
370 tasks.push(video.removeTorrent(file))
374 return Promise.all(tasks)
376 logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err)
380 getOriginalFile = function (this: VideoInstance) {
381 if (Array.isArray(this.VideoFiles) === false) return undefined
383 // The original file is the file that have the higher resolution
384 return maxBy(this.VideoFiles, file => file.resolution)
387 getVideoFilename = function (this: VideoInstance, videoFile: VideoFileInstance) {
388 return this.uuid + '-' + videoFile.resolution + videoFile.extname
391 getThumbnailName = function (this: VideoInstance) {
392 // We always have a copy of the thumbnail
393 const extension = '.jpg'
394 return this.uuid + extension
397 getPreviewName = function (this: VideoInstance) {
398 const extension = '.jpg'
399 return this.uuid + extension
402 getTorrentFileName = function (this: VideoInstance, videoFile: VideoFileInstance) {
403 const extension = '.torrent'
404 return this.uuid + '-' + videoFile.resolution + extension
407 isOwned = function (this: VideoInstance) {
408 return this.remote === false
411 createPreview = function (this: VideoInstance, videoFile: VideoFileInstance) {
412 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
414 return generateImageFromVideoFile(
415 this.getVideoFilePath(videoFile),
416 CONFIG.STORAGE.PREVIEWS_DIR,
417 this.getPreviewName(),
422 createThumbnail = function (this: VideoInstance, videoFile: VideoFileInstance) {
423 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
425 return generateImageFromVideoFile(
426 this.getVideoFilePath(videoFile),
427 CONFIG.STORAGE.THUMBNAILS_DIR,
428 this.getThumbnailName(),
433 getVideoFilePath = function (this: VideoInstance, videoFile: VideoFileInstance) {
434 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
437 createTorrentAndSetInfoHash = async function (this: VideoInstance, videoFile: VideoFileInstance) {
440 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
443 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
447 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
449 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
450 logger.info('Creating torrent %s.', filePath)
452 await writeFilePromise(filePath, torrent)
454 const parsedTorrent = parseTorrent(torrent)
455 videoFile.infoHash = parsedTorrent.infoHash
458 getEmbedPath = function (this: VideoInstance) {
459 return '/videos/embed/' + this.uuid
462 getThumbnailPath = function (this: VideoInstance) {
463 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
466 getPreviewPath = function (this: VideoInstance) {
467 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
470 toFormattedJSON = function (this: VideoInstance) {
473 if (this.VideoChannel.Account.Server) {
474 serverHost = this.VideoChannel.Account.Server.host
476 // It means it's our video
477 serverHost = CONFIG.WEBSERVER.HOST
484 category: this.category,
485 categoryLabel: this.getCategoryLabel(),
486 licence: this.licence,
487 licenceLabel: this.getLicenceLabel(),
488 language: this.language,
489 languageLabel: this.getLanguageLabel(),
491 description: this.getTruncatedDescription(),
493 isLocal: this.isOwned(),
494 account: this.VideoChannel.Account.name,
495 duration: this.duration,
498 dislikes: this.dislikes,
499 tags: map<TagInstance, string>(this.Tags, 'name'),
500 thumbnailPath: this.getThumbnailPath(),
501 previewPath: this.getPreviewPath(),
502 embedPath: this.getEmbedPath(),
503 createdAt: this.createdAt,
504 updatedAt: this.updatedAt
510 toFormattedDetailsJSON = function (this: VideoInstance) {
511 const formattedJson = this.toFormattedJSON()
513 // Maybe our server is not up to date and there are new privacy settings since our version
514 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
515 if (!privacyLabel) privacyLabel = 'Unknown'
517 const detailsJson = {
519 privacy: this.privacy,
520 descriptionPath: this.getDescriptionPath(),
521 channel: this.VideoChannel.toFormattedJSON(),
525 // Format and sort video files
526 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
527 detailsJson.files = this.VideoFiles
529 let resolutionLabel = videoFile.resolution + 'p'
531 const videoFileJson = {
532 resolution: videoFile.resolution,
534 magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs),
535 size: videoFile.size,
536 torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp),
537 fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp)
543 if (a.resolution < b.resolution) return 1
544 if (a.resolution === b.resolution) return 0
548 return Object.assign(formattedJson, detailsJson)
551 toActivityPubObject = function (this: VideoInstance) {
552 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
553 if (!this.Tags) this.Tags = []
555 const tag = this.Tags.map(t => ({
556 type: 'Hashtag' as 'Hashtag',
561 for (const file of this.VideoFiles) {
564 mimeType: 'video/' + file.extname.replace('.', ''),
565 url: getVideoFileUrl(this, file, baseUrlHttp),
566 width: file.resolution,
572 mimeType: 'application/x-bittorrent',
573 url: getTorrentUrl(this, file, baseUrlHttp),
574 width: file.resolution
579 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
580 url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs),
581 width: file.resolution
585 const videoObject: VideoTorrentObject = {
586 type: 'Video' as 'Video',
587 id: getActivityPubUrl('video', this.uuid),
589 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
590 duration: 'PT' + this.duration + 'S',
594 identifier: this.category + '',
595 name: this.getCategoryLabel()
598 identifier: this.licence + '',
599 name: this.getLicenceLabel()
602 identifier: this.language + '',
603 name: this.getLanguageLabel()
607 published: this.createdAt.toISOString(),
608 updated: this.updatedAt.toISOString(),
609 mediaType: 'text/markdown',
610 content: this.getTruncatedDescription(),
613 url: getThumbnailUrl(this, baseUrlHttp),
614 mediaType: 'image/jpeg',
615 width: THUMBNAILS_SIZE.width,
616 height: THUMBNAILS_SIZE.height
624 getTruncatedDescription = function (this: VideoInstance) {
626 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
629 return truncate(this.description, options)
632 optimizeOriginalVideofile = async function (this: VideoInstance) {
633 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
634 const newExtname = '.mp4'
635 const inputVideoFile = this.getOriginalFile()
636 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
637 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
639 const transcodeOptions = {
640 inputPath: videoInputPath,
641 outputPath: videoOutputPath
645 // Could be very long!
646 await transcode(transcodeOptions)
648 await unlinkPromise(videoInputPath)
650 // Important to do this before getVideoFilename() to take in account the new file extension
651 inputVideoFile.set('extname', newExtname)
653 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
654 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
656 inputVideoFile.set('size', stats.size)
658 await this.createTorrentAndSetInfoHash(inputVideoFile)
659 await inputVideoFile.save()
662 // Auto destruction...
663 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
669 transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) {
670 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
671 const extname = '.mp4'
673 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
674 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
676 const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({
682 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
684 const transcodeOptions = {
685 inputPath: videoInputPath,
686 outputPath: videoOutputPath,
690 await transcode(transcodeOptions)
692 const stats = await statPromise(videoOutputPath)
694 newVideoFile.set('size', stats.size)
696 await this.createTorrentAndSetInfoHash(newVideoFile)
698 await newVideoFile.save()
700 this.VideoFiles.push(newVideoFile)
703 getOriginalFileHeight = function (this: VideoInstance) {
704 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
706 return getVideoFileHeight(originalFilePath)
709 getDescriptionPath = function (this: VideoInstance) {
710 return `/api/${API_VERSION}/videos/${this.uuid}/description`
713 getCategoryLabel = function (this: VideoInstance) {
714 let categoryLabel = VIDEO_CATEGORIES[this.category]
716 // Maybe our server is not up to date and there are new categories since our version
717 if (!categoryLabel) categoryLabel = 'Misc'
722 getLicenceLabel = function (this: VideoInstance) {
723 let licenceLabel = VIDEO_LICENCES[this.licence]
725 // Maybe our server is not up to date and there are new licences since our version
726 if (!licenceLabel) licenceLabel = 'Unknown'
731 getLanguageLabel = function (this: VideoInstance) {
732 // Language is an optional attribute
733 let languageLabel = VIDEO_LANGUAGES[this.language]
734 if (!languageLabel) languageLabel = 'Unknown'
739 removeThumbnail = function (this: VideoInstance) {
740 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
741 return unlinkPromise(thumbnailPath)
744 removePreview = function (this: VideoInstance) {
745 // Same name than video thumbnail
746 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
749 removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) {
750 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
751 return unlinkPromise(filePath)
754 removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) {
755 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
756 return unlinkPromise(torrentPath)
759 // ------------------------------ STATICS ------------------------------
761 generateThumbnailFromData = function (video: VideoInstance, thumbnailData: string) {
762 // Creating the thumbnail for a remote video
764 const thumbnailName = video.getThumbnailName()
765 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
766 return writeFilePromise(thumbnailPath, Buffer.from(thumbnailData, 'binary')).then(() => {
773 include: [ Video['sequelize'].models.VideoFile ]
776 return Video.findAll(query)
779 listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) {
784 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
787 model: Video['sequelize'].models.VideoChannel,
791 model: Video['sequelize'].models.Account,
799 Video['sequelize'].models.Tag
803 return Video.findAndCountAll(query).then(({ rows, count }) => {
811 listForApi = function (start: number, count: number, sort: string) {
816 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
819 model: Video['sequelize'].models.VideoChannel,
823 model: Video['sequelize'].models.Account,
827 model: Video['sequelize'].models.Server,
834 Video['sequelize'].models.Tag
836 where: createBaseVideosWhere()
839 return Video.findAndCountAll(query).then(({ rows, count }) => {
847 loadByHostAndUUID = function (fromHost: string, uuid: string, t?: Sequelize.Transaction) {
848 const query: Sequelize.FindOptions<VideoAttributes> = {
854 model: Video['sequelize'].models.VideoFile
857 model: Video['sequelize'].models.VideoChannel,
860 model: Video['sequelize'].models.Account,
863 model: Video['sequelize'].models.Server,
876 if (t !== undefined) query.transaction = t
878 return Video.findOne(query)
881 listOwnedAndPopulateAccountAndTags = function () {
887 Video['sequelize'].models.VideoFile,
889 model: Video['sequelize'].models.VideoChannel,
890 include: [ Video['sequelize'].models.Account ]
892 Video['sequelize'].models.Tag
896 return Video.findAll(query)
899 listOwnedByAccount = function (account: string) {
906 model: Video['sequelize'].models.VideoFile
909 model: Video['sequelize'].models.VideoChannel,
912 model: Video['sequelize'].models.Account,
922 return Video.findAll(query)
925 load = function (id: number) {
926 return Video.findById(id)
929 loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
930 const query: Sequelize.FindOptions<VideoAttributes> = {
934 include: [ Video['sequelize'].models.VideoFile ]
937 if (t !== undefined) query.transaction = t
939 return Video.findOne(query)
942 loadByUrlAndPopulateAccount = function (url: string, t?: Sequelize.Transaction) {
943 const query: Sequelize.FindOptions<VideoAttributes> = {
948 Video['sequelize'].models.VideoFile,
950 model: Video['sequelize'].models.VideoChannel,
951 include: [ Video['sequelize'].models.Account ]
956 if (t !== undefined) query.transaction = t
958 return Video.findOne(query)
961 loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) {
962 const query: Sequelize.FindOptions<VideoAttributes> = {
969 include: [ Video['sequelize'].models.VideoFile ]
972 if (t !== undefined) query.transaction = t
974 return Video.findOne(query)
977 loadLocalVideoByUUID = function (uuid: string, t?: Sequelize.Transaction) {
978 const query: Sequelize.FindOptions<VideoAttributes> = {
983 include: [ Video['sequelize'].models.VideoFile ]
986 if (t !== undefined) query.transaction = t
988 return Video.findOne(query)
991 loadAndPopulateAccount = function (id: number) {
994 Video['sequelize'].models.VideoFile,
996 model: Video['sequelize'].models.VideoChannel,
997 include: [ Video['sequelize'].models.Account ]
1002 return Video.findById(id, options)
1005 loadAndPopulateAccountAndServerAndTags = function (id: number) {
1009 model: Video['sequelize'].models.VideoChannel,
1012 model: Video['sequelize'].models.Account,
1013 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1017 Video['sequelize'].models.Tag,
1018 Video['sequelize'].models.VideoFile
1022 return Video.findById(id, options)
1025 loadByUUIDAndPopulateAccountAndServerAndTags = function (uuid: string) {
1032 model: Video['sequelize'].models.VideoChannel,
1035 model: Video['sequelize'].models.Account,
1036 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1040 Video['sequelize'].models.Tag,
1041 Video['sequelize'].models.VideoFile
1045 return Video.findOne(options)
1048 searchAndPopulateAccountAndServerAndTags = function (value: string, field: string, start: number, count: number, sort: string) {
1049 const serverInclude: Sequelize.IncludeOptions = {
1050 model: Video['sequelize'].models.Server,
1054 const accountInclude: Sequelize.IncludeOptions = {
1055 model: Video['sequelize'].models.Account,
1056 include: [ serverInclude ]
1059 const videoChannelInclude: Sequelize.IncludeOptions = {
1060 model: Video['sequelize'].models.VideoChannel,
1061 include: [ accountInclude ],
1065 const tagInclude: Sequelize.IncludeOptions = {
1066 model: Video['sequelize'].models.Tag
1069 const query: Sequelize.FindOptions<VideoAttributes> = {
1071 where: createBaseVideosWhere(),
1074 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
1077 if (field === 'tags') {
1078 const escapedValue = Video['sequelize'].escape('%' + value + '%')
1079 query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
1080 `(SELECT "VideoTags"."videoId"
1082 INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
1083 WHERE name ILIKE ${escapedValue}
1086 } else if (field === 'host') {
1087 // FIXME: Include our server? (not stored in the database)
1088 serverInclude.where = {
1090 [Sequelize.Op.iLike]: '%' + value + '%'
1093 serverInclude.required = true
1094 } else if (field === 'account') {
1095 accountInclude.where = {
1097 [Sequelize.Op.iLike]: '%' + value + '%'
1101 query.where[field] = {
1102 [Sequelize.Op.iLike]: '%' + value + '%'
1107 videoChannelInclude, tagInclude
1110 return Video.findAndCountAll(query).then(({ rows, count }) => {
1118 // ---------------------------------------------------------------------------
1120 function createBaseVideosWhere () {
1123 [Sequelize.Op.notIn]: Video['sequelize'].literal(
1124 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
1127 privacy: VideoPrivacy.PUBLIC
1131 function getBaseUrls (video: VideoInstance) {
1135 if (video.isOwned()) {
1136 baseUrlHttp = CONFIG.WEBSERVER.URL
1137 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1139 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host
1140 baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host
1143 return { baseUrlHttp, baseUrlWs }
1146 function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) {
1147 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName()
1150 function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1151 return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile)
1154 function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1155 return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile)
1158 function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) {
1159 const xs = getTorrentUrl(video, videoFile, baseUrlHttp)
1160 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1161 const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ]
1163 const magnetHash = {
1167 infoHash: videoFile.infoHash,
1171 return magnetUtil.encode(magnetHash)