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,
14 isVideoDescriptionValid,
27 } from '../../helpers'
28 import { isVideoUrlValid } from '../../helpers/custom-validators/videos'
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/index'
50 const Buffer = safeBuffer.Buffer
52 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
53 let getOriginalFile: VideoMethods.GetOriginalFile
54 let getVideoFilename: VideoMethods.GetVideoFilename
55 let getThumbnailName: VideoMethods.GetThumbnailName
56 let getThumbnailPath: VideoMethods.GetThumbnailPath
57 let getPreviewName: VideoMethods.GetPreviewName
58 let getPreviewPath: VideoMethods.GetPreviewPath
59 let getTorrentFileName: VideoMethods.GetTorrentFileName
60 let isOwned: VideoMethods.IsOwned
61 let toFormattedJSON: VideoMethods.ToFormattedJSON
62 let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON
63 let toActivityPubObject: VideoMethods.ToActivityPubObject
64 let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile
65 let transcodeOriginalVideofile: VideoMethods.TranscodeOriginalVideofile
66 let createPreview: VideoMethods.CreatePreview
67 let createThumbnail: VideoMethods.CreateThumbnail
68 let getVideoFilePath: VideoMethods.GetVideoFilePath
69 let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash
70 let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight
71 let getEmbedPath: VideoMethods.GetEmbedPath
72 let getDescriptionPath: VideoMethods.GetDescriptionPath
73 let getTruncatedDescription: VideoMethods.GetTruncatedDescription
74 let getCategoryLabel: VideoMethods.GetCategoryLabel
75 let getLicenceLabel: VideoMethods.GetLicenceLabel
76 let getLanguageLabel: VideoMethods.GetLanguageLabel
78 let generateThumbnailFromData: VideoMethods.GenerateThumbnailFromData
79 let list: VideoMethods.List
80 let listForApi: VideoMethods.ListForApi
81 let listUserVideosForApi: VideoMethods.ListUserVideosForApi
82 let loadByHostAndUUID: VideoMethods.LoadByHostAndUUID
83 let listOwnedAndPopulateAccountAndTags: VideoMethods.ListOwnedAndPopulateAccountAndTags
84 let listOwnedByAccount: VideoMethods.ListOwnedByAccount
85 let load: VideoMethods.Load
86 let loadByUrlAndPopulateAccount: VideoMethods.LoadByUrlAndPopulateAccount
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' ]
264 const classMethods = [
267 generateThumbnailFromData,
270 listUserVideosForApi,
271 listOwnedAndPopulateAccountAndTags,
274 loadByUrlAndPopulateAccount,
275 loadAndPopulateAccount,
276 loadAndPopulateAccountAndServerAndTags,
280 loadLocalVideoByUUID,
281 loadByUUIDAndPopulateAccountAndServerAndTags,
282 searchAndPopulateAccountAndServerAndTags
284 const instanceMethods = [
287 createTorrentAndSetInfoHash,
303 toFormattedDetailsJSON,
304 optimizeOriginalVideofile,
305 transcodeOriginalVideofile,
306 getOriginalFileHeight,
308 getTruncatedDescription,
314 addMethodsToModel(Video, classMethods, instanceMethods)
319 // ------------------------------ METHODS ------------------------------
321 function associate (models) {
322 Video.belongsTo(models.VideoChannel, {
330 Video.belongsToMany(models.Tag, {
331 foreignKey: 'videoId',
332 through: models.VideoTag,
336 Video.hasMany(models.VideoAbuse, {
344 Video.hasMany(models.VideoFile, {
353 function afterDestroy (video: VideoInstance) {
357 video.removeThumbnail()
360 if (video.isOwned()) {
362 video.removePreview(),
363 sendDeleteVideo(video, undefined)
366 // Remove physical files and torrents
367 video.VideoFiles.forEach(file => {
368 tasks.push(video.removeFile(file))
369 tasks.push(video.removeTorrent(file))
373 return Promise.all(tasks)
375 logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err)
379 getOriginalFile = function (this: VideoInstance) {
380 if (Array.isArray(this.VideoFiles) === false) return undefined
382 // The original file is the file that have the higher resolution
383 return maxBy(this.VideoFiles, file => file.resolution)
386 getVideoFilename = function (this: VideoInstance, videoFile: VideoFileInstance) {
387 return this.uuid + '-' + videoFile.resolution + videoFile.extname
390 getThumbnailName = function (this: VideoInstance) {
391 // We always have a copy of the thumbnail
392 const extension = '.jpg'
393 return this.uuid + extension
396 getPreviewName = function (this: VideoInstance) {
397 const extension = '.jpg'
398 return this.uuid + extension
401 getTorrentFileName = function (this: VideoInstance, videoFile: VideoFileInstance) {
402 const extension = '.torrent'
403 return this.uuid + '-' + videoFile.resolution + extension
406 isOwned = function (this: VideoInstance) {
407 return this.remote === false
410 createPreview = function (this: VideoInstance, videoFile: VideoFileInstance) {
411 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
413 return generateImageFromVideoFile(
414 this.getVideoFilePath(videoFile),
415 CONFIG.STORAGE.PREVIEWS_DIR,
416 this.getPreviewName(),
421 createThumbnail = function (this: VideoInstance, videoFile: VideoFileInstance) {
422 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
424 return generateImageFromVideoFile(
425 this.getVideoFilePath(videoFile),
426 CONFIG.STORAGE.THUMBNAILS_DIR,
427 this.getThumbnailName(),
432 getVideoFilePath = function (this: VideoInstance, videoFile: VideoFileInstance) {
433 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
436 createTorrentAndSetInfoHash = async function (this: VideoInstance, videoFile: VideoFileInstance) {
439 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
442 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
446 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
448 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
449 logger.info('Creating torrent %s.', filePath)
451 await writeFilePromise(filePath, torrent)
453 const parsedTorrent = parseTorrent(torrent)
454 videoFile.infoHash = parsedTorrent.infoHash
457 getEmbedPath = function (this: VideoInstance) {
458 return '/videos/embed/' + this.uuid
461 getThumbnailPath = function (this: VideoInstance) {
462 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
465 getPreviewPath = function (this: VideoInstance) {
466 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
469 toFormattedJSON = function (this: VideoInstance) {
472 if (this.VideoChannel.Account.Server) {
473 serverHost = this.VideoChannel.Account.Server.host
475 // It means it's our video
476 serverHost = CONFIG.WEBSERVER.HOST
483 category: this.category,
484 categoryLabel: this.getCategoryLabel(),
485 licence: this.licence,
486 licenceLabel: this.getLicenceLabel(),
487 language: this.language,
488 languageLabel: this.getLanguageLabel(),
490 description: this.getTruncatedDescription(),
492 isLocal: this.isOwned(),
493 account: this.VideoChannel.Account.name,
494 duration: this.duration,
497 dislikes: this.dislikes,
498 tags: map<TagInstance, string>(this.Tags, 'name'),
499 thumbnailPath: this.getThumbnailPath(),
500 previewPath: this.getPreviewPath(),
501 embedPath: this.getEmbedPath(),
502 createdAt: this.createdAt,
503 updatedAt: this.updatedAt
509 toFormattedDetailsJSON = function (this: VideoInstance) {
510 const formattedJson = this.toFormattedJSON()
512 // Maybe our server is not up to date and there are new privacy settings since our version
513 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
514 if (!privacyLabel) privacyLabel = 'Unknown'
516 const detailsJson = {
518 privacy: this.privacy,
519 descriptionPath: this.getDescriptionPath(),
520 channel: this.VideoChannel.toFormattedJSON(),
524 // Format and sort video files
525 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
526 detailsJson.files = this.VideoFiles
528 let resolutionLabel = videoFile.resolution + 'p'
530 const videoFileJson = {
531 resolution: videoFile.resolution,
533 magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs),
534 size: videoFile.size,
535 torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp),
536 fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp)
542 if (a.resolution < b.resolution) return 1
543 if (a.resolution === b.resolution) return 0
547 return Object.assign(formattedJson, detailsJson)
550 toActivityPubObject = function (this: VideoInstance) {
551 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
552 if (!this.Tags) this.Tags = []
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',
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
617 url // FIXME: needed?
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)