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, createSearchTrigramQuery, 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 { VideosSearchQuery } from '../../../shared/models/search'
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'),
103 fields: [ 'createdAt' ]
106 fields: [ 'duration' ]
118 fields: [ 'channelId' ]
121 fields: [ 'id', 'privacy', 'state', 'waitTranscoding' ]
129 export enum ScopeNames {
130 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
131 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
132 WITH_TAGS = 'WITH_TAGS',
133 WITH_FILES = 'WITH_FILES',
134 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE'
137 type AvailableForListOptions = {
139 filter?: VideoFilter,
140 categoryOneOf?: number[],
142 licenceOneOf?: number[],
143 languageOneOf?: string[],
144 tagsOneOf?: string[],
145 tagsAllOf?: string[],
148 videoChannelId?: number
152 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
153 const accountInclude = {
154 attributes: [ 'id', 'name' ],
155 model: AccountModel.unscoped(),
160 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
161 model: ActorModel.unscoped(),
163 where: VideoModel.buildActorWhereWithFilter(options.filter),
166 attributes: [ 'host' ],
167 model: ServerModel.unscoped(),
171 model: AvatarModel.unscoped(),
179 const videoChannelInclude = {
180 attributes: [ 'name', 'description', 'id' ],
181 model: VideoChannelModel.unscoped(),
186 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
187 model: ActorModel.unscoped(),
191 attributes: [ 'host' ],
192 model: ServerModel.unscoped(),
196 model: AvatarModel.unscoped(),
205 // Force actorId to be a number to avoid SQL injections
206 const actorIdNumber = parseInt(options.actorId.toString(), 10)
207 const query: IFindOptions<VideoModel> = {
210 [Sequelize.Op.notIn]: Sequelize.literal(
211 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
213 [ Sequelize.Op.in ]: Sequelize.literal(
215 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
216 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
217 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
219 'SELECT "video"."id" AS "id" FROM "video" ' +
220 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
221 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
222 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
223 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
224 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
228 // Always list public videos
229 privacy: VideoPrivacy.PUBLIC,
230 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
231 [ Sequelize.Op.or ]: [
233 state: VideoState.PUBLISHED
236 [ Sequelize.Op.and ]: {
237 state: VideoState.TO_TRANSCODE,
238 waitTranscoding: false
243 include: [ videoChannelInclude ]
246 if (options.withFiles === true) {
248 model: VideoFileModel.unscoped(),
253 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
254 if (options.tagsAllOf || options.tagsOneOf) {
255 const createTagsIn = (tags: string[]) => {
256 return tags.map(t => VideoModel.sequelize.escape(t))
260 if (options.tagsOneOf) {
261 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
263 'SELECT "videoId" FROM "videoTag" ' +
264 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
265 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
270 if (options.tagsAllOf) {
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.tagsAllOf) + ')' +
276 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
282 if (options.nsfw === true || options.nsfw === false) {
283 query.where['nsfw'] = options.nsfw
286 if (options.categoryOneOf) {
287 query.where['category'] = {
288 [Sequelize.Op.or]: options.categoryOneOf
292 if (options.licenceOneOf) {
293 query.where['licence'] = {
294 [Sequelize.Op.or]: options.licenceOneOf
298 if (options.languageOneOf) {
299 query.where['language'] = {
300 [Sequelize.Op.or]: options.languageOneOf
304 if (options.accountId) {
305 accountInclude.where = {
306 id: options.accountId
310 if (options.videoChannelId) {
311 videoChannelInclude.where = {
312 id: options.videoChannelId
318 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
321 model: () => VideoChannelModel.unscoped(),
326 exclude: [ 'privateKey', 'publicKey' ]
328 model: () => ActorModel.unscoped(),
332 attributes: [ 'host' ],
333 model: () => ServerModel.unscoped(),
337 model: () => AvatarModel.unscoped(),
343 model: () => AccountModel.unscoped(),
347 model: () => ActorModel.unscoped(),
349 exclude: [ 'privateKey', 'publicKey' ]
354 attributes: [ 'host' ],
355 model: () => ServerModel.unscoped(),
359 model: () => AvatarModel.unscoped(),
370 [ScopeNames.WITH_TAGS]: {
371 include: [ () => TagModel ]
373 [ScopeNames.WITH_FILES]: {
376 model: () => VideoFileModel.unscoped(),
381 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
384 model: () => ScheduleVideoUpdateModel.unscoped(),
394 export class VideoModel extends Model<VideoModel> {
397 @Default(DataType.UUIDV4)
399 @Column(DataType.UUID)
403 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
409 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
415 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
421 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
422 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
426 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
431 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
437 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
438 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
443 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
444 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
448 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
478 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
479 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
484 commentsEnabled: boolean
488 waitTranscoding: boolean
492 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
503 @Default(Sequelize.NOW)
507 @ForeignKey(() => VideoChannelModel)
511 @BelongsTo(() => VideoChannelModel, {
517 VideoChannel: VideoChannelModel
519 @BelongsToMany(() => TagModel, {
520 foreignKey: 'videoId',
521 through: () => VideoTagModel,
526 @HasMany(() => VideoAbuseModel, {
533 VideoAbuses: VideoAbuseModel[]
535 @HasMany(() => VideoFileModel, {
542 VideoFiles: VideoFileModel[]
544 @HasMany(() => VideoShareModel, {
551 VideoShares: VideoShareModel[]
553 @HasMany(() => AccountVideoRateModel, {
560 AccountVideoRates: AccountVideoRateModel[]
562 @HasMany(() => VideoCommentModel, {
570 VideoComments: VideoCommentModel[]
572 @HasOne(() => ScheduleVideoUpdateModel, {
579 ScheduleVideoUpdate: ScheduleVideoUpdateModel
581 @HasMany(() => VideoCaptionModel, {
588 ['separate' as any]: true
590 VideoCaptions: VideoCaptionModel[]
593 static async sendDelete (instance: VideoModel, options) {
594 if (instance.isOwned()) {
595 if (!instance.VideoChannel) {
596 instance.VideoChannel = await instance.$get('VideoChannel', {
600 include: [ ActorModel ]
603 transaction: options.transaction
604 }) as VideoChannelModel
607 logger.debug('Sending delete of video %s.', instance.url)
609 return sendDeleteVideo(instance, options.transaction)
616 static async removeFiles (instance: VideoModel) {
617 const tasks: Promise<any>[] = []
619 logger.debug('Removing files of video %s.', instance.url)
621 tasks.push(instance.removeThumbnail())
623 if (instance.isOwned()) {
624 if (!Array.isArray(instance.VideoFiles)) {
625 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
628 tasks.push(instance.removePreview())
630 // Remove physical files and torrents
631 instance.VideoFiles.forEach(file => {
632 tasks.push(instance.removeFile(file))
633 tasks.push(instance.removeTorrent(file))
637 // Do not wait video deletion because we could be in a transaction
640 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
647 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
650 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
651 function getRawQuery (select: string) {
652 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
653 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
654 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
655 'WHERE "Account"."actorId" = ' + actorId
656 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
657 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
658 'WHERE "VideoShare"."actorId" = ' + actorId
660 return `(${queryVideo}) UNION (${queryVideoShare})`
663 const rawQuery = getRawQuery('"Video"."id"')
664 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
670 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
673 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
676 { privacy: VideoPrivacy.PUBLIC },
677 { privacy: VideoPrivacy.UNLISTED }
682 attributes: [ 'language' ],
683 model: VideoCaptionModel.unscoped(),
687 attributes: [ 'id', 'url' ],
688 model: VideoShareModel.unscoped(),
690 // We only want videos shared by this actor
692 [Sequelize.Op.and]: [
695 [Sequelize.Op.not]: null
705 attributes: [ 'id', 'url' ],
706 model: ActorModel.unscoped()
711 model: VideoChannelModel.unscoped(),
715 attributes: [ 'name' ],
716 model: AccountModel.unscoped(),
720 attributes: [ 'id', 'url', 'followersUrl' ],
721 model: ActorModel.unscoped(),
727 attributes: [ 'id', 'url', 'followersUrl' ],
728 model: ActorModel.unscoped(),
738 return Bluebird.all([
739 // FIXME: typing issue
740 VideoModel.findAll(query as any),
741 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
742 ]).then(([ rows, totals ]) => {
743 // totals: totalVideos + totalVideoShares
745 let totalVideoShares = 0
746 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
747 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
749 const total = totalVideos + totalVideoShares
757 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
758 const query: IFindOptions<VideoModel> = {
761 order: getSort(sort),
764 model: VideoChannelModel,
777 model: ScheduleVideoUpdateModel,
783 if (withFiles === true) {
785 model: VideoFileModel.unscoped(),
790 if (hideNSFW === true) {
796 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
804 static async listForApi (options: {
810 categoryOneOf?: number[],
811 licenceOneOf?: number[],
812 languageOneOf?: string[],
813 tagsOneOf?: string[],
814 tagsAllOf?: string[],
815 filter?: VideoFilter,
817 videoChannelId?: number
820 offset: options.start,
821 limit: options.count,
822 order: getSort(options.sort)
825 const serverActor = await getServerActor()
828 ScopeNames.AVAILABLE_FOR_LIST, {
829 actorId: serverActor.id,
831 categoryOneOf: options.categoryOneOf,
832 licenceOneOf: options.licenceOneOf,
833 languageOneOf: options.languageOneOf,
834 tagsOneOf: options.tagsOneOf,
835 tagsAllOf: options.tagsAllOf,
836 filter: options.filter,
837 withFiles: options.withFiles,
838 accountId: options.accountId,
839 videoChannelId: options.videoChannelId
840 } as AvailableForListOptions
844 return VideoModel.scope(scopes)
845 .findAndCountAll(query)
846 .then(({ rows, count }) => {
854 static async searchAndPopulateAccountAndServer (options: {
859 startDate?: string // ISO 8601
860 endDate?: string // ISO 8601
862 categoryOneOf?: number[]
863 licenceOneOf?: number[]
864 languageOneOf?: string[]
867 durationMin?: number // seconds
868 durationMax?: number // seconds
872 if (options.startDate || options.endDate) {
873 const publishedAtRange = { }
875 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
876 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
878 whereAnd.push({ publishedAt: publishedAtRange })
881 if (options.durationMin || options.durationMax) {
882 const durationRange = { }
884 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
885 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
887 whereAnd.push({ duration: durationRange })
890 whereAnd.push(createSearchTrigramQuery('VideoModel.name', options.search))
892 const query: IFindOptions<VideoModel> = {
894 include: [ createSimilarityAttribute('VideoModel.name', options.search) ]
896 offset: options.start,
897 limit: options.count,
898 order: getSort(options.sort),
900 [ Sequelize.Op.and ]: whereAnd
904 const serverActor = await getServerActor()
907 ScopeNames.AVAILABLE_FOR_LIST, {
908 actorId: serverActor.id,
910 categoryOneOf: options.categoryOneOf,
911 licenceOneOf: options.licenceOneOf,
912 languageOneOf: options.languageOneOf,
913 tagsOneOf: options.tagsOneOf,
914 tagsAllOf: options.tagsAllOf
915 } as AvailableForListOptions
919 return VideoModel.scope(scopes)
920 .findAndCountAll(query)
921 .then(({ rows, count }) => {
929 static load (id: number) {
930 return VideoModel.findById(id)
933 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
934 const query: IFindOptions<VideoModel> = {
940 if (t !== undefined) query.transaction = t
942 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
945 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
946 const query: IFindOptions<VideoModel> = {
955 if (t !== undefined) query.transaction = t
957 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
960 static loadAndPopulateAccountAndServerAndTags (id: number) {
962 order: [ [ 'Tags', 'name', 'ASC' ] ]
966 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
967 .findById(id, options)
970 static loadByUUID (uuid: string) {
978 .scope([ ScopeNames.WITH_FILES ])
982 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
984 order: [ [ 'Tags', 'name', 'ASC' ] ],
992 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
996 static async getStats () {
997 const totalLocalVideos = await VideoModel.count({
1002 const totalVideos = await VideoModel.count()
1004 let totalLocalVideoViews = await VideoModel.sum('views', {
1009 // Sequelize could return null...
1010 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1014 totalLocalVideoViews,
1019 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1020 if (filter && filter === 'local') {
1029 private static getCategoryLabel (id: number) {
1030 return VIDEO_CATEGORIES[id] || 'Misc'
1033 private static getLicenceLabel (id: number) {
1034 return VIDEO_LICENCES[id] || 'Unknown'
1037 private static getLanguageLabel (id: string) {
1038 return VIDEO_LANGUAGES[id] || 'Unknown'
1041 private static getPrivacyLabel (id: number) {
1042 return VIDEO_PRIVACIES[id] || 'Unknown'
1045 private static getStateLabel (id: number) {
1046 return VIDEO_STATES[id] || 'Unknown'
1049 getOriginalFile () {
1050 if (Array.isArray(this.VideoFiles) === false) return undefined
1052 // The original file is the file that have the higher resolution
1053 return maxBy(this.VideoFiles, file => file.resolution)
1056 getVideoFilename (videoFile: VideoFileModel) {
1057 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1060 getThumbnailName () {
1061 // We always have a copy of the thumbnail
1062 const extension = '.jpg'
1063 return this.uuid + extension
1067 const extension = '.jpg'
1068 return this.uuid + extension
1071 getTorrentFileName (videoFile: VideoFileModel) {
1072 const extension = '.torrent'
1073 return this.uuid + '-' + videoFile.resolution + extension
1077 return this.remote === false
1080 createPreview (videoFile: VideoFileModel) {
1081 return generateImageFromVideoFile(
1082 this.getVideoFilePath(videoFile),
1083 CONFIG.STORAGE.PREVIEWS_DIR,
1084 this.getPreviewName(),
1089 createThumbnail (videoFile: VideoFileModel) {
1090 return generateImageFromVideoFile(
1091 this.getVideoFilePath(videoFile),
1092 CONFIG.STORAGE.THUMBNAILS_DIR,
1093 this.getThumbnailName(),
1098 getTorrentFilePath (videoFile: VideoFileModel) {
1099 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1102 getVideoFilePath (videoFile: VideoFileModel) {
1103 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1106 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1108 // Keep the extname, it's used by the client to stream the file inside a web browser
1109 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1110 createdBy: 'PeerTube',
1112 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1113 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1116 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1120 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1122 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1123 logger.info('Creating torrent %s.', filePath)
1125 await writeFilePromise(filePath, torrent)
1127 const parsedTorrent = parseTorrent(torrent)
1128 videoFile.infoHash = parsedTorrent.infoHash
1131 getEmbedStaticPath () {
1132 return '/videos/embed/' + this.uuid
1135 getThumbnailStaticPath () {
1136 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1139 getPreviewStaticPath () {
1140 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1143 toFormattedJSON (options?: {
1144 additionalAttributes: {
1146 waitTranscoding?: boolean,
1147 scheduledUpdate?: boolean
1150 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1151 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1153 const videoObject: Video = {
1159 label: VideoModel.getCategoryLabel(this.category)
1163 label: VideoModel.getLicenceLabel(this.licence)
1167 label: VideoModel.getLanguageLabel(this.language)
1171 label: VideoModel.getPrivacyLabel(this.privacy)
1174 description: this.getTruncatedDescription(),
1175 isLocal: this.isOwned(),
1176 duration: this.duration,
1179 dislikes: this.dislikes,
1180 thumbnailPath: this.getThumbnailStaticPath(),
1181 previewPath: this.getPreviewStaticPath(),
1182 embedPath: this.getEmbedStaticPath(),
1183 createdAt: this.createdAt,
1184 updatedAt: this.updatedAt,
1185 publishedAt: this.publishedAt,
1187 id: formattedAccount.id,
1188 uuid: formattedAccount.uuid,
1189 name: formattedAccount.name,
1190 displayName: formattedAccount.displayName,
1191 url: formattedAccount.url,
1192 host: formattedAccount.host,
1193 avatar: formattedAccount.avatar
1196 id: formattedVideoChannel.id,
1197 uuid: formattedVideoChannel.uuid,
1198 name: formattedVideoChannel.name,
1199 displayName: formattedVideoChannel.displayName,
1200 url: formattedVideoChannel.url,
1201 host: formattedVideoChannel.host,
1202 avatar: formattedVideoChannel.avatar
1207 if (options.additionalAttributes.state === true) {
1208 videoObject.state = {
1210 label: VideoModel.getStateLabel(this.state)
1214 if (options.additionalAttributes.waitTranscoding === true) {
1215 videoObject.waitTranscoding = this.waitTranscoding
1218 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1219 videoObject.scheduledUpdate = {
1220 updateAt: this.ScheduleVideoUpdate.updateAt,
1221 privacy: this.ScheduleVideoUpdate.privacy || undefined
1229 toFormattedDetailsJSON (): VideoDetails {
1230 const formattedJson = this.toFormattedJSON({
1231 additionalAttributes: {
1232 scheduledUpdate: true
1236 const detailsJson = {
1237 support: this.support,
1238 descriptionPath: this.getDescriptionPath(),
1239 channel: this.VideoChannel.toFormattedJSON(),
1240 account: this.VideoChannel.Account.toFormattedJSON(),
1241 tags: map(this.Tags, 'name'),
1242 commentsEnabled: this.commentsEnabled,
1243 waitTranscoding: this.waitTranscoding,
1246 label: VideoModel.getStateLabel(this.state)
1251 // Format and sort video files
1252 detailsJson.files = this.getFormattedVideoFilesJSON()
1254 return Object.assign(formattedJson, detailsJson)
1257 getFormattedVideoFilesJSON (): VideoFile[] {
1258 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1260 return this.VideoFiles
1262 let resolutionLabel = videoFile.resolution + 'p'
1266 id: videoFile.resolution,
1267 label: resolutionLabel
1269 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1270 size: videoFile.size,
1272 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1273 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1274 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1275 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1279 if (a.resolution.id < b.resolution.id) return 1
1280 if (a.resolution.id === b.resolution.id) return 0
1285 toActivityPubObject (): VideoTorrentObject {
1286 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1287 if (!this.Tags) this.Tags = []
1289 const tag = this.Tags.map(t => ({
1290 type: 'Hashtag' as 'Hashtag',
1295 if (this.language) {
1297 identifier: this.language,
1298 name: VideoModel.getLanguageLabel(this.language)
1303 if (this.category) {
1305 identifier: this.category + '',
1306 name: VideoModel.getCategoryLabel(this.category)
1313 identifier: this.licence + '',
1314 name: VideoModel.getLicenceLabel(this.licence)
1319 for (const file of this.VideoFiles) {
1322 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1323 href: this.getVideoFileUrl(file, baseUrlHttp),
1324 width: file.resolution,
1330 mimeType: 'application/x-bittorrent',
1331 href: this.getTorrentUrl(file, baseUrlHttp),
1332 width: file.resolution
1337 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1338 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1339 width: file.resolution
1343 // Add video url too
1346 mimeType: 'text/html',
1347 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1350 const subtitleLanguage = []
1351 for (const caption of this.VideoCaptions) {
1352 subtitleLanguage.push({
1353 identifier: caption.language,
1354 name: VideoCaptionModel.getLanguageLabel(caption.language)
1359 type: 'Video' as 'Video',
1362 duration: this.getActivityStreamDuration(),
1369 sensitive: this.nsfw,
1370 waitTranscoding: this.waitTranscoding,
1372 commentsEnabled: this.commentsEnabled,
1373 published: this.publishedAt.toISOString(),
1374 updated: this.updatedAt.toISOString(),
1375 mediaType: 'text/markdown',
1376 content: this.getTruncatedDescription(),
1377 support: this.support,
1381 url: this.getThumbnailUrl(baseUrlHttp),
1382 mediaType: 'image/jpeg',
1383 width: THUMBNAILS_SIZE.width,
1384 height: THUMBNAILS_SIZE.height
1387 likes: getVideoLikesActivityPubUrl(this),
1388 dislikes: getVideoDislikesActivityPubUrl(this),
1389 shares: getVideoSharesActivityPubUrl(this),
1390 comments: getVideoCommentsActivityPubUrl(this),
1394 id: this.VideoChannel.Account.Actor.url
1398 id: this.VideoChannel.Actor.url
1404 getTruncatedDescription () {
1405 if (!this.description) return null
1407 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1408 return peertubeTruncate(this.description, maxLength)
1411 async optimizeOriginalVideofile () {
1412 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1413 const newExtname = '.mp4'
1414 const inputVideoFile = this.getOriginalFile()
1415 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1416 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1418 const transcodeOptions = {
1419 inputPath: videoInputPath,
1420 outputPath: videoTranscodedPath
1423 // Could be very long!
1424 await transcode(transcodeOptions)
1427 await unlinkPromise(videoInputPath)
1429 // Important to do this before getVideoFilename() to take in account the new file extension
1430 inputVideoFile.set('extname', newExtname)
1432 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1433 await renamePromise(videoTranscodedPath, videoOutputPath)
1434 const stats = await statPromise(videoOutputPath)
1435 const fps = await getVideoFileFPS(videoOutputPath)
1437 inputVideoFile.set('size', stats.size)
1438 inputVideoFile.set('fps', fps)
1440 await this.createTorrentAndSetInfoHash(inputVideoFile)
1441 await inputVideoFile.save()
1444 // Auto destruction...
1445 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1451 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1452 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1453 const extname = '.mp4'
1455 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1456 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1458 const newVideoFile = new VideoFileModel({
1464 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1466 const transcodeOptions = {
1467 inputPath: videoInputPath,
1468 outputPath: videoOutputPath,
1473 await transcode(transcodeOptions)
1475 const stats = await statPromise(videoOutputPath)
1476 const fps = await getVideoFileFPS(videoOutputPath)
1478 newVideoFile.set('size', stats.size)
1479 newVideoFile.set('fps', fps)
1481 await this.createTorrentAndSetInfoHash(newVideoFile)
1483 await newVideoFile.save()
1485 this.VideoFiles.push(newVideoFile)
1488 async importVideoFile (inputFilePath: string) {
1489 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1490 const { size } = await statPromise(inputFilePath)
1491 const fps = await getVideoFileFPS(inputFilePath)
1493 let updatedVideoFile = new VideoFileModel({
1494 resolution: videoFileResolution,
1495 extname: extname(inputFilePath),
1501 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1503 if (currentVideoFile) {
1504 // Remove old file and old torrent
1505 await this.removeFile(currentVideoFile)
1506 await this.removeTorrent(currentVideoFile)
1507 // Remove the old video file from the array
1508 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1510 // Update the database
1511 currentVideoFile.set('extname', updatedVideoFile.extname)
1512 currentVideoFile.set('size', updatedVideoFile.size)
1513 currentVideoFile.set('fps', updatedVideoFile.fps)
1515 updatedVideoFile = currentVideoFile
1518 const outputPath = this.getVideoFilePath(updatedVideoFile)
1519 await copyFilePromise(inputFilePath, outputPath)
1521 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1523 await updatedVideoFile.save()
1525 this.VideoFiles.push(updatedVideoFile)
1528 getOriginalFileResolution () {
1529 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1531 return getVideoFileResolution(originalFilePath)
1534 getDescriptionPath () {
1535 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1538 removeThumbnail () {
1539 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1540 return unlinkPromise(thumbnailPath)
1544 // Same name than video thumbnail
1545 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1548 removeFile (videoFile: VideoFileModel) {
1549 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1550 return unlinkPromise(filePath)
1553 removeTorrent (videoFile: VideoFileModel) {
1554 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1555 return unlinkPromise(torrentPath)
1558 getActivityStreamDuration () {
1559 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1560 return 'PT' + this.duration + 'S'
1563 private getBaseUrls () {
1567 if (this.isOwned()) {
1568 baseUrlHttp = CONFIG.WEBSERVER.URL
1569 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1571 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1572 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1575 return { baseUrlHttp, baseUrlWs }
1578 private getThumbnailUrl (baseUrlHttp: string) {
1579 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1582 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1583 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1586 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1587 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1590 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1591 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1594 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1595 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1598 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1599 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1600 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1601 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1603 const magnetHash = {
1607 infoHash: videoFile.infoHash,
1611 return magnetUtil.encode(magnetHash)