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)
554 const tag = this.Tags.map(t => ({
555 type: 'Hashtag' as 'Hashtag',
560 for (const file of this.VideoFiles) {
563 mimeType: 'video/' + file.extname.replace('.', ''),
564 url: getVideoFileUrl(this, file, baseUrlHttp),
565 width: file.resolution,
571 mimeType: 'application/x-bittorrent',
572 url: getTorrentUrl(this, file, baseUrlHttp),
573 width: file.resolution
578 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
579 url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs),
580 width: file.resolution
584 const videoObject: VideoTorrentObject = {
585 type: 'Video' as 'Video',
586 id: getActivityPubUrl('video', this.uuid),
588 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
589 duration: 'PT' + this.duration + 'S',
593 identifier: this.category + '',
594 name: this.getCategoryLabel()
597 identifier: this.licence + '',
598 name: this.getLicenceLabel()
601 identifier: this.language + '',
602 name: this.getLanguageLabel()
606 published: this.createdAt.toISOString(),
607 updated: this.updatedAt.toISOString(),
608 mediaType: 'text/markdown',
609 content: this.getTruncatedDescription(),
612 url: getThumbnailUrl(this, baseUrlHttp),
613 mediaType: 'image/jpeg',
614 width: THUMBNAILS_SIZE.width,
615 height: THUMBNAILS_SIZE.height
623 getTruncatedDescription = function (this: VideoInstance) {
625 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
628 return truncate(this.description, options)
631 optimizeOriginalVideofile = async function (this: VideoInstance) {
632 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
633 const newExtname = '.mp4'
634 const inputVideoFile = this.getOriginalFile()
635 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
636 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
638 const transcodeOptions = {
639 inputPath: videoInputPath,
640 outputPath: videoOutputPath
644 // Could be very long!
645 await transcode(transcodeOptions)
647 await unlinkPromise(videoInputPath)
649 // Important to do this before getVideoFilename() to take in account the new file extension
650 inputVideoFile.set('extname', newExtname)
652 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
653 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
655 inputVideoFile.set('size', stats.size)
657 await this.createTorrentAndSetInfoHash(inputVideoFile)
658 await inputVideoFile.save()
661 // Auto destruction...
662 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
668 transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) {
669 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
670 const extname = '.mp4'
672 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
673 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
675 const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({
681 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
683 const transcodeOptions = {
684 inputPath: videoInputPath,
685 outputPath: videoOutputPath,
689 await transcode(transcodeOptions)
691 const stats = await statPromise(videoOutputPath)
693 newVideoFile.set('size', stats.size)
695 await this.createTorrentAndSetInfoHash(newVideoFile)
697 await newVideoFile.save()
699 this.VideoFiles.push(newVideoFile)
702 getOriginalFileHeight = function (this: VideoInstance) {
703 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
705 return getVideoFileHeight(originalFilePath)
708 getDescriptionPath = function (this: VideoInstance) {
709 return `/api/${API_VERSION}/videos/${this.uuid}/description`
712 getCategoryLabel = function (this: VideoInstance) {
713 let categoryLabel = VIDEO_CATEGORIES[this.category]
715 // Maybe our server is not up to date and there are new categories since our version
716 if (!categoryLabel) categoryLabel = 'Misc'
721 getLicenceLabel = function (this: VideoInstance) {
722 let licenceLabel = VIDEO_LICENCES[this.licence]
724 // Maybe our server is not up to date and there are new licences since our version
725 if (!licenceLabel) licenceLabel = 'Unknown'
730 getLanguageLabel = function (this: VideoInstance) {
731 // Language is an optional attribute
732 let languageLabel = VIDEO_LANGUAGES[this.language]
733 if (!languageLabel) languageLabel = 'Unknown'
738 removeThumbnail = function (this: VideoInstance) {
739 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
740 return unlinkPromise(thumbnailPath)
743 removePreview = function (this: VideoInstance) {
744 // Same name than video thumbnail
745 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
748 removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) {
749 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
750 return unlinkPromise(filePath)
753 removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) {
754 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
755 return unlinkPromise(torrentPath)
758 // ------------------------------ STATICS ------------------------------
760 generateThumbnailFromData = function (video: VideoInstance, thumbnailData: string) {
761 // Creating the thumbnail for a remote video
763 const thumbnailName = video.getThumbnailName()
764 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
765 return writeFilePromise(thumbnailPath, Buffer.from(thumbnailData, 'binary')).then(() => {
772 include: [ Video['sequelize'].models.VideoFile ]
775 return Video.findAll(query)
778 listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) {
783 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
786 model: Video['sequelize'].models.VideoChannel,
790 model: Video['sequelize'].models.Account,
798 Video['sequelize'].models.Tag
802 return Video.findAndCountAll(query).then(({ rows, count }) => {
810 listForApi = function (start: number, count: number, sort: string) {
815 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
818 model: Video['sequelize'].models.VideoChannel,
822 model: Video['sequelize'].models.Account,
826 model: Video['sequelize'].models.Server,
833 Video['sequelize'].models.Tag
835 where: createBaseVideosWhere()
838 return Video.findAndCountAll(query).then(({ rows, count }) => {
846 loadByHostAndUUID = function (fromHost: string, uuid: string, t?: Sequelize.Transaction) {
847 const query: Sequelize.FindOptions<VideoAttributes> = {
853 model: Video['sequelize'].models.VideoFile
856 model: Video['sequelize'].models.VideoChannel,
859 model: Video['sequelize'].models.Account,
862 model: Video['sequelize'].models.Server,
875 if (t !== undefined) query.transaction = t
877 return Video.findOne(query)
880 listOwnedAndPopulateAccountAndTags = function () {
886 Video['sequelize'].models.VideoFile,
888 model: Video['sequelize'].models.VideoChannel,
889 include: [ Video['sequelize'].models.Account ]
891 Video['sequelize'].models.Tag
895 return Video.findAll(query)
898 listOwnedByAccount = function (account: string) {
905 model: Video['sequelize'].models.VideoFile
908 model: Video['sequelize'].models.VideoChannel,
911 model: Video['sequelize'].models.Account,
921 return Video.findAll(query)
924 load = function (id: number) {
925 return Video.findById(id)
928 loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
929 const query: Sequelize.FindOptions<VideoAttributes> = {
933 include: [ Video['sequelize'].models.VideoFile ]
936 if (t !== undefined) query.transaction = t
938 return Video.findOne(query)
941 loadByUrlAndPopulateAccount = function (url: string, t?: Sequelize.Transaction) {
942 const query: Sequelize.FindOptions<VideoAttributes> = {
947 Video['sequelize'].models.VideoFile,
949 model: Video['sequelize'].models.VideoChannel,
950 include: [ Video['sequelize'].models.Account ]
955 if (t !== undefined) query.transaction = t
957 return Video.findOne(query)
960 loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) {
961 const query: Sequelize.FindOptions<VideoAttributes> = {
968 include: [ Video['sequelize'].models.VideoFile ]
971 if (t !== undefined) query.transaction = t
973 return Video.findOne(query)
976 loadLocalVideoByUUID = function (uuid: string, t?: Sequelize.Transaction) {
977 const query: Sequelize.FindOptions<VideoAttributes> = {
982 include: [ Video['sequelize'].models.VideoFile ]
985 if (t !== undefined) query.transaction = t
987 return Video.findOne(query)
990 loadAndPopulateAccount = function (id: number) {
993 Video['sequelize'].models.VideoFile,
995 model: Video['sequelize'].models.VideoChannel,
996 include: [ Video['sequelize'].models.Account ]
1001 return Video.findById(id, options)
1004 loadAndPopulateAccountAndServerAndTags = function (id: number) {
1008 model: Video['sequelize'].models.VideoChannel,
1011 model: Video['sequelize'].models.Account,
1012 include: [ { model: Video['sequelize'].models.Server, required: false } ]
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 } ]
1039 Video['sequelize'].models.Tag,
1040 Video['sequelize'].models.VideoFile
1044 return Video.findOne(options)
1047 searchAndPopulateAccountAndServerAndTags = function (value: string, field: string, start: number, count: number, sort: string) {
1048 const serverInclude: Sequelize.IncludeOptions = {
1049 model: Video['sequelize'].models.Server,
1053 const accountInclude: Sequelize.IncludeOptions = {
1054 model: Video['sequelize'].models.Account,
1055 include: [ serverInclude ]
1058 const videoChannelInclude: Sequelize.IncludeOptions = {
1059 model: Video['sequelize'].models.VideoChannel,
1060 include: [ accountInclude ],
1064 const tagInclude: Sequelize.IncludeOptions = {
1065 model: Video['sequelize'].models.Tag
1068 const query: Sequelize.FindOptions<VideoAttributes> = {
1070 where: createBaseVideosWhere(),
1073 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
1076 if (field === 'tags') {
1077 const escapedValue = Video['sequelize'].escape('%' + value + '%')
1078 query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
1079 `(SELECT "VideoTags"."videoId"
1081 INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
1082 WHERE name ILIKE ${escapedValue}
1085 } else if (field === 'host') {
1086 // FIXME: Include our server? (not stored in the database)
1087 serverInclude.where = {
1089 [Sequelize.Op.iLike]: '%' + value + '%'
1092 serverInclude.required = true
1093 } else if (field === 'account') {
1094 accountInclude.where = {
1096 [Sequelize.Op.iLike]: '%' + value + '%'
1100 query.where[field] = {
1101 [Sequelize.Op.iLike]: '%' + value + '%'
1106 videoChannelInclude, tagInclude
1109 return Video.findAndCountAll(query).then(({ rows, count }) => {
1117 // ---------------------------------------------------------------------------
1119 function createBaseVideosWhere () {
1122 [Sequelize.Op.notIn]: Video['sequelize'].literal(
1123 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
1126 privacy: VideoPrivacy.PUBLIC
1130 function getBaseUrls (video: VideoInstance) {
1134 if (video.isOwned()) {
1135 baseUrlHttp = CONFIG.WEBSERVER.URL
1136 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1138 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host
1139 baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host
1142 return { baseUrlHttp, baseUrlWs }
1145 function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) {
1146 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName()
1149 function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1150 return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile)
1153 function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1154 return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile)
1157 function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) {
1158 const xs = getTorrentUrl(video, videoFile, baseUrlHttp)
1159 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1160 const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ]
1162 const magnetHash = {
1166 infoHash: videoFile.infoHash,
1170 return magnetUtil.encode(magnetHash)