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'),
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'
133 type AvailableForListOptions = {
135 filter?: VideoFilter,
136 categoryOneOf?: number[],
138 licenceOneOf?: number[],
139 languageOneOf?: string[],
140 tagsOneOf?: string[],
141 tagsAllOf?: string[],
144 videoChannelId?: number
148 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
149 const accountInclude = {
150 attributes: [ 'id', 'name' ],
151 model: AccountModel.unscoped(),
156 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
157 model: ActorModel.unscoped(),
159 where: VideoModel.buildActorWhereWithFilter(options.filter),
162 attributes: [ 'host' ],
163 model: ServerModel.unscoped(),
167 model: AvatarModel.unscoped(),
175 const videoChannelInclude = {
176 attributes: [ 'name', 'description', 'id' ],
177 model: VideoChannelModel.unscoped(),
182 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
183 model: ActorModel.unscoped(),
187 attributes: [ 'host' ],
188 model: ServerModel.unscoped(),
192 model: AvatarModel.unscoped(),
201 // Force actorId to be a number to avoid SQL injections
202 const actorIdNumber = parseInt(options.actorId.toString(), 10)
203 const query: IFindOptions<VideoModel> = {
206 [Sequelize.Op.notIn]: Sequelize.literal(
207 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
209 [ Sequelize.Op.in ]: Sequelize.literal(
211 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
212 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
213 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
215 'SELECT "video"."id" AS "id" FROM "video" ' +
216 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
217 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
218 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
219 'WHERE "actor"."serverId" IS NULL OR ' +
220 '"actor"."id" IN (SELECT "targetActorId" FROM "actorFollow" WHERE "actorId" = 1)' + // Subquery for optimization
224 // Always list public videos
225 privacy: VideoPrivacy.PUBLIC,
226 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
227 [ Sequelize.Op.or ]: [
229 state: VideoState.PUBLISHED
232 [ Sequelize.Op.and ]: {
233 state: VideoState.TO_TRANSCODE,
234 waitTranscoding: false
239 include: [ videoChannelInclude ]
242 if (options.withFiles === true) {
244 model: VideoFileModel.unscoped(),
249 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
250 if (options.tagsAllOf || options.tagsOneOf) {
251 const createTagsIn = (tags: string[]) => {
252 return tags.map(t => VideoModel.sequelize.escape(t))
256 if (options.tagsOneOf) {
257 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
259 'SELECT "videoId" FROM "videoTag" ' +
260 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
261 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
266 if (options.tagsAllOf) {
267 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
269 'SELECT "videoId" FROM "videoTag" ' +
270 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
271 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
272 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
278 if (options.nsfw === true || options.nsfw === false) {
279 query.where['nsfw'] = options.nsfw
282 if (options.categoryOneOf) {
283 query.where['category'] = {
284 [Sequelize.Op.or]: options.categoryOneOf
288 if (options.licenceOneOf) {
289 query.where['licence'] = {
290 [Sequelize.Op.or]: options.licenceOneOf
294 if (options.languageOneOf) {
295 query.where['language'] = {
296 [Sequelize.Op.or]: options.languageOneOf
300 if (options.accountId) {
301 accountInclude.where = {
302 id: options.accountId
306 if (options.videoChannelId) {
307 videoChannelInclude.where = {
308 id: options.videoChannelId
314 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
317 model: () => VideoChannelModel.unscoped(),
322 exclude: [ 'privateKey', 'publicKey' ]
324 model: () => ActorModel.unscoped(),
328 attributes: [ 'host' ],
329 model: () => ServerModel.unscoped(),
333 model: () => AvatarModel.unscoped(),
339 model: () => AccountModel.unscoped(),
343 model: () => ActorModel.unscoped(),
345 exclude: [ 'privateKey', 'publicKey' ]
350 attributes: [ 'host' ],
351 model: () => ServerModel.unscoped(),
355 model: () => AvatarModel.unscoped(),
366 [ScopeNames.WITH_TAGS]: {
367 include: [ () => TagModel ]
369 [ScopeNames.WITH_FILES]: {
372 model: () => VideoFileModel.unscoped(),
377 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
380 model: () => ScheduleVideoUpdateModel.unscoped(),
390 export class VideoModel extends Model<VideoModel> {
393 @Default(DataType.UUIDV4)
395 @Column(DataType.UUID)
399 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
405 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
411 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
417 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
418 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
422 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
427 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
433 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
434 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
439 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
440 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
444 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
474 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
475 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
480 commentsEnabled: boolean
484 waitTranscoding: boolean
488 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
499 @Default(Sequelize.NOW)
503 @ForeignKey(() => VideoChannelModel)
507 @BelongsTo(() => VideoChannelModel, {
513 VideoChannel: VideoChannelModel
515 @BelongsToMany(() => TagModel, {
516 foreignKey: 'videoId',
517 through: () => VideoTagModel,
522 @HasMany(() => VideoAbuseModel, {
529 VideoAbuses: VideoAbuseModel[]
531 @HasMany(() => VideoFileModel, {
538 VideoFiles: VideoFileModel[]
540 @HasMany(() => VideoShareModel, {
547 VideoShares: VideoShareModel[]
549 @HasMany(() => AccountVideoRateModel, {
556 AccountVideoRates: AccountVideoRateModel[]
558 @HasMany(() => VideoCommentModel, {
566 VideoComments: VideoCommentModel[]
568 @HasOne(() => ScheduleVideoUpdateModel, {
575 ScheduleVideoUpdate: ScheduleVideoUpdateModel
577 @HasMany(() => VideoCaptionModel, {
584 ['separate' as any]: true
586 VideoCaptions: VideoCaptionModel[]
589 static async sendDelete (instance: VideoModel, options) {
590 if (instance.isOwned()) {
591 if (!instance.VideoChannel) {
592 instance.VideoChannel = await instance.$get('VideoChannel', {
596 include: [ ActorModel ]
599 transaction: options.transaction
600 }) as VideoChannelModel
603 logger.debug('Sending delete of video %s.', instance.url)
605 return sendDeleteVideo(instance, options.transaction)
612 static async removeFiles (instance: VideoModel) {
613 const tasks: Promise<any>[] = []
615 logger.debug('Removing files of video %s.', instance.url)
617 tasks.push(instance.removeThumbnail())
619 if (instance.isOwned()) {
620 if (!Array.isArray(instance.VideoFiles)) {
621 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
624 tasks.push(instance.removePreview())
626 // Remove physical files and torrents
627 instance.VideoFiles.forEach(file => {
628 tasks.push(instance.removeFile(file))
629 tasks.push(instance.removeTorrent(file))
633 // Do not wait video deletion because we could be in a transaction
636 logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, { err })
643 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
646 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
647 function getRawQuery (select: string) {
648 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
649 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
650 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
651 'WHERE "Account"."actorId" = ' + actorId
652 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
653 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
654 'WHERE "VideoShare"."actorId" = ' + actorId
656 return `(${queryVideo}) UNION (${queryVideoShare})`
659 const rawQuery = getRawQuery('"Video"."id"')
660 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
666 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
669 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
672 { privacy: VideoPrivacy.PUBLIC },
673 { privacy: VideoPrivacy.UNLISTED }
678 attributes: [ 'language' ],
679 model: VideoCaptionModel.unscoped(),
683 attributes: [ 'id', 'url' ],
684 model: VideoShareModel.unscoped(),
686 // We only want videos shared by this actor
688 [Sequelize.Op.and]: [
691 [Sequelize.Op.not]: null
701 attributes: [ 'id', 'url' ],
702 model: ActorModel.unscoped()
707 model: VideoChannelModel.unscoped(),
711 attributes: [ 'name' ],
712 model: AccountModel.unscoped(),
716 attributes: [ 'id', 'url', 'followersUrl' ],
717 model: ActorModel.unscoped(),
723 attributes: [ 'id', 'url', 'followersUrl' ],
724 model: ActorModel.unscoped(),
734 return Bluebird.all([
735 // FIXME: typing issue
736 VideoModel.findAll(query as any),
737 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
738 ]).then(([ rows, totals ]) => {
739 // totals: totalVideos + totalVideoShares
741 let totalVideoShares = 0
742 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
743 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
745 const total = totalVideos + totalVideoShares
753 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
754 const query: IFindOptions<VideoModel> = {
757 order: getSort(sort),
760 model: VideoChannelModel,
773 model: ScheduleVideoUpdateModel,
779 if (withFiles === true) {
781 model: VideoFileModel.unscoped(),
786 if (hideNSFW === true) {
792 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
800 static async listForApi (options: {
806 categoryOneOf?: number[],
807 licenceOneOf?: number[],
808 languageOneOf?: string[],
809 tagsOneOf?: string[],
810 tagsAllOf?: string[],
811 filter?: VideoFilter,
813 videoChannelId?: number
816 offset: options.start,
817 limit: options.count,
818 order: getSort(options.sort)
821 const serverActor = await getServerActor()
824 ScopeNames.AVAILABLE_FOR_LIST, {
825 actorId: serverActor.id,
827 categoryOneOf: options.categoryOneOf,
828 licenceOneOf: options.licenceOneOf,
829 languageOneOf: options.languageOneOf,
830 tagsOneOf: options.tagsOneOf,
831 tagsAllOf: options.tagsAllOf,
832 filter: options.filter,
833 withFiles: options.withFiles,
834 accountId: options.accountId,
835 videoChannelId: options.videoChannelId
836 } as AvailableForListOptions
840 return VideoModel.scope(scopes)
841 .findAndCountAll(query)
842 .then(({ rows, count }) => {
850 static async searchAndPopulateAccountAndServer (options: {
855 startDate?: string // ISO 8601
856 endDate?: string // ISO 8601
858 categoryOneOf?: number[]
859 licenceOneOf?: number[]
860 languageOneOf?: string[]
863 durationMin?: number // seconds
864 durationMax?: number // seconds
868 if (options.startDate || options.endDate) {
869 const publishedAtRange = { }
871 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
872 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
874 whereAnd.push({ publishedAt: publishedAtRange })
877 if (options.durationMin || options.durationMax) {
878 const durationRange = { }
880 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
881 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
883 whereAnd.push({ duration: durationRange })
886 whereAnd.push(createSearchTrigramQuery('VideoModel.name', options.search))
888 const query: IFindOptions<VideoModel> = {
890 include: [ createSimilarityAttribute('VideoModel.name', options.search) ]
892 offset: options.start,
893 limit: options.count,
894 order: getSort(options.sort),
896 [ Sequelize.Op.and ]: whereAnd
900 const serverActor = await getServerActor()
903 ScopeNames.AVAILABLE_FOR_LIST, {
904 actorId: serverActor.id,
906 categoryOneOf: options.categoryOneOf,
907 licenceOneOf: options.licenceOneOf,
908 languageOneOf: options.languageOneOf,
909 tagsOneOf: options.tagsOneOf,
910 tagsAllOf: options.tagsAllOf
911 } as AvailableForListOptions
915 return VideoModel.scope(scopes)
916 .findAndCountAll(query)
917 .then(({ rows, count }) => {
925 static load (id: number) {
926 return VideoModel.findById(id)
929 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
930 const query: IFindOptions<VideoModel> = {
936 if (t !== undefined) query.transaction = t
938 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
941 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
942 const query: IFindOptions<VideoModel> = {
951 if (t !== undefined) query.transaction = t
953 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
956 static loadAndPopulateAccountAndServerAndTags (id: number) {
958 order: [ [ 'Tags', 'name', 'ASC' ] ]
962 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
963 .findById(id, options)
966 static loadByUUID (uuid: string) {
974 .scope([ ScopeNames.WITH_FILES ])
978 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
980 order: [ [ 'Tags', 'name', 'ASC' ] ],
988 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
992 static async getStats () {
993 const totalLocalVideos = await VideoModel.count({
998 const totalVideos = await VideoModel.count()
1000 let totalLocalVideoViews = await VideoModel.sum('views', {
1005 // Sequelize could return null...
1006 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1010 totalLocalVideoViews,
1015 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1016 if (filter && filter === 'local') {
1025 private static getCategoryLabel (id: number) {
1026 return VIDEO_CATEGORIES[id] || 'Misc'
1029 private static getLicenceLabel (id: number) {
1030 return VIDEO_LICENCES[id] || 'Unknown'
1033 private static getLanguageLabel (id: string) {
1034 return VIDEO_LANGUAGES[id] || 'Unknown'
1037 private static getPrivacyLabel (id: number) {
1038 return VIDEO_PRIVACIES[id] || 'Unknown'
1041 private static getStateLabel (id: number) {
1042 return VIDEO_STATES[id] || 'Unknown'
1045 getOriginalFile () {
1046 if (Array.isArray(this.VideoFiles) === false) return undefined
1048 // The original file is the file that have the higher resolution
1049 return maxBy(this.VideoFiles, file => file.resolution)
1052 getVideoFilename (videoFile: VideoFileModel) {
1053 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1056 getThumbnailName () {
1057 // We always have a copy of the thumbnail
1058 const extension = '.jpg'
1059 return this.uuid + extension
1063 const extension = '.jpg'
1064 return this.uuid + extension
1067 getTorrentFileName (videoFile: VideoFileModel) {
1068 const extension = '.torrent'
1069 return this.uuid + '-' + videoFile.resolution + extension
1073 return this.remote === false
1076 createPreview (videoFile: VideoFileModel) {
1077 return generateImageFromVideoFile(
1078 this.getVideoFilePath(videoFile),
1079 CONFIG.STORAGE.PREVIEWS_DIR,
1080 this.getPreviewName(),
1085 createThumbnail (videoFile: VideoFileModel) {
1086 return generateImageFromVideoFile(
1087 this.getVideoFilePath(videoFile),
1088 CONFIG.STORAGE.THUMBNAILS_DIR,
1089 this.getThumbnailName(),
1094 getTorrentFilePath (videoFile: VideoFileModel) {
1095 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1098 getVideoFilePath (videoFile: VideoFileModel) {
1099 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1102 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1104 // Keep the extname, it's used by the client to stream the file inside a web browser
1105 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1106 createdBy: 'PeerTube',
1108 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1109 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1112 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1116 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1118 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1119 logger.info('Creating torrent %s.', filePath)
1121 await writeFilePromise(filePath, torrent)
1123 const parsedTorrent = parseTorrent(torrent)
1124 videoFile.infoHash = parsedTorrent.infoHash
1127 getEmbedStaticPath () {
1128 return '/videos/embed/' + this.uuid
1131 getThumbnailStaticPath () {
1132 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1135 getPreviewStaticPath () {
1136 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1139 toFormattedJSON (options?: {
1140 additionalAttributes: {
1142 waitTranscoding?: boolean,
1143 scheduledUpdate?: boolean
1146 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1147 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1149 const videoObject: Video = {
1155 label: VideoModel.getCategoryLabel(this.category)
1159 label: VideoModel.getLicenceLabel(this.licence)
1163 label: VideoModel.getLanguageLabel(this.language)
1167 label: VideoModel.getPrivacyLabel(this.privacy)
1170 description: this.getTruncatedDescription(),
1171 isLocal: this.isOwned(),
1172 duration: this.duration,
1175 dislikes: this.dislikes,
1176 thumbnailPath: this.getThumbnailStaticPath(),
1177 previewPath: this.getPreviewStaticPath(),
1178 embedPath: this.getEmbedStaticPath(),
1179 createdAt: this.createdAt,
1180 updatedAt: this.updatedAt,
1181 publishedAt: this.publishedAt,
1183 id: formattedAccount.id,
1184 uuid: formattedAccount.uuid,
1185 name: formattedAccount.name,
1186 displayName: formattedAccount.displayName,
1187 url: formattedAccount.url,
1188 host: formattedAccount.host,
1189 avatar: formattedAccount.avatar
1192 id: formattedVideoChannel.id,
1193 uuid: formattedVideoChannel.uuid,
1194 name: formattedVideoChannel.name,
1195 displayName: formattedVideoChannel.displayName,
1196 url: formattedVideoChannel.url,
1197 host: formattedVideoChannel.host,
1198 avatar: formattedVideoChannel.avatar
1203 if (options.additionalAttributes.state === true) {
1204 videoObject.state = {
1206 label: VideoModel.getStateLabel(this.state)
1210 if (options.additionalAttributes.waitTranscoding === true) {
1211 videoObject.waitTranscoding = this.waitTranscoding
1214 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1215 videoObject.scheduledUpdate = {
1216 updateAt: this.ScheduleVideoUpdate.updateAt,
1217 privacy: this.ScheduleVideoUpdate.privacy || undefined
1225 toFormattedDetailsJSON (): VideoDetails {
1226 const formattedJson = this.toFormattedJSON({
1227 additionalAttributes: {
1228 scheduledUpdate: true
1232 const detailsJson = {
1233 support: this.support,
1234 descriptionPath: this.getDescriptionPath(),
1235 channel: this.VideoChannel.toFormattedJSON(),
1236 account: this.VideoChannel.Account.toFormattedJSON(),
1237 tags: map(this.Tags, 'name'),
1238 commentsEnabled: this.commentsEnabled,
1239 waitTranscoding: this.waitTranscoding,
1242 label: VideoModel.getStateLabel(this.state)
1247 // Format and sort video files
1248 detailsJson.files = this.getFormattedVideoFilesJSON()
1250 return Object.assign(formattedJson, detailsJson)
1253 getFormattedVideoFilesJSON (): VideoFile[] {
1254 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1256 return this.VideoFiles
1258 let resolutionLabel = videoFile.resolution + 'p'
1262 id: videoFile.resolution,
1263 label: resolutionLabel
1265 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1266 size: videoFile.size,
1268 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1269 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1270 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1271 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1275 if (a.resolution.id < b.resolution.id) return 1
1276 if (a.resolution.id === b.resolution.id) return 0
1281 toActivityPubObject (): VideoTorrentObject {
1282 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1283 if (!this.Tags) this.Tags = []
1285 const tag = this.Tags.map(t => ({
1286 type: 'Hashtag' as 'Hashtag',
1291 if (this.language) {
1293 identifier: this.language,
1294 name: VideoModel.getLanguageLabel(this.language)
1299 if (this.category) {
1301 identifier: this.category + '',
1302 name: VideoModel.getCategoryLabel(this.category)
1309 identifier: this.licence + '',
1310 name: VideoModel.getLicenceLabel(this.licence)
1315 for (const file of this.VideoFiles) {
1318 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1319 href: this.getVideoFileUrl(file, baseUrlHttp),
1320 width: file.resolution,
1326 mimeType: 'application/x-bittorrent',
1327 href: this.getTorrentUrl(file, baseUrlHttp),
1328 width: file.resolution
1333 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1334 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1335 width: file.resolution
1339 // Add video url too
1342 mimeType: 'text/html',
1343 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1346 const subtitleLanguage = []
1347 for (const caption of this.VideoCaptions) {
1348 subtitleLanguage.push({
1349 identifier: caption.language,
1350 name: VideoCaptionModel.getLanguageLabel(caption.language)
1355 type: 'Video' as 'Video',
1358 duration: this.getActivityStreamDuration(),
1365 sensitive: this.nsfw,
1366 waitTranscoding: this.waitTranscoding,
1368 commentsEnabled: this.commentsEnabled,
1369 published: this.publishedAt.toISOString(),
1370 updated: this.updatedAt.toISOString(),
1371 mediaType: 'text/markdown',
1372 content: this.getTruncatedDescription(),
1373 support: this.support,
1377 url: this.getThumbnailUrl(baseUrlHttp),
1378 mediaType: 'image/jpeg',
1379 width: THUMBNAILS_SIZE.width,
1380 height: THUMBNAILS_SIZE.height
1383 likes: getVideoLikesActivityPubUrl(this),
1384 dislikes: getVideoDislikesActivityPubUrl(this),
1385 shares: getVideoSharesActivityPubUrl(this),
1386 comments: getVideoCommentsActivityPubUrl(this),
1390 id: this.VideoChannel.Account.Actor.url
1394 id: this.VideoChannel.Actor.url
1400 getTruncatedDescription () {
1401 if (!this.description) return null
1403 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1404 return peertubeTruncate(this.description, maxLength)
1407 async optimizeOriginalVideofile () {
1408 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1409 const newExtname = '.mp4'
1410 const inputVideoFile = this.getOriginalFile()
1411 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1412 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1414 const transcodeOptions = {
1415 inputPath: videoInputPath,
1416 outputPath: videoTranscodedPath
1419 // Could be very long!
1420 await transcode(transcodeOptions)
1423 await unlinkPromise(videoInputPath)
1425 // Important to do this before getVideoFilename() to take in account the new file extension
1426 inputVideoFile.set('extname', newExtname)
1428 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1429 await renamePromise(videoTranscodedPath, videoOutputPath)
1430 const stats = await statPromise(videoOutputPath)
1431 const fps = await getVideoFileFPS(videoOutputPath)
1433 inputVideoFile.set('size', stats.size)
1434 inputVideoFile.set('fps', fps)
1436 await this.createTorrentAndSetInfoHash(inputVideoFile)
1437 await inputVideoFile.save()
1440 // Auto destruction...
1441 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1447 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1448 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1449 const extname = '.mp4'
1451 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1452 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1454 const newVideoFile = new VideoFileModel({
1460 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1462 const transcodeOptions = {
1463 inputPath: videoInputPath,
1464 outputPath: videoOutputPath,
1469 await transcode(transcodeOptions)
1471 const stats = await statPromise(videoOutputPath)
1472 const fps = await getVideoFileFPS(videoOutputPath)
1474 newVideoFile.set('size', stats.size)
1475 newVideoFile.set('fps', fps)
1477 await this.createTorrentAndSetInfoHash(newVideoFile)
1479 await newVideoFile.save()
1481 this.VideoFiles.push(newVideoFile)
1484 async importVideoFile (inputFilePath: string) {
1485 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1486 const { size } = await statPromise(inputFilePath)
1487 const fps = await getVideoFileFPS(inputFilePath)
1489 let updatedVideoFile = new VideoFileModel({
1490 resolution: videoFileResolution,
1491 extname: extname(inputFilePath),
1497 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1499 if (currentVideoFile) {
1500 // Remove old file and old torrent
1501 await this.removeFile(currentVideoFile)
1502 await this.removeTorrent(currentVideoFile)
1503 // Remove the old video file from the array
1504 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1506 // Update the database
1507 currentVideoFile.set('extname', updatedVideoFile.extname)
1508 currentVideoFile.set('size', updatedVideoFile.size)
1509 currentVideoFile.set('fps', updatedVideoFile.fps)
1511 updatedVideoFile = currentVideoFile
1514 const outputPath = this.getVideoFilePath(updatedVideoFile)
1515 await copyFilePromise(inputFilePath, outputPath)
1517 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1519 await updatedVideoFile.save()
1521 this.VideoFiles.push(updatedVideoFile)
1524 getOriginalFileResolution () {
1525 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1527 return getVideoFileResolution(originalFilePath)
1530 getDescriptionPath () {
1531 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1534 removeThumbnail () {
1535 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1536 return unlinkPromise(thumbnailPath)
1540 // Same name than video thumbnail
1541 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1544 removeFile (videoFile: VideoFileModel) {
1545 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1546 return unlinkPromise(filePath)
1549 removeTorrent (videoFile: VideoFileModel) {
1550 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1551 return unlinkPromise(torrentPath)
1554 getActivityStreamDuration () {
1555 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1556 return 'PT' + this.duration + 'S'
1559 private getBaseUrls () {
1563 if (this.isOwned()) {
1564 baseUrlHttp = CONFIG.WEBSERVER.URL
1565 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1567 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1568 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1571 return { baseUrlHttp, baseUrlWs }
1574 private getThumbnailUrl (baseUrlHttp: string) {
1575 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1578 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1579 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1582 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1583 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1586 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1587 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1590 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1591 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1594 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1595 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1596 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1597 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1599 const magnetHash = {
1603 infoHash: videoFile.infoHash,
1607 return magnetUtil.encode(magnetHash)