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'
41 } from '../../initializers'
43 import { addMethodsToModel, getSort } from '../utils'
45 import { TagInstance } from './tag-interface'
46 import { VideoFileInstance, VideoFileModel } from './video-file-interface'
47 import { VideoAttributes, VideoInstance, VideoMethods } from './video-interface'
48 import { sendDeleteVideo } from '../../lib/activitypub/send-request'
49 import { isVideoUrlValid } from '../../helpers/custom-validators/videos'
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 loadByUUID: VideoMethods.LoadByUUID
88 let loadByUUIDOrURL: VideoMethods.LoadByUUIDOrURL
89 let loadLocalVideoByUUID: VideoMethods.LoadLocalVideoByUUID
90 let loadAndPopulateAccount: VideoMethods.LoadAndPopulateAccount
91 let loadAndPopulateAccountAndServerAndTags: VideoMethods.LoadAndPopulateAccountAndServerAndTags
92 let loadByUUIDAndPopulateAccountAndServerAndTags: VideoMethods.LoadByUUIDAndPopulateAccountAndServerAndTags
93 let searchAndPopulateAccountAndServerAndTags: VideoMethods.SearchAndPopulateAccountAndServerAndTags
94 let removeThumbnail: VideoMethods.RemoveThumbnail
95 let removePreview: VideoMethods.RemovePreview
96 let removeFile: VideoMethods.RemoveFile
97 let removeTorrent: VideoMethods.RemoveTorrent
99 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
100 Video = sequelize.define<VideoInstance, VideoAttributes>('Video',
103 type: DataTypes.UUID,
104 defaultValue: DataTypes.UUIDV4,
111 type: DataTypes.STRING,
114 nameValid: value => {
115 const res = isVideoNameValid(value)
116 if (res === false) throw new Error('Video name is not valid.')
121 type: DataTypes.INTEGER,
124 categoryValid: value => {
125 const res = isVideoCategoryValid(value)
126 if (res === false) throw new Error('Video category is not valid.')
131 type: DataTypes.INTEGER,
135 licenceValid: value => {
136 const res = isVideoLicenceValid(value)
137 if (res === false) throw new Error('Video licence is not valid.')
142 type: DataTypes.INTEGER,
145 languageValid: value => {
146 const res = isVideoLanguageValid(value)
147 if (res === false) throw new Error('Video language is not valid.')
152 type: DataTypes.INTEGER,
155 privacyValid: value => {
156 const res = isVideoPrivacyValid(value)
157 if (res === false) throw new Error('Video privacy is not valid.')
162 type: DataTypes.BOOLEAN,
165 nsfwValid: value => {
166 const res = isVideoNSFWValid(value)
167 if (res === false) throw new Error('Video nsfw attribute is not valid.')
172 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max),
175 descriptionValid: value => {
176 const res = isVideoDescriptionValid(value)
177 if (res === false) throw new Error('Video description is not valid.')
182 type: DataTypes.INTEGER,
185 durationValid: value => {
186 const res = isVideoDurationValid(value)
187 if (res === false) throw new Error('Video duration is not valid.')
192 type: DataTypes.INTEGER,
201 type: DataTypes.INTEGER,
210 type: DataTypes.INTEGER,
219 type: DataTypes.BOOLEAN,
224 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max),
228 const res = isVideoUrlValid(value)
229 if (res === false) throw new Error('Video URL is not valid.')
240 fields: [ 'createdAt' ]
243 fields: [ 'duration' ]
255 fields: [ 'channelId' ]
258 fields: [ 'parentId' ]
267 const classMethods = [
270 generateThumbnailFromData,
273 listUserVideosForApi,
274 listOwnedAndPopulateAccountAndTags,
277 loadAndPopulateAccount,
278 loadAndPopulateAccountAndServerAndTags,
282 loadLocalVideoByUUID,
283 loadByUUIDAndPopulateAccountAndServerAndTags,
284 searchAndPopulateAccountAndServerAndTags
286 const instanceMethods = [
289 createTorrentAndSetInfoHash,
305 toFormattedDetailsJSON,
306 optimizeOriginalVideofile,
307 transcodeOriginalVideofile,
308 getOriginalFileHeight,
310 getTruncatedDescription,
316 addMethodsToModel(Video, classMethods, instanceMethods)
321 // ------------------------------ METHODS ------------------------------
323 function associate (models) {
324 Video.belongsTo(models.VideoChannel, {
332 Video.belongsTo(models.VideoChannel, {
340 Video.belongsToMany(models.Tag, {
341 foreignKey: 'videoId',
342 through: models.VideoTag,
346 Video.hasMany(models.VideoAbuse, {
354 Video.hasMany(models.VideoFile, {
363 function afterDestroy (video: VideoInstance) {
367 video.removeThumbnail()
370 if (video.isOwned()) {
372 video.removePreview(),
373 sendDeleteVideo(video, undefined)
376 // Remove physical files and torrents
377 video.VideoFiles.forEach(file => {
378 tasks.push(video.removeFile(file))
379 tasks.push(video.removeTorrent(file))
383 return Promise.all(tasks)
385 logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err)
389 getOriginalFile = function (this: VideoInstance) {
390 if (Array.isArray(this.VideoFiles) === false) return undefined
392 // The original file is the file that have the higher resolution
393 return maxBy(this.VideoFiles, file => file.resolution)
396 getVideoFilename = function (this: VideoInstance, videoFile: VideoFileInstance) {
397 return this.uuid + '-' + videoFile.resolution + videoFile.extname
400 getThumbnailName = function (this: VideoInstance) {
401 // We always have a copy of the thumbnail
402 const extension = '.jpg'
403 return this.uuid + extension
406 getPreviewName = function (this: VideoInstance) {
407 const extension = '.jpg'
408 return this.uuid + extension
411 getTorrentFileName = function (this: VideoInstance, videoFile: VideoFileInstance) {
412 const extension = '.torrent'
413 return this.uuid + '-' + videoFile.resolution + extension
416 isOwned = function (this: VideoInstance) {
417 return this.remote === false
420 createPreview = function (this: VideoInstance, videoFile: VideoFileInstance) {
421 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
423 return generateImageFromVideoFile(
424 this.getVideoFilePath(videoFile),
425 CONFIG.STORAGE.PREVIEWS_DIR,
426 this.getPreviewName(),
431 createThumbnail = function (this: VideoInstance, videoFile: VideoFileInstance) {
432 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
434 return generateImageFromVideoFile(
435 this.getVideoFilePath(videoFile),
436 CONFIG.STORAGE.THUMBNAILS_DIR,
437 this.getThumbnailName(),
442 getVideoFilePath = function (this: VideoInstance, videoFile: VideoFileInstance) {
443 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
446 createTorrentAndSetInfoHash = async function (this: VideoInstance, videoFile: VideoFileInstance) {
449 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
452 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
456 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
458 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
459 logger.info('Creating torrent %s.', filePath)
461 await writeFilePromise(filePath, torrent)
463 const parsedTorrent = parseTorrent(torrent)
464 videoFile.infoHash = parsedTorrent.infoHash
467 getEmbedPath = function (this: VideoInstance) {
468 return '/videos/embed/' + this.uuid
471 getThumbnailPath = function (this: VideoInstance) {
472 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
475 getPreviewPath = function (this: VideoInstance) {
476 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
479 toFormattedJSON = function (this: VideoInstance) {
482 if (this.VideoChannel.Account.Server) {
483 serverHost = this.VideoChannel.Account.Server.host
485 // It means it's our video
486 serverHost = CONFIG.WEBSERVER.HOST
493 category: this.category,
494 categoryLabel: this.getCategoryLabel(),
495 licence: this.licence,
496 licenceLabel: this.getLicenceLabel(),
497 language: this.language,
498 languageLabel: this.getLanguageLabel(),
500 description: this.getTruncatedDescription(),
502 isLocal: this.isOwned(),
503 account: this.VideoChannel.Account.name,
504 duration: this.duration,
507 dislikes: this.dislikes,
508 tags: map<TagInstance, string>(this.Tags, 'name'),
509 thumbnailPath: this.getThumbnailPath(),
510 previewPath: this.getPreviewPath(),
511 embedPath: this.getEmbedPath(),
512 createdAt: this.createdAt,
513 updatedAt: this.updatedAt
519 toFormattedDetailsJSON = function (this: VideoInstance) {
520 const formattedJson = this.toFormattedJSON()
522 // Maybe our server is not up to date and there are new privacy settings since our version
523 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
524 if (!privacyLabel) privacyLabel = 'Unknown'
526 const detailsJson = {
528 privacy: this.privacy,
529 descriptionPath: this.getDescriptionPath(),
530 channel: this.VideoChannel.toFormattedJSON(),
534 // Format and sort video files
535 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
536 detailsJson.files = this.VideoFiles
538 let resolutionLabel = videoFile.resolution + 'p'
540 const videoFileJson = {
541 resolution: videoFile.resolution,
543 magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs),
544 size: videoFile.size,
545 torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp),
546 fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp)
552 if (a.resolution < b.resolution) return 1
553 if (a.resolution === b.resolution) return 0
557 return Object.assign(formattedJson, detailsJson)
560 toActivityPubObject = function (this: VideoInstance) {
561 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
563 const tag = this.Tags.map(t => ({
564 type: 'Hashtag' as 'Hashtag',
569 for (const file of this.VideoFiles) {
572 mimeType: 'video/' + file.extname,
573 url: getVideoFileUrl(this, file, baseUrlHttp),
574 width: file.resolution,
580 mimeType: 'application/x-bittorrent',
581 url: getTorrentUrl(this, file, baseUrlHttp),
582 width: file.resolution
587 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
588 url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs),
589 width: file.resolution
593 const videoObject: VideoTorrentObject = {
594 type: 'Video' as 'Video',
595 id: getActivityPubUrl('video', this.uuid),
597 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
598 duration: 'PT' + this.duration + 'S',
602 identifier: this.category + '',
603 name: this.getCategoryLabel()
606 identifier: this.licence + '',
607 name: this.getLicenceLabel()
610 identifier: this.language + '',
611 name: this.getLanguageLabel()
615 published: this.createdAt,
616 updated: this.updatedAt,
617 mediaType: 'text/markdown',
618 content: this.getTruncatedDescription(),
621 url: getThumbnailUrl(this, baseUrlHttp),
622 mediaType: 'image/jpeg',
623 width: THUMBNAILS_SIZE.width,
624 height: THUMBNAILS_SIZE.height
632 getTruncatedDescription = function (this: VideoInstance) {
634 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
637 return truncate(this.description, options)
640 optimizeOriginalVideofile = async function (this: VideoInstance) {
641 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
642 const newExtname = '.mp4'
643 const inputVideoFile = this.getOriginalFile()
644 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
645 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
647 const transcodeOptions = {
648 inputPath: videoInputPath,
649 outputPath: videoOutputPath
653 // Could be very long!
654 await transcode(transcodeOptions)
656 await unlinkPromise(videoInputPath)
658 // Important to do this before getVideoFilename() to take in account the new file extension
659 inputVideoFile.set('extname', newExtname)
661 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
662 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
664 inputVideoFile.set('size', stats.size)
666 await this.createTorrentAndSetInfoHash(inputVideoFile)
667 await inputVideoFile.save()
670 // Auto destruction...
671 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
677 transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) {
678 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
679 const extname = '.mp4'
681 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
682 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
684 const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({
690 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
692 const transcodeOptions = {
693 inputPath: videoInputPath,
694 outputPath: videoOutputPath,
698 await transcode(transcodeOptions)
700 const stats = await statPromise(videoOutputPath)
702 newVideoFile.set('size', stats.size)
704 await this.createTorrentAndSetInfoHash(newVideoFile)
706 await newVideoFile.save()
708 this.VideoFiles.push(newVideoFile)
711 getOriginalFileHeight = function (this: VideoInstance) {
712 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
714 return getVideoFileHeight(originalFilePath)
717 getDescriptionPath = function (this: VideoInstance) {
718 return `/api/${API_VERSION}/videos/${this.uuid}/description`
721 getCategoryLabel = function (this: VideoInstance) {
722 let categoryLabel = VIDEO_CATEGORIES[this.category]
724 // Maybe our server is not up to date and there are new categories since our version
725 if (!categoryLabel) categoryLabel = 'Misc'
730 getLicenceLabel = function (this: VideoInstance) {
731 let licenceLabel = VIDEO_LICENCES[this.licence]
733 // Maybe our server is not up to date and there are new licences since our version
734 if (!licenceLabel) licenceLabel = 'Unknown'
739 getLanguageLabel = function (this: VideoInstance) {
740 // Language is an optional attribute
741 let languageLabel = VIDEO_LANGUAGES[this.language]
742 if (!languageLabel) languageLabel = 'Unknown'
747 removeThumbnail = function (this: VideoInstance) {
748 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
749 return unlinkPromise(thumbnailPath)
752 removePreview = function (this: VideoInstance) {
753 // Same name than video thumbnail
754 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
757 removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) {
758 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
759 return unlinkPromise(filePath)
762 removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) {
763 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
764 return unlinkPromise(torrentPath)
767 // ------------------------------ STATICS ------------------------------
769 generateThumbnailFromData = function (video: VideoInstance, thumbnailData: string) {
770 // Creating the thumbnail for a remote video
772 const thumbnailName = video.getThumbnailName()
773 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
774 return writeFilePromise(thumbnailPath, Buffer.from(thumbnailData, 'binary')).then(() => {
781 include: [ Video['sequelize'].models.VideoFile ]
784 return Video.findAll(query)
787 listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) {
792 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
795 model: Video['sequelize'].models.VideoChannel,
799 model: Video['sequelize'].models.Account,
807 Video['sequelize'].models.Tag
811 return Video.findAndCountAll(query).then(({ rows, count }) => {
819 listForApi = function (start: number, count: number, sort: string) {
824 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
827 model: Video['sequelize'].models.VideoChannel,
830 model: Video['sequelize'].models.Account,
833 model: Video['sequelize'].models.Server,
840 Video['sequelize'].models.Tag
842 where: createBaseVideosWhere()
845 return Video.findAndCountAll(query).then(({ rows, count }) => {
853 loadByHostAndUUID = function (fromHost: string, uuid: string, t?: Sequelize.Transaction) {
854 const query: Sequelize.FindOptions<VideoAttributes> = {
860 model: Video['sequelize'].models.VideoFile
863 model: Video['sequelize'].models.VideoChannel,
866 model: Video['sequelize'].models.Account,
869 model: Video['sequelize'].models.Server,
882 if (t !== undefined) query.transaction = t
884 return Video.findOne(query)
887 listOwnedAndPopulateAccountAndTags = function () {
893 Video['sequelize'].models.VideoFile,
895 model: Video['sequelize'].models.VideoChannel,
896 include: [ Video['sequelize'].models.Account ]
898 Video['sequelize'].models.Tag
902 return Video.findAll(query)
905 listOwnedByAccount = function (account: string) {
912 model: Video['sequelize'].models.VideoFile
915 model: Video['sequelize'].models.VideoChannel,
918 model: Video['sequelize'].models.Account,
928 return Video.findAll(query)
931 load = function (id: number) {
932 return Video.findById(id)
935 loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
936 const query: Sequelize.FindOptions<VideoAttributes> = {
940 include: [ Video['sequelize'].models.VideoFile ]
943 if (t !== undefined) query.transaction = t
945 return Video.findOne(query)
948 loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) {
949 const query: Sequelize.FindOptions<VideoAttributes> = {
956 include: [ Video['sequelize'].models.VideoFile ]
959 if (t !== undefined) query.transaction = t
961 return Video.findOne(query)
964 loadLocalVideoByUUID = function (uuid: string, t?: Sequelize.Transaction) {
965 const query: Sequelize.FindOptions<VideoAttributes> = {
970 include: [ Video['sequelize'].models.VideoFile ]
973 if (t !== undefined) query.transaction = t
975 return Video.findOne(query)
978 loadAndPopulateAccount = function (id: number) {
981 Video['sequelize'].models.VideoFile,
983 model: Video['sequelize'].models.VideoChannel,
984 include: [ Video['sequelize'].models.Account ]
989 return Video.findById(id, options)
992 loadAndPopulateAccountAndServerAndTags = function (id: number) {
996 model: Video['sequelize'].models.VideoChannel,
999 model: Video['sequelize'].models.Account,
1000 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1004 Video['sequelize'].models.Tag,
1005 Video['sequelize'].models.VideoFile
1009 return Video.findById(id, options)
1012 loadByUUIDAndPopulateAccountAndServerAndTags = function (uuid: string) {
1019 model: Video['sequelize'].models.VideoChannel,
1022 model: Video['sequelize'].models.Account,
1023 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1027 Video['sequelize'].models.Tag,
1028 Video['sequelize'].models.VideoFile
1032 return Video.findOne(options)
1035 searchAndPopulateAccountAndServerAndTags = function (value: string, field: string, start: number, count: number, sort: string) {
1036 const serverInclude: Sequelize.IncludeOptions = {
1037 model: Video['sequelize'].models.Server,
1041 const accountInclude: Sequelize.IncludeOptions = {
1042 model: Video['sequelize'].models.Account,
1043 include: [ serverInclude ]
1046 const videoChannelInclude: Sequelize.IncludeOptions = {
1047 model: Video['sequelize'].models.VideoChannel,
1048 include: [ accountInclude ],
1052 const tagInclude: Sequelize.IncludeOptions = {
1053 model: Video['sequelize'].models.Tag
1056 const query: Sequelize.FindOptions<VideoAttributes> = {
1058 where: createBaseVideosWhere(),
1061 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
1064 if (field === 'tags') {
1065 const escapedValue = Video['sequelize'].escape('%' + value + '%')
1066 query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
1067 `(SELECT "VideoTags"."videoId"
1069 INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
1070 WHERE name ILIKE ${escapedValue}
1073 } else if (field === 'host') {
1074 // FIXME: Include our server? (not stored in the database)
1075 serverInclude.where = {
1077 [Sequelize.Op.iLike]: '%' + value + '%'
1080 serverInclude.required = true
1081 } else if (field === 'account') {
1082 accountInclude.where = {
1084 [Sequelize.Op.iLike]: '%' + value + '%'
1088 query.where[field] = {
1089 [Sequelize.Op.iLike]: '%' + value + '%'
1094 videoChannelInclude, tagInclude
1097 return Video.findAndCountAll(query).then(({ rows, count }) => {
1105 // ---------------------------------------------------------------------------
1107 function createBaseVideosWhere () {
1110 [Sequelize.Op.notIn]: Video['sequelize'].literal(
1111 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
1114 privacy: VideoPrivacy.PUBLIC
1118 function getBaseUrls (video: VideoInstance) {
1122 if (video.isOwned()) {
1123 baseUrlHttp = CONFIG.WEBSERVER.URL
1124 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1126 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host
1127 baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host
1130 return { baseUrlHttp, baseUrlWs }
1133 function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) {
1134 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName()
1137 function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1138 return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile)
1141 function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1142 return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile)
1145 function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) {
1146 const xs = getTorrentUrl(video, videoFile, baseUrlHttp)
1147 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1148 const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ]
1150 const magnetHash = {
1154 infoHash: videoFile.infoHash,
1158 return magnetUtil.encode(magnetHash)