1 import * as Bluebird from 'bluebird'
2 import { map, maxBy, truncate } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
6 import * as Sequelize from 'sequelize'
7 import { VideoPrivacy, VideoResolution } from '../../../shared'
8 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects/video-torrent-object'
9 import { activityPubCollection } from '../../helpers/activitypub'
10 import { isVideoCategoryValid, isVideoLanguageValid, isVideoPrivacyValid, isVideoUrlValid } from '../../helpers/custom-validators/videos'
23 } from '../../initializers/constants'
24 import { sendDeleteVideo } from '../../lib/index'
26 import { addMethodsToModel, getSort } from '../utils'
28 import { TagInstance } from './tag-interface'
29 import { VideoFileInstance, VideoFileModel } from './video-file-interface'
30 import { VideoAttributes, VideoInstance, VideoMethods } from './video-interface'
31 import { isVideoNameValid, isVideoLicenceValid, isVideoNSFWValid, isVideoDescriptionValid, isVideoDurationValid } from '../../helpers/index'
32 import { logger } from '../../helpers/logger'
33 import { generateImageFromVideoFile, transcode, getVideoFileHeight } from '../../helpers/ffmpeg-utils'
34 import { createTorrentPromise, writeFilePromise, unlinkPromise, renamePromise, statPromise } from '../../helpers/core-utils'
35 import { getAnnounceActivityPubUrl } from '../../lib/activitypub/url'
37 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
38 let getOriginalFile: VideoMethods.GetOriginalFile
39 let getVideoFilename: VideoMethods.GetVideoFilename
40 let getThumbnailName: VideoMethods.GetThumbnailName
41 let getThumbnailPath: VideoMethods.GetThumbnailPath
42 let getPreviewName: VideoMethods.GetPreviewName
43 let getPreviewPath: VideoMethods.GetPreviewPath
44 let getTorrentFileName: VideoMethods.GetTorrentFileName
45 let isOwned: VideoMethods.IsOwned
46 let toFormattedJSON: VideoMethods.ToFormattedJSON
47 let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON
48 let toActivityPubObject: VideoMethods.ToActivityPubObject
49 let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile
50 let transcodeOriginalVideofile: VideoMethods.TranscodeOriginalVideofile
51 let createPreview: VideoMethods.CreatePreview
52 let createThumbnail: VideoMethods.CreateThumbnail
53 let getVideoFilePath: VideoMethods.GetVideoFilePath
54 let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash
55 let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight
56 let getEmbedPath: VideoMethods.GetEmbedPath
57 let getDescriptionPath: VideoMethods.GetDescriptionPath
58 let getTruncatedDescription: VideoMethods.GetTruncatedDescription
59 let getCategoryLabel: VideoMethods.GetCategoryLabel
60 let getLicenceLabel: VideoMethods.GetLicenceLabel
61 let getLanguageLabel: VideoMethods.GetLanguageLabel
63 let list: VideoMethods.List
64 let listForApi: VideoMethods.ListForApi
65 let listAllAndSharedByAccountForOutbox: VideoMethods.ListAllAndSharedByAccountForOutbox
66 let listUserVideosForApi: VideoMethods.ListUserVideosForApi
67 let load: VideoMethods.Load
68 let loadByUrlAndPopulateAccount: VideoMethods.LoadByUrlAndPopulateAccount
69 let loadByUUID: VideoMethods.LoadByUUID
70 let loadByUUIDOrURL: VideoMethods.LoadByUUIDOrURL
71 let loadAndPopulateAccountAndServerAndTags: VideoMethods.LoadAndPopulateAccountAndServerAndTags
72 let loadByUUIDAndPopulateAccountAndServerAndTags: VideoMethods.LoadByUUIDAndPopulateAccountAndServerAndTags
73 let searchAndPopulateAccountAndServerAndTags: VideoMethods.SearchAndPopulateAccountAndServerAndTags
74 let removeThumbnail: VideoMethods.RemoveThumbnail
75 let removePreview: VideoMethods.RemovePreview
76 let removeFile: VideoMethods.RemoveFile
77 let removeTorrent: VideoMethods.RemoveTorrent
79 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
80 Video = sequelize.define<VideoInstance, VideoAttributes>('Video',
84 defaultValue: DataTypes.UUIDV4,
91 type: DataTypes.STRING,
95 const res = isVideoNameValid(value)
96 if (res === false) throw new Error('Video name is not valid.')
101 type: DataTypes.INTEGER,
104 categoryValid: value => {
105 const res = isVideoCategoryValid(value)
106 if (res === false) throw new Error('Video category is not valid.')
111 type: DataTypes.INTEGER,
115 licenceValid: value => {
116 const res = isVideoLicenceValid(value)
117 if (res === false) throw new Error('Video licence is not valid.')
122 type: DataTypes.INTEGER,
125 languageValid: value => {
126 const res = isVideoLanguageValid(value)
127 if (res === false) throw new Error('Video language is not valid.')
132 type: DataTypes.INTEGER,
135 privacyValid: value => {
136 const res = isVideoPrivacyValid(value)
137 if (res === false) throw new Error('Video privacy is not valid.')
142 type: DataTypes.BOOLEAN,
145 nsfwValid: value => {
146 const res = isVideoNSFWValid(value)
147 if (res === false) throw new Error('Video nsfw attribute is not valid.')
152 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max),
155 descriptionValid: value => {
156 const res = isVideoDescriptionValid(value)
157 if (res === false) throw new Error('Video description is not valid.')
162 type: DataTypes.INTEGER,
165 durationValid: value => {
166 const res = isVideoDurationValid(value)
167 if (res === false) throw new Error('Video duration is not valid.')
172 type: DataTypes.INTEGER,
181 type: DataTypes.INTEGER,
190 type: DataTypes.INTEGER,
199 type: DataTypes.BOOLEAN,
204 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max),
208 const res = isVideoUrlValid(value)
209 if (res === false) throw new Error('Video URL is not valid.')
220 fields: [ 'createdAt' ]
223 fields: [ 'duration' ]
235 fields: [ 'channelId' ]
244 const classMethods = [
248 listAllAndSharedByAccountForOutbox,
250 listUserVideosForApi,
252 loadByUrlAndPopulateAccount,
253 loadAndPopulateAccountAndServerAndTags,
256 loadByUUIDAndPopulateAccountAndServerAndTags,
257 searchAndPopulateAccountAndServerAndTags
259 const instanceMethods = [
262 createTorrentAndSetInfoHash,
278 toFormattedDetailsJSON,
279 optimizeOriginalVideofile,
280 transcodeOriginalVideofile,
281 getOriginalFileHeight,
283 getTruncatedDescription,
289 addMethodsToModel(Video, classMethods, instanceMethods)
294 // ------------------------------ METHODS ------------------------------
296 function associate (models) {
297 Video.belongsTo(models.VideoChannel, {
305 Video.belongsToMany(models.Tag, {
306 foreignKey: 'videoId',
307 through: models.VideoTag,
311 Video.hasMany(models.VideoAbuse, {
319 Video.hasMany(models.VideoFile, {
327 Video.hasMany(models.VideoShare, {
335 Video.hasMany(models.AccountVideoRate, {
344 function afterDestroy (video: VideoInstance) {
348 video.removeThumbnail()
351 if (video.isOwned()) {
353 video.removePreview(),
354 sendDeleteVideo(video, undefined)
357 // Remove physical files and torrents
358 video.VideoFiles.forEach(file => {
359 tasks.push(video.removeFile(file))
360 tasks.push(video.removeTorrent(file))
364 return Promise.all(tasks)
366 logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err)
370 getOriginalFile = function (this: VideoInstance) {
371 if (Array.isArray(this.VideoFiles) === false) return undefined
373 // The original file is the file that have the higher resolution
374 return maxBy(this.VideoFiles, file => file.resolution)
377 getVideoFilename = function (this: VideoInstance, videoFile: VideoFileInstance) {
378 return this.uuid + '-' + videoFile.resolution + videoFile.extname
381 getThumbnailName = function (this: VideoInstance) {
382 // We always have a copy of the thumbnail
383 const extension = '.jpg'
384 return this.uuid + extension
387 getPreviewName = function (this: VideoInstance) {
388 const extension = '.jpg'
389 return this.uuid + extension
392 getTorrentFileName = function (this: VideoInstance, videoFile: VideoFileInstance) {
393 const extension = '.torrent'
394 return this.uuid + '-' + videoFile.resolution + extension
397 isOwned = function (this: VideoInstance) {
398 return this.remote === false
401 createPreview = function (this: VideoInstance, videoFile: VideoFileInstance) {
402 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
404 return generateImageFromVideoFile(
405 this.getVideoFilePath(videoFile),
406 CONFIG.STORAGE.PREVIEWS_DIR,
407 this.getPreviewName(),
412 createThumbnail = function (this: VideoInstance, videoFile: VideoFileInstance) {
413 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
415 return generateImageFromVideoFile(
416 this.getVideoFilePath(videoFile),
417 CONFIG.STORAGE.THUMBNAILS_DIR,
418 this.getThumbnailName(),
423 getVideoFilePath = function (this: VideoInstance, videoFile: VideoFileInstance) {
424 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
427 createTorrentAndSetInfoHash = async function (this: VideoInstance, videoFile: VideoFileInstance) {
430 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
433 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
437 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
439 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
440 logger.info('Creating torrent %s.', filePath)
442 await writeFilePromise(filePath, torrent)
444 const parsedTorrent = parseTorrent(torrent)
445 videoFile.infoHash = parsedTorrent.infoHash
448 getEmbedPath = function (this: VideoInstance) {
449 return '/videos/embed/' + this.uuid
452 getThumbnailPath = function (this: VideoInstance) {
453 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
456 getPreviewPath = function (this: VideoInstance) {
457 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
460 toFormattedJSON = function (this: VideoInstance) {
463 if (this.VideoChannel.Account.Server) {
464 serverHost = this.VideoChannel.Account.Server.host
466 // It means it's our video
467 serverHost = CONFIG.WEBSERVER.HOST
474 category: this.category,
475 categoryLabel: this.getCategoryLabel(),
476 licence: this.licence,
477 licenceLabel: this.getLicenceLabel(),
478 language: this.language,
479 languageLabel: this.getLanguageLabel(),
481 description: this.getTruncatedDescription(),
483 isLocal: this.isOwned(),
484 account: this.VideoChannel.Account.name,
485 duration: this.duration,
488 dislikes: this.dislikes,
489 tags: map<TagInstance, string>(this.Tags, 'name'),
490 thumbnailPath: this.getThumbnailPath(),
491 previewPath: this.getPreviewPath(),
492 embedPath: this.getEmbedPath(),
493 createdAt: this.createdAt,
494 updatedAt: this.updatedAt
500 toFormattedDetailsJSON = function (this: VideoInstance) {
501 const formattedJson = this.toFormattedJSON()
503 // Maybe our server is not up to date and there are new privacy settings since our version
504 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
505 if (!privacyLabel) privacyLabel = 'Unknown'
507 const detailsJson = {
509 privacy: this.privacy,
510 descriptionPath: this.getDescriptionPath(),
511 channel: this.VideoChannel.toFormattedJSON(),
515 // Format and sort video files
516 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
517 detailsJson.files = this.VideoFiles
519 let resolutionLabel = videoFile.resolution + 'p'
521 const videoFileJson = {
522 resolution: videoFile.resolution,
524 magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs),
525 size: videoFile.size,
526 torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp),
527 fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp)
533 if (a.resolution < b.resolution) return 1
534 if (a.resolution === b.resolution) return 0
538 return Object.assign(formattedJson, detailsJson)
541 toActivityPubObject = function (this: VideoInstance) {
542 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
543 if (!this.Tags) this.Tags = []
545 const tag = this.Tags.map(t => ({
546 type: 'Hashtag' as 'Hashtag',
553 identifier: this.language + '',
554 name: this.getLanguageLabel()
561 if (Array.isArray(this.AccountVideoRates)) {
562 const likes: string[] = []
563 const dislikes: string[] = []
565 for (const rate of this.AccountVideoRates) {
566 if (rate.type === 'like') {
567 likes.push(rate.Account.url)
568 } else if (rate.type === 'dislike') {
569 dislikes.push(rate.Account.url)
573 likesObject = activityPubCollection(likes)
574 dislikesObject = activityPubCollection(dislikes)
578 if (Array.isArray(this.VideoShares)) {
579 const shares: string[] = []
581 for (const videoShare of this.VideoShares) {
582 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Account)
583 shares.push(shareUrl)
586 sharesObject = activityPubCollection(shares)
590 for (const file of this.VideoFiles) {
593 mimeType: 'video/' + file.extname.replace('.', ''),
594 url: getVideoFileUrl(this, file, baseUrlHttp),
595 width: file.resolution,
601 mimeType: 'application/x-bittorrent',
602 url: getTorrentUrl(this, file, baseUrlHttp),
603 width: file.resolution
608 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
609 url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs),
610 width: file.resolution
614 const videoObject: VideoTorrentObject = {
615 type: 'Video' as 'Video',
618 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
619 duration: 'PT' + this.duration + 'S',
623 identifier: this.category + '',
624 name: this.getCategoryLabel()
627 identifier: this.licence + '',
628 name: this.getLicenceLabel()
633 published: this.createdAt.toISOString(),
634 updated: this.updatedAt.toISOString(),
635 mediaType: 'text/markdown',
636 content: this.getTruncatedDescription(),
639 url: getThumbnailUrl(this, baseUrlHttp),
640 mediaType: 'image/jpeg',
641 width: THUMBNAILS_SIZE.width,
642 height: THUMBNAILS_SIZE.height
646 dislikes: dislikesObject,
653 getTruncatedDescription = function (this: VideoInstance) {
655 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
658 return truncate(this.description, options)
661 optimizeOriginalVideofile = async function (this: VideoInstance) {
662 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
663 const newExtname = '.mp4'
664 const inputVideoFile = this.getOriginalFile()
665 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
666 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
668 const transcodeOptions = {
669 inputPath: videoInputPath,
670 outputPath: videoOutputPath
674 // Could be very long!
675 await transcode(transcodeOptions)
677 await unlinkPromise(videoInputPath)
679 // Important to do this before getVideoFilename() to take in account the new file extension
680 inputVideoFile.set('extname', newExtname)
682 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
683 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
685 inputVideoFile.set('size', stats.size)
687 await this.createTorrentAndSetInfoHash(inputVideoFile)
688 await inputVideoFile.save()
691 // Auto destruction...
692 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
698 transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) {
699 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
700 const extname = '.mp4'
702 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
703 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
705 const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({
711 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
713 const transcodeOptions = {
714 inputPath: videoInputPath,
715 outputPath: videoOutputPath,
719 await transcode(transcodeOptions)
721 const stats = await statPromise(videoOutputPath)
723 newVideoFile.set('size', stats.size)
725 await this.createTorrentAndSetInfoHash(newVideoFile)
727 await newVideoFile.save()
729 this.VideoFiles.push(newVideoFile)
732 getOriginalFileHeight = function (this: VideoInstance) {
733 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
735 return getVideoFileHeight(originalFilePath)
738 getDescriptionPath = function (this: VideoInstance) {
739 return `/api/${API_VERSION}/videos/${this.uuid}/description`
742 getCategoryLabel = function (this: VideoInstance) {
743 let categoryLabel = VIDEO_CATEGORIES[this.category]
745 // Maybe our server is not up to date and there are new categories since our version
746 if (!categoryLabel) categoryLabel = 'Misc'
751 getLicenceLabel = function (this: VideoInstance) {
752 let licenceLabel = VIDEO_LICENCES[this.licence]
754 // Maybe our server is not up to date and there are new licences since our version
755 if (!licenceLabel) licenceLabel = 'Unknown'
760 getLanguageLabel = function (this: VideoInstance) {
761 // Language is an optional attribute
762 let languageLabel = VIDEO_LANGUAGES[this.language]
763 if (!languageLabel) languageLabel = 'Unknown'
768 removeThumbnail = function (this: VideoInstance) {
769 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
770 return unlinkPromise(thumbnailPath)
773 removePreview = function (this: VideoInstance) {
774 // Same name than video thumbnail
775 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
778 removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) {
779 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
780 return unlinkPromise(filePath)
783 removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) {
784 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
785 return unlinkPromise(torrentPath)
788 // ------------------------------ STATICS ------------------------------
792 include: [ Video['sequelize'].models.VideoFile ]
795 return Video.findAll(query)
798 listAllAndSharedByAccountForOutbox = function (accountId: number, start: number, count: number) {
799 function getRawQuery (select: string) {
800 const queryVideo = 'SELECT ' + select + ' FROM "Videos" AS "Video" ' +
801 'INNER JOIN "VideoChannels" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
802 'WHERE "VideoChannel"."accountId" = ' + accountId
803 const queryVideoShare = 'SELECT ' + select + ' FROM "VideoShares" AS "VideoShare" ' +
804 'INNER JOIN "Videos" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
805 'WHERE "VideoShare"."accountId" = ' + accountId
807 let rawQuery = `(${queryVideo}) UNION (${queryVideoShare})`
812 const rawQuery = getRawQuery('"Video"."id"')
813 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
819 order: [ getSort('createdAt'), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
822 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
827 model: Video['sequelize'].models.VideoShare,
830 [Sequelize.Op.and]: [
833 [Sequelize.Op.not]: null
841 include: [ Video['sequelize'].models.Account ]
844 model: Video['sequelize'].models.VideoChannel,
848 model: Video['sequelize'].models.Account,
854 model: Video['sequelize'].models.AccountVideoRate,
855 include: [ Video['sequelize'].models.Account ]
857 Video['sequelize'].models.VideoFile,
858 Video['sequelize'].models.Tag
862 return Bluebird.all([
863 Video.findAll(query),
864 Video['sequelize'].query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
865 ]).then(([ rows, totals ]) => {
866 // totals: totalVideos + totalVideoShares
868 let totalVideoShares = 0
869 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
870 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
872 const total = totalVideos + totalVideoShares
880 listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) {
885 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
888 model: Video['sequelize'].models.VideoChannel,
892 model: Video['sequelize'].models.Account,
900 Video['sequelize'].models.Tag
904 return Video.findAndCountAll(query).then(({ rows, count }) => {
912 listForApi = function (start: number, count: number, sort: string) {
917 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
920 model: Video['sequelize'].models.VideoChannel,
924 model: Video['sequelize'].models.Account,
928 model: Video['sequelize'].models.Server,
935 Video['sequelize'].models.Tag
937 where: createBaseVideosWhere()
940 return Video.findAndCountAll(query).then(({ rows, count }) => {
948 load = function (id: number) {
949 return Video.findById(id)
952 loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
953 const query: Sequelize.FindOptions<VideoAttributes> = {
957 include: [ Video['sequelize'].models.VideoFile ]
960 if (t !== undefined) query.transaction = t
962 return Video.findOne(query)
965 loadByUrlAndPopulateAccount = function (url: string, t?: Sequelize.Transaction) {
966 const query: Sequelize.FindOptions<VideoAttributes> = {
971 Video['sequelize'].models.VideoFile,
973 model: Video['sequelize'].models.VideoChannel,
974 include: [ Video['sequelize'].models.Account ]
979 if (t !== undefined) query.transaction = t
981 return Video.findOne(query)
984 loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) {
985 const query: Sequelize.FindOptions<VideoAttributes> = {
992 include: [ Video['sequelize'].models.VideoFile ]
995 if (t !== undefined) query.transaction = t
997 return Video.findOne(query)
1000 loadAndPopulateAccountAndServerAndTags = function (id: number) {
1002 order: [ [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
1005 model: Video['sequelize'].models.VideoChannel,
1008 model: Video['sequelize'].models.Account,
1009 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1014 model: Video['sequelize'].models.AccountVideoRate,
1015 include: [ Video['sequelize'].models.Account ]
1018 model: Video['sequelize'].models.VideoShare,
1019 include: [ Video['sequelize'].models.Account ]
1021 Video['sequelize'].models.Tag,
1022 Video['sequelize'].models.VideoFile
1026 return Video.findById(id, options)
1029 loadByUUIDAndPopulateAccountAndServerAndTags = function (uuid: string) {
1031 order: [ [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
1037 model: Video['sequelize'].models.VideoChannel,
1040 model: Video['sequelize'].models.Account,
1041 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1046 model: Video['sequelize'].models.AccountVideoRate,
1047 include: [ Video['sequelize'].models.Account ]
1050 model: Video['sequelize'].models.VideoShare,
1051 include: [ Video['sequelize'].models.Account ]
1053 Video['sequelize'].models.Tag,
1054 Video['sequelize'].models.VideoFile
1058 return Video.findOne(options)
1061 searchAndPopulateAccountAndServerAndTags = function (value: string, field: string, start: number, count: number, sort: string) {
1062 const serverInclude: Sequelize.IncludeOptions = {
1063 model: Video['sequelize'].models.Server,
1067 const accountInclude: Sequelize.IncludeOptions = {
1068 model: Video['sequelize'].models.Account,
1069 include: [ serverInclude ]
1072 const videoChannelInclude: Sequelize.IncludeOptions = {
1073 model: Video['sequelize'].models.VideoChannel,
1074 include: [ accountInclude ],
1078 const tagInclude: Sequelize.IncludeOptions = {
1079 model: Video['sequelize'].models.Tag
1082 const query: Sequelize.FindOptions<VideoAttributes> = {
1084 where: createBaseVideosWhere(),
1087 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
1090 if (field === 'tags') {
1091 const escapedValue = Video['sequelize'].escape('%' + value + '%')
1092 query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
1093 `(SELECT "VideoTags"."videoId"
1095 INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
1096 WHERE name ILIKE ${escapedValue}
1099 } else if (field === 'host') {
1100 // FIXME: Include our server? (not stored in the database)
1101 serverInclude.where = {
1103 [Sequelize.Op.iLike]: '%' + value + '%'
1106 serverInclude.required = true
1107 } else if (field === 'account') {
1108 accountInclude.where = {
1110 [Sequelize.Op.iLike]: '%' + value + '%'
1114 query.where[field] = {
1115 [Sequelize.Op.iLike]: '%' + value + '%'
1120 videoChannelInclude, tagInclude
1123 return Video.findAndCountAll(query).then(({ rows, count }) => {
1131 // ---------------------------------------------------------------------------
1133 function createBaseVideosWhere () {
1136 [Sequelize.Op.notIn]: Video['sequelize'].literal(
1137 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
1140 privacy: VideoPrivacy.PUBLIC
1144 function getBaseUrls (video: VideoInstance) {
1148 if (video.isOwned()) {
1149 baseUrlHttp = CONFIG.WEBSERVER.URL
1150 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1152 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host
1153 baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host
1156 return { baseUrlHttp, baseUrlWs }
1159 function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) {
1160 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName()
1163 function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1164 return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile)
1167 function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1168 return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile)
1171 function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) {
1172 const xs = getTorrentUrl(video, videoFile, baseUrlHttp)
1173 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1174 const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ]
1176 const magnetHash = {
1180 infoHash: videoFile.infoHash,
1184 return magnetUtil.encode(magnetHash)