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 { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
11 import { isVideoCategoryValid, isVideoLanguageValid, isVideoPrivacyValid } from '../../helpers/custom-validators/videos'
12 import { generateImageFromVideoFile, getVideoFileHeight, transcode } from '../../helpers/ffmpeg-utils'
14 isActivityPubUrlValid,
15 isVideoDescriptionValid,
20 } from '../../helpers/index'
21 import { logger } from '../../helpers/logger'
34 } from '../../initializers/constants'
35 import { getAnnounceActivityPubUrl } from '../../lib/activitypub/url'
36 import { sendDeleteVideo } from '../../lib/index'
37 import { addMethodsToModel, getSort } from '../utils'
38 import { TagInstance } from './tag-interface'
39 import { VideoFileInstance, VideoFileModel } from './video-file-interface'
40 import { VideoAttributes, VideoInstance, VideoMethods } from './video-interface'
42 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
43 let getOriginalFile: VideoMethods.GetOriginalFile
44 let getVideoFilename: VideoMethods.GetVideoFilename
45 let getThumbnailName: VideoMethods.GetThumbnailName
46 let getThumbnailPath: VideoMethods.GetThumbnailPath
47 let getPreviewName: VideoMethods.GetPreviewName
48 let getPreviewPath: VideoMethods.GetPreviewPath
49 let getTorrentFileName: VideoMethods.GetTorrentFileName
50 let isOwned: VideoMethods.IsOwned
51 let toFormattedJSON: VideoMethods.ToFormattedJSON
52 let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON
53 let toActivityPubObject: VideoMethods.ToActivityPubObject
54 let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile
55 let transcodeOriginalVideofile: VideoMethods.TranscodeOriginalVideofile
56 let createPreview: VideoMethods.CreatePreview
57 let createThumbnail: VideoMethods.CreateThumbnail
58 let getVideoFilePath: VideoMethods.GetVideoFilePath
59 let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash
60 let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight
61 let getEmbedPath: VideoMethods.GetEmbedPath
62 let getDescriptionPath: VideoMethods.GetDescriptionPath
63 let getTruncatedDescription: VideoMethods.GetTruncatedDescription
64 let getCategoryLabel: VideoMethods.GetCategoryLabel
65 let getLicenceLabel: VideoMethods.GetLicenceLabel
66 let getLanguageLabel: VideoMethods.GetLanguageLabel
68 let list: VideoMethods.List
69 let listForApi: VideoMethods.ListForApi
70 let listAllAndSharedByAccountForOutbox: VideoMethods.ListAllAndSharedByAccountForOutbox
71 let listUserVideosForApi: VideoMethods.ListUserVideosForApi
72 let load: VideoMethods.Load
73 let loadByUrlAndPopulateAccount: VideoMethods.LoadByUrlAndPopulateAccount
74 let loadByUUID: VideoMethods.LoadByUUID
75 let loadByUUIDOrURL: VideoMethods.LoadByUUIDOrURL
76 let loadAndPopulateAccountAndServerAndTags: VideoMethods.LoadAndPopulateAccountAndServerAndTags
77 let loadByUUIDAndPopulateAccountAndServerAndTags: VideoMethods.LoadByUUIDAndPopulateAccountAndServerAndTags
78 let searchAndPopulateAccountAndServerAndTags: VideoMethods.SearchAndPopulateAccountAndServerAndTags
79 let removeThumbnail: VideoMethods.RemoveThumbnail
80 let removePreview: VideoMethods.RemovePreview
81 let removeFile: VideoMethods.RemoveFile
82 let removeTorrent: VideoMethods.RemoveTorrent
84 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
85 Video = sequelize.define<VideoInstance, VideoAttributes>('Video',
89 defaultValue: DataTypes.UUIDV4,
96 type: DataTypes.STRING,
100 const res = isVideoNameValid(value)
101 if (res === false) throw new Error('Video name is not valid.')
106 type: DataTypes.INTEGER,
109 categoryValid: value => {
110 const res = isVideoCategoryValid(value)
111 if (res === false) throw new Error('Video category is not valid.')
116 type: DataTypes.INTEGER,
120 licenceValid: value => {
121 const res = isVideoLicenceValid(value)
122 if (res === false) throw new Error('Video licence is not valid.')
127 type: DataTypes.INTEGER,
130 languageValid: value => {
131 const res = isVideoLanguageValid(value)
132 if (res === false) throw new Error('Video language is not valid.')
137 type: DataTypes.INTEGER,
140 privacyValid: value => {
141 const res = isVideoPrivacyValid(value)
142 if (res === false) throw new Error('Video privacy is not valid.')
147 type: DataTypes.BOOLEAN,
150 nsfwValid: value => {
151 const res = isVideoNSFWValid(value)
152 if (res === false) throw new Error('Video nsfw attribute is not valid.')
157 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max),
160 descriptionValid: value => {
161 const res = isVideoDescriptionValid(value)
162 if (res === false) throw new Error('Video description is not valid.')
167 type: DataTypes.INTEGER,
170 durationValid: value => {
171 const res = isVideoDurationValid(value)
172 if (res === false) throw new Error('Video duration is not valid.')
177 type: DataTypes.INTEGER,
186 type: DataTypes.INTEGER,
195 type: DataTypes.INTEGER,
204 type: DataTypes.BOOLEAN,
209 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max),
213 const res = isActivityPubUrlValid(value)
214 if (res === false) throw new Error('Video URL is not valid.')
225 fields: [ 'createdAt' ]
228 fields: [ 'duration' ]
240 fields: [ 'channelId' ]
249 const classMethods = [
253 listAllAndSharedByAccountForOutbox,
255 listUserVideosForApi,
257 loadByUrlAndPopulateAccount,
258 loadAndPopulateAccountAndServerAndTags,
261 loadByUUIDAndPopulateAccountAndServerAndTags,
262 searchAndPopulateAccountAndServerAndTags
264 const instanceMethods = [
267 createTorrentAndSetInfoHash,
283 toFormattedDetailsJSON,
284 optimizeOriginalVideofile,
285 transcodeOriginalVideofile,
286 getOriginalFileHeight,
288 getTruncatedDescription,
294 addMethodsToModel(Video, classMethods, instanceMethods)
299 // ------------------------------ METHODS ------------------------------
301 function associate (models) {
302 Video.belongsTo(models.VideoChannel, {
310 Video.belongsToMany(models.Tag, {
311 foreignKey: 'videoId',
312 through: models.VideoTag,
316 Video.hasMany(models.VideoAbuse, {
324 Video.hasMany(models.VideoFile, {
332 Video.hasMany(models.VideoShare, {
340 Video.hasMany(models.AccountVideoRate, {
349 function afterDestroy (video: VideoInstance) {
353 video.removeThumbnail()
356 if (video.isOwned()) {
358 video.removePreview(),
359 sendDeleteVideo(video, undefined)
362 // Remove physical files and torrents
363 video.VideoFiles.forEach(file => {
364 tasks.push(video.removeFile(file))
365 tasks.push(video.removeTorrent(file))
369 return Promise.all(tasks)
371 logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err)
375 getOriginalFile = function (this: VideoInstance) {
376 if (Array.isArray(this.VideoFiles) === false) return undefined
378 // The original file is the file that have the higher resolution
379 return maxBy(this.VideoFiles, file => file.resolution)
382 getVideoFilename = function (this: VideoInstance, videoFile: VideoFileInstance) {
383 return this.uuid + '-' + videoFile.resolution + videoFile.extname
386 getThumbnailName = function (this: VideoInstance) {
387 // We always have a copy of the thumbnail
388 const extension = '.jpg'
389 return this.uuid + extension
392 getPreviewName = function (this: VideoInstance) {
393 const extension = '.jpg'
394 return this.uuid + extension
397 getTorrentFileName = function (this: VideoInstance, videoFile: VideoFileInstance) {
398 const extension = '.torrent'
399 return this.uuid + '-' + videoFile.resolution + extension
402 isOwned = function (this: VideoInstance) {
403 return this.remote === false
406 createPreview = function (this: VideoInstance, videoFile: VideoFileInstance) {
407 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
409 return generateImageFromVideoFile(
410 this.getVideoFilePath(videoFile),
411 CONFIG.STORAGE.PREVIEWS_DIR,
412 this.getPreviewName(),
417 createThumbnail = function (this: VideoInstance, videoFile: VideoFileInstance) {
418 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
420 return generateImageFromVideoFile(
421 this.getVideoFilePath(videoFile),
422 CONFIG.STORAGE.THUMBNAILS_DIR,
423 this.getThumbnailName(),
428 getVideoFilePath = function (this: VideoInstance, videoFile: VideoFileInstance) {
429 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
432 createTorrentAndSetInfoHash = async function (this: VideoInstance, videoFile: VideoFileInstance) {
435 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
438 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
442 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
444 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
445 logger.info('Creating torrent %s.', filePath)
447 await writeFilePromise(filePath, torrent)
449 const parsedTorrent = parseTorrent(torrent)
450 videoFile.infoHash = parsedTorrent.infoHash
453 getEmbedPath = function (this: VideoInstance) {
454 return '/videos/embed/' + this.uuid
457 getThumbnailPath = function (this: VideoInstance) {
458 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
461 getPreviewPath = function (this: VideoInstance) {
462 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
465 toFormattedJSON = function (this: VideoInstance) {
468 if (this.VideoChannel.Account.Server) {
469 serverHost = this.VideoChannel.Account.Server.host
471 // It means it's our video
472 serverHost = CONFIG.WEBSERVER.HOST
479 category: this.category,
480 categoryLabel: this.getCategoryLabel(),
481 licence: this.licence,
482 licenceLabel: this.getLicenceLabel(),
483 language: this.language,
484 languageLabel: this.getLanguageLabel(),
486 description: this.getTruncatedDescription(),
488 isLocal: this.isOwned(),
489 account: this.VideoChannel.Account.name,
490 duration: this.duration,
493 dislikes: this.dislikes,
494 tags: map<TagInstance, string>(this.Tags, 'name'),
495 thumbnailPath: this.getThumbnailPath(),
496 previewPath: this.getPreviewPath(),
497 embedPath: this.getEmbedPath(),
498 createdAt: this.createdAt,
499 updatedAt: this.updatedAt
505 toFormattedDetailsJSON = function (this: VideoInstance) {
506 const formattedJson = this.toFormattedJSON()
508 // Maybe our server is not up to date and there are new privacy settings since our version
509 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
510 if (!privacyLabel) privacyLabel = 'Unknown'
512 const detailsJson = {
514 privacy: this.privacy,
515 descriptionPath: this.getDescriptionPath(),
516 channel: this.VideoChannel.toFormattedJSON(),
520 // Format and sort video files
521 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
522 detailsJson.files = this.VideoFiles
524 let resolutionLabel = videoFile.resolution + 'p'
526 const videoFileJson = {
527 resolution: videoFile.resolution,
529 magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs),
530 size: videoFile.size,
531 torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp),
532 fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp)
538 if (a.resolution < b.resolution) return 1
539 if (a.resolution === b.resolution) return 0
543 return Object.assign(formattedJson, detailsJson)
546 toActivityPubObject = function (this: VideoInstance) {
547 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
548 if (!this.Tags) this.Tags = []
550 const tag = this.Tags.map(t => ({
551 type: 'Hashtag' as 'Hashtag',
558 identifier: this.language + '',
559 name: this.getLanguageLabel()
566 if (Array.isArray(this.AccountVideoRates)) {
567 const likes: string[] = []
568 const dislikes: string[] = []
570 for (const rate of this.AccountVideoRates) {
571 if (rate.type === 'like') {
572 likes.push(rate.Account.url)
573 } else if (rate.type === 'dislike') {
574 dislikes.push(rate.Account.url)
578 likesObject = activityPubCollection(likes)
579 dislikesObject = activityPubCollection(dislikes)
583 if (Array.isArray(this.VideoShares)) {
584 const shares: string[] = []
586 for (const videoShare of this.VideoShares) {
587 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Account)
588 shares.push(shareUrl)
591 sharesObject = activityPubCollection(shares)
595 for (const file of this.VideoFiles) {
598 mimeType: 'video/' + file.extname.replace('.', ''),
599 url: getVideoFileUrl(this, file, baseUrlHttp),
600 width: file.resolution,
606 mimeType: 'application/x-bittorrent',
607 url: getTorrentUrl(this, file, baseUrlHttp),
608 width: file.resolution
613 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
614 url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs),
615 width: file.resolution
622 mimeType: 'text/html',
623 url: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
626 const videoObject: VideoTorrentObject = {
627 type: 'Video' as 'Video',
630 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
631 duration: 'PT' + this.duration + 'S',
635 identifier: this.category + '',
636 name: this.getCategoryLabel()
639 identifier: this.licence + '',
640 name: this.getLicenceLabel()
645 published: this.createdAt.toISOString(),
646 updated: this.updatedAt.toISOString(),
647 mediaType: 'text/markdown',
648 content: this.getTruncatedDescription(),
651 url: getThumbnailUrl(this, baseUrlHttp),
652 mediaType: 'image/jpeg',
653 width: THUMBNAILS_SIZE.width,
654 height: THUMBNAILS_SIZE.height
658 dislikes: dislikesObject,
665 getTruncatedDescription = function (this: VideoInstance) {
667 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
670 return truncate(this.description, options)
673 optimizeOriginalVideofile = async function (this: VideoInstance) {
674 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
675 const newExtname = '.mp4'
676 const inputVideoFile = this.getOriginalFile()
677 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
678 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
680 const transcodeOptions = {
681 inputPath: videoInputPath,
682 outputPath: videoOutputPath
686 // Could be very long!
687 await transcode(transcodeOptions)
689 await unlinkPromise(videoInputPath)
691 // Important to do this before getVideoFilename() to take in account the new file extension
692 inputVideoFile.set('extname', newExtname)
694 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
695 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
697 inputVideoFile.set('size', stats.size)
699 await this.createTorrentAndSetInfoHash(inputVideoFile)
700 await inputVideoFile.save()
703 // Auto destruction...
704 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
710 transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) {
711 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
712 const extname = '.mp4'
714 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
715 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
717 const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({
723 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
725 const transcodeOptions = {
726 inputPath: videoInputPath,
727 outputPath: videoOutputPath,
731 await transcode(transcodeOptions)
733 const stats = await statPromise(videoOutputPath)
735 newVideoFile.set('size', stats.size)
737 await this.createTorrentAndSetInfoHash(newVideoFile)
739 await newVideoFile.save()
741 this.VideoFiles.push(newVideoFile)
744 getOriginalFileHeight = function (this: VideoInstance) {
745 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
747 return getVideoFileHeight(originalFilePath)
750 getDescriptionPath = function (this: VideoInstance) {
751 return `/api/${API_VERSION}/videos/${this.uuid}/description`
754 getCategoryLabel = function (this: VideoInstance) {
755 let categoryLabel = VIDEO_CATEGORIES[this.category]
757 // Maybe our server is not up to date and there are new categories since our version
758 if (!categoryLabel) categoryLabel = 'Misc'
763 getLicenceLabel = function (this: VideoInstance) {
764 let licenceLabel = VIDEO_LICENCES[this.licence]
766 // Maybe our server is not up to date and there are new licences since our version
767 if (!licenceLabel) licenceLabel = 'Unknown'
772 getLanguageLabel = function (this: VideoInstance) {
773 // Language is an optional attribute
774 let languageLabel = VIDEO_LANGUAGES[this.language]
775 if (!languageLabel) languageLabel = 'Unknown'
780 removeThumbnail = function (this: VideoInstance) {
781 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
782 return unlinkPromise(thumbnailPath)
785 removePreview = function (this: VideoInstance) {
786 // Same name than video thumbnail
787 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
790 removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) {
791 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
792 return unlinkPromise(filePath)
795 removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) {
796 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
797 return unlinkPromise(torrentPath)
800 // ------------------------------ STATICS ------------------------------
804 include: [ Video['sequelize'].models.VideoFile ]
807 return Video.findAll(query)
810 listAllAndSharedByAccountForOutbox = function (accountId: number, start: number, count: number) {
811 function getRawQuery (select: string) {
812 const queryVideo = 'SELECT ' + select + ' FROM "Videos" AS "Video" ' +
813 'INNER JOIN "VideoChannels" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
814 'WHERE "VideoChannel"."accountId" = ' + accountId
815 const queryVideoShare = 'SELECT ' + select + ' FROM "VideoShares" AS "VideoShare" ' +
816 'INNER JOIN "Videos" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
817 'WHERE "VideoShare"."accountId" = ' + accountId
819 let rawQuery = `(${queryVideo}) UNION (${queryVideoShare})`
824 const rawQuery = getRawQuery('"Video"."id"')
825 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
831 order: [ getSort('createdAt'), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
834 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
839 model: Video['sequelize'].models.VideoShare,
842 [Sequelize.Op.and]: [
845 [Sequelize.Op.not]: null
853 include: [ Video['sequelize'].models.Account ]
856 model: Video['sequelize'].models.VideoChannel,
860 model: Video['sequelize'].models.Account,
866 model: Video['sequelize'].models.AccountVideoRate,
867 include: [ Video['sequelize'].models.Account ]
869 Video['sequelize'].models.VideoFile,
870 Video['sequelize'].models.Tag
874 return Bluebird.all([
875 Video.findAll(query),
876 Video['sequelize'].query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
877 ]).then(([ rows, totals ]) => {
878 // totals: totalVideos + totalVideoShares
880 let totalVideoShares = 0
881 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
882 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
884 const total = totalVideos + totalVideoShares
892 listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) {
897 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
900 model: Video['sequelize'].models.VideoChannel,
904 model: Video['sequelize'].models.Account,
912 Video['sequelize'].models.Tag
916 return Video.findAndCountAll(query).then(({ rows, count }) => {
924 listForApi = function (start: number, count: number, sort: string) {
929 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
932 model: Video['sequelize'].models.VideoChannel,
936 model: Video['sequelize'].models.Account,
940 model: Video['sequelize'].models.Server,
947 Video['sequelize'].models.Tag
949 where: createBaseVideosWhere()
952 return Video.findAndCountAll(query).then(({ rows, count }) => {
960 load = function (id: number) {
961 return Video.findById(id)
964 loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
965 const query: Sequelize.FindOptions<VideoAttributes> = {
969 include: [ Video['sequelize'].models.VideoFile ]
972 if (t !== undefined) query.transaction = t
974 return Video.findOne(query)
977 loadByUrlAndPopulateAccount = function (url: string, t?: Sequelize.Transaction) {
978 const query: Sequelize.FindOptions<VideoAttributes> = {
983 Video['sequelize'].models.VideoFile,
985 model: Video['sequelize'].models.VideoChannel,
986 include: [ Video['sequelize'].models.Account ]
991 if (t !== undefined) query.transaction = t
993 return Video.findOne(query)
996 loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) {
997 const query: Sequelize.FindOptions<VideoAttributes> = {
1004 include: [ Video['sequelize'].models.VideoFile ]
1007 if (t !== undefined) query.transaction = t
1009 return Video.findOne(query)
1012 loadAndPopulateAccountAndServerAndTags = function (id: number) {
1014 order: [ [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
1017 model: Video['sequelize'].models.VideoChannel,
1020 model: Video['sequelize'].models.Account,
1021 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1026 model: Video['sequelize'].models.AccountVideoRate,
1027 include: [ Video['sequelize'].models.Account ]
1030 model: Video['sequelize'].models.VideoShare,
1031 include: [ Video['sequelize'].models.Account ]
1033 Video['sequelize'].models.Tag,
1034 Video['sequelize'].models.VideoFile
1038 return Video.findById(id, options)
1041 loadByUUIDAndPopulateAccountAndServerAndTags = function (uuid: string) {
1043 order: [ [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
1049 model: Video['sequelize'].models.VideoChannel,
1052 model: Video['sequelize'].models.Account,
1053 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1058 model: Video['sequelize'].models.AccountVideoRate,
1059 include: [ Video['sequelize'].models.Account ]
1062 model: Video['sequelize'].models.VideoShare,
1063 include: [ Video['sequelize'].models.Account ]
1065 Video['sequelize'].models.Tag,
1066 Video['sequelize'].models.VideoFile
1070 return Video.findOne(options)
1073 searchAndPopulateAccountAndServerAndTags = function (value: string, field: string, start: number, count: number, sort: string) {
1074 const serverInclude: Sequelize.IncludeOptions = {
1075 model: Video['sequelize'].models.Server,
1079 const accountInclude: Sequelize.IncludeOptions = {
1080 model: Video['sequelize'].models.Account,
1081 include: [ serverInclude ]
1084 const videoChannelInclude: Sequelize.IncludeOptions = {
1085 model: Video['sequelize'].models.VideoChannel,
1086 include: [ accountInclude ],
1090 const tagInclude: Sequelize.IncludeOptions = {
1091 model: Video['sequelize'].models.Tag
1094 const query: Sequelize.FindOptions<VideoAttributes> = {
1096 where: createBaseVideosWhere(),
1099 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
1102 if (field === 'tags') {
1103 const escapedValue = Video['sequelize'].escape('%' + value + '%')
1104 query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
1105 `(SELECT "VideoTags"."videoId"
1107 INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
1108 WHERE name ILIKE ${escapedValue}
1111 } else if (field === 'host') {
1112 // FIXME: Include our server? (not stored in the database)
1113 serverInclude.where = {
1115 [Sequelize.Op.iLike]: '%' + value + '%'
1118 serverInclude.required = true
1119 } else if (field === 'account') {
1120 accountInclude.where = {
1122 [Sequelize.Op.iLike]: '%' + value + '%'
1126 query.where[field] = {
1127 [Sequelize.Op.iLike]: '%' + value + '%'
1132 videoChannelInclude, tagInclude
1135 return Video.findAndCountAll(query).then(({ rows, count }) => {
1143 // ---------------------------------------------------------------------------
1145 function createBaseVideosWhere () {
1148 [Sequelize.Op.notIn]: Video['sequelize'].literal(
1149 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
1152 privacy: VideoPrivacy.PUBLIC
1156 function getBaseUrls (video: VideoInstance) {
1160 if (video.isOwned()) {
1161 baseUrlHttp = CONFIG.WEBSERVER.URL
1162 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1164 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host
1165 baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host
1168 return { baseUrlHttp, baseUrlWs }
1171 function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) {
1172 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName()
1175 function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1176 return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile)
1179 function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1180 return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile)
1183 function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) {
1184 const xs = getTorrentUrl(video, videoFile, baseUrlHttp)
1185 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1186 const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ]
1188 const magnetHash = {
1192 infoHash: videoFile.infoHash,
1196 return magnetUtil.encode(magnetHash)