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 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 +
461 [ Op.in ]: Sequelize.literal(
463 'SELECT "video"."id" AS "id" FROM "video" ' +
464 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
465 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
466 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
467 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
468 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
478 if (options.withFiles === true) {
481 [ Op.in ]: Sequelize.literal(
482 '(SELECT "videoId" FROM "videoFile")'
488 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
489 if (options.tagsAllOf || options.tagsOneOf) {
490 if (options.tagsOneOf) {
491 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
495 [ Op.in ]: Sequelize.literal(
497 'SELECT "videoId" FROM "videoTag" ' +
498 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
499 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
506 if (options.tagsAllOf) {
507 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
511 [ Op.in ]: Sequelize.literal(
513 'SELECT "videoId" FROM "videoTag" ' +
514 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
515 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' +
516 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
524 if (options.nsfw === true || options.nsfw === false) {
525 whereAnd.push({ nsfw: options.nsfw })
528 if (options.categoryOneOf) {
531 [ Op.or ]: options.categoryOneOf
536 if (options.licenceOneOf) {
539 [ Op.or ]: options.licenceOneOf
544 if (options.languageOneOf) {
545 let videoLanguages = options.languageOneOf
546 if (options.languageOneOf.find(l => l === '_unknown')) {
547 videoLanguages = videoLanguages.concat([ null ])
554 [ Op.or ]: videoLanguages
559 [ Op.in ]: Sequelize.literal(
561 'SELECT "videoId" FROM "videoCaption" ' +
562 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
571 if (options.trendingDays) {
572 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
574 query.subQuery = false
577 if (options.historyOfUser) {
579 model: UserVideoHistoryModel,
582 userId: options.historyOfUser.id
586 // Even if the relation is n:m, we know that a user only have 0..1 video history
587 // So we won't have multiple rows for the same video
588 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
589 query.subQuery = false
598 [ ScopeNames.WITH_THUMBNAILS ]: {
601 model: ThumbnailModel,
606 [ ScopeNames.WITH_USER_ID ]: {
609 attributes: [ 'accountId' ],
610 model: VideoChannelModel.unscoped(),
614 attributes: [ 'userId' ],
615 model: AccountModel.unscoped(),
622 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
625 model: VideoChannelModel.unscoped(),
630 exclude: [ 'privateKey', 'publicKey' ]
632 model: ActorModel.unscoped(),
636 attributes: [ 'host' ],
637 model: ServerModel.unscoped(),
641 model: AvatarModel.unscoped(),
647 model: AccountModel.unscoped(),
651 model: ActorModel.unscoped(),
653 exclude: [ 'privateKey', 'publicKey' ]
658 attributes: [ 'host' ],
659 model: ServerModel.unscoped(),
663 model: AvatarModel.unscoped(),
674 [ ScopeNames.WITH_TAGS ]: {
675 include: [ TagModel ]
677 [ ScopeNames.WITH_BLACKLISTED ]: {
680 attributes: [ 'id', 'reason', 'unfederated' ],
681 model: VideoBlacklistModel,
686 [ ScopeNames.WITH_WEBTORRENT_FILES ]: (withRedundancies = false) => {
687 let subInclude: any[] = []
689 if (withRedundancies === true) {
692 attributes: [ 'fileUrl' ],
693 model: VideoRedundancyModel.unscoped(),
702 model: VideoFileModel.unscoped(),
703 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
710 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
711 const subInclude: IncludeOptions[] = [
713 model: VideoFileModel.unscoped(),
718 if (withRedundancies === true) {
720 attributes: [ 'fileUrl' ],
721 model: VideoRedundancyModel.unscoped(),
729 model: VideoStreamingPlaylistModel.unscoped(),
730 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
737 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
740 model: ScheduleVideoUpdateModel.unscoped(),
745 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
749 attributes: [ 'currentTime' ],
750 model: UserVideoHistoryModel.unscoped(),
764 export class VideoModel extends Model<VideoModel> {
767 @Default(DataType.UUIDV4)
769 @Column(DataType.UUID)
773 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
779 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
785 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
791 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
792 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
796 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
801 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
807 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
808 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
813 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
814 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
818 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
848 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
849 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
854 commentsEnabled: boolean
858 downloadEnabled: boolean
862 waitTranscoding: boolean
866 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
877 @Default(DataType.NOW)
884 originallyPublishedAt: Date
886 @ForeignKey(() => VideoChannelModel)
890 @BelongsTo(() => VideoChannelModel, {
896 VideoChannel: VideoChannelModel
898 @BelongsToMany(() => TagModel, {
899 foreignKey: 'videoId',
900 through: () => VideoTagModel,
905 @HasMany(() => ThumbnailModel, {
913 Thumbnails: ThumbnailModel[]
915 @HasMany(() => VideoPlaylistElementModel, {
922 VideoPlaylistElements: VideoPlaylistElementModel[]
924 @HasMany(() => VideoAbuseModel, {
931 VideoAbuses: VideoAbuseModel[]
933 @HasMany(() => VideoFileModel, {
941 VideoFiles: VideoFileModel[]
943 @HasMany(() => VideoStreamingPlaylistModel, {
951 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
953 @HasMany(() => VideoShareModel, {
960 VideoShares: VideoShareModel[]
962 @HasMany(() => AccountVideoRateModel, {
969 AccountVideoRates: AccountVideoRateModel[]
971 @HasMany(() => VideoCommentModel, {
979 VideoComments: VideoCommentModel[]
981 @HasMany(() => VideoViewModel, {
988 VideoViews: VideoViewModel[]
990 @HasMany(() => UserVideoHistoryModel, {
997 UserVideoHistories: UserVideoHistoryModel[]
999 @HasOne(() => ScheduleVideoUpdateModel, {
1006 ScheduleVideoUpdate: ScheduleVideoUpdateModel
1008 @HasOne(() => VideoBlacklistModel, {
1015 VideoBlacklist: VideoBlacklistModel
1017 @HasOne(() => VideoImportModel, {
1022 onDelete: 'set null'
1024 VideoImport: VideoImportModel
1026 @HasMany(() => VideoCaptionModel, {
1031 onDelete: 'cascade',
1033 [ 'separate' as any ]: true
1035 VideoCaptions: VideoCaptionModel[]
1038 static async sendDelete (instance: MVideoAccountLight, options) {
1039 if (instance.isOwned()) {
1040 if (!instance.VideoChannel) {
1041 instance.VideoChannel = await instance.$get('VideoChannel', {
1046 transaction: options.transaction
1047 }) as MChannelAccountDefault
1050 return sendDeleteVideo(instance, options.transaction)
1057 static async removeFiles (instance: VideoModel) {
1058 const tasks: Promise<any>[] = []
1060 logger.info('Removing files of video %s.', instance.url)
1062 if (instance.isOwned()) {
1063 if (!Array.isArray(instance.VideoFiles)) {
1064 instance.VideoFiles = await instance.$get('VideoFiles')
1067 // Remove physical files and torrents
1068 instance.VideoFiles.forEach(file => {
1069 tasks.push(instance.removeFile(file))
1070 tasks.push(instance.removeTorrent(file))
1073 // Remove playlists file
1074 tasks.push(instance.removeStreamingPlaylist())
1077 // Do not wait video deletion because we could be in a transaction
1080 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1086 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1093 return VideoModel.scope([
1094 ScopeNames.WITH_WEBTORRENT_FILES,
1095 ScopeNames.WITH_STREAMING_PLAYLISTS,
1096 ScopeNames.WITH_THUMBNAILS
1100 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1101 function getRawQuery (select: string) {
1102 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1103 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1104 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1105 'WHERE "Account"."actorId" = ' + actorId
1106 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1107 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1108 'WHERE "VideoShare"."actorId" = ' + actorId
1110 return `(${queryVideo}) UNION (${queryVideoShare})`
1113 const rawQuery = getRawQuery('"Video"."id"')
1114 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1120 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1123 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1126 { privacy: VideoPrivacy.PUBLIC },
1127 { privacy: VideoPrivacy.UNLISTED }
1132 attributes: [ 'language' ],
1133 model: VideoCaptionModel.unscoped(),
1137 attributes: [ 'id', 'url' ],
1138 model: VideoShareModel.unscoped(),
1140 // We only want videos shared by this actor
1155 attributes: [ 'id', 'url' ],
1156 model: ActorModel.unscoped()
1161 model: VideoChannelModel.unscoped(),
1165 attributes: [ 'name' ],
1166 model: AccountModel.unscoped(),
1170 attributes: [ 'id', 'url', 'followersUrl' ],
1171 model: ActorModel.unscoped(),
1177 attributes: [ 'id', 'url', 'followersUrl' ],
1178 model: ActorModel.unscoped(),
1188 return Bluebird.all([
1189 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1190 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1191 ]).then(([ rows, totals ]) => {
1192 // totals: totalVideos + totalVideoShares
1194 let totalVideoShares = 0
1195 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1196 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1198 const total = totalVideos + totalVideoShares
1206 static listUserVideosForApi (
1213 function buildBaseQuery (): FindOptions {
1217 order: getVideoSort(sort),
1220 model: VideoChannelModel,
1224 model: AccountModel,
1236 baseQuery = Object.assign(baseQuery, {
1239 [ Op.iLike ]: '%' + search + '%'
1248 const countQuery = buildBaseQuery()
1249 const findQuery = buildBaseQuery()
1251 const findScopes: (string | ScopeOptions)[] = [
1252 ScopeNames.WITH_SCHEDULED_UPDATE,
1253 ScopeNames.WITH_BLACKLISTED,
1254 ScopeNames.WITH_THUMBNAILS
1257 return Promise.all([
1258 VideoModel.count(countQuery),
1259 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1260 ]).then(([ count, rows ]) => {
1268 static async listForApi (options: {
1273 includeLocalVideos: boolean,
1275 categoryOneOf?: number[],
1276 licenceOneOf?: number[],
1277 languageOneOf?: string[],
1278 tagsOneOf?: string[],
1279 tagsAllOf?: string[],
1280 filter?: VideoFilter,
1282 videoChannelId?: number,
1283 followerActorId?: number
1284 videoPlaylistId?: number,
1285 trendingDays?: number,
1286 user?: MUserAccountId,
1287 historyOfUser?: MUserId,
1288 countVideos?: boolean
1290 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1291 throw new Error('Try to filter all-local but no user has not the see all videos right')
1294 const query: FindOptions & { where?: null } = {
1295 offset: options.start,
1296 limit: options.count,
1297 order: getVideoSort(options.sort)
1300 let trendingDays: number
1301 if (options.sort.endsWith('trending')) {
1302 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1304 query.group = 'VideoModel.id'
1307 const serverActor = await getServerActor()
1309 // followerActorId === null has a meaning, so just check undefined
1310 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1312 const queryOptions = {
1314 serverAccountId: serverActor.Account.id,
1316 categoryOneOf: options.categoryOneOf,
1317 licenceOneOf: options.licenceOneOf,
1318 languageOneOf: options.languageOneOf,
1319 tagsOneOf: options.tagsOneOf,
1320 tagsAllOf: options.tagsAllOf,
1321 filter: options.filter,
1322 withFiles: options.withFiles,
1323 accountId: options.accountId,
1324 videoChannelId: options.videoChannelId,
1325 videoPlaylistId: options.videoPlaylistId,
1326 includeLocalVideos: options.includeLocalVideos,
1328 historyOfUser: options.historyOfUser,
1332 return VideoModel.getAvailableForApi(query, queryOptions, options.countVideos)
1335 static async searchAndPopulateAccountAndServer (options: {
1336 includeLocalVideos: boolean
1341 startDate?: string // ISO 8601
1342 endDate?: string // ISO 8601
1343 originallyPublishedStartDate?: string
1344 originallyPublishedEndDate?: string
1346 categoryOneOf?: number[]
1347 licenceOneOf?: number[]
1348 languageOneOf?: string[]
1349 tagsOneOf?: string[]
1350 tagsAllOf?: string[]
1351 durationMin?: number // seconds
1352 durationMax?: number // seconds
1353 user?: MUserAccountId,
1354 filter?: VideoFilter
1358 if (options.startDate || options.endDate) {
1359 const publishedAtRange = {}
1361 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1362 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1364 whereAnd.push({ publishedAt: publishedAtRange })
1367 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1368 const originallyPublishedAtRange = {}
1370 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1371 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1373 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1376 if (options.durationMin || options.durationMax) {
1377 const durationRange = {}
1379 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1380 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1382 whereAnd.push({ duration: durationRange })
1385 const attributesInclude = []
1386 const escapedSearch = VideoModel.sequelize.escape(options.search)
1387 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1388 if (options.search) {
1389 const trigramSearch = {
1391 [ Op.in ]: Sequelize.literal(
1393 'SELECT "video"."id" FROM "video" ' +
1395 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1396 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1398 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1399 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1400 'WHERE lower("tag"."name") = lower(' + escapedSearch + ')' +
1406 if (validator.isUUID(options.search)) {
1411 uuid: options.search
1416 whereAnd.push(trigramSearch)
1419 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1422 // Cannot search on similarity if we don't have a search
1423 if (!options.search) {
1424 attributesInclude.push(
1425 Sequelize.literal('0 as similarity')
1431 include: attributesInclude
1433 offset: options.start,
1434 limit: options.count,
1435 order: getVideoSort(options.sort)
1438 const serverActor = await getServerActor()
1439 const queryOptions = {
1440 followerActorId: serverActor.id,
1441 serverAccountId: serverActor.Account.id,
1442 includeLocalVideos: options.includeLocalVideos,
1444 categoryOneOf: options.categoryOneOf,
1445 licenceOneOf: options.licenceOneOf,
1446 languageOneOf: options.languageOneOf,
1447 tagsOneOf: options.tagsOneOf,
1448 tagsAllOf: options.tagsAllOf,
1450 filter: options.filter,
1454 return VideoModel.getAvailableForApi(query, queryOptions)
1457 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1458 const where = buildWhereIdOrUUID(id)
1464 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1467 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1468 const where = buildWhereIdOrUUID(id)
1474 return VideoModel.scope([
1475 ScopeNames.WITH_THUMBNAILS,
1476 ScopeNames.WITH_BLACKLISTED
1480 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1481 const where = buildWhereIdOrUUID(id)
1487 return VideoModel.scope([
1488 ScopeNames.WITH_BLACKLISTED,
1489 ScopeNames.WITH_USER_ID,
1490 ScopeNames.WITH_THUMBNAILS
1494 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1495 const where = buildWhereIdOrUUID(id)
1498 attributes: [ 'id' ],
1503 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1506 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1507 const where = buildWhereIdOrUUID(id)
1515 return VideoModel.scope([
1516 ScopeNames.WITH_WEBTORRENT_FILES,
1517 ScopeNames.WITH_STREAMING_PLAYLISTS,
1518 ScopeNames.WITH_THUMBNAILS
1522 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1529 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1532 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1533 const query: FindOptions = {
1540 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1543 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1544 const query: FindOptions = {
1551 return VideoModel.scope([
1552 ScopeNames.WITH_ACCOUNT_DETAILS,
1553 ScopeNames.WITH_WEBTORRENT_FILES,
1554 ScopeNames.WITH_STREAMING_PLAYLISTS,
1555 ScopeNames.WITH_THUMBNAILS,
1556 ScopeNames.WITH_BLACKLISTED
1560 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1561 const where = buildWhereIdOrUUID(id)
1564 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1569 const scopes: (string | ScopeOptions)[] = [
1570 ScopeNames.WITH_TAGS,
1571 ScopeNames.WITH_BLACKLISTED,
1572 ScopeNames.WITH_ACCOUNT_DETAILS,
1573 ScopeNames.WITH_SCHEDULED_UPDATE,
1574 ScopeNames.WITH_WEBTORRENT_FILES,
1575 ScopeNames.WITH_STREAMING_PLAYLISTS,
1576 ScopeNames.WITH_THUMBNAILS
1580 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1588 static loadForGetAPI (parameters: {
1589 id: number | string,
1592 }): Bluebird<MVideoDetails> {
1593 const { id, t, userId } = parameters
1594 const where = buildWhereIdOrUUID(id)
1597 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1602 const scopes: (string | ScopeOptions)[] = [
1603 ScopeNames.WITH_TAGS,
1604 ScopeNames.WITH_BLACKLISTED,
1605 ScopeNames.WITH_ACCOUNT_DETAILS,
1606 ScopeNames.WITH_SCHEDULED_UPDATE,
1607 ScopeNames.WITH_THUMBNAILS,
1608 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1609 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1613 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1621 static async getStats () {
1622 const totalLocalVideos = await VideoModel.count({
1627 const totalVideos = await VideoModel.count()
1629 let totalLocalVideoViews = await VideoModel.sum('views', {
1634 // Sequelize could return null...
1635 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1639 totalLocalVideoViews,
1644 static incrementViews (id: number, views: number) {
1645 return VideoModel.increment('views', {
1653 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1654 // Instances only share videos
1655 const query = 'SELECT 1 FROM "videoShare" ' +
1656 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1657 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1661 type: QueryTypes.SELECT as QueryTypes.SELECT,
1662 bind: { followerActorId, videoId },
1666 return VideoModel.sequelize.query(query, options)
1667 .then(results => results.length === 1)
1670 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1673 channelId: videoChannel.id
1678 return VideoModel.update({ support: videoChannel.support }, options)
1681 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1683 attributes: [ 'id' ],
1685 channelId: videoChannel.id
1689 return VideoModel.findAll(query)
1690 .then(videos => videos.map(v => v.id))
1693 // threshold corresponds to how many video the field should have to be returned
1694 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1695 const serverActor = await getServerActor()
1696 const followerActorId = serverActor.id
1698 const scopeOptions: AvailableForListIDsOptions = {
1699 serverAccountId: serverActor.Account.id,
1701 includeLocalVideos: true,
1702 attributesType: 'none' // Don't break aggregation
1705 const query: FindOptions = {
1706 attributes: [ field ],
1709 having: Sequelize.where(
1710 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1712 order: [ (this.sequelize as any).random() ]
1715 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1717 .then(rows => rows.map(r => r[ field ]))
1720 static buildTrendingQuery (trendingDays: number) {
1724 model: VideoViewModel,
1728 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1734 private static async getAvailableForApi (
1735 query: FindOptions & { where?: null }, // Forbid where field in query
1736 options: AvailableForListIDsOptions,
1739 const idsScope: ScopeOptions = {
1741 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1745 // Remove trending sort on count, because it uses a group by
1746 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1747 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1748 const countScope: ScopeOptions = {
1750 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1754 const [ count, rows ] = await Promise.all([
1756 ? VideoModel.scope(countScope).count(countQuery)
1757 : Promise.resolve<number>(undefined),
1759 VideoModel.scope(idsScope)
1760 .findAll(Object.assign({}, query, { raw: true }))
1761 .then(rows => rows.map(r => r.id))
1762 .then(ids => VideoModel.loadCompleteVideosForApi(ids, query, options))
1771 private static loadCompleteVideosForApi (ids: number[], query: FindOptions, options: AvailableForListIDsOptions) {
1772 if (ids.length === 0) return []
1774 const secondQuery: FindOptions = {
1777 attributes: query.attributes,
1778 order: [ // Keep original order
1780 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1785 const apiScope: (string | ScopeOptions)[] = []
1788 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1793 ScopeNames.FOR_API, {
1795 withFiles: options.withFiles,
1796 videoPlaylistId: options.videoPlaylistId
1801 return VideoModel.scope(apiScope).findAll(secondQuery)
1804 private static isPrivacyForFederation (privacy: VideoPrivacy) {
1805 return privacy === VideoPrivacy.PUBLIC || privacy === VideoPrivacy.UNLISTED
1808 static getCategoryLabel (id: number) {
1809 return VIDEO_CATEGORIES[ id ] || 'Misc'
1812 static getLicenceLabel (id: number) {
1813 return VIDEO_LICENCES[ id ] || 'Unknown'
1816 static getLanguageLabel (id: string) {
1817 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1820 static getPrivacyLabel (id: number) {
1821 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1824 static getStateLabel (id: number) {
1825 return VIDEO_STATES[ id ] || 'Unknown'
1829 return !!this.VideoBlacklist
1833 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1834 this.VideoChannel.Account.isBlocked()
1837 getQualityFileBy <T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1838 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1839 const file = fun(this.VideoFiles, file => file.resolution)
1841 return Object.assign(file, { Video: this })
1844 // No webtorrent files, try with streaming playlist files
1845 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1846 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1848 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1849 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1855 getMaxQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1856 return this.getQualityFileBy(maxBy)
1859 getMinQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1860 return this.getQualityFileBy(minBy)
1863 getWebTorrentFile <T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1864 if (Array.isArray(this.VideoFiles) === false) return undefined
1866 const file = this.VideoFiles.find(f => f.resolution === resolution)
1867 if (!file) return undefined
1869 return Object.assign(file, { Video: this })
1872 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1873 thumbnail.videoId = this.id
1875 const savedThumbnail = await thumbnail.save({ transaction })
1877 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1879 // Already have this thumbnail, skip
1880 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1882 this.Thumbnails.push(savedThumbnail)
1885 generateThumbnailName () {
1886 return this.uuid + '.jpg'
1890 if (Array.isArray(this.Thumbnails) === false) return undefined
1892 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1895 generatePreviewName () {
1896 return this.uuid + '.jpg'
1900 if (Array.isArray(this.Thumbnails) === false) return undefined
1902 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1906 return this.remote === false
1909 getWatchStaticPath () {
1910 return '/videos/watch/' + this.uuid
1913 getEmbedStaticPath () {
1914 return '/videos/embed/' + this.uuid
1917 getMiniatureStaticPath () {
1918 const thumbnail = this.getMiniature()
1919 if (!thumbnail) return null
1921 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1924 getPreviewStaticPath () {
1925 const preview = this.getPreview()
1926 if (!preview) return null
1928 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1929 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1932 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1933 return videoModelToFormattedJSON(this, options)
1936 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1937 return videoModelToFormattedDetailsJSON(this)
1940 getFormattedVideoFilesJSON (): VideoFile[] {
1941 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1942 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1945 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1946 return videoModelToActivityPubObject(this)
1949 getTruncatedDescription () {
1950 if (!this.description) return null
1952 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1953 return peertubeTruncate(this.description, { length: maxLength })
1956 getMaxQualityResolution () {
1957 const file = this.getMaxQualityFile()
1958 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1959 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1961 return getVideoFileResolution(originalFilePath)
1964 getDescriptionAPIPath () {
1965 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1968 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1969 if (!this.VideoStreamingPlaylists) return undefined
1971 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1972 playlist.Video = this
1977 setHLSPlaylist (playlist: MStreamingPlaylist) {
1978 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1980 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1981 this.VideoStreamingPlaylists = toAdd
1985 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1986 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1990 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1991 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1992 return remove(filePath)
1993 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1996 removeTorrent (videoFile: MVideoFile) {
1997 const torrentPath = getTorrentFilePath(this, videoFile)
1998 return remove(torrentPath)
1999 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
2002 removeStreamingPlaylist (isRedundancy = false) {
2003 const directoryPath = getHLSDirectory(this, isRedundancy)
2005 return remove(directoryPath)
2006 .catch(err => logger.warn('Cannot delete playlist directory %s.', directoryPath, { err }))
2010 if (this.isOwned()) return false
2012 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2015 hasPrivacyForFederation () {
2016 return VideoModel.isPrivacyForFederation(this.privacy)
2019 isNewVideo (newPrivacy: VideoPrivacy) {
2020 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
2024 this.changed('updatedAt', true)
2030 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2033 setPrivacy (newPrivacy: VideoPrivacy) {
2034 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2035 this.publishedAt = new Date()
2038 this.privacy = newPrivacy
2042 return this.privacy === VideoPrivacy.PRIVATE ||
2043 this.privacy === VideoPrivacy.UNLISTED ||
2044 this.privacy === VideoPrivacy.INTERNAL
2047 async publishIfNeededAndSave (t: Transaction) {
2048 if (this.state !== VideoState.PUBLISHED) {
2049 this.state = VideoState.PUBLISHED
2050 this.publishedAt = new Date()
2051 await this.save({ transaction: t })
2060 if (this.isOwned()) {
2062 baseUrlHttp: WEBSERVER.URL,
2063 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2068 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2069 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2073 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2074 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2077 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2078 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2081 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2082 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2085 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2086 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2089 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2090 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2093 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2094 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2097 getBandwidthBits (videoFile: MVideoFile) {
2098 return Math.ceil((videoFile.size * 8) / this.duration)