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'
97 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
98 const indexes: Sequelize.DefineIndexesOptions[] = [
99 buildTrigramSearchIndex('video_name_trigram', 'name'),
101 { fields: [ 'createdAt' ] },
102 { fields: [ 'publishedAt' ] },
103 { fields: [ 'duration' ] },
104 { fields: [ 'category' ] },
105 { fields: [ 'licence' ] },
106 { fields: [ 'nsfw' ] },
107 { fields: [ 'language' ] },
108 { fields: [ 'waitTranscoding' ] },
109 { fields: [ 'state' ] },
110 { fields: [ 'remote' ] },
111 { fields: [ 'views' ] },
112 { fields: [ 'likes' ] },
113 { fields: [ 'channelId' ] },
124 export enum ScopeNames {
125 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
126 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
127 WITH_TAGS = 'WITH_TAGS',
128 WITH_FILES = 'WITH_FILES',
129 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE'
132 type AvailableForListOptions = {
134 filter?: VideoFilter,
135 categoryOneOf?: number[],
137 licenceOneOf?: number[],
138 languageOneOf?: string[],
139 tagsOneOf?: string[],
140 tagsAllOf?: string[],
143 videoChannelId?: number
147 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
148 const accountInclude = {
149 attributes: [ 'id', 'name' ],
150 model: AccountModel.unscoped(),
155 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
156 model: ActorModel.unscoped(),
158 where: VideoModel.buildActorWhereWithFilter(options.filter),
161 attributes: [ 'host' ],
162 model: ServerModel.unscoped(),
166 model: AvatarModel.unscoped(),
174 const videoChannelInclude = {
175 attributes: [ 'name', 'description', 'id' ],
176 model: VideoChannelModel.unscoped(),
181 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
182 model: ActorModel.unscoped(),
186 attributes: [ 'host' ],
187 model: ServerModel.unscoped(),
191 model: AvatarModel.unscoped(),
200 // Force actorId to be a number to avoid SQL injections
201 const actorIdNumber = parseInt(options.actorId.toString(), 10)
202 const query: IFindOptions<VideoModel> = {
205 [Sequelize.Op.notIn]: Sequelize.literal(
206 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
208 [ Sequelize.Op.in ]: Sequelize.literal(
210 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
211 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
212 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
214 'SELECT "video"."id" AS "id" FROM "video" ' +
215 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
216 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
217 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
218 'LEFT JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
219 'WHERE "actor"."serverId" IS NULL OR "actorFollow"."actorId" = ' + actorIdNumber +
223 // Always list public videos
224 privacy: VideoPrivacy.PUBLIC,
225 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
226 [ Sequelize.Op.or ]: [
228 state: VideoState.PUBLISHED
231 [ Sequelize.Op.and ]: {
232 state: VideoState.TO_TRANSCODE,
233 waitTranscoding: false
238 include: [ videoChannelInclude ]
241 if (options.withFiles === true) {
243 model: VideoFileModel.unscoped(),
248 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
249 if (options.tagsAllOf || options.tagsOneOf) {
250 const createTagsIn = (tags: string[]) => {
251 return tags.map(t => VideoModel.sequelize.escape(t))
255 if (options.tagsOneOf) {
256 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
258 'SELECT "videoId" FROM "videoTag" ' +
259 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
260 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
265 if (options.tagsAllOf) {
266 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
268 'SELECT "videoId" FROM "videoTag" ' +
269 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
270 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
271 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
277 if (options.nsfw === true || options.nsfw === false) {
278 query.where['nsfw'] = options.nsfw
281 if (options.categoryOneOf) {
282 query.where['category'] = {
283 [Sequelize.Op.or]: options.categoryOneOf
287 if (options.licenceOneOf) {
288 query.where['licence'] = {
289 [Sequelize.Op.or]: options.licenceOneOf
293 if (options.languageOneOf) {
294 query.where['language'] = {
295 [Sequelize.Op.or]: options.languageOneOf
299 if (options.accountId) {
300 accountInclude.where = {
301 id: options.accountId
305 if (options.videoChannelId) {
306 videoChannelInclude.where = {
307 id: options.videoChannelId
313 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
316 model: () => VideoChannelModel.unscoped(),
321 exclude: [ 'privateKey', 'publicKey' ]
323 model: () => ActorModel.unscoped(),
327 attributes: [ 'host' ],
328 model: () => ServerModel.unscoped(),
332 model: () => AvatarModel.unscoped(),
338 model: () => AccountModel.unscoped(),
342 model: () => ActorModel.unscoped(),
344 exclude: [ 'privateKey', 'publicKey' ]
349 attributes: [ 'host' ],
350 model: () => ServerModel.unscoped(),
354 model: () => AvatarModel.unscoped(),
365 [ScopeNames.WITH_TAGS]: {
366 include: [ () => TagModel ]
368 [ScopeNames.WITH_FILES]: {
371 model: () => VideoFileModel.unscoped(),
376 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
379 model: () => ScheduleVideoUpdateModel.unscoped(),
389 export class VideoModel extends Model<VideoModel> {
392 @Default(DataType.UUIDV4)
394 @Column(DataType.UUID)
398 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
404 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
410 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
416 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
417 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
421 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
426 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
432 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
433 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
438 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
439 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
443 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
473 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
474 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
479 commentsEnabled: boolean
483 waitTranscoding: boolean
487 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
498 @Default(Sequelize.NOW)
502 @ForeignKey(() => VideoChannelModel)
506 @BelongsTo(() => VideoChannelModel, {
512 VideoChannel: VideoChannelModel
514 @BelongsToMany(() => TagModel, {
515 foreignKey: 'videoId',
516 through: () => VideoTagModel,
521 @HasMany(() => VideoAbuseModel, {
528 VideoAbuses: VideoAbuseModel[]
530 @HasMany(() => VideoFileModel, {
537 VideoFiles: VideoFileModel[]
539 @HasMany(() => VideoShareModel, {
546 VideoShares: VideoShareModel[]
548 @HasMany(() => AccountVideoRateModel, {
555 AccountVideoRates: AccountVideoRateModel[]
557 @HasMany(() => VideoCommentModel, {
565 VideoComments: VideoCommentModel[]
567 @HasOne(() => ScheduleVideoUpdateModel, {
574 ScheduleVideoUpdate: ScheduleVideoUpdateModel
576 @HasMany(() => VideoCaptionModel, {
583 ['separate' as any]: true
585 VideoCaptions: VideoCaptionModel[]
588 static async sendDelete (instance: VideoModel, options) {
589 if (instance.isOwned()) {
590 if (!instance.VideoChannel) {
591 instance.VideoChannel = await instance.$get('VideoChannel', {
595 include: [ ActorModel ]
598 transaction: options.transaction
599 }) as VideoChannelModel
602 logger.debug('Sending delete of video %s.', instance.url)
604 return sendDeleteVideo(instance, options.transaction)
611 static async removeFiles (instance: VideoModel) {
612 const tasks: Promise<any>[] = []
614 logger.debug('Removing files of video %s.', instance.url)
616 tasks.push(instance.removeThumbnail())
618 if (instance.isOwned()) {
619 if (!Array.isArray(instance.VideoFiles)) {
620 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
623 tasks.push(instance.removePreview())
625 // Remove physical files and torrents
626 instance.VideoFiles.forEach(file => {
627 tasks.push(instance.removeFile(file))
628 tasks.push(instance.removeTorrent(file))
632 // Do not wait video deletion because we could be in a transaction
635 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
642 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
645 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
646 function getRawQuery (select: string) {
647 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
648 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
649 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
650 'WHERE "Account"."actorId" = ' + actorId
651 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
652 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
653 'WHERE "VideoShare"."actorId" = ' + actorId
655 return `(${queryVideo}) UNION (${queryVideoShare})`
658 const rawQuery = getRawQuery('"Video"."id"')
659 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
665 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
668 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
671 { privacy: VideoPrivacy.PUBLIC },
672 { privacy: VideoPrivacy.UNLISTED }
677 attributes: [ 'language' ],
678 model: VideoCaptionModel.unscoped(),
682 attributes: [ 'id', 'url' ],
683 model: VideoShareModel.unscoped(),
685 // We only want videos shared by this actor
687 [Sequelize.Op.and]: [
690 [Sequelize.Op.not]: null
700 attributes: [ 'id', 'url' ],
701 model: ActorModel.unscoped()
706 model: VideoChannelModel.unscoped(),
710 attributes: [ 'name' ],
711 model: AccountModel.unscoped(),
715 attributes: [ 'id', 'url', 'followersUrl' ],
716 model: ActorModel.unscoped(),
722 attributes: [ 'id', 'url', 'followersUrl' ],
723 model: ActorModel.unscoped(),
733 return Bluebird.all([
734 // FIXME: typing issue
735 VideoModel.findAll(query as any),
736 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
737 ]).then(([ rows, totals ]) => {
738 // totals: totalVideos + totalVideoShares
740 let totalVideoShares = 0
741 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
742 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
744 const total = totalVideos + totalVideoShares
752 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
753 const query: IFindOptions<VideoModel> = {
756 order: getSort(sort),
759 model: VideoChannelModel,
772 model: ScheduleVideoUpdateModel,
778 if (withFiles === true) {
780 model: VideoFileModel.unscoped(),
785 if (hideNSFW === true) {
791 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
799 static async listForApi (options: {
805 categoryOneOf?: number[],
806 licenceOneOf?: number[],
807 languageOneOf?: string[],
808 tagsOneOf?: string[],
809 tagsAllOf?: string[],
810 filter?: VideoFilter,
812 videoChannelId?: number
815 offset: options.start,
816 limit: options.count,
817 order: getSort(options.sort)
820 const serverActor = await getServerActor()
823 ScopeNames.AVAILABLE_FOR_LIST, {
824 actorId: serverActor.id,
826 categoryOneOf: options.categoryOneOf,
827 licenceOneOf: options.licenceOneOf,
828 languageOneOf: options.languageOneOf,
829 tagsOneOf: options.tagsOneOf,
830 tagsAllOf: options.tagsAllOf,
831 filter: options.filter,
832 withFiles: options.withFiles,
833 accountId: options.accountId,
834 videoChannelId: options.videoChannelId
835 } as AvailableForListOptions
839 return VideoModel.scope(scopes)
840 .findAndCountAll(query)
841 .then(({ rows, count }) => {
849 static async searchAndPopulateAccountAndServer (options: {
854 startDate?: string // ISO 8601
855 endDate?: string // ISO 8601
857 categoryOneOf?: number[]
858 licenceOneOf?: number[]
859 languageOneOf?: string[]
862 durationMin?: number // seconds
863 durationMax?: number // seconds
867 if (options.startDate || options.endDate) {
868 const publishedAtRange = { }
870 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
871 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
873 whereAnd.push({ publishedAt: publishedAtRange })
876 if (options.durationMin || options.durationMax) {
877 const durationRange = { }
879 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
880 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
882 whereAnd.push({ duration: durationRange })
885 const attributesInclude = []
886 if (options.search) {
889 [ Sequelize.Op.or ]: [
890 createSearchTrigramQuery('VideoModel.name', options.search),
894 [ Sequelize.Op.in ]: Sequelize.literal(
896 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
897 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
898 'WHERE "tag"."name" = ' + VideoModel.sequelize.escape(options.search) +
907 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
910 // Cannot search on similarity if we don't have a search
911 if (!options.search) {
912 attributesInclude.push(
913 Sequelize.literal('0 as similarity')
917 const query: IFindOptions<VideoModel> = {
919 include: attributesInclude
921 offset: options.start,
922 limit: options.count,
923 order: getSort(options.sort),
925 [ Sequelize.Op.and ]: whereAnd
929 const serverActor = await getServerActor()
932 ScopeNames.AVAILABLE_FOR_LIST, {
933 actorId: serverActor.id,
935 categoryOneOf: options.categoryOneOf,
936 licenceOneOf: options.licenceOneOf,
937 languageOneOf: options.languageOneOf,
938 tagsOneOf: options.tagsOneOf,
939 tagsAllOf: options.tagsAllOf
940 } as AvailableForListOptions
944 return VideoModel.scope(scopes)
945 .findAndCountAll(query)
946 .then(({ rows, count }) => {
954 static load (id: number) {
955 return VideoModel.findById(id)
958 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
959 const query: IFindOptions<VideoModel> = {
965 if (t !== undefined) query.transaction = t
967 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
970 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
971 const query: IFindOptions<VideoModel> = {
980 if (t !== undefined) query.transaction = t
982 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
985 static loadAndPopulateAccountAndServerAndTags (id: number) {
987 order: [ [ 'Tags', 'name', 'ASC' ] ]
991 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
992 .findById(id, options)
995 static loadByUUID (uuid: string) {
1003 .scope([ ScopeNames.WITH_FILES ])
1007 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1009 order: [ [ 'Tags', 'name', 'ASC' ] ],
1017 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
1021 static async getStats () {
1022 const totalLocalVideos = await VideoModel.count({
1027 const totalVideos = await VideoModel.count()
1029 let totalLocalVideoViews = await VideoModel.sum('views', {
1034 // Sequelize could return null...
1035 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1039 totalLocalVideoViews,
1044 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1045 if (filter && filter === 'local') {
1054 private static getCategoryLabel (id: number) {
1055 return VIDEO_CATEGORIES[id] || 'Misc'
1058 private static getLicenceLabel (id: number) {
1059 return VIDEO_LICENCES[id] || 'Unknown'
1062 private static getLanguageLabel (id: string) {
1063 return VIDEO_LANGUAGES[id] || 'Unknown'
1066 private static getPrivacyLabel (id: number) {
1067 return VIDEO_PRIVACIES[id] || 'Unknown'
1070 private static getStateLabel (id: number) {
1071 return VIDEO_STATES[id] || 'Unknown'
1074 getOriginalFile () {
1075 if (Array.isArray(this.VideoFiles) === false) return undefined
1077 // The original file is the file that have the higher resolution
1078 return maxBy(this.VideoFiles, file => file.resolution)
1081 getVideoFilename (videoFile: VideoFileModel) {
1082 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1085 getThumbnailName () {
1086 // We always have a copy of the thumbnail
1087 const extension = '.jpg'
1088 return this.uuid + extension
1092 const extension = '.jpg'
1093 return this.uuid + extension
1096 getTorrentFileName (videoFile: VideoFileModel) {
1097 const extension = '.torrent'
1098 return this.uuid + '-' + videoFile.resolution + extension
1102 return this.remote === false
1105 createPreview (videoFile: VideoFileModel) {
1106 return generateImageFromVideoFile(
1107 this.getVideoFilePath(videoFile),
1108 CONFIG.STORAGE.PREVIEWS_DIR,
1109 this.getPreviewName(),
1114 createThumbnail (videoFile: VideoFileModel) {
1115 return generateImageFromVideoFile(
1116 this.getVideoFilePath(videoFile),
1117 CONFIG.STORAGE.THUMBNAILS_DIR,
1118 this.getThumbnailName(),
1123 getTorrentFilePath (videoFile: VideoFileModel) {
1124 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1127 getVideoFilePath (videoFile: VideoFileModel) {
1128 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1131 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1133 // Keep the extname, it's used by the client to stream the file inside a web browser
1134 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1135 createdBy: 'PeerTube',
1137 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1138 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1141 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1145 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1147 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1148 logger.info('Creating torrent %s.', filePath)
1150 await writeFilePromise(filePath, torrent)
1152 const parsedTorrent = parseTorrent(torrent)
1153 videoFile.infoHash = parsedTorrent.infoHash
1156 getEmbedStaticPath () {
1157 return '/videos/embed/' + this.uuid
1160 getThumbnailStaticPath () {
1161 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1164 getPreviewStaticPath () {
1165 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1168 toFormattedJSON (options?: {
1169 additionalAttributes: {
1171 waitTranscoding?: boolean,
1172 scheduledUpdate?: boolean
1175 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1176 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1178 const videoObject: Video = {
1184 label: VideoModel.getCategoryLabel(this.category)
1188 label: VideoModel.getLicenceLabel(this.licence)
1192 label: VideoModel.getLanguageLabel(this.language)
1196 label: VideoModel.getPrivacyLabel(this.privacy)
1199 description: this.getTruncatedDescription(),
1200 isLocal: this.isOwned(),
1201 duration: this.duration,
1204 dislikes: this.dislikes,
1205 thumbnailPath: this.getThumbnailStaticPath(),
1206 previewPath: this.getPreviewStaticPath(),
1207 embedPath: this.getEmbedStaticPath(),
1208 createdAt: this.createdAt,
1209 updatedAt: this.updatedAt,
1210 publishedAt: this.publishedAt,
1212 id: formattedAccount.id,
1213 uuid: formattedAccount.uuid,
1214 name: formattedAccount.name,
1215 displayName: formattedAccount.displayName,
1216 url: formattedAccount.url,
1217 host: formattedAccount.host,
1218 avatar: formattedAccount.avatar
1221 id: formattedVideoChannel.id,
1222 uuid: formattedVideoChannel.uuid,
1223 name: formattedVideoChannel.name,
1224 displayName: formattedVideoChannel.displayName,
1225 url: formattedVideoChannel.url,
1226 host: formattedVideoChannel.host,
1227 avatar: formattedVideoChannel.avatar
1232 if (options.additionalAttributes.state === true) {
1233 videoObject.state = {
1235 label: VideoModel.getStateLabel(this.state)
1239 if (options.additionalAttributes.waitTranscoding === true) {
1240 videoObject.waitTranscoding = this.waitTranscoding
1243 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1244 videoObject.scheduledUpdate = {
1245 updateAt: this.ScheduleVideoUpdate.updateAt,
1246 privacy: this.ScheduleVideoUpdate.privacy || undefined
1254 toFormattedDetailsJSON (): VideoDetails {
1255 const formattedJson = this.toFormattedJSON({
1256 additionalAttributes: {
1257 scheduledUpdate: true
1261 const detailsJson = {
1262 support: this.support,
1263 descriptionPath: this.getDescriptionPath(),
1264 channel: this.VideoChannel.toFormattedJSON(),
1265 account: this.VideoChannel.Account.toFormattedJSON(),
1266 tags: map(this.Tags, 'name'),
1267 commentsEnabled: this.commentsEnabled,
1268 waitTranscoding: this.waitTranscoding,
1271 label: VideoModel.getStateLabel(this.state)
1276 // Format and sort video files
1277 detailsJson.files = this.getFormattedVideoFilesJSON()
1279 return Object.assign(formattedJson, detailsJson)
1282 getFormattedVideoFilesJSON (): VideoFile[] {
1283 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1285 return this.VideoFiles
1287 let resolutionLabel = videoFile.resolution + 'p'
1291 id: videoFile.resolution,
1292 label: resolutionLabel
1294 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1295 size: videoFile.size,
1297 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1298 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1299 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1300 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1304 if (a.resolution.id < b.resolution.id) return 1
1305 if (a.resolution.id === b.resolution.id) return 0
1310 toActivityPubObject (): VideoTorrentObject {
1311 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1312 if (!this.Tags) this.Tags = []
1314 const tag = this.Tags.map(t => ({
1315 type: 'Hashtag' as 'Hashtag',
1320 if (this.language) {
1322 identifier: this.language,
1323 name: VideoModel.getLanguageLabel(this.language)
1328 if (this.category) {
1330 identifier: this.category + '',
1331 name: VideoModel.getCategoryLabel(this.category)
1338 identifier: this.licence + '',
1339 name: VideoModel.getLicenceLabel(this.licence)
1344 for (const file of this.VideoFiles) {
1347 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1348 href: this.getVideoFileUrl(file, baseUrlHttp),
1349 width: file.resolution,
1355 mimeType: 'application/x-bittorrent',
1356 href: this.getTorrentUrl(file, baseUrlHttp),
1357 width: file.resolution
1362 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1363 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1364 width: file.resolution
1368 // Add video url too
1371 mimeType: 'text/html',
1372 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1375 const subtitleLanguage = []
1376 for (const caption of this.VideoCaptions) {
1377 subtitleLanguage.push({
1378 identifier: caption.language,
1379 name: VideoCaptionModel.getLanguageLabel(caption.language)
1384 type: 'Video' as 'Video',
1387 duration: this.getActivityStreamDuration(),
1394 sensitive: this.nsfw,
1395 waitTranscoding: this.waitTranscoding,
1397 commentsEnabled: this.commentsEnabled,
1398 published: this.publishedAt.toISOString(),
1399 updated: this.updatedAt.toISOString(),
1400 mediaType: 'text/markdown',
1401 content: this.getTruncatedDescription(),
1402 support: this.support,
1406 url: this.getThumbnailUrl(baseUrlHttp),
1407 mediaType: 'image/jpeg',
1408 width: THUMBNAILS_SIZE.width,
1409 height: THUMBNAILS_SIZE.height
1412 likes: getVideoLikesActivityPubUrl(this),
1413 dislikes: getVideoDislikesActivityPubUrl(this),
1414 shares: getVideoSharesActivityPubUrl(this),
1415 comments: getVideoCommentsActivityPubUrl(this),
1419 id: this.VideoChannel.Account.Actor.url
1423 id: this.VideoChannel.Actor.url
1429 getTruncatedDescription () {
1430 if (!this.description) return null
1432 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1433 return peertubeTruncate(this.description, maxLength)
1436 async optimizeOriginalVideofile () {
1437 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1438 const newExtname = '.mp4'
1439 const inputVideoFile = this.getOriginalFile()
1440 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1441 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1443 const transcodeOptions = {
1444 inputPath: videoInputPath,
1445 outputPath: videoTranscodedPath
1448 // Could be very long!
1449 await transcode(transcodeOptions)
1452 await unlinkPromise(videoInputPath)
1454 // Important to do this before getVideoFilename() to take in account the new file extension
1455 inputVideoFile.set('extname', newExtname)
1457 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1458 await renamePromise(videoTranscodedPath, videoOutputPath)
1459 const stats = await statPromise(videoOutputPath)
1460 const fps = await getVideoFileFPS(videoOutputPath)
1462 inputVideoFile.set('size', stats.size)
1463 inputVideoFile.set('fps', fps)
1465 await this.createTorrentAndSetInfoHash(inputVideoFile)
1466 await inputVideoFile.save()
1469 // Auto destruction...
1470 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1476 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1477 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1478 const extname = '.mp4'
1480 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1481 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1483 const newVideoFile = new VideoFileModel({
1489 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1491 const transcodeOptions = {
1492 inputPath: videoInputPath,
1493 outputPath: videoOutputPath,
1498 await transcode(transcodeOptions)
1500 const stats = await statPromise(videoOutputPath)
1501 const fps = await getVideoFileFPS(videoOutputPath)
1503 newVideoFile.set('size', stats.size)
1504 newVideoFile.set('fps', fps)
1506 await this.createTorrentAndSetInfoHash(newVideoFile)
1508 await newVideoFile.save()
1510 this.VideoFiles.push(newVideoFile)
1513 async importVideoFile (inputFilePath: string) {
1514 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1515 const { size } = await statPromise(inputFilePath)
1516 const fps = await getVideoFileFPS(inputFilePath)
1518 let updatedVideoFile = new VideoFileModel({
1519 resolution: videoFileResolution,
1520 extname: extname(inputFilePath),
1526 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1528 if (currentVideoFile) {
1529 // Remove old file and old torrent
1530 await this.removeFile(currentVideoFile)
1531 await this.removeTorrent(currentVideoFile)
1532 // Remove the old video file from the array
1533 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1535 // Update the database
1536 currentVideoFile.set('extname', updatedVideoFile.extname)
1537 currentVideoFile.set('size', updatedVideoFile.size)
1538 currentVideoFile.set('fps', updatedVideoFile.fps)
1540 updatedVideoFile = currentVideoFile
1543 const outputPath = this.getVideoFilePath(updatedVideoFile)
1544 await copyFilePromise(inputFilePath, outputPath)
1546 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1548 await updatedVideoFile.save()
1550 this.VideoFiles.push(updatedVideoFile)
1553 getOriginalFileResolution () {
1554 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1556 return getVideoFileResolution(originalFilePath)
1559 getDescriptionPath () {
1560 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1563 removeThumbnail () {
1564 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1565 return unlinkPromise(thumbnailPath)
1569 // Same name than video thumbnail
1570 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1573 removeFile (videoFile: VideoFileModel) {
1574 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1575 return unlinkPromise(filePath)
1578 removeTorrent (videoFile: VideoFileModel) {
1579 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1580 return unlinkPromise(torrentPath)
1583 getActivityStreamDuration () {
1584 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1585 return 'PT' + this.duration + 'S'
1588 private getBaseUrls () {
1592 if (this.isOwned()) {
1593 baseUrlHttp = CONFIG.WEBSERVER.URL
1594 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1596 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1597 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1600 return { baseUrlHttp, baseUrlWs }
1603 private getThumbnailUrl (baseUrlHttp: string) {
1604 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1607 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1608 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1611 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1612 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1615 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1616 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1619 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1620 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1623 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1624 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1625 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1626 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1628 const magnetHash = {
1632 infoHash: videoFile.infoHash,
1636 return magnetUtil.encode(magnetHash)