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'
65 STATIC_DOWNLOAD_PATHS,
74 } from '../../initializers'
76 getVideoCommentsActivityPubUrl,
77 getVideoDislikesActivityPubUrl,
78 getVideoLikesActivityPubUrl,
79 getVideoSharesActivityPubUrl
80 } from '../../lib/activitypub'
81 import { sendDeleteVideo } from '../../lib/activitypub/send'
82 import { AccountModel } from '../account/account'
83 import { AccountVideoRateModel } from '../account/account-video-rate'
84 import { ActorModel } from '../activitypub/actor'
85 import { AvatarModel } from '../avatar/avatar'
86 import { ServerModel } from '../server/server'
87 import { buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
88 import { TagModel } from './tag'
89 import { VideoAbuseModel } from './video-abuse'
90 import { VideoChannelModel } from './video-channel'
91 import { VideoCommentModel } from './video-comment'
92 import { VideoFileModel } from './video-file'
93 import { VideoShareModel } from './video-share'
94 import { VideoTagModel } from './video-tag'
95 import { ScheduleVideoUpdateModel } from './schedule-video-update'
96 import { VideoCaptionModel } from './video-caption'
97 import { VideoBlacklistModel } from './video-blacklist'
99 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
100 const indexes: Sequelize.DefineIndexesOptions[] = [
101 buildTrigramSearchIndex('video_name_trigram', 'name'),
103 { fields: [ 'createdAt' ] },
104 { fields: [ 'publishedAt' ] },
105 { fields: [ 'duration' ] },
106 { fields: [ 'category' ] },
107 { fields: [ 'licence' ] },
108 { fields: [ 'nsfw' ] },
109 { fields: [ 'language' ] },
110 { fields: [ 'waitTranscoding' ] },
111 { fields: [ 'state' ] },
112 { fields: [ 'remote' ] },
113 { fields: [ 'views' ] },
114 { fields: [ 'likes' ] },
115 { fields: [ 'channelId' ] },
126 export enum ScopeNames {
127 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
128 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
129 WITH_TAGS = 'WITH_TAGS',
130 WITH_FILES = 'WITH_FILES',
131 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
132 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
135 type AvailableForListOptions = {
137 includeLocalVideos: boolean,
138 filter?: VideoFilter,
139 categoryOneOf?: number[],
141 licenceOneOf?: number[],
142 languageOneOf?: string[],
143 tagsOneOf?: string[],
144 tagsAllOf?: string[],
147 videoChannelId?: number
151 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
152 const accountInclude = {
153 attributes: [ 'id', 'name' ],
154 model: AccountModel.unscoped(),
159 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
160 model: ActorModel.unscoped(),
162 where: VideoModel.buildActorWhereWithFilter(options.filter),
165 attributes: [ 'host' ],
166 model: ServerModel.unscoped(),
170 model: AvatarModel.unscoped(),
178 const videoChannelInclude = {
179 attributes: [ 'name', 'description', 'id' ],
180 model: VideoChannelModel.unscoped(),
185 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
186 model: ActorModel.unscoped(),
190 attributes: [ 'host' ],
191 model: ServerModel.unscoped(),
195 model: AvatarModel.unscoped(),
204 // FIXME: It would be more efficient to use a CTE so we join AFTER the filters, but sequelize does not support it...
205 const query: IFindOptions<VideoModel> = {
208 [Sequelize.Op.notIn]: Sequelize.literal(
209 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
212 // Always list public videos
213 privacy: VideoPrivacy.PUBLIC,
214 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
215 [ Sequelize.Op.or ]: [
217 state: VideoState.PUBLISHED
220 [ Sequelize.Op.and ]: {
221 state: VideoState.TO_TRANSCODE,
222 waitTranscoding: false
227 include: [ videoChannelInclude ]
230 if (options.actorId) {
231 let localVideosReq = ''
232 if (options.includeLocalVideos === true) {
233 localVideosReq = ' UNION ALL ' +
234 'SELECT "video"."id" AS "id" FROM "video" ' +
235 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
236 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
237 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
238 'WHERE "actor"."serverId" IS NULL'
241 // Force actorId to be a number to avoid SQL injections
242 const actorIdNumber = parseInt(options.actorId.toString(), 10)
243 query.where['id'][ Sequelize.Op.in ] = Sequelize.literal(
245 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
246 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
247 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
249 'SELECT "video"."id" AS "id" FROM "video" ' +
250 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
251 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
252 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
253 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
254 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
260 if (options.withFiles === true) {
262 model: VideoFileModel.unscoped(),
267 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
268 if (options.tagsAllOf || options.tagsOneOf) {
269 const createTagsIn = (tags: string[]) => {
270 return tags.map(t => VideoModel.sequelize.escape(t))
274 if (options.tagsOneOf) {
275 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
277 'SELECT "videoId" FROM "videoTag" ' +
278 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
279 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
284 if (options.tagsAllOf) {
285 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
287 'SELECT "videoId" FROM "videoTag" ' +
288 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
289 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
290 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
296 if (options.nsfw === true || options.nsfw === false) {
297 query.where['nsfw'] = options.nsfw
300 if (options.categoryOneOf) {
301 query.where['category'] = {
302 [Sequelize.Op.or]: options.categoryOneOf
306 if (options.licenceOneOf) {
307 query.where['licence'] = {
308 [Sequelize.Op.or]: options.licenceOneOf
312 if (options.languageOneOf) {
313 query.where['language'] = {
314 [Sequelize.Op.or]: options.languageOneOf
318 if (options.accountId) {
319 accountInclude.where = {
320 id: options.accountId
324 if (options.videoChannelId) {
325 videoChannelInclude.where = {
326 id: options.videoChannelId
332 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
335 model: () => VideoChannelModel.unscoped(),
340 exclude: [ 'privateKey', 'publicKey' ]
342 model: () => ActorModel.unscoped(),
346 attributes: [ 'host' ],
347 model: () => ServerModel.unscoped(),
351 model: () => AvatarModel.unscoped(),
357 model: () => AccountModel.unscoped(),
361 model: () => ActorModel.unscoped(),
363 exclude: [ 'privateKey', 'publicKey' ]
368 attributes: [ 'host' ],
369 model: () => ServerModel.unscoped(),
373 model: () => AvatarModel.unscoped(),
384 [ScopeNames.WITH_TAGS]: {
385 include: [ () => TagModel ]
387 [ScopeNames.WITH_BLACKLISTED]: {
390 attributes: [ 'id', 'reason' ],
391 model: () => VideoBlacklistModel,
396 [ScopeNames.WITH_FILES]: {
399 model: () => VideoFileModel.unscoped(),
404 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
407 model: () => ScheduleVideoUpdateModel.unscoped(),
417 export class VideoModel extends Model<VideoModel> {
420 @Default(DataType.UUIDV4)
422 @Column(DataType.UUID)
426 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
432 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
438 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
444 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
445 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
449 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
454 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
460 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
461 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
466 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
467 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
471 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
501 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
502 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
507 commentsEnabled: boolean
511 waitTranscoding: boolean
515 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
526 @Default(Sequelize.NOW)
530 @ForeignKey(() => VideoChannelModel)
534 @BelongsTo(() => VideoChannelModel, {
540 VideoChannel: VideoChannelModel
542 @BelongsToMany(() => TagModel, {
543 foreignKey: 'videoId',
544 through: () => VideoTagModel,
549 @HasMany(() => VideoAbuseModel, {
556 VideoAbuses: VideoAbuseModel[]
558 @HasMany(() => VideoFileModel, {
565 VideoFiles: VideoFileModel[]
567 @HasMany(() => VideoShareModel, {
574 VideoShares: VideoShareModel[]
576 @HasMany(() => AccountVideoRateModel, {
583 AccountVideoRates: AccountVideoRateModel[]
585 @HasMany(() => VideoCommentModel, {
593 VideoComments: VideoCommentModel[]
595 @HasOne(() => ScheduleVideoUpdateModel, {
602 ScheduleVideoUpdate: ScheduleVideoUpdateModel
604 @HasOne(() => VideoBlacklistModel, {
611 VideoBlacklist: VideoBlacklistModel
613 @HasMany(() => VideoCaptionModel, {
620 ['separate' as any]: true
622 VideoCaptions: VideoCaptionModel[]
625 static async sendDelete (instance: VideoModel, options) {
626 if (instance.isOwned()) {
627 if (!instance.VideoChannel) {
628 instance.VideoChannel = await instance.$get('VideoChannel', {
632 include: [ ActorModel ]
635 transaction: options.transaction
636 }) as VideoChannelModel
639 return sendDeleteVideo(instance, options.transaction)
646 static async removeFiles (instance: VideoModel) {
647 const tasks: Promise<any>[] = []
649 logger.info('Removing files of video %s.', instance.url)
651 tasks.push(instance.removeThumbnail())
653 if (instance.isOwned()) {
654 if (!Array.isArray(instance.VideoFiles)) {
655 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
658 tasks.push(instance.removePreview())
660 // Remove physical files and torrents
661 instance.VideoFiles.forEach(file => {
662 tasks.push(instance.removeFile(file))
663 tasks.push(instance.removeTorrent(file))
667 // Do not wait video deletion because we could be in a transaction
670 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
677 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
680 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
681 function getRawQuery (select: string) {
682 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
683 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
684 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
685 'WHERE "Account"."actorId" = ' + actorId
686 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
687 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
688 'WHERE "VideoShare"."actorId" = ' + actorId
690 return `(${queryVideo}) UNION (${queryVideoShare})`
693 const rawQuery = getRawQuery('"Video"."id"')
694 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
700 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
703 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
706 { privacy: VideoPrivacy.PUBLIC },
707 { privacy: VideoPrivacy.UNLISTED }
712 attributes: [ 'language' ],
713 model: VideoCaptionModel.unscoped(),
717 attributes: [ 'id', 'url' ],
718 model: VideoShareModel.unscoped(),
720 // We only want videos shared by this actor
722 [Sequelize.Op.and]: [
725 [Sequelize.Op.not]: null
735 attributes: [ 'id', 'url' ],
736 model: ActorModel.unscoped()
741 model: VideoChannelModel.unscoped(),
745 attributes: [ 'name' ],
746 model: AccountModel.unscoped(),
750 attributes: [ 'id', 'url', 'followersUrl' ],
751 model: ActorModel.unscoped(),
757 attributes: [ 'id', 'url', 'followersUrl' ],
758 model: ActorModel.unscoped(),
768 return Bluebird.all([
769 // FIXME: typing issue
770 VideoModel.findAll(query as any),
771 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
772 ]).then(([ rows, totals ]) => {
773 // totals: totalVideos + totalVideoShares
775 let totalVideoShares = 0
776 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
777 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
779 const total = totalVideos + totalVideoShares
787 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
788 const query: IFindOptions<VideoModel> = {
791 order: getSort(sort),
794 model: VideoChannelModel,
807 model: ScheduleVideoUpdateModel,
811 model: VideoBlacklistModel,
817 if (withFiles === true) {
819 model: VideoFileModel.unscoped(),
824 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
832 static async listForApi (options: {
837 includeLocalVideos: boolean,
839 categoryOneOf?: number[],
840 licenceOneOf?: number[],
841 languageOneOf?: string[],
842 tagsOneOf?: string[],
843 tagsAllOf?: string[],
844 filter?: VideoFilter,
846 videoChannelId?: number,
850 offset: options.start,
851 limit: options.count,
852 order: getSort(options.sort)
855 // actorId === null has a meaning, so just check undefined
856 const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id
860 ScopeNames.AVAILABLE_FOR_LIST, {
863 categoryOneOf: options.categoryOneOf,
864 licenceOneOf: options.licenceOneOf,
865 languageOneOf: options.languageOneOf,
866 tagsOneOf: options.tagsOneOf,
867 tagsAllOf: options.tagsAllOf,
868 filter: options.filter,
869 withFiles: options.withFiles,
870 accountId: options.accountId,
871 videoChannelId: options.videoChannelId,
872 includeLocalVideos: options.includeLocalVideos
873 } as AvailableForListOptions
877 return VideoModel.scope(scopes)
878 .findAndCountAll(query)
879 .then(({ rows, count }) => {
887 static async searchAndPopulateAccountAndServer (options: {
888 includeLocalVideos: boolean
893 startDate?: string // ISO 8601
894 endDate?: string // ISO 8601
896 categoryOneOf?: number[]
897 licenceOneOf?: number[]
898 languageOneOf?: string[]
901 durationMin?: number // seconds
902 durationMax?: number // seconds
906 if (options.startDate || options.endDate) {
907 const publishedAtRange = { }
909 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
910 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
912 whereAnd.push({ publishedAt: publishedAtRange })
915 if (options.durationMin || options.durationMax) {
916 const durationRange = { }
918 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
919 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
921 whereAnd.push({ duration: durationRange })
924 const attributesInclude = []
925 const escapedSearch = VideoModel.sequelize.escape(options.search)
926 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
927 if (options.search) {
931 [ Sequelize.Op.in ]: Sequelize.literal(
933 'SELECT "video"."id" FROM "video" ' +
935 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
936 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
938 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
939 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
940 'WHERE "tag"."name" = ' + escapedSearch +
947 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
950 // Cannot search on similarity if we don't have a search
951 if (!options.search) {
952 attributesInclude.push(
953 Sequelize.literal('0 as similarity')
957 const query: IFindOptions<VideoModel> = {
959 include: attributesInclude
961 offset: options.start,
962 limit: options.count,
963 order: getSort(options.sort),
965 [ Sequelize.Op.and ]: whereAnd
969 const serverActor = await getServerActor()
972 ScopeNames.AVAILABLE_FOR_LIST, {
973 actorId: serverActor.id,
974 includeLocalVideos: options.includeLocalVideos,
976 categoryOneOf: options.categoryOneOf,
977 licenceOneOf: options.licenceOneOf,
978 languageOneOf: options.languageOneOf,
979 tagsOneOf: options.tagsOneOf,
980 tagsAllOf: options.tagsAllOf
981 } as AvailableForListOptions
985 return VideoModel.scope(scopes)
986 .findAndCountAll(query)
987 .then(({ rows, count }) => {
995 static load (id: number, t?: Sequelize.Transaction) {
996 const options = t ? { transaction: t } : undefined
998 return VideoModel.findById(id, options)
1001 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
1002 const query: IFindOptions<VideoModel> = {
1008 if (t !== undefined) query.transaction = t
1010 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1013 static loadAndPopulateAccountAndServerAndTags (id: number) {
1015 order: [ [ 'Tags', 'name', 'ASC' ] ]
1020 ScopeNames.WITH_TAGS,
1021 ScopeNames.WITH_BLACKLISTED,
1022 ScopeNames.WITH_FILES,
1023 ScopeNames.WITH_ACCOUNT_DETAILS,
1024 ScopeNames.WITH_SCHEDULED_UPDATE
1026 .findById(id, options)
1029 static loadByUUID (uuid: string) {
1037 .scope([ ScopeNames.WITH_FILES ])
1041 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1043 order: [ [ 'Tags', 'name', 'ASC' ] ],
1052 ScopeNames.WITH_TAGS,
1053 ScopeNames.WITH_BLACKLISTED,
1054 ScopeNames.WITH_FILES,
1055 ScopeNames.WITH_ACCOUNT_DETAILS,
1056 ScopeNames.WITH_SCHEDULED_UPDATE
1061 static async getStats () {
1062 const totalLocalVideos = await VideoModel.count({
1067 const totalVideos = await VideoModel.count()
1069 let totalLocalVideoViews = await VideoModel.sum('views', {
1074 // Sequelize could return null...
1075 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1079 totalLocalVideoViews,
1084 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1085 if (filter && filter === 'local') {
1094 private static getCategoryLabel (id: number) {
1095 return VIDEO_CATEGORIES[id] || 'Misc'
1098 private static getLicenceLabel (id: number) {
1099 return VIDEO_LICENCES[id] || 'Unknown'
1102 private static getLanguageLabel (id: string) {
1103 return VIDEO_LANGUAGES[id] || 'Unknown'
1106 private static getPrivacyLabel (id: number) {
1107 return VIDEO_PRIVACIES[id] || 'Unknown'
1110 private static getStateLabel (id: number) {
1111 return VIDEO_STATES[id] || 'Unknown'
1114 getOriginalFile () {
1115 if (Array.isArray(this.VideoFiles) === false) return undefined
1117 // The original file is the file that have the higher resolution
1118 return maxBy(this.VideoFiles, file => file.resolution)
1121 getVideoFilename (videoFile: VideoFileModel) {
1122 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1125 getThumbnailName () {
1126 // We always have a copy of the thumbnail
1127 const extension = '.jpg'
1128 return this.uuid + extension
1132 const extension = '.jpg'
1133 return this.uuid + extension
1136 getTorrentFileName (videoFile: VideoFileModel) {
1137 const extension = '.torrent'
1138 return this.uuid + '-' + videoFile.resolution + extension
1142 return this.remote === false
1145 createPreview (videoFile: VideoFileModel) {
1146 return generateImageFromVideoFile(
1147 this.getVideoFilePath(videoFile),
1148 CONFIG.STORAGE.PREVIEWS_DIR,
1149 this.getPreviewName(),
1154 createThumbnail (videoFile: VideoFileModel) {
1155 return generateImageFromVideoFile(
1156 this.getVideoFilePath(videoFile),
1157 CONFIG.STORAGE.THUMBNAILS_DIR,
1158 this.getThumbnailName(),
1163 getTorrentFilePath (videoFile: VideoFileModel) {
1164 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1167 getVideoFilePath (videoFile: VideoFileModel) {
1168 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1171 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1173 // Keep the extname, it's used by the client to stream the file inside a web browser
1174 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1175 createdBy: 'PeerTube',
1177 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1178 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1181 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1185 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1187 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1188 logger.info('Creating torrent %s.', filePath)
1190 await writeFilePromise(filePath, torrent)
1192 const parsedTorrent = parseTorrent(torrent)
1193 videoFile.infoHash = parsedTorrent.infoHash
1196 getEmbedStaticPath () {
1197 return '/videos/embed/' + this.uuid
1200 getThumbnailStaticPath () {
1201 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1204 getPreviewStaticPath () {
1205 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1208 toFormattedJSON (options?: {
1209 additionalAttributes: {
1211 waitTranscoding?: boolean,
1212 scheduledUpdate?: boolean,
1213 blacklistInfo?: boolean
1216 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1217 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1219 const videoObject: Video = {
1225 label: VideoModel.getCategoryLabel(this.category)
1229 label: VideoModel.getLicenceLabel(this.licence)
1233 label: VideoModel.getLanguageLabel(this.language)
1237 label: VideoModel.getPrivacyLabel(this.privacy)
1240 description: this.getTruncatedDescription(),
1241 isLocal: this.isOwned(),
1242 duration: this.duration,
1245 dislikes: this.dislikes,
1246 thumbnailPath: this.getThumbnailStaticPath(),
1247 previewPath: this.getPreviewStaticPath(),
1248 embedPath: this.getEmbedStaticPath(),
1249 createdAt: this.createdAt,
1250 updatedAt: this.updatedAt,
1251 publishedAt: this.publishedAt,
1253 id: formattedAccount.id,
1254 uuid: formattedAccount.uuid,
1255 name: formattedAccount.name,
1256 displayName: formattedAccount.displayName,
1257 url: formattedAccount.url,
1258 host: formattedAccount.host,
1259 avatar: formattedAccount.avatar
1262 id: formattedVideoChannel.id,
1263 uuid: formattedVideoChannel.uuid,
1264 name: formattedVideoChannel.name,
1265 displayName: formattedVideoChannel.displayName,
1266 url: formattedVideoChannel.url,
1267 host: formattedVideoChannel.host,
1268 avatar: formattedVideoChannel.avatar
1273 if (options.additionalAttributes.state === true) {
1274 videoObject.state = {
1276 label: VideoModel.getStateLabel(this.state)
1280 if (options.additionalAttributes.waitTranscoding === true) {
1281 videoObject.waitTranscoding = this.waitTranscoding
1284 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1285 videoObject.scheduledUpdate = {
1286 updateAt: this.ScheduleVideoUpdate.updateAt,
1287 privacy: this.ScheduleVideoUpdate.privacy || undefined
1291 if (options.additionalAttributes.blacklistInfo === true) {
1292 videoObject.blacklisted = !!this.VideoBlacklist
1293 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1300 toFormattedDetailsJSON (): VideoDetails {
1301 const formattedJson = this.toFormattedJSON({
1302 additionalAttributes: {
1303 scheduledUpdate: true,
1308 const detailsJson = {
1309 support: this.support,
1310 descriptionPath: this.getDescriptionPath(),
1311 channel: this.VideoChannel.toFormattedJSON(),
1312 account: this.VideoChannel.Account.toFormattedJSON(),
1313 tags: map(this.Tags, 'name'),
1314 commentsEnabled: this.commentsEnabled,
1315 waitTranscoding: this.waitTranscoding,
1318 label: VideoModel.getStateLabel(this.state)
1323 // Format and sort video files
1324 detailsJson.files = this.getFormattedVideoFilesJSON()
1326 return Object.assign(formattedJson, detailsJson)
1329 getFormattedVideoFilesJSON (): VideoFile[] {
1330 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1332 return this.VideoFiles
1334 let resolutionLabel = videoFile.resolution + 'p'
1338 id: videoFile.resolution,
1339 label: resolutionLabel
1341 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1342 size: videoFile.size,
1344 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1345 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1346 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1347 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1351 if (a.resolution.id < b.resolution.id) return 1
1352 if (a.resolution.id === b.resolution.id) return 0
1357 toActivityPubObject (): VideoTorrentObject {
1358 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1359 if (!this.Tags) this.Tags = []
1361 const tag = this.Tags.map(t => ({
1362 type: 'Hashtag' as 'Hashtag',
1367 if (this.language) {
1369 identifier: this.language,
1370 name: VideoModel.getLanguageLabel(this.language)
1375 if (this.category) {
1377 identifier: this.category + '',
1378 name: VideoModel.getCategoryLabel(this.category)
1385 identifier: this.licence + '',
1386 name: VideoModel.getLicenceLabel(this.licence)
1391 for (const file of this.VideoFiles) {
1394 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1395 href: this.getVideoFileUrl(file, baseUrlHttp),
1396 height: file.resolution,
1403 mimeType: 'application/x-bittorrent',
1404 href: this.getTorrentUrl(file, baseUrlHttp),
1405 height: file.resolution
1410 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1411 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1412 height: file.resolution
1416 // Add video url too
1419 mimeType: 'text/html',
1420 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1423 const subtitleLanguage = []
1424 for (const caption of this.VideoCaptions) {
1425 subtitleLanguage.push({
1426 identifier: caption.language,
1427 name: VideoCaptionModel.getLanguageLabel(caption.language)
1432 type: 'Video' as 'Video',
1435 duration: this.getActivityStreamDuration(),
1442 sensitive: this.nsfw,
1443 waitTranscoding: this.waitTranscoding,
1445 commentsEnabled: this.commentsEnabled,
1446 published: this.publishedAt.toISOString(),
1447 updated: this.updatedAt.toISOString(),
1448 mediaType: 'text/markdown',
1449 content: this.getTruncatedDescription(),
1450 support: this.support,
1454 url: this.getThumbnailUrl(baseUrlHttp),
1455 mediaType: 'image/jpeg',
1456 width: THUMBNAILS_SIZE.width,
1457 height: THUMBNAILS_SIZE.height
1460 likes: getVideoLikesActivityPubUrl(this),
1461 dislikes: getVideoDislikesActivityPubUrl(this),
1462 shares: getVideoSharesActivityPubUrl(this),
1463 comments: getVideoCommentsActivityPubUrl(this),
1467 id: this.VideoChannel.Account.Actor.url
1471 id: this.VideoChannel.Actor.url
1477 getTruncatedDescription () {
1478 if (!this.description) return null
1480 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1481 return peertubeTruncate(this.description, maxLength)
1484 async optimizeOriginalVideofile () {
1485 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1486 const newExtname = '.mp4'
1487 const inputVideoFile = this.getOriginalFile()
1488 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1489 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1491 const transcodeOptions = {
1492 inputPath: videoInputPath,
1493 outputPath: videoTranscodedPath
1496 // Could be very long!
1497 await transcode(transcodeOptions)
1500 await unlinkPromise(videoInputPath)
1502 // Important to do this before getVideoFilename() to take in account the new file extension
1503 inputVideoFile.set('extname', newExtname)
1505 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1506 await renamePromise(videoTranscodedPath, videoOutputPath)
1507 const stats = await statPromise(videoOutputPath)
1508 const fps = await getVideoFileFPS(videoOutputPath)
1510 inputVideoFile.set('size', stats.size)
1511 inputVideoFile.set('fps', fps)
1513 await this.createTorrentAndSetInfoHash(inputVideoFile)
1514 await inputVideoFile.save()
1517 // Auto destruction...
1518 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1524 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1525 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1526 const extname = '.mp4'
1528 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1529 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1531 const newVideoFile = new VideoFileModel({
1537 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1539 const transcodeOptions = {
1540 inputPath: videoInputPath,
1541 outputPath: videoOutputPath,
1546 await transcode(transcodeOptions)
1548 const stats = await statPromise(videoOutputPath)
1549 const fps = await getVideoFileFPS(videoOutputPath)
1551 newVideoFile.set('size', stats.size)
1552 newVideoFile.set('fps', fps)
1554 await this.createTorrentAndSetInfoHash(newVideoFile)
1556 await newVideoFile.save()
1558 this.VideoFiles.push(newVideoFile)
1561 async importVideoFile (inputFilePath: string) {
1562 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1563 const { size } = await statPromise(inputFilePath)
1564 const fps = await getVideoFileFPS(inputFilePath)
1566 let updatedVideoFile = new VideoFileModel({
1567 resolution: videoFileResolution,
1568 extname: extname(inputFilePath),
1574 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1576 if (currentVideoFile) {
1577 // Remove old file and old torrent
1578 await this.removeFile(currentVideoFile)
1579 await this.removeTorrent(currentVideoFile)
1580 // Remove the old video file from the array
1581 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1583 // Update the database
1584 currentVideoFile.set('extname', updatedVideoFile.extname)
1585 currentVideoFile.set('size', updatedVideoFile.size)
1586 currentVideoFile.set('fps', updatedVideoFile.fps)
1588 updatedVideoFile = currentVideoFile
1591 const outputPath = this.getVideoFilePath(updatedVideoFile)
1592 await copyFilePromise(inputFilePath, outputPath)
1594 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1596 await updatedVideoFile.save()
1598 this.VideoFiles.push(updatedVideoFile)
1601 getOriginalFileResolution () {
1602 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1604 return getVideoFileResolution(originalFilePath)
1607 getDescriptionPath () {
1608 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1611 removeThumbnail () {
1612 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1613 return unlinkPromise(thumbnailPath)
1614 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1618 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1619 return unlinkPromise(previewPath)
1620 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1623 removeFile (videoFile: VideoFileModel) {
1624 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1625 return unlinkPromise(filePath)
1626 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1629 removeTorrent (videoFile: VideoFileModel) {
1630 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1631 return unlinkPromise(torrentPath)
1632 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1635 getActivityStreamDuration () {
1636 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1637 return 'PT' + this.duration + 'S'
1641 if (this.isOwned()) return false
1643 const now = Date.now()
1644 const createdAtTime = this.createdAt.getTime()
1645 const updatedAtTime = this.updatedAt.getTime()
1647 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1648 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1651 private getBaseUrls () {
1655 if (this.isOwned()) {
1656 baseUrlHttp = CONFIG.WEBSERVER.URL
1657 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1659 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1660 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1663 return { baseUrlHttp, baseUrlWs }
1666 private getThumbnailUrl (baseUrlHttp: string) {
1667 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1670 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1671 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1674 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1675 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1678 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1679 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1682 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1683 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1686 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1687 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1688 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1689 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1691 const magnetHash = {
1695 infoHash: videoFile.infoHash,
1699 return magnetUtil.encode(magnetHash)