1 import * as Bluebird from 'bluebird'
2 import { maxBy, minBy } from 'lodash'
3 import { join } from 'path'
36 } from 'sequelize-typescript'
37 import { UserRight, VideoPrivacy, VideoState } from '../../../shared'
38 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
39 import { Video, VideoDetails } from '../../../shared/models/videos'
40 import { VideoFilter } from '../../../shared/models/videos/video-query.type'
41 import { peertubeTruncate } from '../../helpers/core-utils'
42 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
43 import { isBooleanValid } from '../../helpers/custom-validators/misc'
46 isVideoDescriptionValid,
54 } from '../../helpers/custom-validators/videos'
55 import { getVideoFileResolution } from '../../helpers/ffmpeg-utils'
56 import { logger } from '../../helpers/logger'
57 import { getServerActor } from '../../helpers/utils'
64 STATIC_DOWNLOAD_PATHS,
72 } from '../../initializers/constants'
73 import { sendDeleteVideo } from '../../lib/activitypub/send'
74 import { AccountModel } from '../account/account'
75 import { AccountVideoRateModel } from '../account/account-video-rate'
76 import { ActorModel } from '../activitypub/actor'
77 import { AvatarModel } from '../avatar/avatar'
78 import { ServerModel } from '../server/server'
80 buildBlockedAccountSQL,
81 buildTrigramSearchIndex,
84 createSimilarityAttribute,
89 import { TagModel } from './tag'
90 import { VideoAbuseModel } from './video-abuse'
91 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
92 import { VideoCommentModel } from './video-comment'
93 import { VideoFileModel } from './video-file'
94 import { VideoShareModel } from './video-share'
95 import { VideoTagModel } from './video-tag'
96 import { ScheduleVideoUpdateModel } from './schedule-video-update'
97 import { VideoCaptionModel } from './video-caption'
98 import { VideoBlacklistModel } from './video-blacklist'
99 import { remove } from 'fs-extra'
100 import { VideoViewModel } from './video-views'
101 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
103 videoFilesModelToFormattedJSON,
104 VideoFormattingJSONOptions,
105 videoModelToActivityPubObject,
106 videoModelToFormattedDetailsJSON,
107 videoModelToFormattedJSON
108 } from './video-format-utils'
109 import { UserVideoHistoryModel } from '../account/user-video-history'
110 import { VideoImportModel } from './video-import'
111 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
112 import { VideoPlaylistElementModel } from './video-playlist-element'
113 import { CONFIG } from '../../initializers/config'
114 import { ThumbnailModel } from './thumbnail'
115 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
116 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
119 MChannelAccountDefault,
122 MStreamingPlaylistFilesVideo,
126 MVideoAccountLightBlacklistAllFiles,
131 MVideoFormattableDetails,
136 MVideoThumbnailBlacklist,
140 } from '../../typings/models'
141 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../typings/models/video/video-file'
142 import { MThumbnail } from '../../typings/models/video/thumbnail'
143 import { VideoFile } from '@shared/models/videos/video-file.model'
144 import { getHLSDirectory, getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
145 import * as validator from 'validator'
147 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
148 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
149 buildTrigramSearchIndex('video_name_trigram', 'name'),
151 { fields: [ 'createdAt' ] },
154 { name: 'publishedAt', order: 'DESC' },
155 { name: 'id', order: 'ASC' }
158 { fields: [ 'duration' ] },
159 { fields: [ 'views' ] },
160 { fields: [ 'channelId' ] },
162 fields: [ 'originallyPublishedAt' ],
164 originallyPublishedAt: {
170 fields: [ 'category' ], // We don't care videos with an unknown category
178 fields: [ 'licence' ], // We don't care videos with an unknown licence
186 fields: [ 'language' ], // We don't care videos with an unknown language
194 fields: [ 'nsfw' ], // Most of the videos are not NSFW
200 fields: [ 'remote' ], // Only index local videos
215 export enum ScopeNames {
216 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
218 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
219 WITH_TAGS = 'WITH_TAGS',
220 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
221 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
222 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
223 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
224 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
225 WITH_USER_ID = 'WITH_USER_ID',
226 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
229 export type ForAPIOptions = {
232 videoPlaylistId?: number
236 withAccountBlockerIds?: number[]
239 export type AvailableForListIDsOptions = {
240 serverAccountId: number
241 followerActorId: number
242 includeLocalVideos: boolean
244 attributesType?: 'none' | 'id' | 'all'
247 categoryOneOf?: number[]
249 licenceOneOf?: number[]
250 languageOneOf?: string[]
257 videoChannelId?: number
259 videoPlaylistId?: number
261 trendingDays?: number
262 user?: MUserAccountId
263 historyOfUser?: MUserId
265 baseWhere?: WhereOptions[]
269 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
270 const query: FindOptions = {
273 model: VideoChannelModel.scope({
275 VideoChannelScopeNames.SUMMARY, {
277 withAccountBlockerIds: options.withAccountBlockerIds
284 attributes: [ 'type', 'filename' ],
285 model: ThumbnailModel,
294 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
299 if (options.withFiles === true) {
301 model: VideoFileModel.unscoped(),
306 if (options.videoPlaylistId) {
308 model: VideoPlaylistElementModel.unscoped(),
311 videoPlaylistId: options.videoPlaylistId
318 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
319 const whereAnd = options.baseWhere ? [].concat(options.baseWhere) : []
321 const query: FindOptions = {
326 const attributesType = options.attributesType || 'id'
328 if (attributesType === 'id') query.attributes = [ 'id' ]
329 else if (attributesType === 'none') query.attributes = [ ]
333 [ Op.notIn ]: Sequelize.literal(
334 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
339 if (options.serverAccountId) {
342 [ Op.notIn ]: Sequelize.literal(
344 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
345 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
353 // Only list public/published videos
354 if (!options.filter || options.filter !== 'all-local') {
356 const publishWhere = {
357 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
360 state: VideoState.PUBLISHED
364 state: VideoState.TO_TRANSCODE,
365 waitTranscoding: false
370 whereAnd.push(publishWhere)
372 // List internal videos if the user is logged in
374 const privacyWhere = {
377 privacy: VideoPrivacy.INTERNAL
380 privacy: VideoPrivacy.PUBLIC
385 whereAnd.push(privacyWhere)
386 } else { // Or only public videos
387 const privacyWhere = { privacy: VideoPrivacy.PUBLIC }
388 whereAnd.push(privacyWhere)
392 if (options.videoPlaylistId) {
395 model: VideoPlaylistElementModel.unscoped(),
398 videoPlaylistId: options.videoPlaylistId
402 query.subQuery = false
405 if (options.filter && (options.filter === 'local' || options.filter === 'all-local')) {
411 if (options.accountId || options.videoChannelId) {
412 const videoChannelInclude: IncludeOptions = {
414 model: VideoChannelModel.unscoped(),
418 if (options.videoChannelId) {
419 videoChannelInclude.where = {
420 id: options.videoChannelId
424 if (options.accountId) {
425 const accountInclude: IncludeOptions = {
427 model: AccountModel.unscoped(),
431 accountInclude.where = { id: options.accountId }
432 videoChannelInclude.include = [ accountInclude ]
435 query.include.push(videoChannelInclude)
438 if (options.followerActorId) {
439 let localVideosReq: WhereOptions = {}
440 if (options.includeLocalVideos === true) {
441 localVideosReq = { remote: false }
444 // Force actorId to be a number to avoid SQL injections
445 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
450 [ Op.in ]: Sequelize.literal(
452 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
453 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
454 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
456 'SELECT "video"."id" AS "id" FROM "video" ' +
457 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
458 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
459 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
460 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
461 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
471 if (options.withFiles === true) {
474 [ Op.in ]: Sequelize.literal(
475 '(SELECT "videoId" FROM "videoFile")'
481 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
482 if (options.tagsAllOf || options.tagsOneOf) {
483 if (options.tagsOneOf) {
484 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
488 [ Op.in ]: Sequelize.literal(
490 'SELECT "videoId" FROM "videoTag" ' +
491 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
492 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
499 if (options.tagsAllOf) {
500 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
504 [ Op.in ]: Sequelize.literal(
506 'SELECT "videoId" FROM "videoTag" ' +
507 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
508 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' +
509 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
517 if (options.nsfw === true || options.nsfw === false) {
518 whereAnd.push({ nsfw: options.nsfw })
521 if (options.categoryOneOf) {
524 [ Op.or ]: options.categoryOneOf
529 if (options.licenceOneOf) {
532 [ Op.or ]: options.licenceOneOf
537 if (options.languageOneOf) {
538 let videoLanguages = options.languageOneOf
539 if (options.languageOneOf.find(l => l === '_unknown')) {
540 videoLanguages = videoLanguages.concat([ null ])
547 [ Op.or ]: videoLanguages
552 [ Op.in ]: Sequelize.literal(
554 'SELECT "videoId" FROM "videoCaption" ' +
555 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
564 if (options.trendingDays) {
565 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
567 query.subQuery = false
570 if (options.historyOfUser) {
572 model: UserVideoHistoryModel,
575 userId: options.historyOfUser.id
579 // Even if the relation is n:m, we know that a user only have 0..1 video history
580 // So we won't have multiple rows for the same video
581 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
582 query.subQuery = false
591 [ ScopeNames.WITH_THUMBNAILS ]: {
594 model: ThumbnailModel,
599 [ ScopeNames.WITH_USER_ID ]: {
602 attributes: [ 'accountId' ],
603 model: VideoChannelModel.unscoped(),
607 attributes: [ 'userId' ],
608 model: AccountModel.unscoped(),
615 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
618 model: VideoChannelModel.unscoped(),
623 exclude: [ 'privateKey', 'publicKey' ]
625 model: ActorModel.unscoped(),
629 attributes: [ 'host' ],
630 model: ServerModel.unscoped(),
634 model: AvatarModel.unscoped(),
640 model: AccountModel.unscoped(),
644 model: ActorModel.unscoped(),
646 exclude: [ 'privateKey', 'publicKey' ]
651 attributes: [ 'host' ],
652 model: ServerModel.unscoped(),
656 model: AvatarModel.unscoped(),
667 [ ScopeNames.WITH_TAGS ]: {
668 include: [ TagModel ]
670 [ ScopeNames.WITH_BLACKLISTED ]: {
673 attributes: [ 'id', 'reason', 'unfederated' ],
674 model: VideoBlacklistModel,
679 [ ScopeNames.WITH_WEBTORRENT_FILES ]: (withRedundancies = false) => {
680 let subInclude: any[] = []
682 if (withRedundancies === true) {
685 attributes: [ 'fileUrl' ],
686 model: VideoRedundancyModel.unscoped(),
695 model: VideoFileModel.unscoped(),
696 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
703 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
704 const subInclude: IncludeOptions[] = [
706 model: VideoFileModel.unscoped(),
711 if (withRedundancies === true) {
713 attributes: [ 'fileUrl' ],
714 model: VideoRedundancyModel.unscoped(),
722 model: VideoStreamingPlaylistModel.unscoped(),
723 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
730 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
733 model: ScheduleVideoUpdateModel.unscoped(),
738 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
742 attributes: [ 'currentTime' ],
743 model: UserVideoHistoryModel.unscoped(),
757 export class VideoModel extends Model<VideoModel> {
760 @Default(DataType.UUIDV4)
762 @Column(DataType.UUID)
766 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
772 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
778 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
784 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
785 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
789 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
794 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
800 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
801 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
806 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
807 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
811 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
841 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
842 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
847 commentsEnabled: boolean
851 downloadEnabled: boolean
855 waitTranscoding: boolean
859 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
870 @Default(DataType.NOW)
877 originallyPublishedAt: Date
879 @ForeignKey(() => VideoChannelModel)
883 @BelongsTo(() => VideoChannelModel, {
889 VideoChannel: VideoChannelModel
891 @BelongsToMany(() => TagModel, {
892 foreignKey: 'videoId',
893 through: () => VideoTagModel,
898 @HasMany(() => ThumbnailModel, {
906 Thumbnails: ThumbnailModel[]
908 @HasMany(() => VideoPlaylistElementModel, {
915 VideoPlaylistElements: VideoPlaylistElementModel[]
917 @HasMany(() => VideoAbuseModel, {
924 VideoAbuses: VideoAbuseModel[]
926 @HasMany(() => VideoFileModel, {
934 VideoFiles: VideoFileModel[]
936 @HasMany(() => VideoStreamingPlaylistModel, {
944 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
946 @HasMany(() => VideoShareModel, {
953 VideoShares: VideoShareModel[]
955 @HasMany(() => AccountVideoRateModel, {
962 AccountVideoRates: AccountVideoRateModel[]
964 @HasMany(() => VideoCommentModel, {
972 VideoComments: VideoCommentModel[]
974 @HasMany(() => VideoViewModel, {
981 VideoViews: VideoViewModel[]
983 @HasMany(() => UserVideoHistoryModel, {
990 UserVideoHistories: UserVideoHistoryModel[]
992 @HasOne(() => ScheduleVideoUpdateModel, {
999 ScheduleVideoUpdate: ScheduleVideoUpdateModel
1001 @HasOne(() => VideoBlacklistModel, {
1008 VideoBlacklist: VideoBlacklistModel
1010 @HasOne(() => VideoImportModel, {
1015 onDelete: 'set null'
1017 VideoImport: VideoImportModel
1019 @HasMany(() => VideoCaptionModel, {
1024 onDelete: 'cascade',
1026 [ 'separate' as any ]: true
1028 VideoCaptions: VideoCaptionModel[]
1031 static async sendDelete (instance: MVideoAccountLight, options) {
1032 if (instance.isOwned()) {
1033 if (!instance.VideoChannel) {
1034 instance.VideoChannel = await instance.$get('VideoChannel', {
1039 transaction: options.transaction
1040 }) as MChannelAccountDefault
1043 return sendDeleteVideo(instance, options.transaction)
1050 static async removeFiles (instance: VideoModel) {
1051 const tasks: Promise<any>[] = []
1053 logger.info('Removing files of video %s.', instance.url)
1055 if (instance.isOwned()) {
1056 if (!Array.isArray(instance.VideoFiles)) {
1057 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1060 // Remove physical files and torrents
1061 instance.VideoFiles.forEach(file => {
1062 tasks.push(instance.removeFile(file))
1063 tasks.push(instance.removeTorrent(file))
1066 // Remove playlists file
1067 tasks.push(instance.removeStreamingPlaylist())
1070 // Do not wait video deletion because we could be in a transaction
1073 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1079 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1086 return VideoModel.scope([
1087 ScopeNames.WITH_WEBTORRENT_FILES,
1088 ScopeNames.WITH_STREAMING_PLAYLISTS,
1089 ScopeNames.WITH_THUMBNAILS
1093 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1094 function getRawQuery (select: string) {
1095 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1096 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1097 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1098 'WHERE "Account"."actorId" = ' + actorId
1099 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1100 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1101 'WHERE "VideoShare"."actorId" = ' + actorId
1103 return `(${queryVideo}) UNION (${queryVideoShare})`
1106 const rawQuery = getRawQuery('"Video"."id"')
1107 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1113 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1116 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1119 { privacy: VideoPrivacy.PUBLIC },
1120 { privacy: VideoPrivacy.UNLISTED }
1125 attributes: [ 'language' ],
1126 model: VideoCaptionModel.unscoped(),
1130 attributes: [ 'id', 'url' ],
1131 model: VideoShareModel.unscoped(),
1133 // We only want videos shared by this actor
1148 attributes: [ 'id', 'url' ],
1149 model: ActorModel.unscoped()
1154 model: VideoChannelModel.unscoped(),
1158 attributes: [ 'name' ],
1159 model: AccountModel.unscoped(),
1163 attributes: [ 'id', 'url', 'followersUrl' ],
1164 model: ActorModel.unscoped(),
1170 attributes: [ 'id', 'url', 'followersUrl' ],
1171 model: ActorModel.unscoped(),
1181 return Bluebird.all([
1182 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1183 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1184 ]).then(([ rows, totals ]) => {
1185 // totals: totalVideos + totalVideoShares
1187 let totalVideoShares = 0
1188 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1189 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1191 const total = totalVideos + totalVideoShares
1199 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) {
1200 function buildBaseQuery (): FindOptions {
1204 order: getVideoSort(sort),
1207 model: VideoChannelModel,
1211 model: AccountModel,
1223 const countQuery = buildBaseQuery()
1224 const findQuery = buildBaseQuery()
1226 const findScopes = [
1227 ScopeNames.WITH_SCHEDULED_UPDATE,
1228 ScopeNames.WITH_BLACKLISTED,
1229 ScopeNames.WITH_THUMBNAILS
1232 return Promise.all([
1233 VideoModel.count(countQuery),
1234 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1235 ]).then(([ count, rows ]) => {
1243 static async listForApi (options: {
1248 includeLocalVideos: boolean,
1250 categoryOneOf?: number[],
1251 licenceOneOf?: number[],
1252 languageOneOf?: string[],
1253 tagsOneOf?: string[],
1254 tagsAllOf?: string[],
1255 filter?: VideoFilter,
1257 videoChannelId?: number,
1258 followerActorId?: number
1259 videoPlaylistId?: number,
1260 trendingDays?: number,
1261 user?: MUserAccountId,
1262 historyOfUser?: MUserId
1263 }, countVideos = true) {
1264 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1265 throw new Error('Try to filter all-local but no user has not the see all videos right')
1268 const query: FindOptions & { where?: null } = {
1269 offset: options.start,
1270 limit: options.count,
1271 order: getVideoSort(options.sort)
1274 let trendingDays: number
1275 if (options.sort.endsWith('trending')) {
1276 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1278 query.group = 'VideoModel.id'
1281 const serverActor = await getServerActor()
1283 // followerActorId === null has a meaning, so just check undefined
1284 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1286 const queryOptions = {
1288 serverAccountId: serverActor.Account.id,
1290 categoryOneOf: options.categoryOneOf,
1291 licenceOneOf: options.licenceOneOf,
1292 languageOneOf: options.languageOneOf,
1293 tagsOneOf: options.tagsOneOf,
1294 tagsAllOf: options.tagsAllOf,
1295 filter: options.filter,
1296 withFiles: options.withFiles,
1297 accountId: options.accountId,
1298 videoChannelId: options.videoChannelId,
1299 videoPlaylistId: options.videoPlaylistId,
1300 includeLocalVideos: options.includeLocalVideos,
1302 historyOfUser: options.historyOfUser,
1306 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1309 static async searchAndPopulateAccountAndServer (options: {
1310 includeLocalVideos: boolean
1315 startDate?: string // ISO 8601
1316 endDate?: string // ISO 8601
1317 originallyPublishedStartDate?: string
1318 originallyPublishedEndDate?: string
1320 categoryOneOf?: number[]
1321 licenceOneOf?: number[]
1322 languageOneOf?: string[]
1323 tagsOneOf?: string[]
1324 tagsAllOf?: string[]
1325 durationMin?: number // seconds
1326 durationMax?: number // seconds
1327 user?: MUserAccountId,
1328 filter?: VideoFilter
1332 if (options.startDate || options.endDate) {
1333 const publishedAtRange = {}
1335 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1336 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1338 whereAnd.push({ publishedAt: publishedAtRange })
1341 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1342 const originallyPublishedAtRange = {}
1344 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1345 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1347 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1350 if (options.durationMin || options.durationMax) {
1351 const durationRange = {}
1353 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1354 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1356 whereAnd.push({ duration: durationRange })
1359 const attributesInclude = []
1360 const escapedSearch = VideoModel.sequelize.escape(options.search)
1361 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1362 if (options.search) {
1363 const trigramSearch = {
1365 [ Op.in ]: Sequelize.literal(
1367 'SELECT "video"."id" FROM "video" ' +
1369 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1370 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1372 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1373 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1374 'WHERE lower("tag"."name") = lower(' + escapedSearch + ')' +
1380 if (validator.isUUID(options.search)) {
1385 uuid: options.search
1390 whereAnd.push(trigramSearch)
1393 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1396 // Cannot search on similarity if we don't have a search
1397 if (!options.search) {
1398 attributesInclude.push(
1399 Sequelize.literal('0 as similarity')
1405 include: attributesInclude
1407 offset: options.start,
1408 limit: options.count,
1409 order: getVideoSort(options.sort)
1412 const serverActor = await getServerActor()
1413 const queryOptions = {
1414 followerActorId: serverActor.id,
1415 serverAccountId: serverActor.Account.id,
1416 includeLocalVideos: options.includeLocalVideos,
1418 categoryOneOf: options.categoryOneOf,
1419 licenceOneOf: options.licenceOneOf,
1420 languageOneOf: options.languageOneOf,
1421 tagsOneOf: options.tagsOneOf,
1422 tagsAllOf: options.tagsAllOf,
1424 filter: options.filter,
1428 return VideoModel.getAvailableForApi(query, queryOptions)
1431 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1432 const where = buildWhereIdOrUUID(id)
1438 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1441 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1442 const where = buildWhereIdOrUUID(id)
1448 return VideoModel.scope([
1449 ScopeNames.WITH_THUMBNAILS,
1450 ScopeNames.WITH_BLACKLISTED
1454 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1455 const where = buildWhereIdOrUUID(id)
1461 return VideoModel.scope([
1462 ScopeNames.WITH_BLACKLISTED,
1463 ScopeNames.WITH_USER_ID,
1464 ScopeNames.WITH_THUMBNAILS
1468 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1469 const where = buildWhereIdOrUUID(id)
1472 attributes: [ 'id' ],
1477 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1480 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1481 const where = buildWhereIdOrUUID(id)
1489 return VideoModel.scope([
1490 ScopeNames.WITH_WEBTORRENT_FILES,
1491 ScopeNames.WITH_STREAMING_PLAYLISTS,
1492 ScopeNames.WITH_THUMBNAILS
1496 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1503 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1506 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1507 const query: FindOptions = {
1514 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1517 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1518 const query: FindOptions = {
1525 return VideoModel.scope([
1526 ScopeNames.WITH_ACCOUNT_DETAILS,
1527 ScopeNames.WITH_WEBTORRENT_FILES,
1528 ScopeNames.WITH_STREAMING_PLAYLISTS,
1529 ScopeNames.WITH_THUMBNAILS,
1530 ScopeNames.WITH_BLACKLISTED
1534 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1535 const where = buildWhereIdOrUUID(id)
1538 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1543 const scopes: (string | ScopeOptions)[] = [
1544 ScopeNames.WITH_TAGS,
1545 ScopeNames.WITH_BLACKLISTED,
1546 ScopeNames.WITH_ACCOUNT_DETAILS,
1547 ScopeNames.WITH_SCHEDULED_UPDATE,
1548 ScopeNames.WITH_WEBTORRENT_FILES,
1549 ScopeNames.WITH_STREAMING_PLAYLISTS,
1550 ScopeNames.WITH_THUMBNAILS
1554 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1562 static loadForGetAPI (parameters: {
1563 id: number | string,
1566 }): Bluebird<MVideoDetails> {
1567 const { id, t, userId } = parameters
1568 const where = buildWhereIdOrUUID(id)
1571 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1576 const scopes: (string | ScopeOptions)[] = [
1577 ScopeNames.WITH_TAGS,
1578 ScopeNames.WITH_BLACKLISTED,
1579 ScopeNames.WITH_ACCOUNT_DETAILS,
1580 ScopeNames.WITH_SCHEDULED_UPDATE,
1581 ScopeNames.WITH_THUMBNAILS,
1582 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1583 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1587 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1595 static async getStats () {
1596 const totalLocalVideos = await VideoModel.count({
1601 const totalVideos = await VideoModel.count()
1603 let totalLocalVideoViews = await VideoModel.sum('views', {
1608 // Sequelize could return null...
1609 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1613 totalLocalVideoViews,
1618 static incrementViews (id: number, views: number) {
1619 return VideoModel.increment('views', {
1627 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1628 // Instances only share videos
1629 const query = 'SELECT 1 FROM "videoShare" ' +
1630 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1631 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1635 type: QueryTypes.SELECT as QueryTypes.SELECT,
1636 bind: { followerActorId, videoId },
1640 return VideoModel.sequelize.query(query, options)
1641 .then(results => results.length === 1)
1644 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1647 channelId: videoChannel.id
1652 return VideoModel.update({ support: videoChannel.support }, options)
1655 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1657 attributes: [ 'id' ],
1659 channelId: videoChannel.id
1663 return VideoModel.findAll(query)
1664 .then(videos => videos.map(v => v.id))
1667 // threshold corresponds to how many video the field should have to be returned
1668 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1669 const serverActor = await getServerActor()
1670 const followerActorId = serverActor.id
1672 const scopeOptions: AvailableForListIDsOptions = {
1673 serverAccountId: serverActor.Account.id,
1675 includeLocalVideos: true,
1676 attributesType: 'none' // Don't break aggregation
1679 const query: FindOptions = {
1680 attributes: [ field ],
1683 having: Sequelize.where(
1684 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1686 order: [ (this.sequelize as any).random() ]
1689 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1691 .then(rows => rows.map(r => r[ field ]))
1694 static buildTrendingQuery (trendingDays: number) {
1698 model: VideoViewModel,
1702 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1708 private static async getAvailableForApi (
1709 query: FindOptions & { where?: null }, // Forbid where field in query
1710 options: AvailableForListIDsOptions,
1713 const idsScope: ScopeOptions = {
1715 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1719 // Remove trending sort on count, because it uses a group by
1720 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1721 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1722 const countScope: ScopeOptions = {
1724 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1728 const [ count, ids ] = await Promise.all([
1730 ? VideoModel.scope(countScope).count(countQuery)
1731 : Promise.resolve<number>(undefined),
1733 VideoModel.scope(idsScope)
1735 .then(rows => rows.map(r => r.id))
1738 if (ids.length === 0) return { data: [], total: count }
1740 const secondQuery: FindOptions = {
1743 attributes: query.attributes,
1744 order: [ // Keep original order
1746 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1751 const apiScope: (string | ScopeOptions)[] = []
1754 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1759 ScopeNames.FOR_API, {
1761 withFiles: options.withFiles,
1762 videoPlaylistId: options.videoPlaylistId
1767 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1775 private static isPrivacyForFederation (privacy: VideoPrivacy) {
1776 return privacy === VideoPrivacy.PUBLIC || privacy === VideoPrivacy.UNLISTED
1779 static getCategoryLabel (id: number) {
1780 return VIDEO_CATEGORIES[ id ] || 'Misc'
1783 static getLicenceLabel (id: number) {
1784 return VIDEO_LICENCES[ id ] || 'Unknown'
1787 static getLanguageLabel (id: string) {
1788 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1791 static getPrivacyLabel (id: number) {
1792 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1795 static getStateLabel (id: number) {
1796 return VIDEO_STATES[ id ] || 'Unknown'
1800 return !!this.VideoBlacklist
1804 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1805 this.VideoChannel.Account.isBlocked()
1808 getQualityFileBy <T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1809 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1810 const file = fun(this.VideoFiles, file => file.resolution)
1812 return Object.assign(file, { Video: this })
1815 // No webtorrent files, try with streaming playlist files
1816 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1817 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1819 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1820 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1826 getMaxQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1827 return this.getQualityFileBy(maxBy)
1830 getMinQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1831 return this.getQualityFileBy(minBy)
1834 getWebTorrentFile <T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1835 if (Array.isArray(this.VideoFiles) === false) return undefined
1837 const file = this.VideoFiles.find(f => f.resolution === resolution)
1838 if (!file) return undefined
1840 return Object.assign(file, { Video: this })
1843 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1844 thumbnail.videoId = this.id
1846 const savedThumbnail = await thumbnail.save({ transaction })
1848 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1850 // Already have this thumbnail, skip
1851 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1853 this.Thumbnails.push(savedThumbnail)
1856 generateThumbnailName () {
1857 return this.uuid + '.jpg'
1861 if (Array.isArray(this.Thumbnails) === false) return undefined
1863 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1866 generatePreviewName () {
1867 return this.uuid + '.jpg'
1871 if (Array.isArray(this.Thumbnails) === false) return undefined
1873 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1877 return this.remote === false
1880 getWatchStaticPath () {
1881 return '/videos/watch/' + this.uuid
1884 getEmbedStaticPath () {
1885 return '/videos/embed/' + this.uuid
1888 getMiniatureStaticPath () {
1889 const thumbnail = this.getMiniature()
1890 if (!thumbnail) return null
1892 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1895 getPreviewStaticPath () {
1896 const preview = this.getPreview()
1897 if (!preview) return null
1899 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1900 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1903 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1904 return videoModelToFormattedJSON(this, options)
1907 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1908 return videoModelToFormattedDetailsJSON(this)
1911 getFormattedVideoFilesJSON (): VideoFile[] {
1912 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1913 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1916 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1917 return videoModelToActivityPubObject(this)
1920 getTruncatedDescription () {
1921 if (!this.description) return null
1923 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1924 return peertubeTruncate(this.description, { length: maxLength })
1927 getMaxQualityResolution () {
1928 const file = this.getMaxQualityFile()
1929 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1930 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1932 return getVideoFileResolution(originalFilePath)
1935 getDescriptionAPIPath () {
1936 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1939 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1940 if (!this.VideoStreamingPlaylists) return undefined
1942 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1943 playlist.Video = this
1948 setHLSPlaylist (playlist: MStreamingPlaylist) {
1949 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1951 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1952 this.VideoStreamingPlaylists = toAdd
1956 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1957 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1961 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1962 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1963 return remove(filePath)
1964 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1967 removeTorrent (videoFile: MVideoFile) {
1968 const torrentPath = getTorrentFilePath(this, videoFile)
1969 return remove(torrentPath)
1970 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1973 removeStreamingPlaylist (isRedundancy = false) {
1974 const directoryPath = getHLSDirectory(this, isRedundancy)
1976 return remove(directoryPath)
1977 .catch(err => logger.warn('Cannot delete playlist directory %s.', directoryPath, { err }))
1981 if (this.isOwned()) return false
1983 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1986 hasPrivacyForFederation () {
1987 return VideoModel.isPrivacyForFederation(this.privacy)
1990 isNewVideo (newPrivacy: VideoPrivacy) {
1991 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
1995 this.changed('updatedAt', true)
2001 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2004 setPrivacy (newPrivacy: VideoPrivacy) {
2005 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2006 this.publishedAt = new Date()
2009 this.privacy = newPrivacy
2013 return this.privacy === VideoPrivacy.PRIVATE ||
2014 this.privacy === VideoPrivacy.UNLISTED ||
2015 this.privacy === VideoPrivacy.INTERNAL
2018 async publishIfNeededAndSave (t: Transaction) {
2019 if (this.state !== VideoState.PUBLISHED) {
2020 this.state = VideoState.PUBLISHED
2021 this.publishedAt = new Date()
2022 await this.save({ transaction: t })
2031 if (this.isOwned()) {
2033 baseUrlHttp: WEBSERVER.URL,
2034 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2039 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2040 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2044 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2045 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2048 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2049 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2052 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2053 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2056 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2057 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2060 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2061 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2064 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2065 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2068 getBandwidthBits (videoFile: MVideoFile) {
2069 return Math.ceil((videoFile.size * 8) / this.duration)