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'
41 } from '../../helpers/core-utils'
42 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
43 import { isBooleanValid } from '../../helpers/custom-validators/misc'
46 isVideoDescriptionValid,
54 } from '../../helpers/custom-validators/videos'
55 import { generateImageFromVideoFile, getVideoFileFPS, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
56 import { logger } from '../../helpers/logger'
57 import { getServerActor } from '../../helpers/utils'
64 STATIC_DOWNLOAD_PATHS,
73 } from '../../initializers'
75 getVideoCommentsActivityPubUrl,
76 getVideoDislikesActivityPubUrl,
77 getVideoLikesActivityPubUrl,
78 getVideoSharesActivityPubUrl
79 } from '../../lib/activitypub'
80 import { sendDeleteVideo } from '../../lib/activitypub/send'
81 import { AccountModel } from '../account/account'
82 import { AccountVideoRateModel } from '../account/account-video-rate'
83 import { ActorModel } from '../activitypub/actor'
84 import { AvatarModel } from '../avatar/avatar'
85 import { ServerModel } from '../server/server'
86 import { buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
87 import { TagModel } from './tag'
88 import { VideoAbuseModel } from './video-abuse'
89 import { VideoChannelModel } from './video-channel'
90 import { VideoCommentModel } from './video-comment'
91 import { VideoFileModel } from './video-file'
92 import { VideoShareModel } from './video-share'
93 import { VideoTagModel } from './video-tag'
94 import { ScheduleVideoUpdateModel } from './schedule-video-update'
95 import { VideoCaptionModel } from './video-caption'
96 import { VideoBlacklistModel } from './video-blacklist'
98 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
99 const indexes: Sequelize.DefineIndexesOptions[] = [
100 buildTrigramSearchIndex('video_name_trigram', 'name'),
102 { fields: [ 'createdAt' ] },
103 { fields: [ 'publishedAt' ] },
104 { fields: [ 'duration' ] },
105 { fields: [ 'category' ] },
106 { fields: [ 'licence' ] },
107 { fields: [ 'nsfw' ] },
108 { fields: [ 'language' ] },
109 { fields: [ 'waitTranscoding' ] },
110 { fields: [ 'state' ] },
111 { fields: [ 'remote' ] },
112 { fields: [ 'views' ] },
113 { fields: [ 'likes' ] },
114 { fields: [ 'channelId' ] },
125 export enum ScopeNames {
126 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
127 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
128 WITH_TAGS = 'WITH_TAGS',
129 WITH_FILES = 'WITH_FILES',
130 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
131 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
134 type AvailableForListOptions = {
136 includeLocalVideos: boolean,
137 filter?: VideoFilter,
138 categoryOneOf?: number[],
140 licenceOneOf?: number[],
141 languageOneOf?: string[],
142 tagsOneOf?: string[],
143 tagsAllOf?: string[],
146 videoChannelId?: number
150 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
151 const accountInclude = {
152 attributes: [ 'id', 'name' ],
153 model: AccountModel.unscoped(),
158 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
159 model: ActorModel.unscoped(),
161 where: VideoModel.buildActorWhereWithFilter(options.filter),
164 attributes: [ 'host' ],
165 model: ServerModel.unscoped(),
169 model: AvatarModel.unscoped(),
177 const videoChannelInclude = {
178 attributes: [ 'name', 'description', 'id' ],
179 model: VideoChannelModel.unscoped(),
184 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
185 model: ActorModel.unscoped(),
189 attributes: [ 'host' ],
190 model: ServerModel.unscoped(),
194 model: AvatarModel.unscoped(),
203 // Force actorId to be a number to avoid SQL injections
204 const actorIdNumber = parseInt(options.actorId.toString(), 10)
205 let localVideosReq = ''
206 if (options.includeLocalVideos === true) {
207 localVideosReq = ' UNION ALL ' +
208 'SELECT "video"."id" AS "id" FROM "video" ' +
209 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
210 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
211 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
212 'WHERE "actor"."serverId" IS NULL'
215 // FIXME: It would be more efficient to use a CTE so we join AFTER the filters, but sequelize does not support it...
216 const query: IFindOptions<VideoModel> = {
219 [Sequelize.Op.notIn]: Sequelize.literal(
220 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
222 [ Sequelize.Op.in ]: Sequelize.literal(
224 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
225 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
226 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
228 'SELECT "video"."id" AS "id" FROM "video" ' +
229 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
230 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
231 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
232 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
233 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
238 // Always list public videos
239 privacy: VideoPrivacy.PUBLIC,
240 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
241 [ Sequelize.Op.or ]: [
243 state: VideoState.PUBLISHED
246 [ Sequelize.Op.and ]: {
247 state: VideoState.TO_TRANSCODE,
248 waitTranscoding: false
253 include: [ videoChannelInclude ]
256 if (options.withFiles === true) {
258 model: VideoFileModel.unscoped(),
263 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
264 if (options.tagsAllOf || options.tagsOneOf) {
265 const createTagsIn = (tags: string[]) => {
266 return tags.map(t => VideoModel.sequelize.escape(t))
270 if (options.tagsOneOf) {
271 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
273 'SELECT "videoId" FROM "videoTag" ' +
274 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
275 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
280 if (options.tagsAllOf) {
281 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
283 'SELECT "videoId" FROM "videoTag" ' +
284 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
285 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
286 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
292 if (options.nsfw === true || options.nsfw === false) {
293 query.where['nsfw'] = options.nsfw
296 if (options.categoryOneOf) {
297 query.where['category'] = {
298 [Sequelize.Op.or]: options.categoryOneOf
302 if (options.licenceOneOf) {
303 query.where['licence'] = {
304 [Sequelize.Op.or]: options.licenceOneOf
308 if (options.languageOneOf) {
309 query.where['language'] = {
310 [Sequelize.Op.or]: options.languageOneOf
314 if (options.accountId) {
315 accountInclude.where = {
316 id: options.accountId
320 if (options.videoChannelId) {
321 videoChannelInclude.where = {
322 id: options.videoChannelId
328 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
331 model: () => VideoChannelModel.unscoped(),
336 exclude: [ 'privateKey', 'publicKey' ]
338 model: () => ActorModel.unscoped(),
342 attributes: [ 'host' ],
343 model: () => ServerModel.unscoped(),
347 model: () => AvatarModel.unscoped(),
353 model: () => AccountModel.unscoped(),
357 model: () => ActorModel.unscoped(),
359 exclude: [ 'privateKey', 'publicKey' ]
364 attributes: [ 'host' ],
365 model: () => ServerModel.unscoped(),
369 model: () => AvatarModel.unscoped(),
380 [ScopeNames.WITH_TAGS]: {
381 include: [ () => TagModel ]
383 [ScopeNames.WITH_BLACKLISTED]: {
386 attributes: [ 'id', 'reason' ],
387 model: () => VideoBlacklistModel,
392 [ScopeNames.WITH_FILES]: {
395 model: () => VideoFileModel.unscoped(),
400 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
403 model: () => ScheduleVideoUpdateModel.unscoped(),
413 export class VideoModel extends Model<VideoModel> {
416 @Default(DataType.UUIDV4)
418 @Column(DataType.UUID)
422 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
428 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
434 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
440 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
441 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
445 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
450 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
456 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
457 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
462 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
463 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
467 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
497 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
498 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
503 commentsEnabled: boolean
507 waitTranscoding: boolean
511 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
522 @Default(Sequelize.NOW)
526 @ForeignKey(() => VideoChannelModel)
530 @BelongsTo(() => VideoChannelModel, {
536 VideoChannel: VideoChannelModel
538 @BelongsToMany(() => TagModel, {
539 foreignKey: 'videoId',
540 through: () => VideoTagModel,
545 @HasMany(() => VideoAbuseModel, {
552 VideoAbuses: VideoAbuseModel[]
554 @HasMany(() => VideoFileModel, {
561 VideoFiles: VideoFileModel[]
563 @HasMany(() => VideoShareModel, {
570 VideoShares: VideoShareModel[]
572 @HasMany(() => AccountVideoRateModel, {
579 AccountVideoRates: AccountVideoRateModel[]
581 @HasMany(() => VideoCommentModel, {
589 VideoComments: VideoCommentModel[]
591 @HasOne(() => ScheduleVideoUpdateModel, {
598 ScheduleVideoUpdate: ScheduleVideoUpdateModel
600 @HasOne(() => VideoBlacklistModel, {
607 VideoBlacklist: VideoBlacklistModel
609 @HasMany(() => VideoCaptionModel, {
616 ['separate' as any]: true
618 VideoCaptions: VideoCaptionModel[]
621 static async sendDelete (instance: VideoModel, options) {
622 if (instance.isOwned()) {
623 if (!instance.VideoChannel) {
624 instance.VideoChannel = await instance.$get('VideoChannel', {
628 include: [ ActorModel ]
631 transaction: options.transaction
632 }) as VideoChannelModel
635 return sendDeleteVideo(instance, options.transaction)
642 static async removeFiles (instance: VideoModel) {
643 const tasks: Promise<any>[] = []
645 logger.info('Removing files of video %s.', instance.url)
647 tasks.push(instance.removeThumbnail())
649 if (instance.isOwned()) {
650 if (!Array.isArray(instance.VideoFiles)) {
651 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
654 tasks.push(instance.removePreview())
656 // Remove physical files and torrents
657 instance.VideoFiles.forEach(file => {
658 tasks.push(instance.removeFile(file))
659 tasks.push(instance.removeTorrent(file))
663 // Do not wait video deletion because we could be in a transaction
666 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
673 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
676 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
677 function getRawQuery (select: string) {
678 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
679 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
680 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
681 'WHERE "Account"."actorId" = ' + actorId
682 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
683 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
684 'WHERE "VideoShare"."actorId" = ' + actorId
686 return `(${queryVideo}) UNION (${queryVideoShare})`
689 const rawQuery = getRawQuery('"Video"."id"')
690 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
696 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
699 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
702 { privacy: VideoPrivacy.PUBLIC },
703 { privacy: VideoPrivacy.UNLISTED }
708 attributes: [ 'language' ],
709 model: VideoCaptionModel.unscoped(),
713 attributes: [ 'id', 'url' ],
714 model: VideoShareModel.unscoped(),
716 // We only want videos shared by this actor
718 [Sequelize.Op.and]: [
721 [Sequelize.Op.not]: null
731 attributes: [ 'id', 'url' ],
732 model: ActorModel.unscoped()
737 model: VideoChannelModel.unscoped(),
741 attributes: [ 'name' ],
742 model: AccountModel.unscoped(),
746 attributes: [ 'id', 'url', 'followersUrl' ],
747 model: ActorModel.unscoped(),
753 attributes: [ 'id', 'url', 'followersUrl' ],
754 model: ActorModel.unscoped(),
764 return Bluebird.all([
765 // FIXME: typing issue
766 VideoModel.findAll(query as any),
767 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
768 ]).then(([ rows, totals ]) => {
769 // totals: totalVideos + totalVideoShares
771 let totalVideoShares = 0
772 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
773 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
775 const total = totalVideos + totalVideoShares
783 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
784 const query: IFindOptions<VideoModel> = {
787 order: getSort(sort),
790 model: VideoChannelModel,
803 model: ScheduleVideoUpdateModel,
807 model: VideoBlacklistModel,
813 if (withFiles === true) {
815 model: VideoFileModel.unscoped(),
820 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
828 static async listForApi (options: {
833 includeLocalVideos: boolean,
835 categoryOneOf?: number[],
836 licenceOneOf?: number[],
837 languageOneOf?: string[],
838 tagsOneOf?: string[],
839 tagsAllOf?: string[],
840 filter?: VideoFilter,
842 videoChannelId?: number,
846 offset: options.start,
847 limit: options.count,
848 order: getSort(options.sort)
851 const actorId = options.actorId || (await getServerActor()).id
855 ScopeNames.AVAILABLE_FOR_LIST, {
858 categoryOneOf: options.categoryOneOf,
859 licenceOneOf: options.licenceOneOf,
860 languageOneOf: options.languageOneOf,
861 tagsOneOf: options.tagsOneOf,
862 tagsAllOf: options.tagsAllOf,
863 filter: options.filter,
864 withFiles: options.withFiles,
865 accountId: options.accountId,
866 videoChannelId: options.videoChannelId,
867 includeLocalVideos: options.includeLocalVideos
868 } as AvailableForListOptions
872 return VideoModel.scope(scopes)
873 .findAndCountAll(query)
874 .then(({ rows, count }) => {
882 static async searchAndPopulateAccountAndServer (options: {
883 includeLocalVideos: boolean
888 startDate?: string // ISO 8601
889 endDate?: string // ISO 8601
891 categoryOneOf?: number[]
892 licenceOneOf?: number[]
893 languageOneOf?: string[]
896 durationMin?: number // seconds
897 durationMax?: number // seconds
901 if (options.startDate || options.endDate) {
902 const publishedAtRange = { }
904 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
905 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
907 whereAnd.push({ publishedAt: publishedAtRange })
910 if (options.durationMin || options.durationMax) {
911 const durationRange = { }
913 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
914 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
916 whereAnd.push({ duration: durationRange })
919 const attributesInclude = []
920 const escapedSearch = VideoModel.sequelize.escape(options.search)
921 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
922 if (options.search) {
926 [ Sequelize.Op.in ]: Sequelize.literal(
928 'SELECT "video"."id" FROM "video" WHERE ' +
929 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
930 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
932 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
933 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
934 'WHERE "tag"."name" = ' + escapedSearch +
941 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
944 // Cannot search on similarity if we don't have a search
945 if (!options.search) {
946 attributesInclude.push(
947 Sequelize.literal('0 as similarity')
951 const query: IFindOptions<VideoModel> = {
953 include: attributesInclude
955 offset: options.start,
956 limit: options.count,
957 order: getSort(options.sort),
959 [ Sequelize.Op.and ]: whereAnd
963 const serverActor = await getServerActor()
966 ScopeNames.AVAILABLE_FOR_LIST, {
967 actorId: serverActor.id,
968 includeLocalVideos: options.includeLocalVideos,
970 categoryOneOf: options.categoryOneOf,
971 licenceOneOf: options.licenceOneOf,
972 languageOneOf: options.languageOneOf,
973 tagsOneOf: options.tagsOneOf,
974 tagsAllOf: options.tagsAllOf
975 } as AvailableForListOptions
979 return VideoModel.scope(scopes)
980 .findAndCountAll(query)
981 .then(({ rows, count }) => {
989 static load (id: number, t?: Sequelize.Transaction) {
990 const options = t ? { transaction: t } : undefined
992 return VideoModel.findById(id, options)
995 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
996 const query: IFindOptions<VideoModel> = {
1002 if (t !== undefined) query.transaction = t
1004 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1007 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
1008 const query: IFindOptions<VideoModel> = {
1010 [Sequelize.Op.or]: [
1017 if (t !== undefined) query.transaction = t
1019 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1022 static loadAndPopulateAccountAndServerAndTags (id: number) {
1024 order: [ [ 'Tags', 'name', 'ASC' ] ]
1029 ScopeNames.WITH_TAGS,
1030 ScopeNames.WITH_BLACKLISTED,
1031 ScopeNames.WITH_FILES,
1032 ScopeNames.WITH_ACCOUNT_DETAILS,
1033 ScopeNames.WITH_SCHEDULED_UPDATE
1035 .findById(id, options)
1038 static loadByUUID (uuid: string) {
1046 .scope([ ScopeNames.WITH_FILES ])
1050 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1052 order: [ [ 'Tags', 'name', 'ASC' ] ],
1061 ScopeNames.WITH_TAGS,
1062 ScopeNames.WITH_BLACKLISTED,
1063 ScopeNames.WITH_FILES,
1064 ScopeNames.WITH_ACCOUNT_DETAILS,
1065 ScopeNames.WITH_SCHEDULED_UPDATE
1070 static async getStats () {
1071 const totalLocalVideos = await VideoModel.count({
1076 const totalVideos = await VideoModel.count()
1078 let totalLocalVideoViews = await VideoModel.sum('views', {
1083 // Sequelize could return null...
1084 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1088 totalLocalVideoViews,
1093 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1094 if (filter && filter === 'local') {
1103 private static getCategoryLabel (id: number) {
1104 return VIDEO_CATEGORIES[id] || 'Misc'
1107 private static getLicenceLabel (id: number) {
1108 return VIDEO_LICENCES[id] || 'Unknown'
1111 private static getLanguageLabel (id: string) {
1112 return VIDEO_LANGUAGES[id] || 'Unknown'
1115 private static getPrivacyLabel (id: number) {
1116 return VIDEO_PRIVACIES[id] || 'Unknown'
1119 private static getStateLabel (id: number) {
1120 return VIDEO_STATES[id] || 'Unknown'
1123 getOriginalFile () {
1124 if (Array.isArray(this.VideoFiles) === false) return undefined
1126 // The original file is the file that have the higher resolution
1127 return maxBy(this.VideoFiles, file => file.resolution)
1130 getVideoFilename (videoFile: VideoFileModel) {
1131 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1134 getThumbnailName () {
1135 // We always have a copy of the thumbnail
1136 const extension = '.jpg'
1137 return this.uuid + extension
1141 const extension = '.jpg'
1142 return this.uuid + extension
1145 getTorrentFileName (videoFile: VideoFileModel) {
1146 const extension = '.torrent'
1147 return this.uuid + '-' + videoFile.resolution + extension
1151 return this.remote === false
1154 createPreview (videoFile: VideoFileModel) {
1155 return generateImageFromVideoFile(
1156 this.getVideoFilePath(videoFile),
1157 CONFIG.STORAGE.PREVIEWS_DIR,
1158 this.getPreviewName(),
1163 createThumbnail (videoFile: VideoFileModel) {
1164 return generateImageFromVideoFile(
1165 this.getVideoFilePath(videoFile),
1166 CONFIG.STORAGE.THUMBNAILS_DIR,
1167 this.getThumbnailName(),
1172 getTorrentFilePath (videoFile: VideoFileModel) {
1173 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1176 getVideoFilePath (videoFile: VideoFileModel) {
1177 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1180 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1182 // Keep the extname, it's used by the client to stream the file inside a web browser
1183 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1184 createdBy: 'PeerTube',
1186 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1187 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1190 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1194 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1196 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1197 logger.info('Creating torrent %s.', filePath)
1199 await writeFilePromise(filePath, torrent)
1201 const parsedTorrent = parseTorrent(torrent)
1202 videoFile.infoHash = parsedTorrent.infoHash
1205 getEmbedStaticPath () {
1206 return '/videos/embed/' + this.uuid
1209 getThumbnailStaticPath () {
1210 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1213 getPreviewStaticPath () {
1214 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1217 toFormattedJSON (options?: {
1218 additionalAttributes: {
1220 waitTranscoding?: boolean,
1221 scheduledUpdate?: boolean,
1222 blacklistInfo?: boolean
1225 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1226 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1228 const videoObject: Video = {
1234 label: VideoModel.getCategoryLabel(this.category)
1238 label: VideoModel.getLicenceLabel(this.licence)
1242 label: VideoModel.getLanguageLabel(this.language)
1246 label: VideoModel.getPrivacyLabel(this.privacy)
1249 description: this.getTruncatedDescription(),
1250 isLocal: this.isOwned(),
1251 duration: this.duration,
1254 dislikes: this.dislikes,
1255 thumbnailPath: this.getThumbnailStaticPath(),
1256 previewPath: this.getPreviewStaticPath(),
1257 embedPath: this.getEmbedStaticPath(),
1258 createdAt: this.createdAt,
1259 updatedAt: this.updatedAt,
1260 publishedAt: this.publishedAt,
1262 id: formattedAccount.id,
1263 uuid: formattedAccount.uuid,
1264 name: formattedAccount.name,
1265 displayName: formattedAccount.displayName,
1266 url: formattedAccount.url,
1267 host: formattedAccount.host,
1268 avatar: formattedAccount.avatar
1271 id: formattedVideoChannel.id,
1272 uuid: formattedVideoChannel.uuid,
1273 name: formattedVideoChannel.name,
1274 displayName: formattedVideoChannel.displayName,
1275 url: formattedVideoChannel.url,
1276 host: formattedVideoChannel.host,
1277 avatar: formattedVideoChannel.avatar
1282 if (options.additionalAttributes.state === true) {
1283 videoObject.state = {
1285 label: VideoModel.getStateLabel(this.state)
1289 if (options.additionalAttributes.waitTranscoding === true) {
1290 videoObject.waitTranscoding = this.waitTranscoding
1293 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1294 videoObject.scheduledUpdate = {
1295 updateAt: this.ScheduleVideoUpdate.updateAt,
1296 privacy: this.ScheduleVideoUpdate.privacy || undefined
1300 if (options.additionalAttributes.blacklistInfo === true) {
1301 videoObject.blacklisted = !!this.VideoBlacklist
1302 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1309 toFormattedDetailsJSON (): VideoDetails {
1310 const formattedJson = this.toFormattedJSON({
1311 additionalAttributes: {
1312 scheduledUpdate: true,
1317 const detailsJson = {
1318 support: this.support,
1319 descriptionPath: this.getDescriptionPath(),
1320 channel: this.VideoChannel.toFormattedJSON(),
1321 account: this.VideoChannel.Account.toFormattedJSON(),
1322 tags: map(this.Tags, 'name'),
1323 commentsEnabled: this.commentsEnabled,
1324 waitTranscoding: this.waitTranscoding,
1327 label: VideoModel.getStateLabel(this.state)
1332 // Format and sort video files
1333 detailsJson.files = this.getFormattedVideoFilesJSON()
1335 return Object.assign(formattedJson, detailsJson)
1338 getFormattedVideoFilesJSON (): VideoFile[] {
1339 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1341 return this.VideoFiles
1343 let resolutionLabel = videoFile.resolution + 'p'
1347 id: videoFile.resolution,
1348 label: resolutionLabel
1350 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1351 size: videoFile.size,
1353 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1354 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1355 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1356 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1360 if (a.resolution.id < b.resolution.id) return 1
1361 if (a.resolution.id === b.resolution.id) return 0
1366 toActivityPubObject (): VideoTorrentObject {
1367 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1368 if (!this.Tags) this.Tags = []
1370 const tag = this.Tags.map(t => ({
1371 type: 'Hashtag' as 'Hashtag',
1376 if (this.language) {
1378 identifier: this.language,
1379 name: VideoModel.getLanguageLabel(this.language)
1384 if (this.category) {
1386 identifier: this.category + '',
1387 name: VideoModel.getCategoryLabel(this.category)
1394 identifier: this.licence + '',
1395 name: VideoModel.getLicenceLabel(this.licence)
1400 for (const file of this.VideoFiles) {
1403 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1404 href: this.getVideoFileUrl(file, baseUrlHttp),
1405 width: file.resolution,
1412 mimeType: 'application/x-bittorrent',
1413 href: this.getTorrentUrl(file, baseUrlHttp),
1414 width: file.resolution
1419 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1420 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1421 width: file.resolution
1425 // Add video url too
1428 mimeType: 'text/html',
1429 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1432 const subtitleLanguage = []
1433 for (const caption of this.VideoCaptions) {
1434 subtitleLanguage.push({
1435 identifier: caption.language,
1436 name: VideoCaptionModel.getLanguageLabel(caption.language)
1441 type: 'Video' as 'Video',
1444 duration: this.getActivityStreamDuration(),
1451 sensitive: this.nsfw,
1452 waitTranscoding: this.waitTranscoding,
1454 commentsEnabled: this.commentsEnabled,
1455 published: this.publishedAt.toISOString(),
1456 updated: this.updatedAt.toISOString(),
1457 mediaType: 'text/markdown',
1458 content: this.getTruncatedDescription(),
1459 support: this.support,
1463 url: this.getThumbnailUrl(baseUrlHttp),
1464 mediaType: 'image/jpeg',
1465 width: THUMBNAILS_SIZE.width,
1466 height: THUMBNAILS_SIZE.height
1469 likes: getVideoLikesActivityPubUrl(this),
1470 dislikes: getVideoDislikesActivityPubUrl(this),
1471 shares: getVideoSharesActivityPubUrl(this),
1472 comments: getVideoCommentsActivityPubUrl(this),
1476 id: this.VideoChannel.Account.Actor.url
1480 id: this.VideoChannel.Actor.url
1486 getTruncatedDescription () {
1487 if (!this.description) return null
1489 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1490 return peertubeTruncate(this.description, maxLength)
1493 async optimizeOriginalVideofile () {
1494 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1495 const newExtname = '.mp4'
1496 const inputVideoFile = this.getOriginalFile()
1497 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1498 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1500 const transcodeOptions = {
1501 inputPath: videoInputPath,
1502 outputPath: videoTranscodedPath
1505 // Could be very long!
1506 await transcode(transcodeOptions)
1509 await unlinkPromise(videoInputPath)
1511 // Important to do this before getVideoFilename() to take in account the new file extension
1512 inputVideoFile.set('extname', newExtname)
1514 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1515 await renamePromise(videoTranscodedPath, videoOutputPath)
1516 const stats = await statPromise(videoOutputPath)
1517 const fps = await getVideoFileFPS(videoOutputPath)
1519 inputVideoFile.set('size', stats.size)
1520 inputVideoFile.set('fps', fps)
1522 await this.createTorrentAndSetInfoHash(inputVideoFile)
1523 await inputVideoFile.save()
1526 // Auto destruction...
1527 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1533 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1534 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1535 const extname = '.mp4'
1537 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1538 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1540 const newVideoFile = new VideoFileModel({
1546 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1548 const transcodeOptions = {
1549 inputPath: videoInputPath,
1550 outputPath: videoOutputPath,
1555 await transcode(transcodeOptions)
1557 const stats = await statPromise(videoOutputPath)
1558 const fps = await getVideoFileFPS(videoOutputPath)
1560 newVideoFile.set('size', stats.size)
1561 newVideoFile.set('fps', fps)
1563 await this.createTorrentAndSetInfoHash(newVideoFile)
1565 await newVideoFile.save()
1567 this.VideoFiles.push(newVideoFile)
1570 async importVideoFile (inputFilePath: string) {
1571 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1572 const { size } = await statPromise(inputFilePath)
1573 const fps = await getVideoFileFPS(inputFilePath)
1575 let updatedVideoFile = new VideoFileModel({
1576 resolution: videoFileResolution,
1577 extname: extname(inputFilePath),
1583 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1585 if (currentVideoFile) {
1586 // Remove old file and old torrent
1587 await this.removeFile(currentVideoFile)
1588 await this.removeTorrent(currentVideoFile)
1589 // Remove the old video file from the array
1590 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1592 // Update the database
1593 currentVideoFile.set('extname', updatedVideoFile.extname)
1594 currentVideoFile.set('size', updatedVideoFile.size)
1595 currentVideoFile.set('fps', updatedVideoFile.fps)
1597 updatedVideoFile = currentVideoFile
1600 const outputPath = this.getVideoFilePath(updatedVideoFile)
1601 await copyFilePromise(inputFilePath, outputPath)
1603 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1605 await updatedVideoFile.save()
1607 this.VideoFiles.push(updatedVideoFile)
1610 getOriginalFileResolution () {
1611 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1613 return getVideoFileResolution(originalFilePath)
1616 getDescriptionPath () {
1617 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1620 removeThumbnail () {
1621 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1622 return unlinkPromise(thumbnailPath)
1623 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1627 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1628 return unlinkPromise(previewPath)
1629 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1632 removeFile (videoFile: VideoFileModel) {
1633 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1634 return unlinkPromise(filePath)
1635 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1638 removeTorrent (videoFile: VideoFileModel) {
1639 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1640 return unlinkPromise(torrentPath)
1641 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1644 getActivityStreamDuration () {
1645 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1646 return 'PT' + this.duration + 'S'
1649 private getBaseUrls () {
1653 if (this.isOwned()) {
1654 baseUrlHttp = CONFIG.WEBSERVER.URL
1655 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1657 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1658 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1661 return { baseUrlHttp, baseUrlWs }
1664 private getThumbnailUrl (baseUrlHttp: string) {
1665 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1668 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1669 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1672 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1673 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1676 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1677 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1680 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1681 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1684 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1685 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1686 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1687 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1689 const magnetHash = {
1693 infoHash: videoFile.infoHash,
1697 return magnetUtil.encode(magnetHash)