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'
29 } from 'sequelize-typescript'
30 import { VideoPrivacy, VideoResolution, VideoState } from '../../../shared'
31 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
32 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
33 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
34 import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils'
35 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
36 import { isBooleanValid } from '../../helpers/custom-validators/misc'
39 isVideoDescriptionValid,
47 } from '../../helpers/custom-validators/videos'
48 import { generateImageFromVideoFile, getVideoFileFPS, getVideoFileResolution, transcode } from '../../helpers/ffmpeg-utils'
49 import { logger } from '../../helpers/logger'
50 import { getServerActor } from '../../helpers/utils'
58 STATIC_DOWNLOAD_PATHS,
67 } from '../../initializers'
69 getVideoCommentsActivityPubUrl,
70 getVideoDislikesActivityPubUrl,
71 getVideoLikesActivityPubUrl,
72 getVideoSharesActivityPubUrl
73 } from '../../lib/activitypub'
74 import { sendDeleteVideo } from '../../lib/activitypub/send'
75 import { AccountModel } from '../account/account'
76 import { AccountVideoRateModel } from '../account/account-video-rate'
77 import { ActorModel } from '../activitypub/actor'
78 import { AvatarModel } from '../avatar/avatar'
79 import { ServerModel } from '../server/server'
80 import { buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
81 import { TagModel } from './tag'
82 import { VideoAbuseModel } from './video-abuse'
83 import { VideoChannelModel } from './video-channel'
84 import { VideoCommentModel } from './video-comment'
85 import { VideoFileModel } from './video-file'
86 import { VideoShareModel } from './video-share'
87 import { VideoTagModel } from './video-tag'
88 import { ScheduleVideoUpdateModel } from './schedule-video-update'
89 import { VideoCaptionModel } from './video-caption'
90 import { VideoBlacklistModel } from './video-blacklist'
91 import { copy, remove, rename, stat, writeFile } from 'fs-extra'
92 import { immutableAssign } from '../../tests/utils'
94 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
95 const indexes: Sequelize.DefineIndexesOptions[] = [
96 buildTrigramSearchIndex('video_name_trigram', 'name'),
98 { fields: [ 'createdAt' ] },
99 { fields: [ 'publishedAt' ] },
100 { fields: [ 'duration' ] },
101 { fields: [ 'category' ] },
102 { fields: [ 'licence' ] },
103 { fields: [ 'nsfw' ] },
104 { fields: [ 'language' ] },
105 { fields: [ 'waitTranscoding' ] },
106 { fields: [ 'state' ] },
107 { fields: [ 'remote' ] },
108 { fields: [ 'views' ] },
109 { fields: [ 'likes' ] },
110 { fields: [ 'channelId' ] },
121 export enum ScopeNames {
122 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
124 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
125 WITH_TAGS = 'WITH_TAGS',
126 WITH_FILES = 'WITH_FILES',
127 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
128 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
131 type ForAPIOptions = {
136 type AvailableForListIDsOptions = {
138 includeLocalVideos: boolean
140 categoryOneOf?: number[]
142 licenceOneOf?: number[]
143 languageOneOf?: string[]
148 videoChannelId?: number
152 [ScopeNames.FOR_API]: (options: ForAPIOptions) => {
153 const accountInclude = {
154 attributes: [ 'id', 'name' ],
155 model: AccountModel.unscoped(),
159 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
160 model: ActorModel.unscoped(),
164 attributes: [ 'host' ],
165 model: ServerModel.unscoped(),
169 model: AvatarModel.unscoped(),
177 const videoChannelInclude = {
178 attributes: [ 'name', 'description', 'id' ],
179 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 const query: IFindOptions<VideoModel> = {
205 [Sequelize.Op.any]: options.ids
208 include: [ videoChannelInclude ]
211 if (options.withFiles === true) {
213 model: VideoFileModel.unscoped(),
220 [ScopeNames.AVAILABLE_FOR_LIST_IDS]: (options: AvailableForListIDsOptions) => {
221 const query: IFindOptions<VideoModel> = {
222 attributes: [ 'id' ],
225 [Sequelize.Op.notIn]: Sequelize.literal(
226 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
229 // Always list public videos
230 privacy: VideoPrivacy.PUBLIC,
231 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
232 [ Sequelize.Op.or ]: [
234 state: VideoState.PUBLISHED
237 [ Sequelize.Op.and ]: {
238 state: VideoState.TO_TRANSCODE,
239 waitTranscoding: false
247 if (options.filter || options.accountId || options.videoChannelId) {
248 const videoChannelInclude: IIncludeOptions = {
250 model: VideoChannelModel.unscoped(),
254 if (options.videoChannelId) {
255 videoChannelInclude.where = {
256 id: options.videoChannelId
260 if (options.filter || options.accountId) {
261 const accountInclude: IIncludeOptions = {
263 model: AccountModel.unscoped(),
267 if (options.filter) {
268 accountInclude.include = [
271 model: ActorModel.unscoped(),
273 where: VideoModel.buildActorWhereWithFilter(options.filter)
278 if (options.accountId) {
279 accountInclude.where = { id: options.accountId }
282 videoChannelInclude.include = [ accountInclude ]
285 query.include.push(videoChannelInclude)
288 if (options.actorId) {
289 let localVideosReq = ''
290 if (options.includeLocalVideos === true) {
291 localVideosReq = ' UNION ALL ' +
292 'SELECT "video"."id" AS "id" FROM "video" ' +
293 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
294 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
295 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
296 'WHERE "actor"."serverId" IS NULL'
299 // Force actorId to be a number to avoid SQL injections
300 const actorIdNumber = parseInt(options.actorId.toString(), 10)
301 query.where['id'][ Sequelize.Op.in ] = Sequelize.literal(
303 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
304 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
305 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
307 'SELECT "video"."id" AS "id" FROM "video" ' +
308 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
309 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
310 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
311 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
312 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
318 if (options.withFiles === true) {
320 model: VideoFileModel.unscoped(),
325 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
326 if (options.tagsAllOf || options.tagsOneOf) {
327 const createTagsIn = (tags: string[]) => {
328 return tags.map(t => VideoModel.sequelize.escape(t))
332 if (options.tagsOneOf) {
333 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
335 'SELECT "videoId" FROM "videoTag" ' +
336 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
337 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
342 if (options.tagsAllOf) {
343 query.where['id'][Sequelize.Op.in] = Sequelize.literal(
345 'SELECT "videoId" FROM "videoTag" ' +
346 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
347 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
348 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
354 if (options.nsfw === true || options.nsfw === false) {
355 query.where['nsfw'] = options.nsfw
358 if (options.categoryOneOf) {
359 query.where['category'] = {
360 [Sequelize.Op.or]: options.categoryOneOf
364 if (options.licenceOneOf) {
365 query.where['licence'] = {
366 [Sequelize.Op.or]: options.licenceOneOf
370 if (options.languageOneOf) {
371 query.where['language'] = {
372 [Sequelize.Op.or]: options.languageOneOf
378 [ScopeNames.WITH_ACCOUNT_DETAILS]: {
381 model: () => VideoChannelModel.unscoped(),
386 exclude: [ 'privateKey', 'publicKey' ]
388 model: () => ActorModel.unscoped(),
392 attributes: [ 'host' ],
393 model: () => ServerModel.unscoped(),
397 model: () => AvatarModel.unscoped(),
403 model: () => AccountModel.unscoped(),
407 model: () => ActorModel.unscoped(),
409 exclude: [ 'privateKey', 'publicKey' ]
414 attributes: [ 'host' ],
415 model: () => ServerModel.unscoped(),
419 model: () => AvatarModel.unscoped(),
430 [ScopeNames.WITH_TAGS]: {
431 include: [ () => TagModel ]
433 [ScopeNames.WITH_BLACKLISTED]: {
436 attributes: [ 'id', 'reason' ],
437 model: () => VideoBlacklistModel,
442 [ScopeNames.WITH_FILES]: {
445 model: () => VideoFileModel.unscoped(),
450 [ScopeNames.WITH_SCHEDULED_UPDATE]: {
453 model: () => ScheduleVideoUpdateModel.unscoped(),
463 export class VideoModel extends Model<VideoModel> {
466 @Default(DataType.UUIDV4)
468 @Column(DataType.UUID)
472 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
478 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
484 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
490 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
491 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
495 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
500 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
506 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
507 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
512 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
513 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
517 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
547 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
548 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
553 commentsEnabled: boolean
557 waitTranscoding: boolean
561 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
572 @Default(Sequelize.NOW)
576 @ForeignKey(() => VideoChannelModel)
580 @BelongsTo(() => VideoChannelModel, {
586 VideoChannel: VideoChannelModel
588 @BelongsToMany(() => TagModel, {
589 foreignKey: 'videoId',
590 through: () => VideoTagModel,
595 @HasMany(() => VideoAbuseModel, {
602 VideoAbuses: VideoAbuseModel[]
604 @HasMany(() => VideoFileModel, {
611 VideoFiles: VideoFileModel[]
613 @HasMany(() => VideoShareModel, {
620 VideoShares: VideoShareModel[]
622 @HasMany(() => AccountVideoRateModel, {
629 AccountVideoRates: AccountVideoRateModel[]
631 @HasMany(() => VideoCommentModel, {
639 VideoComments: VideoCommentModel[]
641 @HasOne(() => ScheduleVideoUpdateModel, {
648 ScheduleVideoUpdate: ScheduleVideoUpdateModel
650 @HasOne(() => VideoBlacklistModel, {
657 VideoBlacklist: VideoBlacklistModel
659 @HasMany(() => VideoCaptionModel, {
666 ['separate' as any]: true
668 VideoCaptions: VideoCaptionModel[]
671 static async sendDelete (instance: VideoModel, options) {
672 if (instance.isOwned()) {
673 if (!instance.VideoChannel) {
674 instance.VideoChannel = await instance.$get('VideoChannel', {
678 include: [ ActorModel ]
681 transaction: options.transaction
682 }) as VideoChannelModel
685 return sendDeleteVideo(instance, options.transaction)
692 static async removeFiles (instance: VideoModel) {
693 const tasks: Promise<any>[] = []
695 logger.info('Removing files of video %s.', instance.url)
697 tasks.push(instance.removeThumbnail())
699 if (instance.isOwned()) {
700 if (!Array.isArray(instance.VideoFiles)) {
701 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
704 tasks.push(instance.removePreview())
706 // Remove physical files and torrents
707 instance.VideoFiles.forEach(file => {
708 tasks.push(instance.removeFile(file))
709 tasks.push(instance.removeTorrent(file))
713 // Do not wait video deletion because we could be in a transaction
716 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
723 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
726 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
727 function getRawQuery (select: string) {
728 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
729 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
730 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
731 'WHERE "Account"."actorId" = ' + actorId
732 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
733 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
734 'WHERE "VideoShare"."actorId" = ' + actorId
736 return `(${queryVideo}) UNION (${queryVideoShare})`
739 const rawQuery = getRawQuery('"Video"."id"')
740 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
746 order: getSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
749 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
752 { privacy: VideoPrivacy.PUBLIC },
753 { privacy: VideoPrivacy.UNLISTED }
758 attributes: [ 'language' ],
759 model: VideoCaptionModel.unscoped(),
763 attributes: [ 'id', 'url' ],
764 model: VideoShareModel.unscoped(),
766 // We only want videos shared by this actor
768 [Sequelize.Op.and]: [
771 [Sequelize.Op.not]: null
781 attributes: [ 'id', 'url' ],
782 model: ActorModel.unscoped()
787 model: VideoChannelModel.unscoped(),
791 attributes: [ 'name' ],
792 model: AccountModel.unscoped(),
796 attributes: [ 'id', 'url', 'followersUrl' ],
797 model: ActorModel.unscoped(),
803 attributes: [ 'id', 'url', 'followersUrl' ],
804 model: ActorModel.unscoped(),
814 return Bluebird.all([
815 // FIXME: typing issue
816 VideoModel.findAll(query as any),
817 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
818 ]).then(([ rows, totals ]) => {
819 // totals: totalVideos + totalVideoShares
821 let totalVideoShares = 0
822 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
823 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
825 const total = totalVideos + totalVideoShares
833 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
834 const query: IFindOptions<VideoModel> = {
837 order: getSort(sort),
840 model: VideoChannelModel,
853 model: ScheduleVideoUpdateModel,
857 model: VideoBlacklistModel,
863 if (withFiles === true) {
865 model: VideoFileModel.unscoped(),
870 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
878 static async listForApi (options: {
883 includeLocalVideos: boolean,
885 categoryOneOf?: number[],
886 licenceOneOf?: number[],
887 languageOneOf?: string[],
888 tagsOneOf?: string[],
889 tagsAllOf?: string[],
890 filter?: VideoFilter,
892 videoChannelId?: number,
896 offset: options.start,
897 limit: options.count,
898 order: getSort(options.sort)
901 // actorId === null has a meaning, so just check undefined
902 const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id
904 const queryOptions = {
907 categoryOneOf: options.categoryOneOf,
908 licenceOneOf: options.licenceOneOf,
909 languageOneOf: options.languageOneOf,
910 tagsOneOf: options.tagsOneOf,
911 tagsAllOf: options.tagsAllOf,
912 filter: options.filter,
913 withFiles: options.withFiles,
914 accountId: options.accountId,
915 videoChannelId: options.videoChannelId,
916 includeLocalVideos: options.includeLocalVideos
919 return VideoModel.getAvailableForApi(query, queryOptions)
922 static async searchAndPopulateAccountAndServer (options: {
923 includeLocalVideos: boolean
928 startDate?: string // ISO 8601
929 endDate?: string // ISO 8601
931 categoryOneOf?: number[]
932 licenceOneOf?: number[]
933 languageOneOf?: string[]
936 durationMin?: number // seconds
937 durationMax?: number // seconds
941 if (options.startDate || options.endDate) {
942 const publishedAtRange = { }
944 if (options.startDate) publishedAtRange[Sequelize.Op.gte] = options.startDate
945 if (options.endDate) publishedAtRange[Sequelize.Op.lte] = options.endDate
947 whereAnd.push({ publishedAt: publishedAtRange })
950 if (options.durationMin || options.durationMax) {
951 const durationRange = { }
953 if (options.durationMin) durationRange[Sequelize.Op.gte] = options.durationMin
954 if (options.durationMax) durationRange[Sequelize.Op.lte] = options.durationMax
956 whereAnd.push({ duration: durationRange })
959 const attributesInclude = []
960 const escapedSearch = VideoModel.sequelize.escape(options.search)
961 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
962 if (options.search) {
966 [ Sequelize.Op.in ]: Sequelize.literal(
968 'SELECT "video"."id" FROM "video" ' +
970 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
971 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
973 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
974 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
975 'WHERE "tag"."name" = ' + escapedSearch +
982 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
985 // Cannot search on similarity if we don't have a search
986 if (!options.search) {
987 attributesInclude.push(
988 Sequelize.literal('0 as similarity')
992 const query: IFindOptions<VideoModel> = {
994 include: attributesInclude
996 offset: options.start,
997 limit: options.count,
998 order: getSort(options.sort),
1000 [ Sequelize.Op.and ]: whereAnd
1004 const serverActor = await getServerActor()
1005 const queryOptions = {
1006 actorId: serverActor.id,
1007 includeLocalVideos: options.includeLocalVideos,
1009 categoryOneOf: options.categoryOneOf,
1010 licenceOneOf: options.licenceOneOf,
1011 languageOneOf: options.languageOneOf,
1012 tagsOneOf: options.tagsOneOf,
1013 tagsAllOf: options.tagsAllOf
1016 return VideoModel.getAvailableForApi(query, queryOptions)
1019 static load (id: number, t?: Sequelize.Transaction) {
1020 const options = t ? { transaction: t } : undefined
1022 return VideoModel.findById(id, options)
1025 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
1026 const query: IFindOptions<VideoModel> = {
1032 if (t !== undefined) query.transaction = t
1034 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1037 static loadAndPopulateAccountAndServerAndTags (id: number) {
1039 order: [ [ 'Tags', 'name', 'ASC' ] ]
1044 ScopeNames.WITH_TAGS,
1045 ScopeNames.WITH_BLACKLISTED,
1046 ScopeNames.WITH_FILES,
1047 ScopeNames.WITH_ACCOUNT_DETAILS,
1048 ScopeNames.WITH_SCHEDULED_UPDATE
1050 .findById(id, options)
1053 static loadByUUID (uuid: string) {
1061 .scope([ ScopeNames.WITH_FILES ])
1065 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1067 order: [ [ 'Tags', 'name', 'ASC' ] ],
1076 ScopeNames.WITH_TAGS,
1077 ScopeNames.WITH_BLACKLISTED,
1078 ScopeNames.WITH_FILES,
1079 ScopeNames.WITH_ACCOUNT_DETAILS,
1080 ScopeNames.WITH_SCHEDULED_UPDATE
1085 static async getStats () {
1086 const totalLocalVideos = await VideoModel.count({
1091 const totalVideos = await VideoModel.count()
1093 let totalLocalVideoViews = await VideoModel.sum('views', {
1098 // Sequelize could return null...
1099 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1103 totalLocalVideoViews,
1108 static incrementViews (id: number, views: number) {
1109 return VideoModel.increment('views', {
1117 // threshold corresponds to how many video the field should have to be returned
1118 static getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1119 const query: IFindOptions<VideoModel> = {
1120 attributes: [ field ],
1123 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1124 [Sequelize.Op.gte]: threshold
1125 }) as any, // FIXME: typings
1128 [Sequelize.Op.not]: null
1130 privacy: VideoPrivacy.PUBLIC,
1131 state: VideoState.PUBLISHED
1133 order: [ this.sequelize.random() ]
1136 return VideoModel.findAll(query)
1137 .then(rows => rows.map(r => r[field]))
1140 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1141 if (filter && filter === 'local') {
1150 private static async getAvailableForApi (query: IFindOptions<VideoModel>, options: AvailableForListIDsOptions) {
1153 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1157 const { count, rows: rowsId } = await VideoModel.scope(idsScope).findAndCountAll(query)
1158 const ids = rowsId.map(r => r.id)
1160 if (ids.length === 0) return { data: [], total: count }
1163 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1165 const rows = await VideoModel.scope(apiScope).findAll(immutableAssign(query, { offset: 0 }))
1173 private static getCategoryLabel (id: number) {
1174 return VIDEO_CATEGORIES[id] || 'Misc'
1177 private static getLicenceLabel (id: number) {
1178 return VIDEO_LICENCES[id] || 'Unknown'
1181 private static getLanguageLabel (id: string) {
1182 return VIDEO_LANGUAGES[id] || 'Unknown'
1185 private static getPrivacyLabel (id: number) {
1186 return VIDEO_PRIVACIES[id] || 'Unknown'
1189 private static getStateLabel (id: number) {
1190 return VIDEO_STATES[id] || 'Unknown'
1193 getOriginalFile () {
1194 if (Array.isArray(this.VideoFiles) === false) return undefined
1196 // The original file is the file that have the higher resolution
1197 return maxBy(this.VideoFiles, file => file.resolution)
1200 getVideoFilename (videoFile: VideoFileModel) {
1201 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1204 getThumbnailName () {
1205 // We always have a copy of the thumbnail
1206 const extension = '.jpg'
1207 return this.uuid + extension
1211 const extension = '.jpg'
1212 return this.uuid + extension
1215 getTorrentFileName (videoFile: VideoFileModel) {
1216 const extension = '.torrent'
1217 return this.uuid + '-' + videoFile.resolution + extension
1221 return this.remote === false
1224 createPreview (videoFile: VideoFileModel) {
1225 return generateImageFromVideoFile(
1226 this.getVideoFilePath(videoFile),
1227 CONFIG.STORAGE.PREVIEWS_DIR,
1228 this.getPreviewName(),
1233 createThumbnail (videoFile: VideoFileModel) {
1234 return generateImageFromVideoFile(
1235 this.getVideoFilePath(videoFile),
1236 CONFIG.STORAGE.THUMBNAILS_DIR,
1237 this.getThumbnailName(),
1242 getTorrentFilePath (videoFile: VideoFileModel) {
1243 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1246 getVideoFilePath (videoFile: VideoFileModel) {
1247 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1250 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1252 // Keep the extname, it's used by the client to stream the file inside a web browser
1253 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1254 createdBy: 'PeerTube',
1256 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1257 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1260 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1264 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1266 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1267 logger.info('Creating torrent %s.', filePath)
1269 await writeFile(filePath, torrent)
1271 const parsedTorrent = parseTorrent(torrent)
1272 videoFile.infoHash = parsedTorrent.infoHash
1275 getEmbedStaticPath () {
1276 return '/videos/embed/' + this.uuid
1279 getThumbnailStaticPath () {
1280 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1283 getPreviewStaticPath () {
1284 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1287 toFormattedJSON (options?: {
1288 additionalAttributes: {
1290 waitTranscoding?: boolean,
1291 scheduledUpdate?: boolean,
1292 blacklistInfo?: boolean
1295 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1296 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1298 const videoObject: Video = {
1304 label: VideoModel.getCategoryLabel(this.category)
1308 label: VideoModel.getLicenceLabel(this.licence)
1312 label: VideoModel.getLanguageLabel(this.language)
1316 label: VideoModel.getPrivacyLabel(this.privacy)
1319 description: this.getTruncatedDescription(),
1320 isLocal: this.isOwned(),
1321 duration: this.duration,
1324 dislikes: this.dislikes,
1325 thumbnailPath: this.getThumbnailStaticPath(),
1326 previewPath: this.getPreviewStaticPath(),
1327 embedPath: this.getEmbedStaticPath(),
1328 createdAt: this.createdAt,
1329 updatedAt: this.updatedAt,
1330 publishedAt: this.publishedAt,
1332 id: formattedAccount.id,
1333 uuid: formattedAccount.uuid,
1334 name: formattedAccount.name,
1335 displayName: formattedAccount.displayName,
1336 url: formattedAccount.url,
1337 host: formattedAccount.host,
1338 avatar: formattedAccount.avatar
1341 id: formattedVideoChannel.id,
1342 uuid: formattedVideoChannel.uuid,
1343 name: formattedVideoChannel.name,
1344 displayName: formattedVideoChannel.displayName,
1345 url: formattedVideoChannel.url,
1346 host: formattedVideoChannel.host,
1347 avatar: formattedVideoChannel.avatar
1352 if (options.additionalAttributes.state === true) {
1353 videoObject.state = {
1355 label: VideoModel.getStateLabel(this.state)
1359 if (options.additionalAttributes.waitTranscoding === true) {
1360 videoObject.waitTranscoding = this.waitTranscoding
1363 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1364 videoObject.scheduledUpdate = {
1365 updateAt: this.ScheduleVideoUpdate.updateAt,
1366 privacy: this.ScheduleVideoUpdate.privacy || undefined
1370 if (options.additionalAttributes.blacklistInfo === true) {
1371 videoObject.blacklisted = !!this.VideoBlacklist
1372 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1379 toFormattedDetailsJSON (): VideoDetails {
1380 const formattedJson = this.toFormattedJSON({
1381 additionalAttributes: {
1382 scheduledUpdate: true,
1387 const detailsJson = {
1388 support: this.support,
1389 descriptionPath: this.getDescriptionPath(),
1390 channel: this.VideoChannel.toFormattedJSON(),
1391 account: this.VideoChannel.Account.toFormattedJSON(),
1392 tags: map(this.Tags, 'name'),
1393 commentsEnabled: this.commentsEnabled,
1394 waitTranscoding: this.waitTranscoding,
1397 label: VideoModel.getStateLabel(this.state)
1402 // Format and sort video files
1403 detailsJson.files = this.getFormattedVideoFilesJSON()
1405 return Object.assign(formattedJson, detailsJson)
1408 getFormattedVideoFilesJSON (): VideoFile[] {
1409 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1411 return this.VideoFiles
1413 let resolutionLabel = videoFile.resolution + 'p'
1417 id: videoFile.resolution,
1418 label: resolutionLabel
1420 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1421 size: videoFile.size,
1423 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1424 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1425 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1426 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1430 if (a.resolution.id < b.resolution.id) return 1
1431 if (a.resolution.id === b.resolution.id) return 0
1436 toActivityPubObject (): VideoTorrentObject {
1437 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1438 if (!this.Tags) this.Tags = []
1440 const tag = this.Tags.map(t => ({
1441 type: 'Hashtag' as 'Hashtag',
1446 if (this.language) {
1448 identifier: this.language,
1449 name: VideoModel.getLanguageLabel(this.language)
1454 if (this.category) {
1456 identifier: this.category + '',
1457 name: VideoModel.getCategoryLabel(this.category)
1464 identifier: this.licence + '',
1465 name: VideoModel.getLicenceLabel(this.licence)
1470 for (const file of this.VideoFiles) {
1473 mimeType: VIDEO_EXT_MIMETYPE[file.extname],
1474 href: this.getVideoFileUrl(file, baseUrlHttp),
1475 height: file.resolution,
1482 mimeType: 'application/x-bittorrent',
1483 href: this.getTorrentUrl(file, baseUrlHttp),
1484 height: file.resolution
1489 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1490 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1491 height: file.resolution
1495 // Add video url too
1498 mimeType: 'text/html',
1499 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1502 const subtitleLanguage = []
1503 for (const caption of this.VideoCaptions) {
1504 subtitleLanguage.push({
1505 identifier: caption.language,
1506 name: VideoCaptionModel.getLanguageLabel(caption.language)
1511 type: 'Video' as 'Video',
1514 duration: this.getActivityStreamDuration(),
1521 sensitive: this.nsfw,
1522 waitTranscoding: this.waitTranscoding,
1524 commentsEnabled: this.commentsEnabled,
1525 published: this.publishedAt.toISOString(),
1526 updated: this.updatedAt.toISOString(),
1527 mediaType: 'text/markdown',
1528 content: this.getTruncatedDescription(),
1529 support: this.support,
1533 url: this.getThumbnailUrl(baseUrlHttp),
1534 mediaType: 'image/jpeg',
1535 width: THUMBNAILS_SIZE.width,
1536 height: THUMBNAILS_SIZE.height
1539 likes: getVideoLikesActivityPubUrl(this),
1540 dislikes: getVideoDislikesActivityPubUrl(this),
1541 shares: getVideoSharesActivityPubUrl(this),
1542 comments: getVideoCommentsActivityPubUrl(this),
1546 id: this.VideoChannel.Account.Actor.url
1550 id: this.VideoChannel.Actor.url
1556 getTruncatedDescription () {
1557 if (!this.description) return null
1559 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1560 return peertubeTruncate(this.description, maxLength)
1563 async optimizeOriginalVideofile () {
1564 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1565 const newExtname = '.mp4'
1566 const inputVideoFile = this.getOriginalFile()
1567 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1568 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1570 const transcodeOptions = {
1571 inputPath: videoInputPath,
1572 outputPath: videoTranscodedPath
1575 // Could be very long!
1576 await transcode(transcodeOptions)
1579 await remove(videoInputPath)
1581 // Important to do this before getVideoFilename() to take in account the new file extension
1582 inputVideoFile.set('extname', newExtname)
1584 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1585 await rename(videoTranscodedPath, videoOutputPath)
1586 const stats = await stat(videoOutputPath)
1587 const fps = await getVideoFileFPS(videoOutputPath)
1589 inputVideoFile.set('size', stats.size)
1590 inputVideoFile.set('fps', fps)
1592 await this.createTorrentAndSetInfoHash(inputVideoFile)
1593 await inputVideoFile.save()
1596 // Auto destruction...
1597 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1603 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1604 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1605 const extname = '.mp4'
1607 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1608 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1610 const newVideoFile = new VideoFileModel({
1616 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1618 const transcodeOptions = {
1619 inputPath: videoInputPath,
1620 outputPath: videoOutputPath,
1625 await transcode(transcodeOptions)
1627 const stats = await stat(videoOutputPath)
1628 const fps = await getVideoFileFPS(videoOutputPath)
1630 newVideoFile.set('size', stats.size)
1631 newVideoFile.set('fps', fps)
1633 await this.createTorrentAndSetInfoHash(newVideoFile)
1635 await newVideoFile.save()
1637 this.VideoFiles.push(newVideoFile)
1640 async importVideoFile (inputFilePath: string) {
1641 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1642 const { size } = await stat(inputFilePath)
1643 const fps = await getVideoFileFPS(inputFilePath)
1645 let updatedVideoFile = new VideoFileModel({
1646 resolution: videoFileResolution,
1647 extname: extname(inputFilePath),
1653 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1655 if (currentVideoFile) {
1656 // Remove old file and old torrent
1657 await this.removeFile(currentVideoFile)
1658 await this.removeTorrent(currentVideoFile)
1659 // Remove the old video file from the array
1660 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1662 // Update the database
1663 currentVideoFile.set('extname', updatedVideoFile.extname)
1664 currentVideoFile.set('size', updatedVideoFile.size)
1665 currentVideoFile.set('fps', updatedVideoFile.fps)
1667 updatedVideoFile = currentVideoFile
1670 const outputPath = this.getVideoFilePath(updatedVideoFile)
1671 await copy(inputFilePath, outputPath)
1673 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1675 await updatedVideoFile.save()
1677 this.VideoFiles.push(updatedVideoFile)
1680 getOriginalFileResolution () {
1681 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1683 return getVideoFileResolution(originalFilePath)
1686 getDescriptionPath () {
1687 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1690 removeThumbnail () {
1691 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1692 return remove(thumbnailPath)
1693 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1697 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1698 return remove(previewPath)
1699 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1702 removeFile (videoFile: VideoFileModel) {
1703 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1704 return remove(filePath)
1705 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1708 removeTorrent (videoFile: VideoFileModel) {
1709 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1710 return remove(torrentPath)
1711 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1714 getActivityStreamDuration () {
1715 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1716 return 'PT' + this.duration + 'S'
1720 if (this.isOwned()) return false
1722 const now = Date.now()
1723 const createdAtTime = this.createdAt.getTime()
1724 const updatedAtTime = this.updatedAt.getTime()
1726 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1727 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1730 private getBaseUrls () {
1734 if (this.isOwned()) {
1735 baseUrlHttp = CONFIG.WEBSERVER.URL
1736 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1738 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1739 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1742 return { baseUrlHttp, baseUrlWs }
1745 private getThumbnailUrl (baseUrlHttp: string) {
1746 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1749 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1750 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1753 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1754 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1757 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1758 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1761 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1762 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1765 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1766 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1767 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1768 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1770 const magnetHash = {
1774 infoHash: videoFile.infoHash,
1778 return magnetUtil.encode(magnetHash)