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 { ActivityUrlObject, 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 { isArray, 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'
93 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
95 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
96 const indexes: Sequelize.DefineIndexesOptions[] = [
97 buildTrigramSearchIndex('video_name_trigram', 'name'),
99 { fields: [ 'createdAt' ] },
100 { fields: [ 'publishedAt' ] },
101 { fields: [ 'duration' ] },
102 { fields: [ 'category' ] },
103 { fields: [ 'licence' ] },
104 { fields: [ 'nsfw' ] },
105 { fields: [ 'language' ] },
106 { fields: [ 'waitTranscoding' ] },
107 { fields: [ 'state' ] },
108 { fields: [ 'remote' ] },
109 { fields: [ 'views' ] },
110 { fields: [ 'likes' ] },
111 { fields: [ 'channelId' ] },
122 export enum ScopeNames {
123 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
125 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
126 WITH_TAGS = 'WITH_TAGS',
127 WITH_FILES = 'WITH_FILES',
128 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
129 WITH_BLACKLISTED = 'WITH_BLACKLISTED'
132 type ForAPIOptions = {
137 type AvailableForListIDsOptions = {
139 includeLocalVideos: boolean
141 categoryOneOf?: number[]
143 licenceOneOf?: number[]
144 languageOneOf?: string[]
149 videoChannelId?: number
150 trendingDays?: number
154 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
155 const accountInclude = {
156 attributes: [ 'id', 'name' ],
157 model: AccountModel.unscoped(),
161 attributes: [ 'id', 'uuid', 'preferredUsername', 'url', 'serverId', 'avatarId' ],
162 model: ActorModel.unscoped(),
166 attributes: [ 'host' ],
167 model: ServerModel.unscoped(),
171 model: AvatarModel.unscoped(),
179 const videoChannelInclude = {
180 attributes: [ 'name', 'description', 'id' ],
181 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 const query: IFindOptions<VideoModel> = {
207 [ Sequelize.Op.any ]: options.ids
210 include: [ videoChannelInclude ]
213 if (options.withFiles === true) {
215 model: VideoFileModel.unscoped(),
222 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
223 const query: IFindOptions<VideoModel> = {
225 attributes: [ 'id' ],
228 [ Sequelize.Op.and ]: [
230 [ Sequelize.Op.notIn ]: Sequelize.literal(
231 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
236 // Always list public videos
237 privacy: VideoPrivacy.PUBLIC,
238 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
239 [ Sequelize.Op.or ]: [
241 state: VideoState.PUBLISHED
244 [ Sequelize.Op.and ]: {
245 state: VideoState.TO_TRANSCODE,
246 waitTranscoding: false
254 if (options.filter || options.accountId || options.videoChannelId) {
255 const videoChannelInclude: IIncludeOptions = {
257 model: VideoChannelModel.unscoped(),
261 if (options.videoChannelId) {
262 videoChannelInclude.where = {
263 id: options.videoChannelId
267 if (options.filter || options.accountId) {
268 const accountInclude: IIncludeOptions = {
270 model: AccountModel.unscoped(),
274 if (options.filter) {
275 accountInclude.include = [
278 model: ActorModel.unscoped(),
280 where: VideoModel.buildActorWhereWithFilter(options.filter)
285 if (options.accountId) {
286 accountInclude.where = { id: options.accountId }
289 videoChannelInclude.include = [ accountInclude ]
292 query.include.push(videoChannelInclude)
295 if (options.actorId) {
296 let localVideosReq = ''
297 if (options.includeLocalVideos === true) {
298 localVideosReq = ' UNION ALL ' +
299 'SELECT "video"."id" AS "id" FROM "video" ' +
300 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
301 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
302 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
303 'WHERE "actor"."serverId" IS NULL'
306 // Force actorId to be a number to avoid SQL injections
307 const actorIdNumber = parseInt(options.actorId.toString(), 10)
308 query.where[ 'id' ][ Sequelize.Op.and ].push({
309 [ Sequelize.Op.in ]: Sequelize.literal(
311 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
312 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
313 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
315 'SELECT "video"."id" AS "id" FROM "video" ' +
316 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
317 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
318 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
319 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
320 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
327 if (options.withFiles === true) {
328 query.where[ 'id' ][ Sequelize.Op.and ].push({
329 [ Sequelize.Op.in ]: Sequelize.literal(
330 '(SELECT "videoId" FROM "videoFile")'
335 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
336 if (options.tagsAllOf || options.tagsOneOf) {
337 const createTagsIn = (tags: string[]) => {
338 return tags.map(t => VideoModel.sequelize.escape(t))
342 if (options.tagsOneOf) {
343 query.where[ 'id' ][ Sequelize.Op.and ].push({
344 [ Sequelize.Op.in ]: Sequelize.literal(
346 'SELECT "videoId" FROM "videoTag" ' +
347 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
348 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsOneOf) + ')' +
354 if (options.tagsAllOf) {
355 query.where[ 'id' ][ Sequelize.Op.and ].push({
356 [ Sequelize.Op.in ]: Sequelize.literal(
358 'SELECT "videoId" FROM "videoTag" ' +
359 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
360 'WHERE "tag"."name" IN (' + createTagsIn(options.tagsAllOf) + ')' +
361 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
368 if (options.nsfw === true || options.nsfw === false) {
369 query.where[ 'nsfw' ] = options.nsfw
372 if (options.categoryOneOf) {
373 query.where[ 'category' ] = {
374 [ Sequelize.Op.or ]: options.categoryOneOf
378 if (options.licenceOneOf) {
379 query.where[ 'licence' ] = {
380 [ Sequelize.Op.or ]: options.licenceOneOf
384 if (options.languageOneOf) {
385 query.where[ 'language' ] = {
386 [ Sequelize.Op.or ]: options.languageOneOf
390 if (options.trendingDays) {
391 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
393 query.subQuery = false
398 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
401 model: () => VideoChannelModel.unscoped(),
406 exclude: [ 'privateKey', 'publicKey' ]
408 model: () => ActorModel.unscoped(),
412 attributes: [ 'host' ],
413 model: () => ServerModel.unscoped(),
417 model: () => AvatarModel.unscoped(),
423 model: () => AccountModel.unscoped(),
427 model: () => ActorModel.unscoped(),
429 exclude: [ 'privateKey', 'publicKey' ]
434 attributes: [ 'host' ],
435 model: () => ServerModel.unscoped(),
439 model: () => AvatarModel.unscoped(),
450 [ ScopeNames.WITH_TAGS ]: {
451 include: [ () => TagModel ]
453 [ ScopeNames.WITH_BLACKLISTED ]: {
456 attributes: [ 'id', 'reason' ],
457 model: () => VideoBlacklistModel,
462 [ ScopeNames.WITH_FILES ]: {
465 model: () => VideoFileModel.unscoped(),
469 model: () => VideoRedundancyModel.unscoped(),
476 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
479 model: () => ScheduleVideoUpdateModel.unscoped(),
489 export class VideoModel extends Model<VideoModel> {
492 @Default(DataType.UUIDV4)
494 @Column(DataType.UUID)
498 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
504 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category'))
510 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence'))
516 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language'))
517 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
521 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
526 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
532 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description'))
533 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
538 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support'))
539 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
543 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
573 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
574 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
579 commentsEnabled: boolean
583 waitTranscoding: boolean
587 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
598 @Default(Sequelize.NOW)
602 @ForeignKey(() => VideoChannelModel)
606 @BelongsTo(() => VideoChannelModel, {
612 VideoChannel: VideoChannelModel
614 @BelongsToMany(() => TagModel, {
615 foreignKey: 'videoId',
616 through: () => VideoTagModel,
621 @HasMany(() => VideoAbuseModel, {
628 VideoAbuses: VideoAbuseModel[]
630 @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 return VideoModel.findById(id, { transaction: t })
1069 static loadWithFile (id: number, t?: Sequelize.Transaction, logging?: boolean) {
1070 return VideoModel.scope(ScopeNames.WITH_FILES)
1071 .findById(id, { transaction: t, logging })
1074 static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) {
1075 const query: IFindOptions<VideoModel> = {
1081 if (t !== undefined) query.transaction = t
1083 return VideoModel.scope([ ScopeNames.WITH_ACCOUNT_DETAILS, ScopeNames.WITH_FILES ]).findOne(query)
1086 static loadAndPopulateAccountAndServerAndTags (id: number) {
1088 order: [ [ 'Tags', 'name', 'ASC' ] ]
1093 ScopeNames.WITH_TAGS,
1094 ScopeNames.WITH_BLACKLISTED,
1095 ScopeNames.WITH_FILES,
1096 ScopeNames.WITH_ACCOUNT_DETAILS,
1097 ScopeNames.WITH_SCHEDULED_UPDATE
1099 .findById(id, options)
1102 static loadByUUID (uuid: string) {
1110 .scope([ ScopeNames.WITH_FILES ])
1114 static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string, t?: Sequelize.Transaction) {
1116 order: [ [ 'Tags', 'name', 'ASC' ] ],
1125 ScopeNames.WITH_TAGS,
1126 ScopeNames.WITH_BLACKLISTED,
1127 ScopeNames.WITH_FILES,
1128 ScopeNames.WITH_ACCOUNT_DETAILS,
1129 ScopeNames.WITH_SCHEDULED_UPDATE
1134 static async getStats () {
1135 const totalLocalVideos = await VideoModel.count({
1140 const totalVideos = await VideoModel.count()
1142 let totalLocalVideoViews = await VideoModel.sum('views', {
1147 // Sequelize could return null...
1148 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1152 totalLocalVideoViews,
1157 static incrementViews (id: number, views: number) {
1158 return VideoModel.increment('views', {
1166 // threshold corresponds to how many video the field should have to be returned
1167 static getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1168 const query: IFindOptions<VideoModel> = {
1169 attributes: [ field ],
1172 having: Sequelize.where(Sequelize.fn('COUNT', Sequelize.col(field)), {
1173 [ Sequelize.Op.gte ]: threshold
1174 }) as any, // FIXME: typings
1177 [ Sequelize.Op.not ]: null
1179 privacy: VideoPrivacy.PUBLIC,
1180 state: VideoState.PUBLISHED
1182 order: [ this.sequelize.random() ]
1185 return VideoModel.findAll(query)
1186 .then(rows => rows.map(r => r[ field ]))
1189 static buildTrendingQuery (trendingDays: number) {
1193 model: VideoViewModel,
1197 [ Sequelize.Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1203 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1204 if (filter && filter === 'local') {
1213 private static async getAvailableForApi (query: IFindOptions<VideoModel>, options: AvailableForListIDsOptions) {
1216 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1220 // Remove trending sort on count, because it uses a group by
1221 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1222 const countQuery = Object.assign({}, query, { attributes: undefined, group: undefined })
1223 const countScope = {
1225 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1229 const [ count, rowsId ] = await Promise.all([
1230 VideoModel.scope(countScope).count(countQuery),
1231 VideoModel.scope(idsScope).findAll(query)
1233 const ids = rowsId.map(r => r.id)
1235 if (ids.length === 0) return { data: [], total: count }
1238 method: [ ScopeNames.FOR_API, { ids, withFiles: options.withFiles } as ForAPIOptions ]
1241 const secondQuery = {
1244 attributes: query.attributes,
1245 order: [ // Keep original order
1247 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1251 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1259 private static getCategoryLabel (id: number) {
1260 return VIDEO_CATEGORIES[ id ] || 'Misc'
1263 private static getLicenceLabel (id: number) {
1264 return VIDEO_LICENCES[ id ] || 'Unknown'
1267 private static getLanguageLabel (id: string) {
1268 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1271 private static getPrivacyLabel (id: number) {
1272 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1275 private static getStateLabel (id: number) {
1276 return VIDEO_STATES[ id ] || 'Unknown'
1279 getOriginalFile () {
1280 if (Array.isArray(this.VideoFiles) === false) return undefined
1282 // The original file is the file that have the higher resolution
1283 return maxBy(this.VideoFiles, file => file.resolution)
1286 getVideoFilename (videoFile: VideoFileModel) {
1287 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1290 getThumbnailName () {
1291 // We always have a copy of the thumbnail
1292 const extension = '.jpg'
1293 return this.uuid + extension
1297 const extension = '.jpg'
1298 return this.uuid + extension
1301 getTorrentFileName (videoFile: VideoFileModel) {
1302 const extension = '.torrent'
1303 return this.uuid + '-' + videoFile.resolution + extension
1307 return this.remote === false
1310 createPreview (videoFile: VideoFileModel) {
1311 return generateImageFromVideoFile(
1312 this.getVideoFilePath(videoFile),
1313 CONFIG.STORAGE.PREVIEWS_DIR,
1314 this.getPreviewName(),
1319 createThumbnail (videoFile: VideoFileModel) {
1320 return generateImageFromVideoFile(
1321 this.getVideoFilePath(videoFile),
1322 CONFIG.STORAGE.THUMBNAILS_DIR,
1323 this.getThumbnailName(),
1328 getTorrentFilePath (videoFile: VideoFileModel) {
1329 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1332 getVideoFilePath (videoFile: VideoFileModel) {
1333 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1336 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1338 // Keep the extname, it's used by the client to stream the file inside a web browser
1339 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1340 createdBy: 'PeerTube',
1342 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ],
1343 [ CONFIG.WEBSERVER.URL + '/tracker/announce' ]
1345 urlList: [ CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1348 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1350 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1351 logger.info('Creating torrent %s.', filePath)
1353 await writeFile(filePath, torrent)
1355 const parsedTorrent = parseTorrent(torrent)
1356 videoFile.infoHash = parsedTorrent.infoHash
1359 getEmbedStaticPath () {
1360 return '/videos/embed/' + this.uuid
1363 getThumbnailStaticPath () {
1364 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
1367 getPreviewStaticPath () {
1368 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
1371 toFormattedJSON (options?: {
1372 additionalAttributes: {
1374 waitTranscoding?: boolean,
1375 scheduledUpdate?: boolean,
1376 blacklistInfo?: boolean
1379 const formattedAccount = this.VideoChannel.Account.toFormattedJSON()
1380 const formattedVideoChannel = this.VideoChannel.toFormattedJSON()
1382 const videoObject: Video = {
1388 label: VideoModel.getCategoryLabel(this.category)
1392 label: VideoModel.getLicenceLabel(this.licence)
1396 label: VideoModel.getLanguageLabel(this.language)
1400 label: VideoModel.getPrivacyLabel(this.privacy)
1403 description: this.getTruncatedDescription(),
1404 isLocal: this.isOwned(),
1405 duration: this.duration,
1408 dislikes: this.dislikes,
1409 thumbnailPath: this.getThumbnailStaticPath(),
1410 previewPath: this.getPreviewStaticPath(),
1411 embedPath: this.getEmbedStaticPath(),
1412 createdAt: this.createdAt,
1413 updatedAt: this.updatedAt,
1414 publishedAt: this.publishedAt,
1416 id: formattedAccount.id,
1417 uuid: formattedAccount.uuid,
1418 name: formattedAccount.name,
1419 displayName: formattedAccount.displayName,
1420 url: formattedAccount.url,
1421 host: formattedAccount.host,
1422 avatar: formattedAccount.avatar
1425 id: formattedVideoChannel.id,
1426 uuid: formattedVideoChannel.uuid,
1427 name: formattedVideoChannel.name,
1428 displayName: formattedVideoChannel.displayName,
1429 url: formattedVideoChannel.url,
1430 host: formattedVideoChannel.host,
1431 avatar: formattedVideoChannel.avatar
1436 if (options.additionalAttributes.state === true) {
1437 videoObject.state = {
1439 label: VideoModel.getStateLabel(this.state)
1443 if (options.additionalAttributes.waitTranscoding === true) {
1444 videoObject.waitTranscoding = this.waitTranscoding
1447 if (options.additionalAttributes.scheduledUpdate === true && this.ScheduleVideoUpdate) {
1448 videoObject.scheduledUpdate = {
1449 updateAt: this.ScheduleVideoUpdate.updateAt,
1450 privacy: this.ScheduleVideoUpdate.privacy || undefined
1454 if (options.additionalAttributes.blacklistInfo === true) {
1455 videoObject.blacklisted = !!this.VideoBlacklist
1456 videoObject.blacklistedReason = this.VideoBlacklist ? this.VideoBlacklist.reason : null
1463 toFormattedDetailsJSON (): VideoDetails {
1464 const formattedJson = this.toFormattedJSON({
1465 additionalAttributes: {
1466 scheduledUpdate: true,
1471 const detailsJson = {
1472 support: this.support,
1473 descriptionPath: this.getDescriptionPath(),
1474 channel: this.VideoChannel.toFormattedJSON(),
1475 account: this.VideoChannel.Account.toFormattedJSON(),
1476 tags: map(this.Tags, 'name'),
1477 commentsEnabled: this.commentsEnabled,
1478 waitTranscoding: this.waitTranscoding,
1481 label: VideoModel.getStateLabel(this.state)
1486 // Format and sort video files
1487 detailsJson.files = this.getFormattedVideoFilesJSON()
1489 return Object.assign(formattedJson, detailsJson)
1492 getFormattedVideoFilesJSON (): VideoFile[] {
1493 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1495 return this.VideoFiles
1497 let resolutionLabel = videoFile.resolution + 'p'
1501 id: videoFile.resolution,
1502 label: resolutionLabel
1504 magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs),
1505 size: videoFile.size,
1507 torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp),
1508 torrentDownloadUrl: this.getTorrentDownloadUrl(videoFile, baseUrlHttp),
1509 fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp),
1510 fileDownloadUrl: this.getVideoFileDownloadUrl(videoFile, baseUrlHttp)
1514 if (a.resolution.id < b.resolution.id) return 1
1515 if (a.resolution.id === b.resolution.id) return 0
1520 toActivityPubObject (): VideoTorrentObject {
1521 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1522 if (!this.Tags) this.Tags = []
1524 const tag = this.Tags.map(t => ({
1525 type: 'Hashtag' as 'Hashtag',
1530 if (this.language) {
1532 identifier: this.language,
1533 name: VideoModel.getLanguageLabel(this.language)
1538 if (this.category) {
1540 identifier: this.category + '',
1541 name: VideoModel.getCategoryLabel(this.category)
1548 identifier: this.licence + '',
1549 name: VideoModel.getLicenceLabel(this.licence)
1553 const url: ActivityUrlObject[] = []
1554 for (const file of this.VideoFiles) {
1557 mimeType: VIDEO_EXT_MIMETYPE[ file.extname ] as any,
1558 href: this.getVideoFileUrl(file, baseUrlHttp),
1559 height: file.resolution,
1566 mimeType: 'application/x-bittorrent' as 'application/x-bittorrent',
1567 href: this.getTorrentUrl(file, baseUrlHttp),
1568 height: file.resolution
1573 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
1574 href: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs),
1575 height: file.resolution
1579 // Add video url too
1582 mimeType: 'text/html',
1583 href: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid
1586 const subtitleLanguage = []
1587 for (const caption of this.VideoCaptions) {
1588 subtitleLanguage.push({
1589 identifier: caption.language,
1590 name: VideoCaptionModel.getLanguageLabel(caption.language)
1595 type: 'Video' as 'Video',
1598 duration: this.getActivityStreamDuration(),
1605 sensitive: this.nsfw,
1606 waitTranscoding: this.waitTranscoding,
1608 commentsEnabled: this.commentsEnabled,
1609 published: this.publishedAt.toISOString(),
1610 updated: this.updatedAt.toISOString(),
1611 mediaType: 'text/markdown',
1612 content: this.getTruncatedDescription(),
1613 support: this.support,
1617 url: this.getThumbnailUrl(baseUrlHttp),
1618 mediaType: 'image/jpeg',
1619 width: THUMBNAILS_SIZE.width,
1620 height: THUMBNAILS_SIZE.height
1623 likes: getVideoLikesActivityPubUrl(this),
1624 dislikes: getVideoDislikesActivityPubUrl(this),
1625 shares: getVideoSharesActivityPubUrl(this),
1626 comments: getVideoCommentsActivityPubUrl(this),
1630 id: this.VideoChannel.Account.Actor.url
1634 id: this.VideoChannel.Actor.url
1640 getTruncatedDescription () {
1641 if (!this.description) return null
1643 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1644 return peertubeTruncate(this.description, maxLength)
1647 async optimizeOriginalVideofile () {
1648 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1649 const newExtname = '.mp4'
1650 const inputVideoFile = this.getOriginalFile()
1651 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
1652 const videoTranscodedPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
1654 const transcodeOptions = {
1655 inputPath: videoInputPath,
1656 outputPath: videoTranscodedPath
1659 // Could be very long!
1660 await transcode(transcodeOptions)
1663 await remove(videoInputPath)
1665 // Important to do this before getVideoFilename() to take in account the new file extension
1666 inputVideoFile.set('extname', newExtname)
1668 const videoOutputPath = this.getVideoFilePath(inputVideoFile)
1669 await rename(videoTranscodedPath, videoOutputPath)
1670 const stats = await stat(videoOutputPath)
1671 const fps = await getVideoFileFPS(videoOutputPath)
1673 inputVideoFile.set('size', stats.size)
1674 inputVideoFile.set('fps', fps)
1676 await this.createTorrentAndSetInfoHash(inputVideoFile)
1677 await inputVideoFile.save()
1680 // Auto destruction...
1681 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err }))
1687 async transcodeOriginalVideofile (resolution: VideoResolution, isPortraitMode: boolean) {
1688 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
1689 const extname = '.mp4'
1691 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
1692 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
1694 const newVideoFile = new VideoFileModel({
1700 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
1702 const transcodeOptions = {
1703 inputPath: videoInputPath,
1704 outputPath: videoOutputPath,
1709 await transcode(transcodeOptions)
1711 const stats = await stat(videoOutputPath)
1712 const fps = await getVideoFileFPS(videoOutputPath)
1714 newVideoFile.set('size', stats.size)
1715 newVideoFile.set('fps', fps)
1717 await this.createTorrentAndSetInfoHash(newVideoFile)
1719 await newVideoFile.save()
1721 this.VideoFiles.push(newVideoFile)
1724 async importVideoFile (inputFilePath: string) {
1725 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
1726 const { size } = await stat(inputFilePath)
1727 const fps = await getVideoFileFPS(inputFilePath)
1729 let updatedVideoFile = new VideoFileModel({
1730 resolution: videoFileResolution,
1731 extname: extname(inputFilePath),
1737 const currentVideoFile = this.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
1739 if (currentVideoFile) {
1740 // Remove old file and old torrent
1741 await this.removeFile(currentVideoFile)
1742 await this.removeTorrent(currentVideoFile)
1743 // Remove the old video file from the array
1744 this.VideoFiles = this.VideoFiles.filter(f => f !== currentVideoFile)
1746 // Update the database
1747 currentVideoFile.set('extname', updatedVideoFile.extname)
1748 currentVideoFile.set('size', updatedVideoFile.size)
1749 currentVideoFile.set('fps', updatedVideoFile.fps)
1751 updatedVideoFile = currentVideoFile
1754 const outputPath = this.getVideoFilePath(updatedVideoFile)
1755 await copy(inputFilePath, outputPath)
1757 await this.createTorrentAndSetInfoHash(updatedVideoFile)
1759 await updatedVideoFile.save()
1761 this.VideoFiles.push(updatedVideoFile)
1764 getOriginalFileResolution () {
1765 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1767 return getVideoFileResolution(originalFilePath)
1770 getDescriptionPath () {
1771 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1774 removeThumbnail () {
1775 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
1776 return remove(thumbnailPath)
1777 .catch(err => logger.warn('Cannot delete thumbnail %s.', thumbnailPath, { err }))
1781 const previewPath = join(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
1782 return remove(previewPath)
1783 .catch(err => logger.warn('Cannot delete preview %s.', previewPath, { err }))
1786 removeFile (videoFile: VideoFileModel) {
1787 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1788 return remove(filePath)
1789 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1792 removeTorrent (videoFile: VideoFileModel) {
1793 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1794 return remove(torrentPath)
1795 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1798 getActivityStreamDuration () {
1799 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
1800 return 'PT' + this.duration + 'S'
1804 if (this.isOwned()) return false
1806 const now = Date.now()
1807 const createdAtTime = this.createdAt.getTime()
1808 const updatedAtTime = this.updatedAt.getTime()
1810 return (now - createdAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL &&
1811 (now - updatedAtTime) > ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL
1818 if (this.isOwned()) {
1819 baseUrlHttp = CONFIG.WEBSERVER.URL
1820 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1822 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1823 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1826 return { baseUrlHttp, baseUrlWs }
1829 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1830 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1831 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1832 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1834 const redundancies = videoFile.RedundancyVideos
1835 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1837 const magnetHash = {
1841 infoHash: videoFile.infoHash,
1845 return magnetUtil.encode(magnetHash)
1848 getThumbnailUrl (baseUrlHttp: string) {
1849 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName()
1852 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1853 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1856 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1857 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1860 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1861 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1864 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1865 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)