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'
96 import { VideoBlacklistModel } from './video-blacklist'
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',
131 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
134 type AvailableForListOptions = {
136 filter?: VideoFilter,
137 categoryOneOf?: number[],
139 licenceOneOf?: number[],
140 languageOneOf?: string[],
141 tagsOneOf?: string[],
142 tagsAllOf?: string[],
145 videoChannelId?: number
149 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
150 const accountInclude = {
151 attributes: [ 'id', 'name' ],
152 model: AccountModel.unscoped(),
157 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
158 model: ActorModel.unscoped(),
160 where: VideoModel.buildActorWhereWithFilter(options.filter),
163 attributes: [ 'host' ],
164 model: ServerModel.unscoped(),
168 model: AvatarModel.unscoped(),
176 const videoChannelInclude = {
177 attributes: [ 'name', 'description', 'id' ],
178 model: VideoChannelModel.unscoped(),
183 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
184 model: ActorModel.unscoped(),
188 attributes: [ 'host' ],
189 model: ServerModel.unscoped(),
193 model: AvatarModel.unscoped(),
202 // Force actorId to be a number to avoid SQL injections
203 const actorIdNumber = parseInt(options.actorId.toString(), 10)
205 // FIXME: It would be more efficient to use a CTE so we join AFTER the filters, but sequelize does not support it...
206 const query: IFindOptions<VideoModel> = {
209 [Sequelize.Op.notIn]: Sequelize.literal(
210 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
212 [ Sequelize.Op.in ]: Sequelize.literal(
214 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
215 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
216 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
218 'SELECT "video"."id" AS "id" FROM "video" ' +
219 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
220 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
221 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
222 'WHERE "actor"."serverId" IS NULL ' +
224 'SELECT "video"."id" AS "id" FROM "video" ' +
225 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
226 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
227 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
228 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
229 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
233 // Always list public videos
234 privacy: VideoPrivacy.PUBLIC,
235 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
236 [ Sequelize.Op.or ]: [
238 state: VideoState.PUBLISHED
241 [ Sequelize.Op.and ]: {
242 state: VideoState.TO_TRANSCODE,
243 waitTranscoding: false
248 include: [ videoChannelInclude ]
251 if (options.withFiles === true) {
253 model: VideoFileModel.unscoped(),
258 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
259 if (options.tagsAllOf || options.tagsOneOf) {
260 const createTagsIn = (tags: string[]) => {
261 return tags.map(t => VideoModel.sequelize.escape(t))
265 if (options.tagsOneOf) {
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.tagsOneOf) + ')' +
275 if (options.tagsAllOf) {
276 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
278 'SELECT "videoId" FROM "videoTag" ' +
279 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
280 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
281 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
287 if (options.nsfw === true || options.nsfw === false) {
288 query.where['nsfw'] = options.nsfw
291 if (options.categoryOneOf) {
292 query.where['category'] = {
293 [Sequelize.Op.or]: options.categoryOneOf
297 if (options.licenceOneOf) {
298 query.where['licence'] = {
299 [Sequelize.Op.or]: options.licenceOneOf
303 if (options.languageOneOf) {
304 query.where['language'] = {
305 [Sequelize.Op.or]: options.languageOneOf
309 if (options.accountId) {
310 accountInclude.where = {
311 id: options.accountId
315 if (options.videoChannelId) {
316 videoChannelInclude.where = {
317 id: options.videoChannelId
323 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
326 model: () => VideoChannelModel.unscoped(),
331 exclude: [ 'privateKey', 'publicKey' ]
333 model: () => ActorModel.unscoped(),
337 attributes: [ 'host' ],
338 model: () => ServerModel.unscoped(),
342 model: () => AvatarModel.unscoped(),
348 model: () => AccountModel.unscoped(),
352 model: () => ActorModel.unscoped(),
354 exclude: [ 'privateKey', 'publicKey' ]
359 attributes: [ 'host' ],
360 model: () => ServerModel.unscoped(),
364 model: () => AvatarModel.unscoped(),
375 [ScopeNames.WITH_TAGS]: {
376 include: [ () => TagModel ]
378 [ScopeNames.WITH_BLACKLISTED]: {
381 attributes: [ 'id', 'reason' ],
382 model: () => VideoBlacklistModel,
387 [ScopeNames.WITH_FILES]: {
390 model: () => VideoFileModel.unscoped(),
395 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
398 model: () => ScheduleVideoUpdateModel.unscoped(),
408 export class VideoModel extends Model<VideoModel> {
411 @Default(DataType.UUIDV4)
413 @Column(DataType.UUID)
417 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
423 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
429 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
435 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
436 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
440 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
445 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
451 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
452 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
457 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
458 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
462 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
492 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
493 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
498 commentsEnabled: boolean
502 waitTranscoding: boolean
506 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
517 @Default(Sequelize.NOW)
521 @ForeignKey(() => VideoChannelModel)
525 @BelongsTo(() => VideoChannelModel, {
531 VideoChannel: VideoChannelModel
533 @BelongsToMany(() => TagModel, {
534 foreignKey: 'videoId',
535 through: () => VideoTagModel,
540 @HasMany(() => VideoAbuseModel, {
547 VideoAbuses: VideoAbuseModel[]
549 @HasMany(() => VideoFileModel, {
556 VideoFiles: VideoFileModel[]
558 @HasMany(() => VideoShareModel, {
565 VideoShares: VideoShareModel[]
567 @HasMany(() => AccountVideoRateModel, {
574 AccountVideoRates: AccountVideoRateModel[]
576 @HasMany(() => VideoCommentModel, {
584 VideoComments: VideoCommentModel[]
586 @HasOne(() => ScheduleVideoUpdateModel, {
593 ScheduleVideoUpdate: ScheduleVideoUpdateModel
595 @HasOne(() => VideoBlacklistModel, {
602 VideoBlacklist: VideoBlacklistModel
604 @HasMany(() => VideoCaptionModel, {
611 ['separate' as any]: true
613 VideoCaptions: VideoCaptionModel[]
616 static async sendDelete (instance: VideoModel, options) {
617 if (instance.isOwned()) {
618 if (!instance.VideoChannel) {
619 instance.VideoChannel = await instance.$get('VideoChannel', {
623 include: [ ActorModel ]
626 transaction: options.transaction
627 }) as VideoChannelModel
630 return sendDeleteVideo(instance, options.transaction)
637 static async removeFiles (instance: VideoModel) {
638 const tasks: Promise<any>[] = []
640 logger.info('Removing files of video %s.', instance.url)
642 tasks.push(instance.removeThumbnail())
644 if (instance.isOwned()) {
645 if (!Array.isArray(instance.VideoFiles)) {
646 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
649 tasks.push(instance.removePreview())
651 // Remove physical files and torrents
652 instance.VideoFiles.forEach(file => {
653 tasks.push(instance.removeFile(file))
654 tasks.push(instance.removeTorrent(file))
658 // Do not wait video deletion because we could be in a transaction
661 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
668 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
671 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
672 function getRawQuery (select: string) {
673 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
674 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
675 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
676 'WHERE "Account"."actorId" = ' + actorId
677 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
678 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
679 'WHERE "VideoShare"."actorId" = ' + actorId
681 return `(${queryVideo}) UNION (${queryVideoShare})`
684 const rawQuery = getRawQuery('"Video"."id"')
685 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
691 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
694 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
697 { privacy: VideoPrivacy.PUBLIC },
698 { privacy: VideoPrivacy.UNLISTED }
703 attributes: [ 'language' ],
704 model: VideoCaptionModel.unscoped(),
708 attributes: [ 'id', 'url' ],
709 model: VideoShareModel.unscoped(),
711 // We only want videos shared by this actor
713 [Sequelize.Op.and]: [
716 [Sequelize.Op.not]: null
726 attributes: [ 'id', 'url' ],
727 model: ActorModel.unscoped()
732 model: VideoChannelModel.unscoped(),
736 attributes: [ 'name' ],
737 model: AccountModel.unscoped(),
741 attributes: [ 'id', 'url', 'followersUrl' ],
742 model: ActorModel.unscoped(),
748 attributes: [ 'id', 'url', 'followersUrl' ],
749 model: ActorModel.unscoped(),
759 return Bluebird.all([
760 // FIXME: typing issue
761 VideoModel.findAll(query as any),
762 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
763 ]).then(([ rows, totals ]) => {
764 // totals: totalVideos + totalVideoShares
766 let totalVideoShares = 0
767 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
768 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
770 const total = totalVideos + totalVideoShares
778 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
779 const query: IFindOptions<VideoModel> = {
782 order: getSort(sort),
785 model: VideoChannelModel,
798 model: ScheduleVideoUpdateModel,
802 model: VideoBlacklistModel,
808 if (withFiles === true) {
810 model: VideoFileModel.unscoped(),
815 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
823 static async listForApi (options: {
829 categoryOneOf?: number[],
830 licenceOneOf?: number[],
831 languageOneOf?: string[],
832 tagsOneOf?: string[],
833 tagsAllOf?: string[],
834 filter?: VideoFilter,
836 videoChannelId?: number
839 offset: options.start,
840 limit: options.count,
841 order: getSort(options.sort)
844 const serverActor = await getServerActor()
847 ScopeNames.AVAILABLE_FOR_LIST, {
848 actorId: serverActor.id,
850 categoryOneOf: options.categoryOneOf,
851 licenceOneOf: options.licenceOneOf,
852 languageOneOf: options.languageOneOf,
853 tagsOneOf: options.tagsOneOf,
854 tagsAllOf: options.tagsAllOf,
855 filter: options.filter,
856 withFiles: options.withFiles,
857 accountId: options.accountId,
858 videoChannelId: options.videoChannelId
859 } as AvailableForListOptions
863 return VideoModel.scope(scopes)
864 .findAndCountAll(query)
865 .then(({ rows, count }) => {
873 static async searchAndPopulateAccountAndServer (options: {
878 startDate?: string // ISO 8601
879 endDate?: string // ISO 8601
881 categoryOneOf?: number[]
882 licenceOneOf?: number[]
883 languageOneOf?: string[]
886 durationMin?: number // seconds
887 durationMax?: number // seconds
891 if (options.startDate || options.endDate) {
892 const publishedAtRange = { }
894 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
895 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
897 whereAnd.push({ publishedAt: publishedAtRange })
900 if (options.durationMin || options.durationMax) {
901 const durationRange = { }
903 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
904 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
906 whereAnd.push({ duration: durationRange })
909 const attributesInclude = []
910 const escapedSearch = VideoModel.sequelize.escape(options.search)
911 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
912 if (options.search) {
916 [ Sequelize.Op.in ]: Sequelize.literal(
918 'SELECT "video"."id" FROM "video" WHERE ' +
919 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
920 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
922 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
923 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
924 'WHERE "tag"."name" = ' + escapedSearch +
931 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
934 // Cannot search on similarity if we don't have a search
935 if (!options.search) {
936 attributesInclude.push(
937 Sequelize.literal('0 as similarity')
941 const query: IFindOptions<VideoModel> = {
943 include: attributesInclude
945 offset: options.start,
946 limit: options.count,
947 order: getSort(options.sort),
949 [ Sequelize.Op.and ]: whereAnd
953 const serverActor = await getServerActor()
956 ScopeNames.AVAILABLE_FOR_LIST, {
957 actorId: serverActor.id,
959 categoryOneOf: options.categoryOneOf,
960 licenceOneOf: options.licenceOneOf,
961 languageOneOf: options.languageOneOf,
962 tagsOneOf: options.tagsOneOf,
963 tagsAllOf: options.tagsAllOf
964 } as AvailableForListOptions
968 return VideoModel.scope(scopes)
969 .findAndCountAll(query)
970 .then(({ rows, count }) => {
978 static load (id: number, t?: Sequelize.Transaction) {
979 const options = t ? { transaction: t } : undefined
981 return VideoModel.findById(id, options)
984 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
985 const query: IFindOptions<VideoModel> = {
991 if (t !== undefined) query.transaction = t
993 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
996 static loadByUUIDOrURLAndPopulateAccount (uuid: string, url: string, t?: Sequelize.Transaction) {
997 const query: IFindOptions<VideoModel> = {
1006 if (t !== undefined) query.transaction = t
1008 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1011 static loadAndPopulateAccountAndServerAndTags (id: number) {
1013 order: [ [ 'Tags', 'name', 'ASC' ] ]
1018 ScopeNames.WITH_TAGS,
1019 ScopeNames.WITH_BLACKLISTED,
1020 ScopeNames.WITH_FILES,
1021 ScopeNames.WITH_ACCOUNT_DETAILS,
1022 ScopeNames.WITH_SCHEDULED_UPDATE
1024 .findById(id, options)
1027 static loadByUUID (uuid: string) {
1035 .scope([ ScopeNames.WITH_FILES ])
1039 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1041 order: [ [ 'Tags', 'name', 'ASC' ] ],
1050 ScopeNames.WITH_TAGS,
1051 ScopeNames.WITH_BLACKLISTED,
1052 ScopeNames.WITH_FILES,
1053 ScopeNames.WITH_ACCOUNT_DETAILS,
1054 ScopeNames.WITH_SCHEDULED_UPDATE
1059 static async getStats () {
1060 const totalLocalVideos = await VideoModel.count({
1065 const totalVideos = await VideoModel.count()
1067 let totalLocalVideoViews = await VideoModel.sum('views', {
1072 // Sequelize could return null...
1073 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1077 totalLocalVideoViews,
1082 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1083 if (filter && filter === 'local') {
1092 private static getCategoryLabel (id: number) {
1093 return VIDEO_CATEGORIES[id] || 'Misc'
1096 private static getLicenceLabel (id: number) {
1097 return VIDEO_LICENCES[id] || 'Unknown'
1100 private static getLanguageLabel (id: string) {
1101 return VIDEO_LANGUAGES[id] || 'Unknown'
1104 private static getPrivacyLabel (id: number) {
1105 return VIDEO_PRIVACIES[id] || 'Unknown'
1108 private static getStateLabel (id: number) {
1109 return VIDEO_STATES[id] || 'Unknown'
1112 getOriginalFile () {
1113 if (Array.isArray(this.VideoFiles) === false) return undefined
1115 // The original file is the file that have the higher resolution
1116 return maxBy(this.VideoFiles, file => file.resolution)
1119 getVideoFilename (videoFile: VideoFileModel) {
1120 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1123 getThumbnailName () {
1124 // We always have a copy of the thumbnail
1125 const extension = '.jpg'
1126 return this.uuid + extension
1130 const extension = '.jpg'
1131 return this.uuid + extension
1134 getTorrentFileName (videoFile: VideoFileModel) {
1135 const extension = '.torrent'
1136 return this.uuid + '-' + videoFile.resolution + extension
1140 return this.remote === false
1143 createPreview (videoFile: VideoFileModel) {
1144 return generateImageFromVideoFile(
1145 this.getVideoFilePath(videoFile),
1146 CONFIG.STORAGE.PREVIEWS_DIR,
1147 this.getPreviewName(),
1152 createThumbnail (videoFile: VideoFileModel) {
1153 return generateImageFromVideoFile(
1154 this.getVideoFilePath(videoFile),
1155 CONFIG.STORAGE.THUMBNAILS_DIR,
1156 this.getThumbnailName(),
1161 getTorrentFilePath (videoFile: VideoFileModel) {
1162 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1165 getVideoFilePath (videoFile: VideoFileModel) {
1166 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1169 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1171 // Keep the extname, it's used by the client to stream the file inside a web browser
1172 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1173 createdBy: 'PeerTube',
1175 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1176 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1179 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1183 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1185 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1186 logger.info('Creating torrent %s.', filePath)
1188 await writeFilePromise(filePath, torrent)
1190 const parsedTorrent = parseTorrent(torrent)
1191 videoFile.infoHash = parsedTorrent.infoHash
1194 getEmbedStaticPath () {
1195 return '/videos/embed/' + this.uuid
1198 getThumbnailStaticPath () {
1199 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1202 getPreviewStaticPath () {
1203 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1206 toFormattedJSON (options?: {
1207 additionalAttributes: {
1209 waitTranscoding?: boolean,
1210 scheduledUpdate?: boolean,
1211 blacklistInfo?: boolean
1214 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1215 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1217 const videoObject: Video = {
1223 label: VideoModel.getCategoryLabel(this.category)
1227 label: VideoModel.getLicenceLabel(this.licence)
1231 label: VideoModel.getLanguageLabel(this.language)
1235 label: VideoModel.getPrivacyLabel(this.privacy)
1238 description: this.getTruncatedDescription(),
1239 isLocal: this.isOwned(),
1240 duration: this.duration,
1243 dislikes: this.dislikes,
1244 thumbnailPath: this.getThumbnailStaticPath(),
1245 previewPath: this.getPreviewStaticPath(),
1246 embedPath: this.getEmbedStaticPath(),
1247 createdAt: this.createdAt,
1248 updatedAt: this.updatedAt,
1249 publishedAt: this.publishedAt,
1251 id: formattedAccount.id,
1252 uuid: formattedAccount.uuid,
1253 name: formattedAccount.name,
1254 displayName: formattedAccount.displayName,
1255 url: formattedAccount.url,
1256 host: formattedAccount.host,
1257 avatar: formattedAccount.avatar
1260 id: formattedVideoChannel.id,
1261 uuid: formattedVideoChannel.uuid,
1262 name: formattedVideoChannel.name,
1263 displayName: formattedVideoChannel.displayName,
1264 url: formattedVideoChannel.url,
1265 host: formattedVideoChannel.host,
1266 avatar: formattedVideoChannel.avatar
1271 if (options.additionalAttributes.state === true) {
1272 videoObject.state = {
1274 label: VideoModel.getStateLabel(this.state)
1278 if (options.additionalAttributes.waitTranscoding === true) {
1279 videoObject.waitTranscoding = this.waitTranscoding
1282 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1283 videoObject.scheduledUpdate = {
1284 updateAt: this.ScheduleVideoUpdate.updateAt,
1285 privacy: this.ScheduleVideoUpdate.privacy || undefined
1289 if (options.additionalAttributes.blacklistInfo === true) {
1290 videoObject.blacklisted = !!this.VideoBlacklist
1291 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1298 toFormattedDetailsJSON (): VideoDetails {
1299 const formattedJson = this.toFormattedJSON({
1300 additionalAttributes: {
1301 scheduledUpdate: true,
1306 const detailsJson = {
1307 support: this.support,
1308 descriptionPath: this.getDescriptionPath(),
1309 channel: this.VideoChannel.toFormattedJSON(),
1310 account: this.VideoChannel.Account.toFormattedJSON(),
1311 tags: map(this.Tags, 'name'),
1312 commentsEnabled: this.commentsEnabled,
1313 waitTranscoding: this.waitTranscoding,
1316 label: VideoModel.getStateLabel(this.state)
1321 // Format and sort video files
1322 detailsJson.files = this.getFormattedVideoFilesJSON()
1324 return Object.assign(formattedJson, detailsJson)
1327 getFormattedVideoFilesJSON (): VideoFile[] {
1328 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1330 return this.VideoFiles
1332 let resolutionLabel = videoFile.resolution + 'p'
1336 id: videoFile.resolution,
1337 label: resolutionLabel
1339 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1340 size: videoFile.size,
1342 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1343 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1344 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1345 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1349 if (a.resolution.id < b.resolution.id) return 1
1350 if (a.resolution.id === b.resolution.id) return 0
1355 toActivityPubObject (): VideoTorrentObject {
1356 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1357 if (!this.Tags) this.Tags = []
1359 const tag = this.Tags.map(t => ({
1360 type: 'Hashtag' as 'Hashtag',
1365 if (this.language) {
1367 identifier: this.language,
1368 name: VideoModel.getLanguageLabel(this.language)
1373 if (this.category) {
1375 identifier: this.category + '',
1376 name: VideoModel.getCategoryLabel(this.category)
1383 identifier: this.licence + '',
1384 name: VideoModel.getLicenceLabel(this.licence)
1389 for (const file of this.VideoFiles) {
1392 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1393 href: this.getVideoFileUrl(file, baseUrlHttp),
1394 width: file.resolution,
1401 mimeType: 'application/x-bittorrent',
1402 href: this.getTorrentUrl(file, baseUrlHttp),
1403 width: file.resolution
1408 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1409 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1410 width: file.resolution
1414 // Add video url too
1417 mimeType: 'text/html',
1418 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1421 const subtitleLanguage = []
1422 for (const caption of this.VideoCaptions) {
1423 subtitleLanguage.push({
1424 identifier: caption.language,
1425 name: VideoCaptionModel.getLanguageLabel(caption.language)
1430 type: 'Video' as 'Video',
1433 duration: this.getActivityStreamDuration(),
1440 sensitive: this.nsfw,
1441 waitTranscoding: this.waitTranscoding,
1443 commentsEnabled: this.commentsEnabled,
1444 published: this.publishedAt.toISOString(),
1445 updated: this.updatedAt.toISOString(),
1446 mediaType: 'text/markdown',
1447 content: this.getTruncatedDescription(),
1448 support: this.support,
1452 url: this.getThumbnailUrl(baseUrlHttp),
1453 mediaType: 'image/jpeg',
1454 width: THUMBNAILS_SIZE.width,
1455 height: THUMBNAILS_SIZE.height
1458 likes: getVideoLikesActivityPubUrl(this),
1459 dislikes: getVideoDislikesActivityPubUrl(this),
1460 shares: getVideoSharesActivityPubUrl(this),
1461 comments: getVideoCommentsActivityPubUrl(this),
1465 id: this.VideoChannel.Account.Actor.url
1469 id: this.VideoChannel.Actor.url
1475 getTruncatedDescription () {
1476 if (!this.description) return null
1478 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1479 return peertubeTruncate(this.description, maxLength)
1482 async optimizeOriginalVideofile () {
1483 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1484 const newExtname = '.mp4'
1485 const inputVideoFile = this.getOriginalFile()
1486 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1487 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1489 const transcodeOptions = {
1490 inputPath: videoInputPath,
1491 outputPath: videoTranscodedPath
1494 // Could be very long!
1495 await transcode(transcodeOptions)
1498 await unlinkPromise(videoInputPath)
1500 // Important to do this before getVideoFilename() to take in account the new file extension
1501 inputVideoFile.set('extname', newExtname)
1503 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1504 await renamePromise(videoTranscodedPath, videoOutputPath)
1505 const stats = await statPromise(videoOutputPath)
1506 const fps = await getVideoFileFPS(videoOutputPath)
1508 inputVideoFile.set('size', stats.size)
1509 inputVideoFile.set('fps', fps)
1511 await this.createTorrentAndSetInfoHash(inputVideoFile)
1512 await inputVideoFile.save()
1515 // Auto destruction...
1516 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1522 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1523 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1524 const extname = '.mp4'
1526 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1527 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1529 const newVideoFile = new VideoFileModel({
1535 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1537 const transcodeOptions = {
1538 inputPath: videoInputPath,
1539 outputPath: videoOutputPath,
1544 await transcode(transcodeOptions)
1546 const stats = await statPromise(videoOutputPath)
1547 const fps = await getVideoFileFPS(videoOutputPath)
1549 newVideoFile.set('size', stats.size)
1550 newVideoFile.set('fps', fps)
1552 await this.createTorrentAndSetInfoHash(newVideoFile)
1554 await newVideoFile.save()
1556 this.VideoFiles.push(newVideoFile)
1559 async importVideoFile (inputFilePath: string) {
1560 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1561 const { size } = await statPromise(inputFilePath)
1562 const fps = await getVideoFileFPS(inputFilePath)
1564 let updatedVideoFile = new VideoFileModel({
1565 resolution: videoFileResolution,
1566 extname: extname(inputFilePath),
1572 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1574 if (currentVideoFile) {
1575 // Remove old file and old torrent
1576 await this.removeFile(currentVideoFile)
1577 await this.removeTorrent(currentVideoFile)
1578 // Remove the old video file from the array
1579 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1581 // Update the database
1582 currentVideoFile.set('extname', updatedVideoFile.extname)
1583 currentVideoFile.set('size', updatedVideoFile.size)
1584 currentVideoFile.set('fps', updatedVideoFile.fps)
1586 updatedVideoFile = currentVideoFile
1589 const outputPath = this.getVideoFilePath(updatedVideoFile)
1590 await copyFilePromise(inputFilePath, outputPath)
1592 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1594 await updatedVideoFile.save()
1596 this.VideoFiles.push(updatedVideoFile)
1599 getOriginalFileResolution () {
1600 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1602 return getVideoFileResolution(originalFilePath)
1605 getDescriptionPath () {
1606 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1609 removeThumbnail () {
1610 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1611 return unlinkPromise(thumbnailPath)
1612 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1616 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1617 return unlinkPromise(previewPath)
1618 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1621 removeFile (videoFile: VideoFileModel) {
1622 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1623 return unlinkPromise(filePath)
1624 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1627 removeTorrent (videoFile: VideoFileModel) {
1628 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1629 return unlinkPromise(torrentPath)
1630 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1633 getActivityStreamDuration () {
1634 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1635 return 'PT' + this.duration + 'S'
1638 private getBaseUrls () {
1642 if (this.isOwned()) {
1643 baseUrlHttp = CONFIG.WEBSERVER.URL
1644 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1646 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1647 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1650 return { baseUrlHttp, baseUrlWs }
1653 private getThumbnailUrl (baseUrlHttp: string) {
1654 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1657 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1658 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1661 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1662 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1665 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1666 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1669 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1670 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1673 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1674 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1675 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1676 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1678 const magnetHash = {
1682 infoHash: videoFile.infoHash,
1686 return magnetUtil.encode(magnetHash)