1 import * as Bluebird from 'bluebird'
2 import { map, maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { extname, join } from 'path'
6 import * as Sequelize from 'sequelize'
28 } from 'sequelize-typescript'
29 import { VideoPrivacy, VideoResolution, VideoState } from '../../../shared'
30 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
31 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
32 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
33 import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils'
34 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
35 import { isBooleanValid } from '../../helpers/custom-validators/misc'
38 isVideoDescriptionValid,
46 } from '../../helpers/custom-validators/videos'
47 import { generateImageFromVideoFile, getVideoFileFPS, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
48 import { logger } from '../../helpers/logger'
49 import { getServerActor } from '../../helpers/utils'
57 STATIC_DOWNLOAD_PATHS,
66 } from '../../initializers'
68 getVideoCommentsActivityPubUrl,
69 getVideoDislikesActivityPubUrl,
70 getVideoLikesActivityPubUrl,
71 getVideoSharesActivityPubUrl
72 } from '../../lib/activitypub'
73 import { sendDeleteVideo } from '../../lib/activitypub/send'
74 import { AccountModel } from '../account/account'
75 import { AccountVideoRateModel } from '../account/account-video-rate'
76 import { ActorModel } from '../activitypub/actor'
77 import { AvatarModel } from '../avatar/avatar'
78 import { ServerModel } from '../server/server'
79 import { buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
80 import { TagModel } from './tag'
81 import { VideoAbuseModel } from './video-abuse'
82 import { VideoChannelModel } from './video-channel'
83 import { VideoCommentModel } from './video-comment'
84 import { VideoFileModel } from './video-file'
85 import { VideoShareModel } from './video-share'
86 import { VideoTagModel } from './video-tag'
87 import { ScheduleVideoUpdateModel } from './schedule-video-update'
88 import { VideoCaptionModel } from './video-caption'
89 import { VideoBlacklistModel } from './video-blacklist'
90 import { copy, remove, rename, stat, writeFile } from 'fs-extra'
92 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
93 const indexes: Sequelize.DefineIndexesOptions[] = [
94 buildTrigramSearchIndex('video_name_trigram', 'name'),
96 { fields: [ 'createdAt' ] },
97 { fields: [ 'publishedAt' ] },
98 { fields: [ 'duration' ] },
99 { fields: [ 'category' ] },
100 { fields: [ 'licence' ] },
101 { fields: [ 'nsfw' ] },
102 { fields: [ 'language' ] },
103 { fields: [ 'waitTranscoding' ] },
104 { fields: [ 'state' ] },
105 { fields: [ 'remote' ] },
106 { fields: [ 'views' ] },
107 { fields: [ 'likes' ] },
108 { fields: [ 'channelId' ] },
119 export enum ScopeNames {
120 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
121 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
122 WITH_TAGS = 'WITH_TAGS',
123 WITH_FILES = 'WITH_FILES',
124 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
125 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
128 type AvailableForListOptions = {
130 includeLocalVideos: boolean,
131 filter?: VideoFilter,
132 categoryOneOf?: number[],
134 licenceOneOf?: number[],
135 languageOneOf?: string[],
136 tagsOneOf?: string[],
137 tagsAllOf?: string[],
140 videoChannelId?: number
144 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
145 const accountInclude = {
146 attributes: [ 'id', 'name' ],
147 model: AccountModel.unscoped(),
152 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
153 model: ActorModel.unscoped(),
155 where: VideoModel.buildActorWhereWithFilter(options.filter),
158 attributes: [ 'host' ],
159 model: ServerModel.unscoped(),
163 model: AvatarModel.unscoped(),
171 const videoChannelInclude = {
172 attributes: [ 'name', 'description', 'id' ],
173 model: VideoChannelModel.unscoped(),
178 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
179 model: ActorModel.unscoped(),
183 attributes: [ 'host' ],
184 model: ServerModel.unscoped(),
188 model: AvatarModel.unscoped(),
197 // FIXME: It would be more efficient to use a CTE so we join AFTER the filters, but sequelize does not support it...
198 const query: IFindOptions<VideoModel> = {
201 [Sequelize.Op.notIn]: Sequelize.literal(
202 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
205 // Always list public videos
206 privacy: VideoPrivacy.PUBLIC,
207 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
208 [ Sequelize.Op.or ]: [
210 state: VideoState.PUBLISHED
213 [ Sequelize.Op.and ]: {
214 state: VideoState.TO_TRANSCODE,
215 waitTranscoding: false
220 include: [ videoChannelInclude ]
223 if (options.actorId) {
224 let localVideosReq = ''
225 if (options.includeLocalVideos === true) {
226 localVideosReq = ' UNION ALL ' +
227 'SELECT "video"."id" AS "id" FROM "video" ' +
228 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
229 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
230 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
231 'WHERE "actor"."serverId" IS NULL'
234 // Force actorId to be a number to avoid SQL injections
235 const actorIdNumber = parseInt(options.actorId.toString(), 10)
236 query.where['id'][ Sequelize.Op.in ] = Sequelize.literal(
238 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
239 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
240 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
242 'SELECT "video"."id" AS "id" FROM "video" ' +
243 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
244 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
245 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
246 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
247 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
253 if (options.withFiles === true) {
255 model: VideoFileModel.unscoped(),
260 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
261 if (options.tagsAllOf || options.tagsOneOf) {
262 const createTagsIn = (tags: string[]) => {
263 return tags.map(t => VideoModel.sequelize.escape(t))
267 if (options.tagsOneOf) {
268 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
270 'SELECT "videoId" FROM "videoTag" ' +
271 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
272 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
277 if (options.tagsAllOf) {
278 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
280 'SELECT "videoId" FROM "videoTag" ' +
281 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
282 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
283 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
289 if (options.nsfw === true || options.nsfw === false) {
290 query.where['nsfw'] = options.nsfw
293 if (options.categoryOneOf) {
294 query.where['category'] = {
295 [Sequelize.Op.or]: options.categoryOneOf
299 if (options.licenceOneOf) {
300 query.where['licence'] = {
301 [Sequelize.Op.or]: options.licenceOneOf
305 if (options.languageOneOf) {
306 query.where['language'] = {
307 [Sequelize.Op.or]: options.languageOneOf
311 if (options.accountId) {
312 accountInclude.where = {
313 id: options.accountId
317 if (options.videoChannelId) {
318 videoChannelInclude.where = {
319 id: options.videoChannelId
325 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
328 model: () => VideoChannelModel.unscoped(),
333 exclude: [ 'privateKey', 'publicKey' ]
335 model: () => ActorModel.unscoped(),
339 attributes: [ 'host' ],
340 model: () => ServerModel.unscoped(),
344 model: () => AvatarModel.unscoped(),
350 model: () => AccountModel.unscoped(),
354 model: () => ActorModel.unscoped(),
356 exclude: [ 'privateKey', 'publicKey' ]
361 attributes: [ 'host' ],
362 model: () => ServerModel.unscoped(),
366 model: () => AvatarModel.unscoped(),
377 [ScopeNames.WITH_TAGS]: {
378 include: [ () => TagModel ]
380 [ScopeNames.WITH_BLACKLISTED]: {
383 attributes: [ 'id', 'reason' ],
384 model: () => VideoBlacklistModel,
389 [ScopeNames.WITH_FILES]: {
392 model: () => VideoFileModel.unscoped(),
397 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
400 model: () => ScheduleVideoUpdateModel.unscoped(),
410 export class VideoModel extends Model<VideoModel> {
413 @Default(DataType.UUIDV4)
415 @Column(DataType.UUID)
419 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
425 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
431 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
437 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
438 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
442 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
447 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
453 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
454 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
459 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
460 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
464 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
494 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
495 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
500 commentsEnabled: boolean
504 waitTranscoding: boolean
508 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
519 @Default(Sequelize.NOW)
523 @ForeignKey(() => VideoChannelModel)
527 @BelongsTo(() => VideoChannelModel, {
533 VideoChannel: VideoChannelModel
535 @BelongsToMany(() => TagModel, {
536 foreignKey: 'videoId',
537 through: () => VideoTagModel,
542 @HasMany(() => VideoAbuseModel, {
549 VideoAbuses: VideoAbuseModel[]
551 @HasMany(() => VideoFileModel, {
558 VideoFiles: VideoFileModel[]
560 @HasMany(() => VideoShareModel, {
567 VideoShares: VideoShareModel[]
569 @HasMany(() => AccountVideoRateModel, {
576 AccountVideoRates: AccountVideoRateModel[]
578 @HasMany(() => VideoCommentModel, {
586 VideoComments: VideoCommentModel[]
588 @HasOne(() => ScheduleVideoUpdateModel, {
595 ScheduleVideoUpdate: ScheduleVideoUpdateModel
597 @HasOne(() => VideoBlacklistModel, {
604 VideoBlacklist: VideoBlacklistModel
606 @HasMany(() => VideoCaptionModel, {
613 ['separate' as any]: true
615 VideoCaptions: VideoCaptionModel[]
618 static async sendDelete (instance: VideoModel, options) {
619 if (instance.isOwned()) {
620 if (!instance.VideoChannel) {
621 instance.VideoChannel = await instance.$get('VideoChannel', {
625 include: [ ActorModel ]
628 transaction: options.transaction
629 }) as VideoChannelModel
632 return sendDeleteVideo(instance, options.transaction)
639 static async removeFiles (instance: VideoModel) {
640 const tasks: Promise<any>[] = []
642 logger.info('Removing files of video %s.', instance.url)
644 tasks.push(instance.removeThumbnail())
646 if (instance.isOwned()) {
647 if (!Array.isArray(instance.VideoFiles)) {
648 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
651 tasks.push(instance.removePreview())
653 // Remove physical files and torrents
654 instance.VideoFiles.forEach(file => {
655 tasks.push(instance.removeFile(file))
656 tasks.push(instance.removeTorrent(file))
660 // Do not wait video deletion because we could be in a transaction
663 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
670 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
673 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
674 function getRawQuery (select: string) {
675 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
676 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
677 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
678 'WHERE "Account"."actorId" = ' + actorId
679 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
680 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
681 'WHERE "VideoShare"."actorId" = ' + actorId
683 return `(${queryVideo}) UNION (${queryVideoShare})`
686 const rawQuery = getRawQuery('"Video"."id"')
687 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
693 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
696 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
699 { privacy: VideoPrivacy.PUBLIC },
700 { privacy: VideoPrivacy.UNLISTED }
705 attributes: [ 'language' ],
706 model: VideoCaptionModel.unscoped(),
710 attributes: [ 'id', 'url' ],
711 model: VideoShareModel.unscoped(),
713 // We only want videos shared by this actor
715 [Sequelize.Op.and]: [
718 [Sequelize.Op.not]: null
728 attributes: [ 'id', 'url' ],
729 model: ActorModel.unscoped()
734 model: VideoChannelModel.unscoped(),
738 attributes: [ 'name' ],
739 model: AccountModel.unscoped(),
743 attributes: [ 'id', 'url', 'followersUrl' ],
744 model: ActorModel.unscoped(),
750 attributes: [ 'id', 'url', 'followersUrl' ],
751 model: ActorModel.unscoped(),
761 return Bluebird.all([
762 // FIXME: typing issue
763 VideoModel.findAll(query as any),
764 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
765 ]).then(([ rows, totals ]) => {
766 // totals: totalVideos + totalVideoShares
768 let totalVideoShares = 0
769 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
770 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
772 const total = totalVideos + totalVideoShares
780 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
781 const query: IFindOptions<VideoModel> = {
784 order: getSort(sort),
787 model: VideoChannelModel,
800 model: ScheduleVideoUpdateModel,
804 model: VideoBlacklistModel,
810 if (withFiles === true) {
812 model: VideoFileModel.unscoped(),
817 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
825 static async listForApi (options: {
830 includeLocalVideos: boolean,
832 categoryOneOf?: number[],
833 licenceOneOf?: number[],
834 languageOneOf?: string[],
835 tagsOneOf?: string[],
836 tagsAllOf?: string[],
837 filter?: VideoFilter,
839 videoChannelId?: number,
843 offset: options.start,
844 limit: options.count,
845 order: getSort(options.sort)
848 // actorId === null has a meaning, so just check undefined
849 const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id
853 ScopeNames.AVAILABLE_FOR_LIST, {
856 categoryOneOf: options.categoryOneOf,
857 licenceOneOf: options.licenceOneOf,
858 languageOneOf: options.languageOneOf,
859 tagsOneOf: options.tagsOneOf,
860 tagsAllOf: options.tagsAllOf,
861 filter: options.filter,
862 withFiles: options.withFiles,
863 accountId: options.accountId,
864 videoChannelId: options.videoChannelId,
865 includeLocalVideos: options.includeLocalVideos
866 } as AvailableForListOptions
870 return VideoModel.scope(scopes)
871 .findAndCountAll(query)
872 .then(({ rows, count }) => {
880 static async searchAndPopulateAccountAndServer (options: {
881 includeLocalVideos: boolean
886 startDate?: string // ISO 8601
887 endDate?: string // ISO 8601
889 categoryOneOf?: number[]
890 licenceOneOf?: number[]
891 languageOneOf?: string[]
894 durationMin?: number // seconds
895 durationMax?: number // seconds
899 if (options.startDate || options.endDate) {
900 const publishedAtRange = { }
902 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
903 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
905 whereAnd.push({ publishedAt: publishedAtRange })
908 if (options.durationMin || options.durationMax) {
909 const durationRange = { }
911 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
912 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
914 whereAnd.push({ duration: durationRange })
917 const attributesInclude = []
918 const escapedSearch = VideoModel.sequelize.escape(options.search)
919 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
920 if (options.search) {
924 [ Sequelize.Op.in ]: Sequelize.literal(
926 'SELECT "video"."id" FROM "video" ' +
928 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
929 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
931 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
932 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
933 'WHERE "tag"."name" = ' + escapedSearch +
940 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
943 // Cannot search on similarity if we don't have a search
944 if (!options.search) {
945 attributesInclude.push(
946 Sequelize.literal('0 as similarity')
950 const query: IFindOptions<VideoModel> = {
952 include: attributesInclude
954 offset: options.start,
955 limit: options.count,
956 order: getSort(options.sort),
958 [ Sequelize.Op.and ]: whereAnd
962 const serverActor = await getServerActor()
965 ScopeNames.AVAILABLE_FOR_LIST, {
966 actorId: serverActor.id,
967 includeLocalVideos: options.includeLocalVideos,
969 categoryOneOf: options.categoryOneOf,
970 licenceOneOf: options.licenceOneOf,
971 languageOneOf: options.languageOneOf,
972 tagsOneOf: options.tagsOneOf,
973 tagsAllOf: options.tagsAllOf
974 } as AvailableForListOptions
978 return VideoModel.scope(scopes)
979 .findAndCountAll(query)
980 .then(({ rows, count }) => {
988 static load (id: number, t?: Sequelize.Transaction) {
989 const options = t ? { transaction: t } : undefined
991 return VideoModel.findById(id, options)
994 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
995 const query: IFindOptions<VideoModel> = {
1001 if (t !== undefined) query.transaction = t
1003 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1006 static loadAndPopulateAccountAndServerAndTags (id: number) {
1008 order: [ [ 'Tags', 'name', 'ASC' ] ]
1013 ScopeNames.WITH_TAGS,
1014 ScopeNames.WITH_BLACKLISTED,
1015 ScopeNames.WITH_FILES,
1016 ScopeNames.WITH_ACCOUNT_DETAILS,
1017 ScopeNames.WITH_SCHEDULED_UPDATE
1019 .findById(id, options)
1022 static loadByUUID (uuid: string) {
1030 .scope([ ScopeNames.WITH_FILES ])
1034 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1036 order: [ [ 'Tags', 'name', 'ASC' ] ],
1045 ScopeNames.WITH_TAGS,
1046 ScopeNames.WITH_BLACKLISTED,
1047 ScopeNames.WITH_FILES,
1048 ScopeNames.WITH_ACCOUNT_DETAILS,
1049 ScopeNames.WITH_SCHEDULED_UPDATE
1054 static async getStats () {
1055 const totalLocalVideos = await VideoModel.count({
1060 const totalVideos = await VideoModel.count()
1062 let totalLocalVideoViews = await VideoModel.sum('views', {
1067 // Sequelize could return null...
1068 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1072 totalLocalVideoViews,
1077 static incrementViews (id: number, views: number) {
1078 return VideoModel.increment('views', {
1086 // threshold corresponds to how many video the field should have to be returned
1087 static getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1088 const query: IFindOptions<VideoModel> = {
1089 attributes: [ field ],
1092 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1093 [Sequelize.Op.gte]: threshold
1094 }) as any, // FIXME: typings
1097 [Sequelize.Op.not]: null,
1099 privacy: VideoPrivacy.PUBLIC,
1100 state: VideoState.PUBLISHED
1102 order: [ this.sequelize.random() ]
1105 return VideoModel.findAll(query)
1106 .then(rows => rows.map(r => r[field]))
1109 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1110 if (filter && filter === 'local') {
1119 private static getCategoryLabel (id: number) {
1120 return VIDEO_CATEGORIES[id] || 'Misc'
1123 private static getLicenceLabel (id: number) {
1124 return VIDEO_LICENCES[id] || 'Unknown'
1127 private static getLanguageLabel (id: string) {
1128 return VIDEO_LANGUAGES[id] || 'Unknown'
1131 private static getPrivacyLabel (id: number) {
1132 return VIDEO_PRIVACIES[id] || 'Unknown'
1135 private static getStateLabel (id: number) {
1136 return VIDEO_STATES[id] || 'Unknown'
1139 getOriginalFile () {
1140 if (Array.isArray(this.VideoFiles) === false) return undefined
1142 // The original file is the file that have the higher resolution
1143 return maxBy(this.VideoFiles, file => file.resolution)
1146 getVideoFilename (videoFile: VideoFileModel) {
1147 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1150 getThumbnailName () {
1151 // We always have a copy of the thumbnail
1152 const extension = '.jpg'
1153 return this.uuid + extension
1157 const extension = '.jpg'
1158 return this.uuid + extension
1161 getTorrentFileName (videoFile: VideoFileModel) {
1162 const extension = '.torrent'
1163 return this.uuid + '-' + videoFile.resolution + extension
1167 return this.remote === false
1170 createPreview (videoFile: VideoFileModel) {
1171 return generateImageFromVideoFile(
1172 this.getVideoFilePath(videoFile),
1173 CONFIG.STORAGE.PREVIEWS_DIR,
1174 this.getPreviewName(),
1179 createThumbnail (videoFile: VideoFileModel) {
1180 return generateImageFromVideoFile(
1181 this.getVideoFilePath(videoFile),
1182 CONFIG.STORAGE.THUMBNAILS_DIR,
1183 this.getThumbnailName(),
1188 getTorrentFilePath (videoFile: VideoFileModel) {
1189 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1192 getVideoFilePath (videoFile: VideoFileModel) {
1193 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1196 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1198 // Keep the extname, it's used by the client to stream the file inside a web browser
1199 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1200 createdBy: 'PeerTube',
1202 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1203 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1206 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1210 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1212 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1213 logger.info('Creating torrent %s.', filePath)
1215 await writeFile(filePath, torrent)
1217 const parsedTorrent = parseTorrent(torrent)
1218 videoFile.infoHash = parsedTorrent.infoHash
1221 getEmbedStaticPath () {
1222 return '/videos/embed/' + this.uuid
1225 getThumbnailStaticPath () {
1226 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1229 getPreviewStaticPath () {
1230 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1233 toFormattedJSON (options?: {
1234 additionalAttributes: {
1236 waitTranscoding?: boolean,
1237 scheduledUpdate?: boolean,
1238 blacklistInfo?: boolean
1241 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1242 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1244 const videoObject: Video = {
1250 label: VideoModel.getCategoryLabel(this.category)
1254 label: VideoModel.getLicenceLabel(this.licence)
1258 label: VideoModel.getLanguageLabel(this.language)
1262 label: VideoModel.getPrivacyLabel(this.privacy)
1265 description: this.getTruncatedDescription(),
1266 isLocal: this.isOwned(),
1267 duration: this.duration,
1270 dislikes: this.dislikes,
1271 thumbnailPath: this.getThumbnailStaticPath(),
1272 previewPath: this.getPreviewStaticPath(),
1273 embedPath: this.getEmbedStaticPath(),
1274 createdAt: this.createdAt,
1275 updatedAt: this.updatedAt,
1276 publishedAt: this.publishedAt,
1278 id: formattedAccount.id,
1279 uuid: formattedAccount.uuid,
1280 name: formattedAccount.name,
1281 displayName: formattedAccount.displayName,
1282 url: formattedAccount.url,
1283 host: formattedAccount.host,
1284 avatar: formattedAccount.avatar
1287 id: formattedVideoChannel.id,
1288 uuid: formattedVideoChannel.uuid,
1289 name: formattedVideoChannel.name,
1290 displayName: formattedVideoChannel.displayName,
1291 url: formattedVideoChannel.url,
1292 host: formattedVideoChannel.host,
1293 avatar: formattedVideoChannel.avatar
1298 if (options.additionalAttributes.state === true) {
1299 videoObject.state = {
1301 label: VideoModel.getStateLabel(this.state)
1305 if (options.additionalAttributes.waitTranscoding === true) {
1306 videoObject.waitTranscoding = this.waitTranscoding
1309 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1310 videoObject.scheduledUpdate = {
1311 updateAt: this.ScheduleVideoUpdate.updateAt,
1312 privacy: this.ScheduleVideoUpdate.privacy || undefined
1316 if (options.additionalAttributes.blacklistInfo === true) {
1317 videoObject.blacklisted = !!this.VideoBlacklist
1318 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1325 toFormattedDetailsJSON (): VideoDetails {
1326 const formattedJson = this.toFormattedJSON({
1327 additionalAttributes: {
1328 scheduledUpdate: true,
1333 const detailsJson = {
1334 support: this.support,
1335 descriptionPath: this.getDescriptionPath(),
1336 channel: this.VideoChannel.toFormattedJSON(),
1337 account: this.VideoChannel.Account.toFormattedJSON(),
1338 tags: map(this.Tags, 'name'),
1339 commentsEnabled: this.commentsEnabled,
1340 waitTranscoding: this.waitTranscoding,
1343 label: VideoModel.getStateLabel(this.state)
1348 // Format and sort video files
1349 detailsJson.files = this.getFormattedVideoFilesJSON()
1351 return Object.assign(formattedJson, detailsJson)
1354 getFormattedVideoFilesJSON (): VideoFile[] {
1355 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1357 return this.VideoFiles
1359 let resolutionLabel = videoFile.resolution + 'p'
1363 id: videoFile.resolution,
1364 label: resolutionLabel
1366 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1367 size: videoFile.size,
1369 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1370 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1371 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1372 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1376 if (a.resolution.id < b.resolution.id) return 1
1377 if (a.resolution.id === b.resolution.id) return 0
1382 toActivityPubObject (): VideoTorrentObject {
1383 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1384 if (!this.Tags) this.Tags = []
1386 const tag = this.Tags.map(t => ({
1387 type: 'Hashtag' as 'Hashtag',
1392 if (this.language) {
1394 identifier: this.language,
1395 name: VideoModel.getLanguageLabel(this.language)
1400 if (this.category) {
1402 identifier: this.category + '',
1403 name: VideoModel.getCategoryLabel(this.category)
1410 identifier: this.licence + '',
1411 name: VideoModel.getLicenceLabel(this.licence)
1416 for (const file of this.VideoFiles) {
1419 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1420 href: this.getVideoFileUrl(file, baseUrlHttp),
1421 height: file.resolution,
1428 mimeType: 'application/x-bittorrent',
1429 href: this.getTorrentUrl(file, baseUrlHttp),
1430 height: file.resolution
1435 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1436 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1437 height: file.resolution
1441 // Add video url too
1444 mimeType: 'text/html',
1445 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1448 const subtitleLanguage = []
1449 for (const caption of this.VideoCaptions) {
1450 subtitleLanguage.push({
1451 identifier: caption.language,
1452 name: VideoCaptionModel.getLanguageLabel(caption.language)
1457 type: 'Video' as 'Video',
1460 duration: this.getActivityStreamDuration(),
1467 sensitive: this.nsfw,
1468 waitTranscoding: this.waitTranscoding,
1470 commentsEnabled: this.commentsEnabled,
1471 published: this.publishedAt.toISOString(),
1472 updated: this.updatedAt.toISOString(),
1473 mediaType: 'text/markdown',
1474 content: this.getTruncatedDescription(),
1475 support: this.support,
1479 url: this.getThumbnailUrl(baseUrlHttp),
1480 mediaType: 'image/jpeg',
1481 width: THUMBNAILS_SIZE.width,
1482 height: THUMBNAILS_SIZE.height
1485 likes: getVideoLikesActivityPubUrl(this),
1486 dislikes: getVideoDislikesActivityPubUrl(this),
1487 shares: getVideoSharesActivityPubUrl(this),
1488 comments: getVideoCommentsActivityPubUrl(this),
1492 id: this.VideoChannel.Account.Actor.url
1496 id: this.VideoChannel.Actor.url
1502 getTruncatedDescription () {
1503 if (!this.description) return null
1505 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1506 return peertubeTruncate(this.description, maxLength)
1509 async optimizeOriginalVideofile () {
1510 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1511 const newExtname = '.mp4'
1512 const inputVideoFile = this.getOriginalFile()
1513 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1514 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1516 const transcodeOptions = {
1517 inputPath: videoInputPath,
1518 outputPath: videoTranscodedPath
1521 // Could be very long!
1522 await transcode(transcodeOptions)
1525 await remove(videoInputPath)
1527 // Important to do this before getVideoFilename() to take in account the new file extension
1528 inputVideoFile.set('extname', newExtname)
1530 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1531 await rename(videoTranscodedPath, videoOutputPath)
1532 const stats = await stat(videoOutputPath)
1533 const fps = await getVideoFileFPS(videoOutputPath)
1535 inputVideoFile.set('size', stats.size)
1536 inputVideoFile.set('fps', fps)
1538 await this.createTorrentAndSetInfoHash(inputVideoFile)
1539 await inputVideoFile.save()
1542 // Auto destruction...
1543 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1549 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1550 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1551 const extname = '.mp4'
1553 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1554 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1556 const newVideoFile = new VideoFileModel({
1562 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1564 const transcodeOptions = {
1565 inputPath: videoInputPath,
1566 outputPath: videoOutputPath,
1571 await transcode(transcodeOptions)
1573 const stats = await stat(videoOutputPath)
1574 const fps = await getVideoFileFPS(videoOutputPath)
1576 newVideoFile.set('size', stats.size)
1577 newVideoFile.set('fps', fps)
1579 await this.createTorrentAndSetInfoHash(newVideoFile)
1581 await newVideoFile.save()
1583 this.VideoFiles.push(newVideoFile)
1586 async importVideoFile (inputFilePath: string) {
1587 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1588 const { size } = await stat(inputFilePath)
1589 const fps = await getVideoFileFPS(inputFilePath)
1591 let updatedVideoFile = new VideoFileModel({
1592 resolution: videoFileResolution,
1593 extname: extname(inputFilePath),
1599 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1601 if (currentVideoFile) {
1602 // Remove old file and old torrent
1603 await this.removeFile(currentVideoFile)
1604 await this.removeTorrent(currentVideoFile)
1605 // Remove the old video file from the array
1606 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1608 // Update the database
1609 currentVideoFile.set('extname', updatedVideoFile.extname)
1610 currentVideoFile.set('size', updatedVideoFile.size)
1611 currentVideoFile.set('fps', updatedVideoFile.fps)
1613 updatedVideoFile = currentVideoFile
1616 const outputPath = this.getVideoFilePath(updatedVideoFile)
1617 await copy(inputFilePath, outputPath)
1619 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1621 await updatedVideoFile.save()
1623 this.VideoFiles.push(updatedVideoFile)
1626 getOriginalFileResolution () {
1627 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1629 return getVideoFileResolution(originalFilePath)
1632 getDescriptionPath () {
1633 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1636 removeThumbnail () {
1637 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1638 return remove(thumbnailPath)
1639 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1643 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1644 return remove(previewPath)
1645 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1648 removeFile (videoFile: VideoFileModel) {
1649 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1650 return remove(filePath)
1651 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1654 removeTorrent (videoFile: VideoFileModel) {
1655 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1656 return remove(torrentPath)
1657 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1660 getActivityStreamDuration () {
1661 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1662 return 'PT' + this.duration + 'S'
1666 if (this.isOwned()) return false
1668 const now = Date.now()
1669 const createdAtTime = this.createdAt.getTime()
1670 const updatedAtTime = this.updatedAt.getTime()
1672 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1673 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1676 private getBaseUrls () {
1680 if (this.isOwned()) {
1681 baseUrlHttp = CONFIG.WEBSERVER.URL
1682 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1684 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1685 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1688 return { baseUrlHttp, baseUrlWs }
1691 private getThumbnailUrl (baseUrlHttp: string) {
1692 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1695 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1696 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1699 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1700 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1703 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1704 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1707 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1708 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1711 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1712 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1713 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1714 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1716 const magnetHash = {
1720 infoHash: videoFile.infoHash,
1724 return magnetUtil.encode(magnetHash)