1 import * as Bluebird from 'bluebird'
2 import { maxBy } from 'lodash'
3 import * as magnetUtil from 'magnet-uri'
4 import * as parseTorrent from 'parse-torrent'
5 import { join } from 'path'
38 } from 'sequelize-typescript'
39 import { UserRight, VideoPrivacy, VideoResolution, VideoState } from '../../../shared'
40 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
41 import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos'
42 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
43 import { peertubeTruncate } from '../../helpers/core-utils'
44 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
45 import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc'
48 isVideoDescriptionValid,
56 } from '../../helpers/custom-validators/videos'
57 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
58 import { logger } from '../../helpers/logger'
59 import { getServerActor } from '../../helpers/utils'
64 HLS_REDUNDANCY_DIRECTORY,
65 HLS_STREAMING_PLAYLIST_DIRECTORY,
68 STATIC_DOWNLOAD_PATHS,
76 } from '../../initializers/constants'
77 import { sendDeleteVideo } from '../../lib/activitypub/send'
78 import { AccountModel } from '../account/account'
79 import { AccountVideoRateModel } from '../account/account-video-rate'
80 import { ActorModel } from '../activitypub/actor'
81 import { AvatarModel } from '../avatar/avatar'
82 import { ServerModel } from '../server/server'
84 buildBlockedAccountSQL,
85 buildTrigramSearchIndex,
88 createSimilarityAttribute,
93 import { TagModel } from './tag'
94 import { VideoAbuseModel } from './video-abuse'
95 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
96 import { VideoCommentModel } from './video-comment'
97 import { VideoFileModel } from './video-file'
98 import { VideoShareModel } from './video-share'
99 import { VideoTagModel } from './video-tag'
100 import { ScheduleVideoUpdateModel } from './schedule-video-update'
101 import { VideoCaptionModel } from './video-caption'
102 import { VideoBlacklistModel } from './video-blacklist'
103 import { remove, writeFile } from 'fs-extra'
104 import { VideoViewModel } from './video-views'
105 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
107 videoFilesModelToFormattedJSON,
108 VideoFormattingJSONOptions,
109 videoModelToActivityPubObject,
110 videoModelToFormattedDetailsJSON,
111 videoModelToFormattedJSON
112 } from './video-format-utils'
113 import { UserVideoHistoryModel } from '../account/user-video-history'
114 import { UserModel } from '../account/user'
115 import { VideoImportModel } from './video-import'
116 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
117 import { VideoPlaylistElementModel } from './video-playlist-element'
118 import { CONFIG } from '../../initializers/config'
119 import { ThumbnailModel } from './thumbnail'
120 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
121 import { createTorrentPromise } from '../../helpers/webtorrent'
123 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
124 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
125 buildTrigramSearchIndex('video_name_trigram', 'name'),
127 { fields: [ 'createdAt' ] },
128 { fields: [ 'publishedAt' ] },
129 { fields: [ 'duration' ] },
130 { fields: [ 'views' ] },
131 { fields: [ 'channelId' ] },
133 fields: [ 'originallyPublishedAt' ],
135 originallyPublishedAt: {
141 fields: [ 'category' ], // We don't care videos with an unknown category
149 fields: [ 'licence' ], // We don't care videos with an unknown licence
157 fields: [ 'language' ], // We don't care videos with an unknown language
165 fields: [ 'nsfw' ], // Most of the videos are not NSFW
171 fields: [ 'remote' ], // Only index local videos
186 export enum ScopeNames {
187 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
189 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
190 WITH_TAGS = 'WITH_TAGS',
191 WITH_FILES = 'WITH_FILES',
192 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
193 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
194 WITH_BLOCKLIST = 'WITH_BLOCKLIST',
195 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
196 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
197 WITH_USER_ID = 'WITH_USER_ID',
198 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
201 export type ForAPIOptions = {
204 videoPlaylistId?: number
208 withAccountBlockerIds?: number[]
211 export type AvailableForListIDsOptions = {
212 serverAccountId: number
213 followerActorId: number
214 includeLocalVideos: boolean
216 attributesType?: 'none' | 'id' | 'all'
219 categoryOneOf?: number[]
221 licenceOneOf?: number[]
222 languageOneOf?: string[]
229 videoChannelId?: number
231 videoPlaylistId?: number
233 trendingDays?: number
235 historyOfUser?: UserModel
237 baseWhere?: WhereOptions[]
241 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
242 const query: FindOptions = {
245 model: VideoChannelModel.scope({
247 VideoChannelScopeNames.SUMMARY, {
249 withAccountBlockerIds: options.withAccountBlockerIds
256 attributes: [ 'type', 'filename' ],
257 model: ThumbnailModel,
266 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
271 if (options.withFiles === true) {
273 model: VideoFileModel.unscoped(),
278 if (options.videoPlaylistId) {
280 model: VideoPlaylistElementModel.unscoped(),
283 videoPlaylistId: options.videoPlaylistId
290 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
291 const whereAnd = options.baseWhere ? options.baseWhere : []
293 const query: FindOptions = {
298 const attributesType = options.attributesType || 'id'
300 if (attributesType === 'id') query.attributes = [ 'id' ]
301 else if (attributesType === 'none') query.attributes = [ ]
305 [ Op.notIn ]: Sequelize.literal(
306 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
311 if (options.serverAccountId) {
314 [ Op.notIn ]: Sequelize.literal(
316 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
317 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
325 // Only list public/published videos
326 if (!options.filter || options.filter !== 'all-local') {
327 const privacyWhere = {
328 // Always list public videos
329 privacy: VideoPrivacy.PUBLIC,
330 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
333 state: VideoState.PUBLISHED
337 state: VideoState.TO_TRANSCODE,
338 waitTranscoding: false
344 whereAnd.push(privacyWhere)
347 if (options.videoPlaylistId) {
350 model: VideoPlaylistElementModel.unscoped(),
353 videoPlaylistId: options.videoPlaylistId
357 query.subQuery = false
360 if (options.filter || options.accountId || options.videoChannelId) {
361 const videoChannelInclude: IncludeOptions = {
363 model: VideoChannelModel.unscoped(),
367 if (options.videoChannelId) {
368 videoChannelInclude.where = {
369 id: options.videoChannelId
373 if (options.filter || options.accountId) {
374 const accountInclude: IncludeOptions = {
376 model: AccountModel.unscoped(),
380 if (options.filter) {
381 accountInclude.include = [
384 model: ActorModel.unscoped(),
386 where: VideoModel.buildActorWhereWithFilter(options.filter)
391 if (options.accountId) {
392 accountInclude.where = { id: options.accountId }
395 videoChannelInclude.include = [ accountInclude ]
398 query.include.push(videoChannelInclude)
401 if (options.followerActorId) {
402 let localVideosReq = ''
403 if (options.includeLocalVideos === true) {
404 localVideosReq = ' UNION ALL ' +
405 'SELECT "video"."id" AS "id" FROM "video" ' +
406 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
407 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
408 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
409 'WHERE "actor"."serverId" IS NULL'
412 // Force actorId to be a number to avoid SQL injections
413 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
416 [ Op.in ]: Sequelize.literal(
418 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
419 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
420 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
422 'SELECT "video"."id" AS "id" FROM "video" ' +
423 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
424 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
425 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
426 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
427 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
435 if (options.withFiles === true) {
438 [ Op.in ]: Sequelize.literal(
439 '(SELECT "videoId" FROM "videoFile")'
445 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
446 if (options.tagsAllOf || options.tagsOneOf) {
447 if (options.tagsOneOf) {
450 [ Op.in ]: Sequelize.literal(
452 'SELECT "videoId" FROM "videoTag" ' +
453 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
454 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' +
461 if (options.tagsAllOf) {
464 [ Op.in ]: Sequelize.literal(
466 'SELECT "videoId" FROM "videoTag" ' +
467 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
468 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' +
469 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length +
477 if (options.nsfw === true || options.nsfw === false) {
478 whereAnd.push({ nsfw: options.nsfw })
481 if (options.categoryOneOf) {
484 [ Op.or ]: options.categoryOneOf
489 if (options.licenceOneOf) {
492 [ Op.or ]: options.licenceOneOf
497 if (options.languageOneOf) {
498 let videoLanguages = options.languageOneOf
499 if (options.languageOneOf.find(l => l === '_unknown')) {
500 videoLanguages = videoLanguages.concat([ null ])
507 [ Op.or ]: videoLanguages
512 [ Op.in ]: Sequelize.literal(
514 'SELECT "videoId" FROM "videoCaption" ' +
515 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
524 if (options.trendingDays) {
525 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
527 query.subQuery = false
530 if (options.historyOfUser) {
532 model: UserVideoHistoryModel,
535 userId: options.historyOfUser.id
539 // Even if the relation is n:m, we know that a user only have 0..1 video history
540 // So we won't have multiple rows for the same video
541 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
542 query.subQuery = false
551 [ScopeNames.WITH_BLOCKLIST]: {
554 [ ScopeNames.WITH_THUMBNAILS ]: {
557 model: ThumbnailModel,
562 [ ScopeNames.WITH_USER_ID ]: {
565 attributes: [ 'accountId' ],
566 model: VideoChannelModel.unscoped(),
570 attributes: [ 'userId' ],
571 model: AccountModel.unscoped(),
578 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
581 model: VideoChannelModel.unscoped(),
586 exclude: [ 'privateKey', 'publicKey' ]
588 model: ActorModel.unscoped(),
592 attributes: [ 'host' ],
593 model: ServerModel.unscoped(),
597 model: AvatarModel.unscoped(),
603 model: AccountModel.unscoped(),
607 model: ActorModel.unscoped(),
609 exclude: [ 'privateKey', 'publicKey' ]
614 attributes: [ 'host' ],
615 model: ServerModel.unscoped(),
619 model: AvatarModel.unscoped(),
630 [ ScopeNames.WITH_TAGS ]: {
631 include: [ TagModel ]
633 [ ScopeNames.WITH_BLACKLISTED ]: {
636 attributes: [ 'id', 'reason' ],
637 model: VideoBlacklistModel,
642 [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => {
643 let subInclude: any[] = []
645 if (withRedundancies === true) {
648 attributes: [ 'fileUrl' ],
649 model: VideoRedundancyModel.unscoped(),
658 model: VideoFileModel.unscoped(),
659 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
666 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
667 let subInclude: any[] = []
669 if (withRedundancies === true) {
672 attributes: [ 'fileUrl' ],
673 model: VideoRedundancyModel.unscoped(),
682 model: VideoStreamingPlaylistModel.unscoped(),
683 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
690 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
693 model: ScheduleVideoUpdateModel.unscoped(),
698 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
702 attributes: [ 'currentTime' ],
703 model: UserVideoHistoryModel.unscoped(),
717 export class VideoModel extends Model<VideoModel> {
720 @Default(DataType.UUIDV4)
722 @Column(DataType.UUID)
726 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
732 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
738 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
744 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
745 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
749 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
754 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
760 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
761 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
766 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
767 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
771 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
801 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
802 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
807 commentsEnabled: boolean
811 downloadEnabled: boolean
815 waitTranscoding: boolean
819 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
830 @Default(DataType.NOW)
837 originallyPublishedAt: Date
839 @ForeignKey(() => VideoChannelModel)
843 @BelongsTo(() => VideoChannelModel, {
849 VideoChannel: VideoChannelModel
851 @BelongsToMany(() => TagModel, {
852 foreignKey: 'videoId',
853 through: () => VideoTagModel,
858 @HasMany(() => ThumbnailModel, {
866 Thumbnails: ThumbnailModel[]
868 @HasMany(() => VideoPlaylistElementModel, {
875 VideoPlaylistElements: VideoPlaylistElementModel[]
877 @HasMany(() => VideoAbuseModel, {
884 VideoAbuses: VideoAbuseModel[]
886 @HasMany(() => VideoFileModel, {
894 VideoFiles: VideoFileModel[]
896 @HasMany(() => VideoStreamingPlaylistModel, {
904 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
906 @HasMany(() => VideoShareModel, {
913 VideoShares: VideoShareModel[]
915 @HasMany(() => AccountVideoRateModel, {
922 AccountVideoRates: AccountVideoRateModel[]
924 @HasMany(() => VideoCommentModel, {
932 VideoComments: VideoCommentModel[]
934 @HasMany(() => VideoViewModel, {
941 VideoViews: VideoViewModel[]
943 @HasMany(() => UserVideoHistoryModel, {
950 UserVideoHistories: UserVideoHistoryModel[]
952 @HasOne(() => ScheduleVideoUpdateModel, {
959 ScheduleVideoUpdate: ScheduleVideoUpdateModel
961 @HasOne(() => VideoBlacklistModel, {
968 VideoBlacklist: VideoBlacklistModel
970 @HasOne(() => VideoImportModel, {
977 VideoImport: VideoImportModel
979 @HasMany(() => VideoCaptionModel, {
986 [ 'separate' as any ]: true
988 VideoCaptions: VideoCaptionModel[]
991 static async sendDelete (instance: VideoModel, options) {
992 if (instance.isOwned()) {
993 if (!instance.VideoChannel) {
994 instance.VideoChannel = await instance.$get('VideoChannel', {
998 include: [ ActorModel ]
1001 transaction: options.transaction
1002 }) as VideoChannelModel
1005 return sendDeleteVideo(instance, options.transaction)
1012 static async removeFiles (instance: VideoModel) {
1013 const tasks: Promise<any>[] = []
1015 logger.info('Removing files of video %s.', instance.url)
1017 if (instance.isOwned()) {
1018 if (!Array.isArray(instance.VideoFiles)) {
1019 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1022 // Remove physical files and torrents
1023 instance.VideoFiles.forEach(file => {
1024 tasks.push(instance.removeFile(file))
1025 tasks.push(instance.removeTorrent(file))
1028 // Remove playlists file
1029 tasks.push(instance.removeStreamingPlaylist())
1032 // Do not wait video deletion because we could be in a transaction
1035 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1041 static listLocal () {
1048 return VideoModel.scope([
1049 ScopeNames.WITH_FILES,
1050 ScopeNames.WITH_STREAMING_PLAYLISTS,
1051 ScopeNames.WITH_THUMBNAILS
1055 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1056 function getRawQuery (select: string) {
1057 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1058 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1059 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1060 'WHERE "Account"."actorId" = ' + actorId
1061 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1062 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1063 'WHERE "VideoShare"."actorId" = ' + actorId
1065 return `(${queryVideo}) UNION (${queryVideoShare})`
1068 const rawQuery = getRawQuery('"Video"."id"')
1069 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1075 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1078 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1081 { privacy: VideoPrivacy.PUBLIC },
1082 { privacy: VideoPrivacy.UNLISTED }
1087 attributes: [ 'language' ],
1088 model: VideoCaptionModel.unscoped(),
1092 attributes: [ 'id', 'url' ],
1093 model: VideoShareModel.unscoped(),
1095 // We only want videos shared by this actor
1110 attributes: [ 'id', 'url' ],
1111 model: ActorModel.unscoped()
1116 model: VideoChannelModel.unscoped(),
1120 attributes: [ 'name' ],
1121 model: AccountModel.unscoped(),
1125 attributes: [ 'id', 'url', 'followersUrl' ],
1126 model: ActorModel.unscoped(),
1132 attributes: [ 'id', 'url', 'followersUrl' ],
1133 model: ActorModel.unscoped(),
1143 return Bluebird.all([
1144 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1145 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1146 ]).then(([ rows, totals ]) => {
1147 // totals: totalVideos + totalVideoShares
1149 let totalVideoShares = 0
1150 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1151 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1153 const total = totalVideos + totalVideoShares
1161 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) {
1162 function buildBaseQuery (): FindOptions {
1166 order: getVideoSort(sort),
1169 model: VideoChannelModel,
1173 model: AccountModel,
1185 const countQuery = buildBaseQuery()
1186 const findQuery = buildBaseQuery()
1188 const findScopes = [
1189 ScopeNames.WITH_SCHEDULED_UPDATE,
1190 ScopeNames.WITH_BLACKLISTED,
1191 ScopeNames.WITH_THUMBNAILS
1194 if (withFiles === true) {
1195 findQuery.include.push({
1196 model: VideoFileModel.unscoped(),
1201 return Promise.all([
1202 VideoModel.count(countQuery),
1203 VideoModel.scope(findScopes).findAll(findQuery)
1204 ]).then(([ count, rows ]) => {
1212 static async listForApi (options: {
1217 includeLocalVideos: boolean,
1219 categoryOneOf?: number[],
1220 licenceOneOf?: number[],
1221 languageOneOf?: string[],
1222 tagsOneOf?: string[],
1223 tagsAllOf?: string[],
1224 filter?: VideoFilter,
1226 videoChannelId?: number,
1227 followerActorId?: number
1228 videoPlaylistId?: number,
1229 trendingDays?: number,
1231 historyOfUser?: UserModel
1232 }, countVideos = true) {
1233 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1234 throw new Error('Try to filter all-local but no user has not the see all videos right')
1237 const query: FindOptions & { where?: null } = {
1238 offset: options.start,
1239 limit: options.count,
1240 order: getVideoSort(options.sort)
1243 let trendingDays: number
1244 if (options.sort.endsWith('trending')) {
1245 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1247 query.group = 'VideoModel.id'
1250 const serverActor = await getServerActor()
1252 // followerActorId === null has a meaning, so just check undefined
1253 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1255 const queryOptions = {
1257 serverAccountId: serverActor.Account.id,
1259 categoryOneOf: options.categoryOneOf,
1260 licenceOneOf: options.licenceOneOf,
1261 languageOneOf: options.languageOneOf,
1262 tagsOneOf: options.tagsOneOf,
1263 tagsAllOf: options.tagsAllOf,
1264 filter: options.filter,
1265 withFiles: options.withFiles,
1266 accountId: options.accountId,
1267 videoChannelId: options.videoChannelId,
1268 videoPlaylistId: options.videoPlaylistId,
1269 includeLocalVideos: options.includeLocalVideos,
1271 historyOfUser: options.historyOfUser,
1275 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1278 static async searchAndPopulateAccountAndServer (options: {
1279 includeLocalVideos: boolean
1284 startDate?: string // ISO 8601
1285 endDate?: string // ISO 8601
1286 originallyPublishedStartDate?: string
1287 originallyPublishedEndDate?: string
1289 categoryOneOf?: number[]
1290 licenceOneOf?: number[]
1291 languageOneOf?: string[]
1292 tagsOneOf?: string[]
1293 tagsAllOf?: string[]
1294 durationMin?: number // seconds
1295 durationMax?: number // seconds
1297 filter?: VideoFilter
1301 if (options.startDate || options.endDate) {
1302 const publishedAtRange = {}
1304 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1305 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1307 whereAnd.push({ publishedAt: publishedAtRange })
1310 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1311 const originallyPublishedAtRange = {}
1313 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1314 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1316 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1319 if (options.durationMin || options.durationMax) {
1320 const durationRange = {}
1322 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1323 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1325 whereAnd.push({ duration: durationRange })
1328 const attributesInclude = []
1329 const escapedSearch = VideoModel.sequelize.escape(options.search)
1330 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1331 if (options.search) {
1335 [ Op.in ]: Sequelize.literal(
1337 'SELECT "video"."id" FROM "video" ' +
1339 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1340 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1342 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1343 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1344 'WHERE "tag"."name" = ' + escapedSearch +
1351 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1354 // Cannot search on similarity if we don't have a search
1355 if (!options.search) {
1356 attributesInclude.push(
1357 Sequelize.literal('0 as similarity')
1363 include: attributesInclude
1365 offset: options.start,
1366 limit: options.count,
1367 order: getVideoSort(options.sort)
1370 const serverActor = await getServerActor()
1371 const queryOptions = {
1372 followerActorId: serverActor.id,
1373 serverAccountId: serverActor.Account.id,
1374 includeLocalVideos: options.includeLocalVideos,
1376 categoryOneOf: options.categoryOneOf,
1377 licenceOneOf: options.licenceOneOf,
1378 languageOneOf: options.languageOneOf,
1379 tagsOneOf: options.tagsOneOf,
1380 tagsAllOf: options.tagsAllOf,
1382 filter: options.filter,
1386 return VideoModel.getAvailableForApi(query, queryOptions)
1389 static load (id: number | string, t?: Transaction) {
1390 const where = buildWhereIdOrUUID(id)
1396 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1399 static loadWithRights (id: number | string, t?: Transaction) {
1400 const where = buildWhereIdOrUUID(id)
1406 return VideoModel.scope([
1407 ScopeNames.WITH_BLACKLISTED,
1408 ScopeNames.WITH_USER_ID,
1409 ScopeNames.WITH_THUMBNAILS
1413 static loadOnlyId (id: number | string, t?: Transaction) {
1414 const where = buildWhereIdOrUUID(id)
1417 attributes: [ 'id' ],
1422 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1425 static loadWithFiles (id: number, t?: Transaction, logging?: boolean) {
1426 return VideoModel.scope([
1427 ScopeNames.WITH_FILES,
1428 ScopeNames.WITH_STREAMING_PLAYLISTS,
1429 ScopeNames.WITH_THUMBNAILS
1430 ]).findByPk(id, { transaction: t, logging })
1433 static loadByUUIDWithFile (uuid: string) {
1440 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1443 static loadByUrl (url: string, transaction?: Transaction) {
1444 const query: FindOptions = {
1451 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1454 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) {
1455 const query: FindOptions = {
1462 return VideoModel.scope([
1463 ScopeNames.WITH_ACCOUNT_DETAILS,
1464 ScopeNames.WITH_FILES,
1465 ScopeNames.WITH_STREAMING_PLAYLISTS,
1466 ScopeNames.WITH_THUMBNAILS
1470 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) {
1471 const where = buildWhereIdOrUUID(id)
1474 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1479 const scopes: (string | ScopeOptions)[] = [
1480 ScopeNames.WITH_TAGS,
1481 ScopeNames.WITH_BLACKLISTED,
1482 ScopeNames.WITH_ACCOUNT_DETAILS,
1483 ScopeNames.WITH_SCHEDULED_UPDATE,
1484 ScopeNames.WITH_FILES,
1485 ScopeNames.WITH_STREAMING_PLAYLISTS,
1486 ScopeNames.WITH_THUMBNAILS
1490 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1498 static loadForGetAPI (parameters: {
1499 id: number | string,
1503 const { id, t, userId } = parameters
1504 const where = buildWhereIdOrUUID(id)
1507 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1512 const scopes: (string | ScopeOptions)[] = [
1513 ScopeNames.WITH_TAGS,
1514 ScopeNames.WITH_BLACKLISTED,
1515 ScopeNames.WITH_ACCOUNT_DETAILS,
1516 ScopeNames.WITH_SCHEDULED_UPDATE,
1517 ScopeNames.WITH_THUMBNAILS,
1518 { method: [ ScopeNames.WITH_FILES, true ] },
1519 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1523 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1531 static async getStats () {
1532 const totalLocalVideos = await VideoModel.count({
1537 const totalVideos = await VideoModel.count()
1539 let totalLocalVideoViews = await VideoModel.sum('views', {
1544 // Sequelize could return null...
1545 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1549 totalLocalVideoViews,
1554 static incrementViews (id: number, views: number) {
1555 return VideoModel.increment('views', {
1563 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1564 // Instances only share videos
1565 const query = 'SELECT 1 FROM "videoShare" ' +
1566 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1567 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1571 type: QueryTypes.SELECT,
1572 bind: { followerActorId, videoId },
1576 return VideoModel.sequelize.query(query, options)
1577 .then(results => results.length === 1)
1580 static bulkUpdateSupportField (videoChannel: VideoChannelModel, t: Transaction) {
1583 channelId: videoChannel.id
1588 return VideoModel.update({ support: videoChannel.support }, options)
1591 static getAllIdsFromChannel (videoChannel: VideoChannelModel) {
1593 attributes: [ 'id' ],
1595 channelId: videoChannel.id
1599 return VideoModel.findAll(query)
1600 .then(videos => videos.map(v => v.id))
1603 // threshold corresponds to how many video the field should have to be returned
1604 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1605 const serverActor = await getServerActor()
1606 const followerActorId = serverActor.id
1608 const scopeOptions: AvailableForListIDsOptions = {
1609 serverAccountId: serverActor.Account.id,
1611 includeLocalVideos: true,
1612 attributesType: 'none' // Don't break aggregation
1615 const query: FindOptions = {
1616 attributes: [ field ],
1619 having: Sequelize.where(
1620 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1622 order: [ (this.sequelize as any).random() ]
1625 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1627 .then(rows => rows.map(r => r[ field ]))
1630 static buildTrendingQuery (trendingDays: number) {
1634 model: VideoViewModel,
1638 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1644 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1645 if (filter && (filter === 'local' || filter === 'all-local')) {
1654 private static async getAvailableForApi (
1655 query: FindOptions & { where?: null }, // Forbid where field in query
1656 options: AvailableForListIDsOptions,
1659 const idsScope: ScopeOptions = {
1661 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1665 // Remove trending sort on count, because it uses a group by
1666 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1667 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1668 const countScope: ScopeOptions = {
1670 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1674 const [ count, ids ] = await Promise.all([
1676 ? VideoModel.scope(countScope).count(countQuery)
1677 : Promise.resolve<number>(undefined),
1679 VideoModel.scope(idsScope)
1681 .then(rows => rows.map(r => r.id))
1684 if (ids.length === 0) return { data: [], total: count }
1686 const secondQuery: FindOptions = {
1689 attributes: query.attributes,
1690 order: [ // Keep original order
1692 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1697 const apiScope: (string | ScopeOptions)[] = []
1700 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1705 ScopeNames.FOR_API, {
1707 withFiles: options.withFiles,
1708 videoPlaylistId: options.videoPlaylistId
1713 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1721 static getCategoryLabel (id: number) {
1722 return VIDEO_CATEGORIES[ id ] || 'Misc'
1725 static getLicenceLabel (id: number) {
1726 return VIDEO_LICENCES[ id ] || 'Unknown'
1729 static getLanguageLabel (id: string) {
1730 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1733 static getPrivacyLabel (id: number) {
1734 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1737 static getStateLabel (id: number) {
1738 return VIDEO_STATES[ id ] || 'Unknown'
1742 return !!this.VideoBlacklist
1746 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1747 this.VideoChannel.Account.isBlocked()
1750 getOriginalFile () {
1751 if (Array.isArray(this.VideoFiles) === false) return undefined
1753 // The original file is the file that have the higher resolution
1754 return maxBy(this.VideoFiles, file => file.resolution)
1757 getFile (resolution: VideoResolution) {
1758 if (Array.isArray(this.VideoFiles) === false) return undefined
1760 return this.VideoFiles.find(f => f.resolution === resolution)
1763 async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) {
1764 thumbnail.videoId = this.id
1766 const savedThumbnail = await thumbnail.save({ transaction })
1768 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1770 // Already have this thumbnail, skip
1771 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1773 this.Thumbnails.push(savedThumbnail)
1776 getVideoFilename (videoFile: VideoFileModel) {
1777 return this.uuid + '-' + videoFile.resolution + videoFile.extname
1780 generateThumbnailName () {
1781 return this.uuid + '.jpg'
1785 if (Array.isArray(this.Thumbnails) === false) return undefined
1787 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1790 generatePreviewName () {
1791 return this.uuid + '.jpg'
1795 if (Array.isArray(this.Thumbnails) === false) return undefined
1797 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1800 getTorrentFileName (videoFile: VideoFileModel) {
1801 const extension = '.torrent'
1802 return this.uuid + '-' + videoFile.resolution + extension
1806 return this.remote === false
1809 getTorrentFilePath (videoFile: VideoFileModel) {
1810 return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1813 getVideoFilePath (videoFile: VideoFileModel) {
1814 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
1817 async createTorrentAndSetInfoHash (videoFile: VideoFileModel) {
1819 // Keep the extname, it's used by the client to stream the file inside a web browser
1820 name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`,
1821 createdBy: 'PeerTube',
1823 [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ],
1824 [ WEBSERVER.URL + '/tracker/announce' ]
1826 urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ]
1829 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
1831 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1832 logger.info('Creating torrent %s.', filePath)
1834 await writeFile(filePath, torrent)
1836 const parsedTorrent = parseTorrent(torrent)
1837 videoFile.infoHash = parsedTorrent.infoHash
1840 getWatchStaticPath () {
1841 return '/videos/watch/' + this.uuid
1844 getEmbedStaticPath () {
1845 return '/videos/embed/' + this.uuid
1848 getMiniatureStaticPath () {
1849 const thumbnail = this.getMiniature()
1850 if (!thumbnail) return null
1852 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1855 getPreviewStaticPath () {
1856 const preview = this.getPreview()
1857 if (!preview) return null
1859 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1860 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1863 toFormattedJSON (options?: VideoFormattingJSONOptions): Video {
1864 return videoModelToFormattedJSON(this, options)
1867 toFormattedDetailsJSON (): VideoDetails {
1868 return videoModelToFormattedDetailsJSON(this)
1871 getFormattedVideoFilesJSON (): VideoFile[] {
1872 return videoFilesModelToFormattedJSON(this, this.VideoFiles)
1875 toActivityPubObject (): VideoTorrentObject {
1876 return videoModelToActivityPubObject(this)
1879 getTruncatedDescription () {
1880 if (!this.description) return null
1882 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1883 return peertubeTruncate(this.description, maxLength)
1886 getOriginalFileResolution () {
1887 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
1889 return getVideoFileResolution(originalFilePath)
1892 getDescriptionAPIPath () {
1893 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1896 removeFile (videoFile: VideoFileModel, isRedundancy = false) {
1897 const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR
1899 const filePath = join(baseDir, this.getVideoFilename(videoFile))
1900 return remove(filePath)
1901 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1904 removeTorrent (videoFile: VideoFileModel) {
1905 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
1906 return remove(torrentPath)
1907 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1910 removeStreamingPlaylist (isRedundancy = false) {
1911 const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY
1913 const filePath = join(baseDir, this.uuid)
1914 return remove(filePath)
1915 .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err }))
1919 if (this.isOwned()) return false
1921 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1925 this.changed('updatedAt', true)
1934 if (this.isOwned()) {
1935 baseUrlHttp = WEBSERVER.URL
1936 baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1938 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host
1939 baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1942 return { baseUrlHttp, baseUrlWs }
1945 generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) {
1946 const xs = this.getTorrentUrl(videoFile, baseUrlHttp)
1947 const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs)
1948 let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ]
1950 const redundancies = videoFile.RedundancyVideos
1951 if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl))
1953 const magnetHash = {
1957 infoHash: videoFile.infoHash,
1961 return magnetUtil.encode(magnetHash)
1964 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1965 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1968 getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1969 return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1972 getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1973 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile)
1976 getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1977 return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
1980 getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1981 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile)
1984 getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) {
1985 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile)
1988 getBandwidthBits (videoFile: VideoFileModel) {
1989 return Math.ceil((videoFile.size * 8) / this.duration)