1 import * as Bluebird from 'bluebird'
2 import { map, maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { extname, join } from 'path'
6 import * as Sequelize from 'sequelize'
28 } from 'sequelize-typescript'
29 import { VideoPrivacy, VideoResolution, VideoState } from '../../../shared'
30 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
31 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
32 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
41 } from '../../helpers/core-utils'
42 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
43 import { isBooleanValid } from '../../helpers/custom-validators/misc'
46 isVideoDescriptionValid,
54 } from '../../helpers/custom-validators/videos'
55 import { generateImageFromVideoFile, getVideoFileFPS, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
56 import { logger } from '../../helpers/logger'
57 import { getServerActor } from '../../helpers/utils'
64 STATIC_DOWNLOAD_PATHS,
73 } from '../../initializers'
75 getVideoCommentsActivityPubUrl,
76 getVideoDislikesActivityPubUrl,
77 getVideoLikesActivityPubUrl,
78 getVideoSharesActivityPubUrl
79 } from '../../lib/activitypub'
80 import { sendDeleteVideo } from '../../lib/activitypub/send'
81 import { AccountModel } from '../account/account'
82 import { AccountVideoRateModel } from '../account/account-video-rate'
83 import { ActorModel } from '../activitypub/actor'
84 import { AvatarModel } from '../avatar/avatar'
85 import { ServerModel } from '../server/server'
86 import { buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
87 import { TagModel } from './tag'
88 import { VideoAbuseModel } from './video-abuse'
89 import { VideoChannelModel } from './video-channel'
90 import { VideoCommentModel } from './video-comment'
91 import { VideoFileModel } from './video-file'
92 import { VideoShareModel } from './video-share'
93 import { VideoTagModel } from './video-tag'
94 import { ScheduleVideoUpdateModel } from './schedule-video-update'
95 import { VideoCaptionModel } from './video-caption'
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)
203 // FIXME: It would be more efficient to use a CTE so we join AFTER the filters, but sequelize does not support it...
204 const query: IFindOptions<VideoModel> = {
207 [Sequelize.Op.notIn]: Sequelize.literal(
208 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
210 [ Sequelize.Op.in ]: Sequelize.literal(
212 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
213 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
214 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
216 'SELECT "video"."id" AS "id" FROM "video" ' +
217 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
218 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
219 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
220 'WHERE "actor"."serverId" IS NULL ' +
222 'SELECT "video"."id" AS "id" FROM "video" ' +
223 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
224 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
225 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
226 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
227 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
231 // Always list public videos
232 privacy: VideoPrivacy.PUBLIC,
233 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
234 [ Sequelize.Op.or ]: [
236 state: VideoState.PUBLISHED
239 [ Sequelize.Op.and ]: {
240 state: VideoState.TO_TRANSCODE,
241 waitTranscoding: false
246 include: [ videoChannelInclude ]
249 if (options.withFiles === true) {
251 model: VideoFileModel.unscoped(),
256 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
257 if (options.tagsAllOf || options.tagsOneOf) {
258 const createTagsIn = (tags: string[]) => {
259 return tags.map(t => VideoModel.sequelize.escape(t))
263 if (options.tagsOneOf) {
264 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
266 'SELECT "videoId" FROM "videoTag" ' +
267 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
268 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
273 if (options.tagsAllOf) {
274 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
276 'SELECT "videoId" FROM "videoTag" ' +
277 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
278 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
279 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
285 if (options.nsfw === true || options.nsfw === false) {
286 query.where['nsfw'] = options.nsfw
289 if (options.categoryOneOf) {
290 query.where['category'] = {
291 [Sequelize.Op.or]: options.categoryOneOf
295 if (options.licenceOneOf) {
296 query.where['licence'] = {
297 [Sequelize.Op.or]: options.licenceOneOf
301 if (options.languageOneOf) {
302 query.where['language'] = {
303 [Sequelize.Op.or]: options.languageOneOf
307 if (options.accountId) {
308 accountInclude.where = {
309 id: options.accountId
313 if (options.videoChannelId) {
314 videoChannelInclude.where = {
315 id: options.videoChannelId
321 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
324 model: () => VideoChannelModel.unscoped(),
329 exclude: [ 'privateKey', 'publicKey' ]
331 model: () => ActorModel.unscoped(),
335 attributes: [ 'host' ],
336 model: () => ServerModel.unscoped(),
340 model: () => AvatarModel.unscoped(),
346 model: () => AccountModel.unscoped(),
350 model: () => ActorModel.unscoped(),
352 exclude: [ 'privateKey', 'publicKey' ]
357 attributes: [ 'host' ],
358 model: () => ServerModel.unscoped(),
362 model: () => AvatarModel.unscoped(),
373 [ScopeNames.WITH_TAGS]: {
374 include: [ () => TagModel ]
376 [ScopeNames.WITH_FILES]: {
379 model: () => VideoFileModel.unscoped(),
384 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
387 model: () => ScheduleVideoUpdateModel.unscoped(),
397 export class VideoModel extends Model<VideoModel> {
400 @Default(DataType.UUIDV4)
402 @Column(DataType.UUID)
406 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
412 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
418 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
424 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
425 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
429 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
434 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
440 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
441 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
446 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
447 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
451 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
481 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
482 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
487 commentsEnabled: boolean
491 waitTranscoding: boolean
495 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
506 @Default(Sequelize.NOW)
510 @ForeignKey(() => VideoChannelModel)
514 @BelongsTo(() => VideoChannelModel, {
520 VideoChannel: VideoChannelModel
522 @BelongsToMany(() => TagModel, {
523 foreignKey: 'videoId',
524 through: () => VideoTagModel,
529 @HasMany(() => VideoAbuseModel, {
536 VideoAbuses: VideoAbuseModel[]
538 @HasMany(() => VideoFileModel, {
545 VideoFiles: VideoFileModel[]
547 @HasMany(() => VideoShareModel, {
554 VideoShares: VideoShareModel[]
556 @HasMany(() => AccountVideoRateModel, {
563 AccountVideoRates: AccountVideoRateModel[]
565 @HasMany(() => VideoCommentModel, {
573 VideoComments: VideoCommentModel[]
575 @HasOne(() => ScheduleVideoUpdateModel, {
582 ScheduleVideoUpdate: ScheduleVideoUpdateModel
584 @HasMany(() => VideoCaptionModel, {
591 ['separate' as any]: true
593 VideoCaptions: VideoCaptionModel[]
596 static async sendDelete (instance: VideoModel, options) {
597 if (instance.isOwned()) {
598 if (!instance.VideoChannel) {
599 instance.VideoChannel = await instance.$get('VideoChannel', {
603 include: [ ActorModel ]
606 transaction: options.transaction
607 }) as VideoChannelModel
610 return sendDeleteVideo(instance, options.transaction)
617 static async removeFiles (instance: VideoModel) {
618 const tasks: Promise<any>[] = []
620 logger.info('Removing files of video %s.', instance.url)
622 tasks.push(instance.removeThumbnail())
624 if (instance.isOwned()) {
625 if (!Array.isArray(instance.VideoFiles)) {
626 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
629 tasks.push(instance.removePreview())
631 // Remove physical files and torrents
632 instance.VideoFiles.forEach(file => {
633 tasks.push(instance.removeFile(file))
634 tasks.push(instance.removeTorrent(file))
638 // Do not wait video deletion because we could be in a transaction
641 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
648 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
651 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
652 function getRawQuery (select: string) {
653 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
654 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
655 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
656 'WHERE "Account"."actorId" = ' + actorId
657 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
658 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
659 'WHERE "VideoShare"."actorId" = ' + actorId
661 return `(${queryVideo}) UNION (${queryVideoShare})`
664 const rawQuery = getRawQuery('"Video"."id"')
665 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
671 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
674 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
677 { privacy: VideoPrivacy.PUBLIC },
678 { privacy: VideoPrivacy.UNLISTED }
683 attributes: [ 'language' ],
684 model: VideoCaptionModel.unscoped(),
688 attributes: [ 'id', 'url' ],
689 model: VideoShareModel.unscoped(),
691 // We only want videos shared by this actor
693 [Sequelize.Op.and]: [
696 [Sequelize.Op.not]: null
706 attributes: [ 'id', 'url' ],
707 model: ActorModel.unscoped()
712 model: VideoChannelModel.unscoped(),
716 attributes: [ 'name' ],
717 model: AccountModel.unscoped(),
721 attributes: [ 'id', 'url', 'followersUrl' ],
722 model: ActorModel.unscoped(),
728 attributes: [ 'id', 'url', 'followersUrl' ],
729 model: ActorModel.unscoped(),
739 return Bluebird.all([
740 // FIXME: typing issue
741 VideoModel.findAll(query as any),
742 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
743 ]).then(([ rows, totals ]) => {
744 // totals: totalVideos + totalVideoShares
746 let totalVideoShares = 0
747 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
748 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
750 const total = totalVideos + totalVideoShares
758 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, hideNSFW: boolean, withFiles = false) {
759 const query: IFindOptions<VideoModel> = {
762 order: getSort(sort),
765 model: VideoChannelModel,
778 model: ScheduleVideoUpdateModel,
784 if (withFiles === true) {
786 model: VideoFileModel.unscoped(),
791 if (hideNSFW === true) {
797 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
805 static async listForApi (options: {
811 categoryOneOf?: number[],
812 licenceOneOf?: number[],
813 languageOneOf?: string[],
814 tagsOneOf?: string[],
815 tagsAllOf?: string[],
816 filter?: VideoFilter,
818 videoChannelId?: number
821 offset: options.start,
822 limit: options.count,
823 order: getSort(options.sort)
826 const serverActor = await getServerActor()
829 ScopeNames.AVAILABLE_FOR_LIST, {
830 actorId: serverActor.id,
832 categoryOneOf: options.categoryOneOf,
833 licenceOneOf: options.licenceOneOf,
834 languageOneOf: options.languageOneOf,
835 tagsOneOf: options.tagsOneOf,
836 tagsAllOf: options.tagsAllOf,
837 filter: options.filter,
838 withFiles: options.withFiles,
839 accountId: options.accountId,
840 videoChannelId: options.videoChannelId
841 } as AvailableForListOptions
845 return VideoModel.scope(scopes)
846 .findAndCountAll(query)
847 .then(({ rows, count }) => {
855 static async searchAndPopulateAccountAndServer (options: {
860 startDate?: string // ISO 8601
861 endDate?: string // ISO 8601
863 categoryOneOf?: number[]
864 licenceOneOf?: number[]
865 languageOneOf?: string[]
868 durationMin?: number // seconds
869 durationMax?: number // seconds
873 if (options.startDate || options.endDate) {
874 const publishedAtRange = { }
876 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
877 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
879 whereAnd.push({ publishedAt: publishedAtRange })
882 if (options.durationMin || options.durationMax) {
883 const durationRange = { }
885 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
886 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
888 whereAnd.push({ duration: durationRange })
891 const attributesInclude = []
892 const escapedSearch = VideoModel.sequelize.escape(options.search)
893 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
894 if (options.search) {
898 [ Sequelize.Op.in ]: Sequelize.literal(
900 'SELECT "video"."id" FROM "video" WHERE ' +
901 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
902 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
904 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
905 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
906 'WHERE "tag"."name" = ' + escapedSearch +
913 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
916 // Cannot search on similarity if we don't have a search
917 if (!options.search) {
918 attributesInclude.push(
919 Sequelize.literal('0 as similarity')
923 const query: IFindOptions<VideoModel> = {
925 include: attributesInclude
927 offset: options.start,
928 limit: options.count,
929 order: getSort(options.sort),
931 [ Sequelize.Op.and ]: whereAnd
935 const serverActor = await getServerActor()
938 ScopeNames.AVAILABLE_FOR_LIST, {
939 actorId: serverActor.id,
941 categoryOneOf: options.categoryOneOf,
942 licenceOneOf: options.licenceOneOf,
943 languageOneOf: options.languageOneOf,
944 tagsOneOf: options.tagsOneOf,
945 tagsAllOf: options.tagsAllOf
946 } as AvailableForListOptions
950 return VideoModel.scope(scopes)
951 .findAndCountAll(query)
952 .then(({ rows, count }) => {
960 static load (id: number, t?: Sequelize.Transaction) {
961 const options = t ? { transaction: t } : undefined
963 return VideoModel.findById(id, options)
966 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
967 const query: IFindOptions<VideoModel> = {
973 if (t !== undefined) query.transaction = t
975 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
978 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
979 const query: IFindOptions<VideoModel> = {
988 if (t !== undefined) query.transaction = t
990 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
993 static loadAndPopulateAccountAndServerAndTags (id: number) {
995 order: [ [ 'Tags', 'name', 'ASC' ] ]
999 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
1000 .findById(id, options)
1003 static loadByUUID (uuid: string) {
1011 .scope([ ScopeNames.WITH_FILES ])
1015 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1017 order: [ [ 'Tags', 'name', 'ASC' ] ],
1025 .scope([ ScopeNames.WITH_TAGS, ScopeNames.WITH_FILES, ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_SCHEDULED_UPDATE ])
1029 static async getStats () {
1030 const totalLocalVideos = await VideoModel.count({
1035 const totalVideos = await VideoModel.count()
1037 let totalLocalVideoViews = await VideoModel.sum('views', {
1042 // Sequelize could return null...
1043 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1047 totalLocalVideoViews,
1052 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1053 if (filter && filter === 'local') {
1062 private static getCategoryLabel (id: number) {
1063 return VIDEO_CATEGORIES[id] || 'Misc'
1066 private static getLicenceLabel (id: number) {
1067 return VIDEO_LICENCES[id] || 'Unknown'
1070 private static getLanguageLabel (id: string) {
1071 return VIDEO_LANGUAGES[id] || 'Unknown'
1074 private static getPrivacyLabel (id: number) {
1075 return VIDEO_PRIVACIES[id] || 'Unknown'
1078 private static getStateLabel (id: number) {
1079 return VIDEO_STATES[id] || 'Unknown'
1082 getOriginalFile () {
1083 if (Array.isArray(this.VideoFiles) === false) return undefined
1085 // The original file is the file that have the higher resolution
1086 return maxBy(this.VideoFiles, file => file.resolution)
1089 getVideoFilename (videoFile: VideoFileModel) {
1090 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1093 getThumbnailName () {
1094 // We always have a copy of the thumbnail
1095 const extension = '.jpg'
1096 return this.uuid + extension
1100 const extension = '.jpg'
1101 return this.uuid + extension
1104 getTorrentFileName (videoFile: VideoFileModel) {
1105 const extension = '.torrent'
1106 return this.uuid + '-' + videoFile.resolution + extension
1110 return this.remote === false
1113 createPreview (videoFile: VideoFileModel) {
1114 return generateImageFromVideoFile(
1115 this.getVideoFilePath(videoFile),
1116 CONFIG.STORAGE.PREVIEWS_DIR,
1117 this.getPreviewName(),
1122 createThumbnail (videoFile: VideoFileModel) {
1123 return generateImageFromVideoFile(
1124 this.getVideoFilePath(videoFile),
1125 CONFIG.STORAGE.THUMBNAILS_DIR,
1126 this.getThumbnailName(),
1131 getTorrentFilePath (videoFile: VideoFileModel) {
1132 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1135 getVideoFilePath (videoFile: VideoFileModel) {
1136 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1139 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1141 // Keep the extname, it's used by the client to stream the file inside a web browser
1142 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1143 createdBy: 'PeerTube',
1145 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1146 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1149 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1153 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1155 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1156 logger.info('Creating torrent %s.', filePath)
1158 await writeFilePromise(filePath, torrent)
1160 const parsedTorrent = parseTorrent(torrent)
1161 videoFile.infoHash = parsedTorrent.infoHash
1164 getEmbedStaticPath () {
1165 return '/videos/embed/' + this.uuid
1168 getThumbnailStaticPath () {
1169 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1172 getPreviewStaticPath () {
1173 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1176 toFormattedJSON (options?: {
1177 additionalAttributes: {
1179 waitTranscoding?: boolean,
1180 scheduledUpdate?: boolean
1183 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1184 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1186 const videoObject: Video = {
1192 label: VideoModel.getCategoryLabel(this.category)
1196 label: VideoModel.getLicenceLabel(this.licence)
1200 label: VideoModel.getLanguageLabel(this.language)
1204 label: VideoModel.getPrivacyLabel(this.privacy)
1207 description: this.getTruncatedDescription(),
1208 isLocal: this.isOwned(),
1209 duration: this.duration,
1212 dislikes: this.dislikes,
1213 thumbnailPath: this.getThumbnailStaticPath(),
1214 previewPath: this.getPreviewStaticPath(),
1215 embedPath: this.getEmbedStaticPath(),
1216 createdAt: this.createdAt,
1217 updatedAt: this.updatedAt,
1218 publishedAt: this.publishedAt,
1220 id: formattedAccount.id,
1221 uuid: formattedAccount.uuid,
1222 name: formattedAccount.name,
1223 displayName: formattedAccount.displayName,
1224 url: formattedAccount.url,
1225 host: formattedAccount.host,
1226 avatar: formattedAccount.avatar
1229 id: formattedVideoChannel.id,
1230 uuid: formattedVideoChannel.uuid,
1231 name: formattedVideoChannel.name,
1232 displayName: formattedVideoChannel.displayName,
1233 url: formattedVideoChannel.url,
1234 host: formattedVideoChannel.host,
1235 avatar: formattedVideoChannel.avatar
1240 if (options.additionalAttributes.state === true) {
1241 videoObject.state = {
1243 label: VideoModel.getStateLabel(this.state)
1247 if (options.additionalAttributes.waitTranscoding === true) {
1248 videoObject.waitTranscoding = this.waitTranscoding
1251 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1252 videoObject.scheduledUpdate = {
1253 updateAt: this.ScheduleVideoUpdate.updateAt,
1254 privacy: this.ScheduleVideoUpdate.privacy || undefined
1262 toFormattedDetailsJSON (): VideoDetails {
1263 const formattedJson = this.toFormattedJSON({
1264 additionalAttributes: {
1265 scheduledUpdate: true
1269 const detailsJson = {
1270 support: this.support,
1271 descriptionPath: this.getDescriptionPath(),
1272 channel: this.VideoChannel.toFormattedJSON(),
1273 account: this.VideoChannel.Account.toFormattedJSON(),
1274 tags: map(this.Tags, 'name'),
1275 commentsEnabled: this.commentsEnabled,
1276 waitTranscoding: this.waitTranscoding,
1279 label: VideoModel.getStateLabel(this.state)
1284 // Format and sort video files
1285 detailsJson.files = this.getFormattedVideoFilesJSON()
1287 return Object.assign(formattedJson, detailsJson)
1290 getFormattedVideoFilesJSON (): VideoFile[] {
1291 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1293 return this.VideoFiles
1295 let resolutionLabel = videoFile.resolution + 'p'
1299 id: videoFile.resolution,
1300 label: resolutionLabel
1302 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1303 size: videoFile.size,
1305 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1306 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1307 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1308 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1312 if (a.resolution.id < b.resolution.id) return 1
1313 if (a.resolution.id === b.resolution.id) return 0
1318 toActivityPubObject (): VideoTorrentObject {
1319 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1320 if (!this.Tags) this.Tags = []
1322 const tag = this.Tags.map(t => ({
1323 type: 'Hashtag' as 'Hashtag',
1328 if (this.language) {
1330 identifier: this.language,
1331 name: VideoModel.getLanguageLabel(this.language)
1336 if (this.category) {
1338 identifier: this.category + '',
1339 name: VideoModel.getCategoryLabel(this.category)
1346 identifier: this.licence + '',
1347 name: VideoModel.getLicenceLabel(this.licence)
1352 for (const file of this.VideoFiles) {
1355 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1356 href: this.getVideoFileUrl(file, baseUrlHttp),
1357 width: file.resolution,
1364 mimeType: 'application/x-bittorrent',
1365 href: this.getTorrentUrl(file, baseUrlHttp),
1366 width: file.resolution
1371 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1372 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1373 width: file.resolution
1377 // Add video url too
1380 mimeType: 'text/html',
1381 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1384 const subtitleLanguage = []
1385 for (const caption of this.VideoCaptions) {
1386 subtitleLanguage.push({
1387 identifier: caption.language,
1388 name: VideoCaptionModel.getLanguageLabel(caption.language)
1393 type: 'Video' as 'Video',
1396 duration: this.getActivityStreamDuration(),
1403 sensitive: this.nsfw,
1404 waitTranscoding: this.waitTranscoding,
1406 commentsEnabled: this.commentsEnabled,
1407 published: this.publishedAt.toISOString(),
1408 updated: this.updatedAt.toISOString(),
1409 mediaType: 'text/markdown',
1410 content: this.getTruncatedDescription(),
1411 support: this.support,
1415 url: this.getThumbnailUrl(baseUrlHttp),
1416 mediaType: 'image/jpeg',
1417 width: THUMBNAILS_SIZE.width,
1418 height: THUMBNAILS_SIZE.height
1421 likes: getVideoLikesActivityPubUrl(this),
1422 dislikes: getVideoDislikesActivityPubUrl(this),
1423 shares: getVideoSharesActivityPubUrl(this),
1424 comments: getVideoCommentsActivityPubUrl(this),
1428 id: this.VideoChannel.Account.Actor.url
1432 id: this.VideoChannel.Actor.url
1438 getTruncatedDescription () {
1439 if (!this.description) return null
1441 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1442 return peertubeTruncate(this.description, maxLength)
1445 async optimizeOriginalVideofile () {
1446 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1447 const newExtname = '.mp4'
1448 const inputVideoFile = this.getOriginalFile()
1449 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1450 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1452 const transcodeOptions = {
1453 inputPath: videoInputPath,
1454 outputPath: videoTranscodedPath
1457 // Could be very long!
1458 await transcode(transcodeOptions)
1461 await unlinkPromise(videoInputPath)
1463 // Important to do this before getVideoFilename() to take in account the new file extension
1464 inputVideoFile.set('extname', newExtname)
1466 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1467 await renamePromise(videoTranscodedPath, videoOutputPath)
1468 const stats = await statPromise(videoOutputPath)
1469 const fps = await getVideoFileFPS(videoOutputPath)
1471 inputVideoFile.set('size', stats.size)
1472 inputVideoFile.set('fps', fps)
1474 await this.createTorrentAndSetInfoHash(inputVideoFile)
1475 await inputVideoFile.save()
1478 // Auto destruction...
1479 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1485 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1486 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1487 const extname = '.mp4'
1489 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1490 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1492 const newVideoFile = new VideoFileModel({
1498 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1500 const transcodeOptions = {
1501 inputPath: videoInputPath,
1502 outputPath: videoOutputPath,
1507 await transcode(transcodeOptions)
1509 const stats = await statPromise(videoOutputPath)
1510 const fps = await getVideoFileFPS(videoOutputPath)
1512 newVideoFile.set('size', stats.size)
1513 newVideoFile.set('fps', fps)
1515 await this.createTorrentAndSetInfoHash(newVideoFile)
1517 await newVideoFile.save()
1519 this.VideoFiles.push(newVideoFile)
1522 async importVideoFile (inputFilePath: string) {
1523 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1524 const { size } = await statPromise(inputFilePath)
1525 const fps = await getVideoFileFPS(inputFilePath)
1527 let updatedVideoFile = new VideoFileModel({
1528 resolution: videoFileResolution,
1529 extname: extname(inputFilePath),
1535 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1537 if (currentVideoFile) {
1538 // Remove old file and old torrent
1539 await this.removeFile(currentVideoFile)
1540 await this.removeTorrent(currentVideoFile)
1541 // Remove the old video file from the array
1542 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1544 // Update the database
1545 currentVideoFile.set('extname', updatedVideoFile.extname)
1546 currentVideoFile.set('size', updatedVideoFile.size)
1547 currentVideoFile.set('fps', updatedVideoFile.fps)
1549 updatedVideoFile = currentVideoFile
1552 const outputPath = this.getVideoFilePath(updatedVideoFile)
1553 await copyFilePromise(inputFilePath, outputPath)
1555 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1557 await updatedVideoFile.save()
1559 this.VideoFiles.push(updatedVideoFile)
1562 getOriginalFileResolution () {
1563 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1565 return getVideoFileResolution(originalFilePath)
1568 getDescriptionPath () {
1569 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1572 removeThumbnail () {
1573 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1574 return unlinkPromise(thumbnailPath)
1575 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1579 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1580 return unlinkPromise(previewPath)
1581 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1584 removeFile (videoFile: VideoFileModel) {
1585 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1586 return unlinkPromise(filePath)
1587 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1590 removeTorrent (videoFile: VideoFileModel) {
1591 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1592 return unlinkPromise(torrentPath)
1593 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1596 getActivityStreamDuration () {
1597 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1598 return 'PT' + this.duration + 'S'
1601 private getBaseUrls () {
1605 if (this.isOwned()) {
1606 baseUrlHttp = CONFIG.WEBSERVER.URL
1607 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1609 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1610 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1613 return { baseUrlHttp, baseUrlWs }
1616 private getThumbnailUrl (baseUrlHttp: string) {
1617 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1620 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1621 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1624 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1625 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1628 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1629 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1632 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1633 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1636 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1637 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1638 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1639 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1641 const magnetHash = {
1645 infoHash: videoFile.infoHash,
1649 return magnetUtil.encode(magnetHash)