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'
65 STATIC_DOWNLOAD_PATHS,
74 } from '../../initializers'
76 getVideoCommentsActivityPubUrl,
77 getVideoDislikesActivityPubUrl,
78 getVideoLikesActivityPubUrl,
79 getVideoSharesActivityPubUrl
80 } from '../../lib/activitypub'
81 import { sendDeleteVideo } from '../../lib/activitypub/send'
82 import { AccountModel } from '../account/account'
83 import { AccountVideoRateModel } from '../account/account-video-rate'
84 import { ActorModel } from '../activitypub/actor'
85 import { AvatarModel } from '../avatar/avatar'
86 import { ServerModel } from '../server/server'
87 import { buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
88 import { TagModel } from './tag'
89 import { VideoAbuseModel } from './video-abuse'
90 import { VideoChannelModel } from './video-channel'
91 import { VideoCommentModel } from './video-comment'
92 import { VideoFileModel } from './video-file'
93 import { VideoShareModel } from './video-share'
94 import { VideoTagModel } from './video-tag'
95 import { ScheduleVideoUpdateModel } from './schedule-video-update'
96 import { VideoCaptionModel } from './video-caption'
97 import { VideoBlacklistModel } from './video-blacklist'
99 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
100 const indexes: Sequelize.DefineIndexesOptions[] = [
101 buildTrigramSearchIndex('video_name_trigram', 'name'),
103 { fields: [ 'createdAt' ] },
104 { fields: [ 'publishedAt' ] },
105 { fields: [ 'duration' ] },
106 { fields: [ 'category' ] },
107 { fields: [ 'licence' ] },
108 { fields: [ 'nsfw' ] },
109 { fields: [ 'language' ] },
110 { fields: [ 'waitTranscoding' ] },
111 { fields: [ 'state' ] },
112 { fields: [ 'remote' ] },
113 { fields: [ 'views' ] },
114 { fields: [ 'likes' ] },
115 { fields: [ 'channelId' ] },
126 export enum ScopeNames {
127 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
128 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
129 WITH_TAGS = 'WITH_TAGS',
130 WITH_FILES = 'WITH_FILES',
131 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
132 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
135 type AvailableForListOptions = {
137 includeLocalVideos: boolean,
138 filter?: VideoFilter,
139 categoryOneOf?: number[],
141 licenceOneOf?: number[],
142 languageOneOf?: string[],
143 tagsOneOf?: string[],
144 tagsAllOf?: string[],
147 videoChannelId?: number
151 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
152 const accountInclude = {
153 attributes: [ 'id', 'name' ],
154 model: AccountModel.unscoped(),
159 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
160 model: ActorModel.unscoped(),
162 where: VideoModel.buildActorWhereWithFilter(options.filter),
165 attributes: [ 'host' ],
166 model: ServerModel.unscoped(),
170 model: AvatarModel.unscoped(),
178 const videoChannelInclude = {
179 attributes: [ 'name', 'description', 'id' ],
180 model: VideoChannelModel.unscoped(),
185 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
186 model: ActorModel.unscoped(),
190 attributes: [ 'host' ],
191 model: ServerModel.unscoped(),
195 model: AvatarModel.unscoped(),
204 // Force actorId to be a number to avoid SQL injections
205 const actorIdNumber = parseInt(options.actorId.toString(), 10)
206 let localVideosReq = ''
207 if (options.includeLocalVideos === true) {
208 localVideosReq = ' UNION ALL ' +
209 'SELECT "video"."id" AS "id" FROM "video" ' +
210 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
211 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
212 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
213 'WHERE "actor"."serverId" IS NULL'
216 // FIXME: It would be more efficient to use a CTE so we join AFTER the filters, but sequelize does not support it...
217 const query: IFindOptions<VideoModel> = {
220 [Sequelize.Op.notIn]: Sequelize.literal(
221 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
223 [ Sequelize.Op.in ]: Sequelize.literal(
225 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
226 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
227 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
229 'SELECT "video"."id" AS "id" FROM "video" ' +
230 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
231 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
232 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
233 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
234 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
239 // Always list public videos
240 privacy: VideoPrivacy.PUBLIC,
241 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
242 [ Sequelize.Op.or ]: [
244 state: VideoState.PUBLISHED
247 [ Sequelize.Op.and ]: {
248 state: VideoState.TO_TRANSCODE,
249 waitTranscoding: false
254 include: [ videoChannelInclude ]
257 if (options.withFiles === true) {
259 model: VideoFileModel.unscoped(),
264 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
265 if (options.tagsAllOf || options.tagsOneOf) {
266 const createTagsIn = (tags: string[]) => {
267 return tags.map(t => VideoModel.sequelize.escape(t))
271 if (options.tagsOneOf) {
272 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
274 'SELECT "videoId" FROM "videoTag" ' +
275 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
276 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
281 if (options.tagsAllOf) {
282 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
284 'SELECT "videoId" FROM "videoTag" ' +
285 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
286 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
287 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
293 if (options.nsfw === true || options.nsfw === false) {
294 query.where['nsfw'] = options.nsfw
297 if (options.categoryOneOf) {
298 query.where['category'] = {
299 [Sequelize.Op.or]: options.categoryOneOf
303 if (options.licenceOneOf) {
304 query.where['licence'] = {
305 [Sequelize.Op.or]: options.licenceOneOf
309 if (options.languageOneOf) {
310 query.where['language'] = {
311 [Sequelize.Op.or]: options.languageOneOf
315 if (options.accountId) {
316 accountInclude.where = {
317 id: options.accountId
321 if (options.videoChannelId) {
322 videoChannelInclude.where = {
323 id: options.videoChannelId
329 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
332 model: () => VideoChannelModel.unscoped(),
337 exclude: [ 'privateKey', 'publicKey' ]
339 model: () => ActorModel.unscoped(),
343 attributes: [ 'host' ],
344 model: () => ServerModel.unscoped(),
348 model: () => AvatarModel.unscoped(),
354 model: () => AccountModel.unscoped(),
358 model: () => ActorModel.unscoped(),
360 exclude: [ 'privateKey', 'publicKey' ]
365 attributes: [ 'host' ],
366 model: () => ServerModel.unscoped(),
370 model: () => AvatarModel.unscoped(),
381 [ScopeNames.WITH_TAGS]: {
382 include: [ () => TagModel ]
384 [ScopeNames.WITH_BLACKLISTED]: {
387 attributes: [ 'id', 'reason' ],
388 model: () => VideoBlacklistModel,
393 [ScopeNames.WITH_FILES]: {
396 model: () => VideoFileModel.unscoped(),
401 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
404 model: () => ScheduleVideoUpdateModel.unscoped(),
414 export class VideoModel extends Model<VideoModel> {
417 @Default(DataType.UUIDV4)
419 @Column(DataType.UUID)
423 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
429 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
435 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
441 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
442 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
446 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
451 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
457 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
458 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
463 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
464 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
468 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
498 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
499 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
504 commentsEnabled: boolean
508 waitTranscoding: boolean
512 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
523 @Default(Sequelize.NOW)
527 @ForeignKey(() => VideoChannelModel)
531 @BelongsTo(() => VideoChannelModel, {
537 VideoChannel: VideoChannelModel
539 @BelongsToMany(() => TagModel, {
540 foreignKey: 'videoId',
541 through: () => VideoTagModel,
546 @HasMany(() => VideoAbuseModel, {
553 VideoAbuses: VideoAbuseModel[]
555 @HasMany(() => VideoFileModel, {
562 VideoFiles: VideoFileModel[]
564 @HasMany(() => VideoShareModel, {
571 VideoShares: VideoShareModel[]
573 @HasMany(() => AccountVideoRateModel, {
580 AccountVideoRates: AccountVideoRateModel[]
582 @HasMany(() => VideoCommentModel, {
590 VideoComments: VideoCommentModel[]
592 @HasOne(() => ScheduleVideoUpdateModel, {
599 ScheduleVideoUpdate: ScheduleVideoUpdateModel
601 @HasOne(() => VideoBlacklistModel, {
608 VideoBlacklist: VideoBlacklistModel
610 @HasMany(() => VideoCaptionModel, {
617 ['separate' as any]: true
619 VideoCaptions: VideoCaptionModel[]
622 static async sendDelete (instance: VideoModel, options) {
623 if (instance.isOwned()) {
624 if (!instance.VideoChannel) {
625 instance.VideoChannel = await instance.$get('VideoChannel', {
629 include: [ ActorModel ]
632 transaction: options.transaction
633 }) as VideoChannelModel
636 return sendDeleteVideo(instance, options.transaction)
643 static async removeFiles (instance: VideoModel) {
644 const tasks: Promise<any>[] = []
646 logger.info('Removing files of video %s.', instance.url)
648 tasks.push(instance.removeThumbnail())
650 if (instance.isOwned()) {
651 if (!Array.isArray(instance.VideoFiles)) {
652 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
655 tasks.push(instance.removePreview())
657 // Remove physical files and torrents
658 instance.VideoFiles.forEach(file => {
659 tasks.push(instance.removeFile(file))
660 tasks.push(instance.removeTorrent(file))
664 // Do not wait video deletion because we could be in a transaction
667 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
674 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
677 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
678 function getRawQuery (select: string) {
679 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
680 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
681 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
682 'WHERE "Account"."actorId" = ' + actorId
683 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
684 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
685 'WHERE "VideoShare"."actorId" = ' + actorId
687 return `(${queryVideo}) UNION (${queryVideoShare})`
690 const rawQuery = getRawQuery('"Video"."id"')
691 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
697 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
700 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
703 { privacy: VideoPrivacy.PUBLIC },
704 { privacy: VideoPrivacy.UNLISTED }
709 attributes: [ 'language' ],
710 model: VideoCaptionModel.unscoped(),
714 attributes: [ 'id', 'url' ],
715 model: VideoShareModel.unscoped(),
717 // We only want videos shared by this actor
719 [Sequelize.Op.and]: [
722 [Sequelize.Op.not]: null
732 attributes: [ 'id', 'url' ],
733 model: ActorModel.unscoped()
738 model: VideoChannelModel.unscoped(),
742 attributes: [ 'name' ],
743 model: AccountModel.unscoped(),
747 attributes: [ 'id', 'url', 'followersUrl' ],
748 model: ActorModel.unscoped(),
754 attributes: [ 'id', 'url', 'followersUrl' ],
755 model: ActorModel.unscoped(),
765 return Bluebird.all([
766 // FIXME: typing issue
767 VideoModel.findAll(query as any),
768 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
769 ]).then(([ rows, totals ]) => {
770 // totals: totalVideos + totalVideoShares
772 let totalVideoShares = 0
773 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
774 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
776 const total = totalVideos + totalVideoShares
784 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
785 const query: IFindOptions<VideoModel> = {
788 order: getSort(sort),
791 model: VideoChannelModel,
804 model: ScheduleVideoUpdateModel,
808 model: VideoBlacklistModel,
814 if (withFiles === true) {
816 model: VideoFileModel.unscoped(),
821 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
829 static async listForApi (options: {
834 includeLocalVideos: boolean,
836 categoryOneOf?: number[],
837 licenceOneOf?: number[],
838 languageOneOf?: string[],
839 tagsOneOf?: string[],
840 tagsAllOf?: string[],
841 filter?: VideoFilter,
843 videoChannelId?: number,
847 offset: options.start,
848 limit: options.count,
849 order: getSort(options.sort)
852 const actorId = options.actorId || (await getServerActor()).id
856 ScopeNames.AVAILABLE_FOR_LIST, {
859 categoryOneOf: options.categoryOneOf,
860 licenceOneOf: options.licenceOneOf,
861 languageOneOf: options.languageOneOf,
862 tagsOneOf: options.tagsOneOf,
863 tagsAllOf: options.tagsAllOf,
864 filter: options.filter,
865 withFiles: options.withFiles,
866 accountId: options.accountId,
867 videoChannelId: options.videoChannelId,
868 includeLocalVideos: options.includeLocalVideos
869 } as AvailableForListOptions
873 return VideoModel.scope(scopes)
874 .findAndCountAll(query)
875 .then(({ rows, count }) => {
883 static async searchAndPopulateAccountAndServer (options: {
884 includeLocalVideos: boolean
889 startDate?: string // ISO 8601
890 endDate?: string // ISO 8601
892 categoryOneOf?: number[]
893 licenceOneOf?: number[]
894 languageOneOf?: string[]
897 durationMin?: number // seconds
898 durationMax?: number // seconds
902 if (options.startDate || options.endDate) {
903 const publishedAtRange = { }
905 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
906 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
908 whereAnd.push({ publishedAt: publishedAtRange })
911 if (options.durationMin || options.durationMax) {
912 const durationRange = { }
914 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
915 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
917 whereAnd.push({ duration: durationRange })
920 const attributesInclude = []
921 const escapedSearch = VideoModel.sequelize.escape(options.search)
922 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
923 if (options.search) {
927 [ Sequelize.Op.in ]: Sequelize.literal(
929 'SELECT "video"."id" FROM "video" WHERE ' +
930 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
931 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
933 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
934 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
935 'WHERE "tag"."name" = ' + escapedSearch +
942 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
945 // Cannot search on similarity if we don't have a search
946 if (!options.search) {
947 attributesInclude.push(
948 Sequelize.literal('0 as similarity')
952 const query: IFindOptions<VideoModel> = {
954 include: attributesInclude
956 offset: options.start,
957 limit: options.count,
958 order: getSort(options.sort),
960 [ Sequelize.Op.and ]: whereAnd
964 const serverActor = await getServerActor()
967 ScopeNames.AVAILABLE_FOR_LIST, {
968 actorId: serverActor.id,
969 includeLocalVideos: options.includeLocalVideos,
971 categoryOneOf: options.categoryOneOf,
972 licenceOneOf: options.licenceOneOf,
973 languageOneOf: options.languageOneOf,
974 tagsOneOf: options.tagsOneOf,
975 tagsAllOf: options.tagsAllOf
976 } as AvailableForListOptions
980 return VideoModel.scope(scopes)
981 .findAndCountAll(query)
982 .then(({ rows, count }) => {
990 static load (id: number, t?: Sequelize.Transaction) {
991 const options = t ? { transaction: t } : undefined
993 return VideoModel.findById(id, options)
996 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
997 const query: IFindOptions<VideoModel> = {
1003 if (t !== undefined) query.transaction = t
1005 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1008 static loadAndPopulateAccountAndServerAndTags (id: number) {
1010 order: [ [ 'Tags', 'name', 'ASC' ] ]
1015 ScopeNames.WITH_TAGS,
1016 ScopeNames.WITH_BLACKLISTED,
1017 ScopeNames.WITH_FILES,
1018 ScopeNames.WITH_ACCOUNT_DETAILS,
1019 ScopeNames.WITH_SCHEDULED_UPDATE
1021 .findById(id, options)
1024 static loadByUUID (uuid: string) {
1032 .scope([ ScopeNames.WITH_FILES ])
1036 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1038 order: [ [ 'Tags', 'name', 'ASC' ] ],
1047 ScopeNames.WITH_TAGS,
1048 ScopeNames.WITH_BLACKLISTED,
1049 ScopeNames.WITH_FILES,
1050 ScopeNames.WITH_ACCOUNT_DETAILS,
1051 ScopeNames.WITH_SCHEDULED_UPDATE
1056 static async getStats () {
1057 const totalLocalVideos = await VideoModel.count({
1062 const totalVideos = await VideoModel.count()
1064 let totalLocalVideoViews = await VideoModel.sum('views', {
1069 // Sequelize could return null...
1070 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1074 totalLocalVideoViews,
1079 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1080 if (filter && filter === 'local') {
1089 private static getCategoryLabel (id: number) {
1090 return VIDEO_CATEGORIES[id] || 'Misc'
1093 private static getLicenceLabel (id: number) {
1094 return VIDEO_LICENCES[id] || 'Unknown'
1097 private static getLanguageLabel (id: string) {
1098 return VIDEO_LANGUAGES[id] || 'Unknown'
1101 private static getPrivacyLabel (id: number) {
1102 return VIDEO_PRIVACIES[id] || 'Unknown'
1105 private static getStateLabel (id: number) {
1106 return VIDEO_STATES[id] || 'Unknown'
1109 getOriginalFile () {
1110 if (Array.isArray(this.VideoFiles) === false) return undefined
1112 // The original file is the file that have the higher resolution
1113 return maxBy(this.VideoFiles, file => file.resolution)
1116 getVideoFilename (videoFile: VideoFileModel) {
1117 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1120 getThumbnailName () {
1121 // We always have a copy of the thumbnail
1122 const extension = '.jpg'
1123 return this.uuid + extension
1127 const extension = '.jpg'
1128 return this.uuid + extension
1131 getTorrentFileName (videoFile: VideoFileModel) {
1132 const extension = '.torrent'
1133 return this.uuid + '-' + videoFile.resolution + extension
1137 return this.remote === false
1140 createPreview (videoFile: VideoFileModel) {
1141 return generateImageFromVideoFile(
1142 this.getVideoFilePath(videoFile),
1143 CONFIG.STORAGE.PREVIEWS_DIR,
1144 this.getPreviewName(),
1149 createThumbnail (videoFile: VideoFileModel) {
1150 return generateImageFromVideoFile(
1151 this.getVideoFilePath(videoFile),
1152 CONFIG.STORAGE.THUMBNAILS_DIR,
1153 this.getThumbnailName(),
1158 getTorrentFilePath (videoFile: VideoFileModel) {
1159 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1162 getVideoFilePath (videoFile: VideoFileModel) {
1163 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1166 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1168 // Keep the extname, it's used by the client to stream the file inside a web browser
1169 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1170 createdBy: 'PeerTube',
1172 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1173 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1176 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1180 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1182 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1183 logger.info('Creating torrent %s.', filePath)
1185 await writeFilePromise(filePath, torrent)
1187 const parsedTorrent = parseTorrent(torrent)
1188 videoFile.infoHash = parsedTorrent.infoHash
1191 getEmbedStaticPath () {
1192 return '/videos/embed/' + this.uuid
1195 getThumbnailStaticPath () {
1196 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1199 getPreviewStaticPath () {
1200 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1203 toFormattedJSON (options?: {
1204 additionalAttributes: {
1206 waitTranscoding?: boolean,
1207 scheduledUpdate?: boolean,
1208 blacklistInfo?: boolean
1211 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1212 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1214 const videoObject: Video = {
1220 label: VideoModel.getCategoryLabel(this.category)
1224 label: VideoModel.getLicenceLabel(this.licence)
1228 label: VideoModel.getLanguageLabel(this.language)
1232 label: VideoModel.getPrivacyLabel(this.privacy)
1235 description: this.getTruncatedDescription(),
1236 isLocal: this.isOwned(),
1237 duration: this.duration,
1240 dislikes: this.dislikes,
1241 thumbnailPath: this.getThumbnailStaticPath(),
1242 previewPath: this.getPreviewStaticPath(),
1243 embedPath: this.getEmbedStaticPath(),
1244 createdAt: this.createdAt,
1245 updatedAt: this.updatedAt,
1246 publishedAt: this.publishedAt,
1248 id: formattedAccount.id,
1249 uuid: formattedAccount.uuid,
1250 name: formattedAccount.name,
1251 displayName: formattedAccount.displayName,
1252 url: formattedAccount.url,
1253 host: formattedAccount.host,
1254 avatar: formattedAccount.avatar
1257 id: formattedVideoChannel.id,
1258 uuid: formattedVideoChannel.uuid,
1259 name: formattedVideoChannel.name,
1260 displayName: formattedVideoChannel.displayName,
1261 url: formattedVideoChannel.url,
1262 host: formattedVideoChannel.host,
1263 avatar: formattedVideoChannel.avatar
1268 if (options.additionalAttributes.state === true) {
1269 videoObject.state = {
1271 label: VideoModel.getStateLabel(this.state)
1275 if (options.additionalAttributes.waitTranscoding === true) {
1276 videoObject.waitTranscoding = this.waitTranscoding
1279 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1280 videoObject.scheduledUpdate = {
1281 updateAt: this.ScheduleVideoUpdate.updateAt,
1282 privacy: this.ScheduleVideoUpdate.privacy || undefined
1286 if (options.additionalAttributes.blacklistInfo === true) {
1287 videoObject.blacklisted = !!this.VideoBlacklist
1288 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1295 toFormattedDetailsJSON (): VideoDetails {
1296 const formattedJson = this.toFormattedJSON({
1297 additionalAttributes: {
1298 scheduledUpdate: true,
1303 const detailsJson = {
1304 support: this.support,
1305 descriptionPath: this.getDescriptionPath(),
1306 channel: this.VideoChannel.toFormattedJSON(),
1307 account: this.VideoChannel.Account.toFormattedJSON(),
1308 tags: map(this.Tags, 'name'),
1309 commentsEnabled: this.commentsEnabled,
1310 waitTranscoding: this.waitTranscoding,
1313 label: VideoModel.getStateLabel(this.state)
1318 // Format and sort video files
1319 detailsJson.files = this.getFormattedVideoFilesJSON()
1321 return Object.assign(formattedJson, detailsJson)
1324 getFormattedVideoFilesJSON (): VideoFile[] {
1325 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1327 return this.VideoFiles
1329 let resolutionLabel = videoFile.resolution + 'p'
1333 id: videoFile.resolution,
1334 label: resolutionLabel
1336 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1337 size: videoFile.size,
1339 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1340 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1341 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1342 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1346 if (a.resolution.id < b.resolution.id) return 1
1347 if (a.resolution.id === b.resolution.id) return 0
1352 toActivityPubObject (): VideoTorrentObject {
1353 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1354 if (!this.Tags) this.Tags = []
1356 const tag = this.Tags.map(t => ({
1357 type: 'Hashtag' as 'Hashtag',
1362 if (this.language) {
1364 identifier: this.language,
1365 name: VideoModel.getLanguageLabel(this.language)
1370 if (this.category) {
1372 identifier: this.category + '',
1373 name: VideoModel.getCategoryLabel(this.category)
1380 identifier: this.licence + '',
1381 name: VideoModel.getLicenceLabel(this.licence)
1386 for (const file of this.VideoFiles) {
1389 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1390 href: this.getVideoFileUrl(file, baseUrlHttp),
1391 height: file.resolution,
1398 mimeType: 'application/x-bittorrent',
1399 href: this.getTorrentUrl(file, baseUrlHttp),
1400 height: file.resolution
1405 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1406 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1407 height: file.resolution
1411 // Add video url too
1414 mimeType: 'text/html',
1415 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1418 const subtitleLanguage = []
1419 for (const caption of this.VideoCaptions) {
1420 subtitleLanguage.push({
1421 identifier: caption.language,
1422 name: VideoCaptionModel.getLanguageLabel(caption.language)
1427 type: 'Video' as 'Video',
1430 duration: this.getActivityStreamDuration(),
1437 sensitive: this.nsfw,
1438 waitTranscoding: this.waitTranscoding,
1440 commentsEnabled: this.commentsEnabled,
1441 published: this.publishedAt.toISOString(),
1442 updated: this.updatedAt.toISOString(),
1443 mediaType: 'text/markdown',
1444 content: this.getTruncatedDescription(),
1445 support: this.support,
1449 url: this.getThumbnailUrl(baseUrlHttp),
1450 mediaType: 'image/jpeg',
1451 width: THUMBNAILS_SIZE.width,
1452 height: THUMBNAILS_SIZE.height
1455 likes: getVideoLikesActivityPubUrl(this),
1456 dislikes: getVideoDislikesActivityPubUrl(this),
1457 shares: getVideoSharesActivityPubUrl(this),
1458 comments: getVideoCommentsActivityPubUrl(this),
1462 id: this.VideoChannel.Account.Actor.url
1466 id: this.VideoChannel.Actor.url
1472 getTruncatedDescription () {
1473 if (!this.description) return null
1475 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1476 return peertubeTruncate(this.description, maxLength)
1479 async optimizeOriginalVideofile () {
1480 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1481 const newExtname = '.mp4'
1482 const inputVideoFile = this.getOriginalFile()
1483 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1484 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1486 const transcodeOptions = {
1487 inputPath: videoInputPath,
1488 outputPath: videoTranscodedPath
1491 // Could be very long!
1492 await transcode(transcodeOptions)
1495 await unlinkPromise(videoInputPath)
1497 // Important to do this before getVideoFilename() to take in account the new file extension
1498 inputVideoFile.set('extname', newExtname)
1500 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1501 await renamePromise(videoTranscodedPath, videoOutputPath)
1502 const stats = await statPromise(videoOutputPath)
1503 const fps = await getVideoFileFPS(videoOutputPath)
1505 inputVideoFile.set('size', stats.size)
1506 inputVideoFile.set('fps', fps)
1508 await this.createTorrentAndSetInfoHash(inputVideoFile)
1509 await inputVideoFile.save()
1512 // Auto destruction...
1513 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1519 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1520 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1521 const extname = '.mp4'
1523 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1524 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1526 const newVideoFile = new VideoFileModel({
1532 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1534 const transcodeOptions = {
1535 inputPath: videoInputPath,
1536 outputPath: videoOutputPath,
1541 await transcode(transcodeOptions)
1543 const stats = await statPromise(videoOutputPath)
1544 const fps = await getVideoFileFPS(videoOutputPath)
1546 newVideoFile.set('size', stats.size)
1547 newVideoFile.set('fps', fps)
1549 await this.createTorrentAndSetInfoHash(newVideoFile)
1551 await newVideoFile.save()
1553 this.VideoFiles.push(newVideoFile)
1556 async importVideoFile (inputFilePath: string) {
1557 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1558 const { size } = await statPromise(inputFilePath)
1559 const fps = await getVideoFileFPS(inputFilePath)
1561 let updatedVideoFile = new VideoFileModel({
1562 resolution: videoFileResolution,
1563 extname: extname(inputFilePath),
1569 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1571 if (currentVideoFile) {
1572 // Remove old file and old torrent
1573 await this.removeFile(currentVideoFile)
1574 await this.removeTorrent(currentVideoFile)
1575 // Remove the old video file from the array
1576 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1578 // Update the database
1579 currentVideoFile.set('extname', updatedVideoFile.extname)
1580 currentVideoFile.set('size', updatedVideoFile.size)
1581 currentVideoFile.set('fps', updatedVideoFile.fps)
1583 updatedVideoFile = currentVideoFile
1586 const outputPath = this.getVideoFilePath(updatedVideoFile)
1587 await copyFilePromise(inputFilePath, outputPath)
1589 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1591 await updatedVideoFile.save()
1593 this.VideoFiles.push(updatedVideoFile)
1596 getOriginalFileResolution () {
1597 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1599 return getVideoFileResolution(originalFilePath)
1602 getDescriptionPath () {
1603 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1606 removeThumbnail () {
1607 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1608 return unlinkPromise(thumbnailPath)
1609 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1613 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1614 return unlinkPromise(previewPath)
1615 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1618 removeFile (videoFile: VideoFileModel) {
1619 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1620 return unlinkPromise(filePath)
1621 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1624 removeTorrent (videoFile: VideoFileModel) {
1625 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1626 return unlinkPromise(torrentPath)
1627 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1630 getActivityStreamDuration () {
1631 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1632 return 'PT' + this.duration + 'S'
1636 if (this.isOwned()) return false
1638 const now = Date.now()
1639 const createdAtTime = this.createdAt.getTime()
1640 const updatedAtTime = this.updatedAt.getTime()
1642 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1643 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1646 private getBaseUrls () {
1650 if (this.isOwned()) {
1651 baseUrlHttp = CONFIG.WEBSERVER.URL
1652 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1654 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1655 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1658 return { baseUrlHttp, baseUrlWs }
1661 private getThumbnailUrl (baseUrlHttp: string) {
1662 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1665 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1666 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1669 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1670 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1673 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1674 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1677 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1678 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1681 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1682 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1683 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1684 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1686 const magnetHash = {
1690 infoHash: videoFile.infoHash,
1694 return magnetUtil.encode(magnetHash)