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, getVideoSort, 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 { VideoViewModel } from './video-views'
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
149 trendingDays?: number
153 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
154 const accountInclude = {
155 attributes: [ 'id', 'name' ],
156 model: AccountModel.unscoped(),
160 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
161 model: ActorModel.unscoped(),
165 attributes: [ 'host' ],
166 model: ServerModel.unscoped(),
170 model: AvatarModel.unscoped(),
178 const videoChannelInclude = {
179 attributes: [ 'name', 'description', 'id' ],
180 model: VideoChannelModel.unscoped(),
184 attributes: [ 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
185 model: ActorModel.unscoped(),
189 attributes: [ 'host' ],
190 model: ServerModel.unscoped(),
194 model: AvatarModel.unscoped(),
203 const query: IFindOptions<VideoModel> = {
206 [ Sequelize.Op.any ]: options.ids
209 include: [ videoChannelInclude ]
212 if (options.withFiles === true) {
214 model: VideoFileModel.unscoped(),
221 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
222 const query: IFindOptions<VideoModel> = {
223 attributes: [ 'id' ],
226 [ Sequelize.Op.and ]: [
228 [ Sequelize.Op.notIn ]: Sequelize.literal(
229 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
234 // Always list public videos
235 privacy: VideoPrivacy.PUBLIC,
236 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
237 [ Sequelize.Op.or ]: [
239 state: VideoState.PUBLISHED
242 [ Sequelize.Op.and ]: {
243 state: VideoState.TO_TRANSCODE,
244 waitTranscoding: false
252 if (options.filter || options.accountId || options.videoChannelId) {
253 const videoChannelInclude: IIncludeOptions = {
255 model: VideoChannelModel.unscoped(),
259 if (options.videoChannelId) {
260 videoChannelInclude.where = {
261 id: options.videoChannelId
265 if (options.filter || options.accountId) {
266 const accountInclude: IIncludeOptions = {
268 model: AccountModel.unscoped(),
272 if (options.filter) {
273 accountInclude.include = [
276 model: ActorModel.unscoped(),
278 where: VideoModel.buildActorWhereWithFilter(options.filter)
283 if (options.accountId) {
284 accountInclude.where = { id: options.accountId }
287 videoChannelInclude.include = [ accountInclude ]
290 query.include.push(videoChannelInclude)
293 if (options.actorId) {
294 let localVideosReq = ''
295 if (options.includeLocalVideos === true) {
296 localVideosReq = ' UNION ALL ' +
297 'SELECT "video"."id" AS "id" FROM "video" ' +
298 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
299 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
300 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
301 'WHERE "actor"."serverId" IS NULL'
304 // Force actorId to be a number to avoid SQL injections
305 const actorIdNumber = parseInt(options.actorId.toString(), 10)
306 query.where[ 'id' ][ Sequelize.Op.and ].push({
307 [ Sequelize.Op.in ]: Sequelize.literal(
309 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
310 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
311 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
313 'SELECT "video"."id" AS "id" FROM "video" ' +
314 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
315 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
316 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
317 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
318 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
325 if (options.withFiles === true) {
326 query.where[ 'id' ][ Sequelize.Op.and ].push({
327 [ Sequelize.Op.in ]: Sequelize.literal(
328 '(SELECT "videoId" FROM "videoFile")'
333 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
334 if (options.tagsAllOf || options.tagsOneOf) {
335 const createTagsIn = (tags: string[]) => {
336 return tags.map(t => VideoModel.sequelize.escape(t))
340 if (options.tagsOneOf) {
341 query.where[ 'id' ][ Sequelize.Op.and ].push({
342 [ Sequelize.Op.in ]: Sequelize.literal(
344 'SELECT "videoId" FROM "videoTag" ' +
345 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
346 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
352 if (options.tagsAllOf) {
353 query.where[ 'id' ][ Sequelize.Op.and ].push({
354 [ Sequelize.Op.in ]: Sequelize.literal(
356 'SELECT "videoId" FROM "videoTag" ' +
357 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
358 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
359 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
366 if (options.nsfw === true || options.nsfw === false) {
367 query.where[ 'nsfw' ] = options.nsfw
370 if (options.categoryOneOf) {
371 query.where[ 'category' ] = {
372 [ Sequelize.Op.or ]: options.categoryOneOf
376 if (options.licenceOneOf) {
377 query.where[ 'licence' ] = {
378 [ Sequelize.Op.or ]: options.licenceOneOf
382 if (options.languageOneOf) {
383 query.where[ 'language' ] = {
384 [ Sequelize.Op.or ]: options.languageOneOf
388 if (options.trendingDays) {
391 model: VideoViewModel,
395 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * options.trendingDays)
400 query.subQuery = false
405 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
408 model: () => VideoChannelModel.unscoped(),
413 exclude: [ 'privateKey', 'publicKey' ]
415 model: () => ActorModel.unscoped(),
419 attributes: [ 'host' ],
420 model: () => ServerModel.unscoped(),
424 model: () => AvatarModel.unscoped(),
430 model: () => AccountModel.unscoped(),
434 model: () => ActorModel.unscoped(),
436 exclude: [ 'privateKey', 'publicKey' ]
441 attributes: [ 'host' ],
442 model: () => ServerModel.unscoped(),
446 model: () => AvatarModel.unscoped(),
457 [ ScopeNames.WITH_TAGS ]: {
458 include: [ () => TagModel ]
460 [ ScopeNames.WITH_BLACKLISTED ]: {
463 attributes: [ 'id', 'reason' ],
464 model: () => VideoBlacklistModel,
469 [ ScopeNames.WITH_FILES ]: {
472 model: () => VideoFileModel.unscoped(),
477 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
480 model: () => ScheduleVideoUpdateModel.unscoped(),
490 export class VideoModel extends Model<VideoModel> {
493 @Default(DataType.UUIDV4)
495 @Column(DataType.UUID)
499 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
505 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
511 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
517 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
518 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
522 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
527 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
533 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
534 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
539 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
540 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
544 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
574 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
575 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
580 commentsEnabled: boolean
584 waitTranscoding: boolean
588 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
599 @Default(Sequelize.NOW)
603 @ForeignKey(() => VideoChannelModel)
607 @BelongsTo(() => VideoChannelModel, {
613 VideoChannel: VideoChannelModel
615 @BelongsToMany(() => TagModel, {
616 foreignKey: 'videoId',
617 through: () => VideoTagModel,
622 @HasMany(() => VideoAbuseModel, {
629 VideoAbuses: VideoAbuseModel[]
631 @HasMany(() => VideoFileModel, {
638 VideoFiles: VideoFileModel[]
640 @HasMany(() => VideoShareModel, {
647 VideoShares: VideoShareModel[]
649 @HasMany(() => AccountVideoRateModel, {
656 AccountVideoRates: AccountVideoRateModel[]
658 @HasMany(() => VideoCommentModel, {
666 VideoComments: VideoCommentModel[]
668 @HasMany(() => VideoViewModel, {
676 VideoViews: VideoViewModel[]
678 @HasOne(() => ScheduleVideoUpdateModel, {
685 ScheduleVideoUpdate: ScheduleVideoUpdateModel
687 @HasOne(() => VideoBlacklistModel, {
694 VideoBlacklist: VideoBlacklistModel
696 @HasMany(() => VideoCaptionModel, {
703 [ 'separate' as any ]: true
705 VideoCaptions: VideoCaptionModel[]
708 static async sendDelete (instance: VideoModel, options) {
709 if (instance.isOwned()) {
710 if (!instance.VideoChannel) {
711 instance.VideoChannel = await instance.$get('VideoChannel', {
715 include: [ ActorModel ]
718 transaction: options.transaction
719 }) as VideoChannelModel
722 return sendDeleteVideo(instance, options.transaction)
729 static async removeFiles (instance: VideoModel) {
730 const tasks: Promise<any>[] = []
732 logger.info('Removing files of video %s.', instance.url)
734 tasks.push(instance.removeThumbnail())
736 if (instance.isOwned()) {
737 if (!Array.isArray(instance.VideoFiles)) {
738 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
741 tasks.push(instance.removePreview())
743 // Remove physical files and torrents
744 instance.VideoFiles.forEach(file => {
745 tasks.push(instance.removeFile(file))
746 tasks.push(instance.removeTorrent(file))
750 // Do not wait video deletion because we could be in a transaction
753 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
760 return VideoModel.scope(ScopeNames.WITH_FILES).findAll()
763 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
764 function getRawQuery (select: string) {
765 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
766 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
767 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
768 'WHERE "Account"."actorId" = ' + actorId
769 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
770 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
771 'WHERE "VideoShare"."actorId" = ' + actorId
773 return `(${queryVideo}) UNION (${queryVideoShare})`
776 const rawQuery = getRawQuery('"Video"."id"')
777 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
783 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ]),
786 [ Sequelize.Op.in ]: Sequelize.literal('(' + rawQuery + ')')
788 [ Sequelize.Op.or ]: [
789 { privacy: VideoPrivacy.PUBLIC },
790 { privacy: VideoPrivacy.UNLISTED }
795 attributes: [ 'language' ],
796 model: VideoCaptionModel.unscoped(),
800 attributes: [ 'id', 'url' ],
801 model: VideoShareModel.unscoped(),
803 // We only want videos shared by this actor
805 [ Sequelize.Op.and ]: [
808 [ Sequelize.Op.not ]: null
818 attributes: [ 'id', 'url' ],
819 model: ActorModel.unscoped()
824 model: VideoChannelModel.unscoped(),
828 attributes: [ 'name' ],
829 model: AccountModel.unscoped(),
833 attributes: [ 'id', 'url', 'followersUrl' ],
834 model: ActorModel.unscoped(),
840 attributes: [ 'id', 'url', 'followersUrl' ],
841 model: ActorModel.unscoped(),
851 return Bluebird.all([
852 // FIXME: typing issue
853 VideoModel.findAll(query as any),
854 VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
855 ]).then(([ rows, totals ]) => {
856 // totals: totalVideos + totalVideoShares
858 let totalVideoShares = 0
859 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
860 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
862 const total = totalVideos + totalVideoShares
870 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
871 const query: IFindOptions<VideoModel> = {
874 order: getVideoSort(sort),
877 model: VideoChannelModel,
890 model: ScheduleVideoUpdateModel,
894 model: VideoBlacklistModel,
900 if (withFiles === true) {
902 model: VideoFileModel.unscoped(),
907 return VideoModel.findAndCountAll(query).then(({ rows, count }) => {
915 static async listForApi (options: {
920 includeLocalVideos: boolean,
922 categoryOneOf?: number[],
923 licenceOneOf?: number[],
924 languageOneOf?: string[],
925 tagsOneOf?: string[],
926 tagsAllOf?: string[],
927 filter?: VideoFilter,
929 videoChannelId?: number,
931 trendingDays?: number
933 const query: IFindOptions<VideoModel> = {
934 offset: options.start,
935 limit: options.count,
936 order: getVideoSort(options.sort)
939 let trendingDays: number
940 if (options.sort.endsWith('trending')) {
941 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
943 query.group = 'VideoModel.id'
946 // actorId === null has a meaning, so just check undefined
947 const actorId = options.actorId !== undefined ? options.actorId : (await getServerActor()).id
949 const queryOptions = {
952 categoryOneOf: options.categoryOneOf,
953 licenceOneOf: options.licenceOneOf,
954 languageOneOf: options.languageOneOf,
955 tagsOneOf: options.tagsOneOf,
956 tagsAllOf: options.tagsAllOf,
957 filter: options.filter,
958 withFiles: options.withFiles,
959 accountId: options.accountId,
960 videoChannelId: options.videoChannelId,
961 includeLocalVideos: options.includeLocalVideos,
965 return VideoModel.getAvailableForApi(query, queryOptions)
968 static async searchAndPopulateAccountAndServer (options: {
969 includeLocalVideos: boolean
974 startDate?: string // ISO 8601
975 endDate?: string // ISO 8601
977 categoryOneOf?: number[]
978 licenceOneOf?: number[]
979 languageOneOf?: string[]
982 durationMin?: number // seconds
983 durationMax?: number // seconds
987 if (options.startDate || options.endDate) {
988 const publishedAtRange = {}
990 if (options.startDate) publishedAtRange[ Sequelize.Op.gte ] = options.startDate
991 if (options.endDate) publishedAtRange[ Sequelize.Op.lte ] = options.endDate
993 whereAnd.push({ publishedAt: publishedAtRange })
996 if (options.durationMin || options.durationMax) {
997 const durationRange = {}
999 if (options.durationMin) durationRange[ Sequelize.Op.gte ] = options.durationMin
1000 if (options.durationMax) durationRange[ Sequelize.Op.lte ] = options.durationMax
1002 whereAnd.push({ duration: durationRange })
1005 const attributesInclude = []
1006 const escapedSearch = VideoModel.sequelize.escape(options.search)
1007 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1008 if (options.search) {
1012 [ Sequelize.Op.in ]: Sequelize.literal(
1014 'SELECT "video"."id" FROM "video" ' +
1016 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1017 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1019 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1020 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1021 'WHERE "tag"."name" = ' + escapedSearch +
1028 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1031 // Cannot search on similarity if we don't have a search
1032 if (!options.search) {
1033 attributesInclude.push(
1034 Sequelize.literal('0 as similarity')
1038 const query: IFindOptions<VideoModel> = {
1040 include: attributesInclude
1042 offset: options.start,
1043 limit: options.count,
1044 order: getVideoSort(options.sort),
1046 [ Sequelize.Op.and ]: whereAnd
1050 const serverActor = await getServerActor()
1051 const queryOptions = {
1052 actorId: serverActor.id,
1053 includeLocalVideos: options.includeLocalVideos,
1055 categoryOneOf: options.categoryOneOf,
1056 licenceOneOf: options.licenceOneOf,
1057 languageOneOf: options.languageOneOf,
1058 tagsOneOf: options.tagsOneOf,
1059 tagsAllOf: options.tagsAllOf
1062 return VideoModel.getAvailableForApi(query, queryOptions)
1065 static load (id: number, t?: Sequelize.Transaction) {
1066 const options = t ? { transaction: t } : undefined
1068 return VideoModel.findById(id, options)
1071 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
1072 const query: IFindOptions<VideoModel> = {
1078 if (t !== undefined) query.transaction = t
1080 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1083 static loadAndPopulateAccountAndServerAndTags (id: number) {
1085 order: [ [ 'Tags', 'name', 'ASC' ] ]
1090 ScopeNames.WITH_TAGS,
1091 ScopeNames.WITH_BLACKLISTED,
1092 ScopeNames.WITH_FILES,
1093 ScopeNames.WITH_ACCOUNT_DETAILS,
1094 ScopeNames.WITH_SCHEDULED_UPDATE
1096 .findById(id, options)
1099 static loadByUUID (uuid: string) {
1107 .scope([ ScopeNames.WITH_FILES ])
1111 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1113 order: [ [ 'Tags', 'name', 'ASC' ] ],
1122 ScopeNames.WITH_TAGS,
1123 ScopeNames.WITH_BLACKLISTED,
1124 ScopeNames.WITH_FILES,
1125 ScopeNames.WITH_ACCOUNT_DETAILS,
1126 ScopeNames.WITH_SCHEDULED_UPDATE
1131 static async getStats () {
1132 const totalLocalVideos = await VideoModel.count({
1137 const totalVideos = await VideoModel.count()
1139 let totalLocalVideoViews = await VideoModel.sum('views', {
1144 // Sequelize could return null...
1145 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1149 totalLocalVideoViews,
1154 static incrementViews (id: number, views: number) {
1155 return VideoModel.increment('views', {
1163 // threshold corresponds to how many video the field should have to be returned
1164 static getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1165 const query: IFindOptions<VideoModel> = {
1166 attributes: [ field ],
1169 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1170 [ Sequelize.Op.gte ]: threshold
1171 }) as any, // FIXME: typings
1174 [ Sequelize.Op.not ]: null
1176 privacy: VideoPrivacy.PUBLIC,
1177 state: VideoState.PUBLISHED
1179 order: [ this.sequelize.random() ]
1182 return VideoModel.findAll(query)
1183 .then(rows => rows.map(r => r[ field ]))
1186 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1187 if (filter && filter === 'local') {
1196 private static async getAvailableForApi (query: IFindOptions<VideoModel>, options: AvailableForListIDsOptions) {
1199 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1203 // Remove trending sort on count, because it uses a group by
1204 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1205 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1206 const countScope = {
1208 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1212 const [ count, rowsId ] = await Promise.all([
1213 VideoModel.scope(countScope).count(countQuery),
1214 VideoModel.scope(idsScope).findAll(query)
1216 const ids = rowsId.map(r => r.id)
1218 if (ids.length === 0) return { data: [], total: count }
1221 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1224 const secondQuery = {
1227 attributes: query.attributes,
1228 order: [ // Keep original order
1230 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1234 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1242 private static getCategoryLabel (id: number) {
1243 return VIDEO_CATEGORIES[ id ] || 'Misc'
1246 private static getLicenceLabel (id: number) {
1247 return VIDEO_LICENCES[ id ] || 'Unknown'
1250 private static getLanguageLabel (id: string) {
1251 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1254 private static getPrivacyLabel (id: number) {
1255 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1258 private static getStateLabel (id: number) {
1259 return VIDEO_STATES[ id ] || 'Unknown'
1262 getOriginalFile () {
1263 if (Array.isArray(this.VideoFiles) === false) return undefined
1265 // The original file is the file that have the higher resolution
1266 return maxBy(this.VideoFiles, file => file.resolution)
1269 getVideoFilename (videoFile: VideoFileModel) {
1270 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1273 getThumbnailName () {
1274 // We always have a copy of the thumbnail
1275 const extension = '.jpg'
1276 return this.uuid + extension
1280 const extension = '.jpg'
1281 return this.uuid + extension
1284 getTorrentFileName (videoFile: VideoFileModel) {
1285 const extension = '.torrent'
1286 return this.uuid + '-' + videoFile.resolution + extension
1290 return this.remote === false
1293 createPreview (videoFile: VideoFileModel) {
1294 return generateImageFromVideoFile(
1295 this.getVideoFilePath(videoFile),
1296 CONFIG.STORAGE.PREVIEWS_DIR,
1297 this.getPreviewName(),
1302 createThumbnail (videoFile: VideoFileModel) {
1303 return generateImageFromVideoFile(
1304 this.getVideoFilePath(videoFile),
1305 CONFIG.STORAGE.THUMBNAILS_DIR,
1306 this.getThumbnailName(),
1311 getTorrentFilePath (videoFile: VideoFileModel) {
1312 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1315 getVideoFilePath (videoFile: VideoFileModel) {
1316 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1319 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1321 // Keep the extname, it's used by the client to stream the file inside a web browser
1322 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1323 createdBy: 'PeerTube',
1325 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1326 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1329 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1333 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1335 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1336 logger.info('Creating torrent %s.', filePath)
1338 await writeFile(filePath, torrent)
1340 const parsedTorrent = parseTorrent(torrent)
1341 videoFile.infoHash = parsedTorrent.infoHash
1344 getEmbedStaticPath () {
1345 return '/videos/embed/' + this.uuid
1348 getThumbnailStaticPath () {
1349 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1352 getPreviewStaticPath () {
1353 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1356 toFormattedJSON (options?: {
1357 additionalAttributes: {
1359 waitTranscoding?: boolean,
1360 scheduledUpdate?: boolean,
1361 blacklistInfo?: boolean
1364 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1365 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1367 const videoObject: Video = {
1373 label: VideoModel.getCategoryLabel(this.category)
1377 label: VideoModel.getLicenceLabel(this.licence)
1381 label: VideoModel.getLanguageLabel(this.language)
1385 label: VideoModel.getPrivacyLabel(this.privacy)
1388 description: this.getTruncatedDescription(),
1389 isLocal: this.isOwned(),
1390 duration: this.duration,
1393 dislikes: this.dislikes,
1394 thumbnailPath: this.getThumbnailStaticPath(),
1395 previewPath: this.getPreviewStaticPath(),
1396 embedPath: this.getEmbedStaticPath(),
1397 createdAt: this.createdAt,
1398 updatedAt: this.updatedAt,
1399 publishedAt: this.publishedAt,
1401 id: formattedAccount.id,
1402 uuid: formattedAccount.uuid,
1403 name: formattedAccount.name,
1404 displayName: formattedAccount.displayName,
1405 url: formattedAccount.url,
1406 host: formattedAccount.host,
1407 avatar: formattedAccount.avatar
1410 id: formattedVideoChannel.id,
1411 uuid: formattedVideoChannel.uuid,
1412 name: formattedVideoChannel.name,
1413 displayName: formattedVideoChannel.displayName,
1414 url: formattedVideoChannel.url,
1415 host: formattedVideoChannel.host,
1416 avatar: formattedVideoChannel.avatar
1421 if (options.additionalAttributes.state === true) {
1422 videoObject.state = {
1424 label: VideoModel.getStateLabel(this.state)
1428 if (options.additionalAttributes.waitTranscoding === true) {
1429 videoObject.waitTranscoding = this.waitTranscoding
1432 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1433 videoObject.scheduledUpdate = {
1434 updateAt: this.ScheduleVideoUpdate.updateAt,
1435 privacy: this.ScheduleVideoUpdate.privacy || undefined
1439 if (options.additionalAttributes.blacklistInfo === true) {
1440 videoObject.blacklisted = !!this.VideoBlacklist
1441 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1448 toFormattedDetailsJSON (): VideoDetails {
1449 const formattedJson = this.toFormattedJSON({
1450 additionalAttributes: {
1451 scheduledUpdate: true,
1456 const detailsJson = {
1457 support: this.support,
1458 descriptionPath: this.getDescriptionPath(),
1459 channel: this.VideoChannel.toFormattedJSON(),
1460 account: this.VideoChannel.Account.toFormattedJSON(),
1461 tags: map(this.Tags, 'name'),
1462 commentsEnabled: this.commentsEnabled,
1463 waitTranscoding: this.waitTranscoding,
1466 label: VideoModel.getStateLabel(this.state)
1471 // Format and sort video files
1472 detailsJson.files = this.getFormattedVideoFilesJSON()
1474 return Object.assign(formattedJson, detailsJson)
1477 getFormattedVideoFilesJSON (): VideoFile[] {
1478 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1480 return this.VideoFiles
1482 let resolutionLabel = videoFile.resolution + 'p'
1486 id: videoFile.resolution,
1487 label: resolutionLabel
1489 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1490 size: videoFile.size,
1492 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1493 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1494 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1495 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1499 if (a.resolution.id < b.resolution.id) return 1
1500 if (a.resolution.id === b.resolution.id) return 0
1505 toActivityPubObject (): VideoTorrentObject {
1506 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1507 if (!this.Tags) this.Tags = []
1509 const tag = this.Tags.map(t => ({
1510 type: 'Hashtag' as 'Hashtag',
1515 if (this.language) {
1517 identifier: this.language,
1518 name: VideoModel.getLanguageLabel(this.language)
1523 if (this.category) {
1525 identifier: this.category + '',
1526 name: VideoModel.getCategoryLabel(this.category)
1533 identifier: this.licence + '',
1534 name: VideoModel.getLicenceLabel(this.licence)
1539 for (const file of this.VideoFiles) {
1542 mimeType: VIDEO_EXT_MIMETYPE[ file.extname ],
1543 href: this.getVideoFileUrl(file, baseUrlHttp),
1544 height: file.resolution,
1551 mimeType: 'application/x-bittorrent',
1552 href: this.getTorrentUrl(file, baseUrlHttp),
1553 height: file.resolution
1558 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
1559 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1560 height: file.resolution
1564 // Add video url too
1567 mimeType: 'text/html',
1568 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1571 const subtitleLanguage = []
1572 for (const caption of this.VideoCaptions) {
1573 subtitleLanguage.push({
1574 identifier: caption.language,
1575 name: VideoCaptionModel.getLanguageLabel(caption.language)
1580 type: 'Video' as 'Video',
1583 duration: this.getActivityStreamDuration(),
1590 sensitive: this.nsfw,
1591 waitTranscoding: this.waitTranscoding,
1593 commentsEnabled: this.commentsEnabled,
1594 published: this.publishedAt.toISOString(),
1595 updated: this.updatedAt.toISOString(),
1596 mediaType: 'text/markdown',
1597 content: this.getTruncatedDescription(),
1598 support: this.support,
1602 url: this.getThumbnailUrl(baseUrlHttp),
1603 mediaType: 'image/jpeg',
1604 width: THUMBNAILS_SIZE.width,
1605 height: THUMBNAILS_SIZE.height
1608 likes: getVideoLikesActivityPubUrl(this),
1609 dislikes: getVideoDislikesActivityPubUrl(this),
1610 shares: getVideoSharesActivityPubUrl(this),
1611 comments: getVideoCommentsActivityPubUrl(this),
1615 id: this.VideoChannel.Account.Actor.url
1619 id: this.VideoChannel.Actor.url
1625 getTruncatedDescription () {
1626 if (!this.description) return null
1628 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1629 return peertubeTruncate(this.description, maxLength)
1632 async optimizeOriginalVideofile () {
1633 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1634 const newExtname = '.mp4'
1635 const inputVideoFile = this.getOriginalFile()
1636 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1637 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1639 const transcodeOptions = {
1640 inputPath: videoInputPath,
1641 outputPath: videoTranscodedPath
1644 // Could be very long!
1645 await transcode(transcodeOptions)
1648 await remove(videoInputPath)
1650 // Important to do this before getVideoFilename() to take in account the new file extension
1651 inputVideoFile.set('extname', newExtname)
1653 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1654 await rename(videoTranscodedPath, videoOutputPath)
1655 const stats = await stat(videoOutputPath)
1656 const fps = await getVideoFileFPS(videoOutputPath)
1658 inputVideoFile.set('size', stats.size)
1659 inputVideoFile.set('fps', fps)
1661 await this.createTorrentAndSetInfoHash(inputVideoFile)
1662 await inputVideoFile.save()
1665 // Auto destruction...
1666 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1672 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1673 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1674 const extname = '.mp4'
1676 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1677 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1679 const newVideoFile = new VideoFileModel({
1685 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1687 const transcodeOptions = {
1688 inputPath: videoInputPath,
1689 outputPath: videoOutputPath,
1694 await transcode(transcodeOptions)
1696 const stats = await stat(videoOutputPath)
1697 const fps = await getVideoFileFPS(videoOutputPath)
1699 newVideoFile.set('size', stats.size)
1700 newVideoFile.set('fps', fps)
1702 await this.createTorrentAndSetInfoHash(newVideoFile)
1704 await newVideoFile.save()
1706 this.VideoFiles.push(newVideoFile)
1709 async importVideoFile (inputFilePath: string) {
1710 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1711 const { size } = await stat(inputFilePath)
1712 const fps = await getVideoFileFPS(inputFilePath)
1714 let updatedVideoFile = new VideoFileModel({
1715 resolution: videoFileResolution,
1716 extname: extname(inputFilePath),
1722 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1724 if (currentVideoFile) {
1725 // Remove old file and old torrent
1726 await this.removeFile(currentVideoFile)
1727 await this.removeTorrent(currentVideoFile)
1728 // Remove the old video file from the array
1729 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1731 // Update the database
1732 currentVideoFile.set('extname', updatedVideoFile.extname)
1733 currentVideoFile.set('size', updatedVideoFile.size)
1734 currentVideoFile.set('fps', updatedVideoFile.fps)
1736 updatedVideoFile = currentVideoFile
1739 const outputPath = this.getVideoFilePath(updatedVideoFile)
1740 await copy(inputFilePath, outputPath)
1742 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1744 await updatedVideoFile.save()
1746 this.VideoFiles.push(updatedVideoFile)
1749 getOriginalFileResolution () {
1750 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1752 return getVideoFileResolution(originalFilePath)
1755 getDescriptionPath () {
1756 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1759 removeThumbnail () {
1760 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1761 return remove(thumbnailPath)
1762 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1766 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1767 return remove(previewPath)
1768 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1771 removeFile (videoFile: VideoFileModel) {
1772 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1773 return remove(filePath)
1774 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1777 removeTorrent (videoFile: VideoFileModel) {
1778 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1779 return remove(torrentPath)
1780 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1783 getActivityStreamDuration () {
1784 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1785 return 'PT' + this.duration + 'S'
1789 if (this.isOwned()) return false
1791 const now = Date.now()
1792 const createdAtTime = this.createdAt.getTime()
1793 const updatedAtTime = this.updatedAt.getTime()
1795 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1796 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1799 private getBaseUrls () {
1803 if (this.isOwned()) {
1804 baseUrlHttp = CONFIG.WEBSERVER.URL
1805 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1807 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1808 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1811 return { baseUrlHttp, baseUrlWs }
1814 private getThumbnailUrl (baseUrlHttp: string) {
1815 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1818 private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1819 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1822 private getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1823 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1826 private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1827 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1830 private getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1831 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1834 private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1835 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1836 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1837 const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1839 const magnetHash = {
1843 infoHash: videoFile.infoHash,
1847 return magnetUtil.encode(magnetHash)