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' ] },
152 { fields: [ 'publishedAt' ] },
153 { fields: [ 'duration' ] },
154 { fields: [ 'views' ] },
155 { fields: [ 'channelId' ] },
157 fields: [ 'originallyPublishedAt' ],
159 originallyPublishedAt: {
165 fields: [ 'category' ], // We don't care videos with an unknown category
173 fields: [ 'licence' ], // We don't care videos with an unknown licence
181 fields: [ 'language' ], // We don't care videos with an unknown language
189 fields: [ 'nsfw' ], // Most of the videos are not NSFW
195 fields: [ 'remote' ], // Only index local videos
210 export enum ScopeNames {
211 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
213 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
214 WITH_TAGS = 'WITH_TAGS',
215 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
216 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
217 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
218 WITH_BLOCKLIST = 'WITH_BLOCKLIST',
219 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
220 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
221 WITH_USER_ID = 'WITH_USER_ID',
222 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
225 export type ForAPIOptions = {
228 videoPlaylistId?: number
232 withAccountBlockerIds?: number[]
235 export type AvailableForListIDsOptions = {
236 serverAccountId: number
237 followerActorId: number
238 includeLocalVideos: boolean
240 attributesType?: 'none' | 'id' | 'all'
243 categoryOneOf?: number[]
245 licenceOneOf?: number[]
246 languageOneOf?: string[]
253 videoChannelId?: number
255 videoPlaylistId?: number
257 trendingDays?: number
258 user?: MUserAccountId
259 historyOfUser?: MUserId
261 baseWhere?: WhereOptions[]
265 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
266 const query: FindOptions = {
269 model: VideoChannelModel.scope({
271 VideoChannelScopeNames.SUMMARY, {
273 withAccountBlockerIds: options.withAccountBlockerIds
280 attributes: [ 'type', 'filename' ],
281 model: ThumbnailModel,
290 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
295 if (options.withFiles === true) {
297 model: VideoFileModel.unscoped(),
302 if (options.videoPlaylistId) {
304 model: VideoPlaylistElementModel.unscoped(),
307 videoPlaylistId: options.videoPlaylistId
314 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
315 const whereAnd = options.baseWhere ? options.baseWhere : []
317 const query: FindOptions = {
322 const attributesType = options.attributesType || 'id'
324 if (attributesType === 'id') query.attributes = [ 'id' ]
325 else if (attributesType === 'none') query.attributes = [ ]
329 [ Op.notIn ]: Sequelize.literal(
330 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
335 if (options.serverAccountId) {
338 [ Op.notIn ]: Sequelize.literal(
340 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
341 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
349 // Only list public/published videos
350 if (!options.filter || options.filter !== 'all-local') {
352 const publishWhere = {
353 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
356 state: VideoState.PUBLISHED
360 state: VideoState.TO_TRANSCODE,
361 waitTranscoding: false
366 whereAnd.push(publishWhere)
368 // List internal videos if the user is logged in
370 const privacyWhere = {
373 privacy: VideoPrivacy.INTERNAL
376 privacy: VideoPrivacy.PUBLIC
381 whereAnd.push(privacyWhere)
382 } else { // Or only public videos
383 const privacyWhere = { privacy: VideoPrivacy.PUBLIC }
384 whereAnd.push(privacyWhere)
388 if (options.videoPlaylistId) {
391 model: VideoPlaylistElementModel.unscoped(),
394 videoPlaylistId: options.videoPlaylistId
398 query.subQuery = false
401 if (options.filter || options.accountId || options.videoChannelId) {
402 const videoChannelInclude: IncludeOptions = {
404 model: VideoChannelModel.unscoped(),
408 if (options.videoChannelId) {
409 videoChannelInclude.where = {
410 id: options.videoChannelId
414 if (options.filter || options.accountId) {
415 const accountInclude: IncludeOptions = {
417 model: AccountModel.unscoped(),
421 if (options.filter) {
422 accountInclude.include = [
425 model: ActorModel.unscoped(),
427 where: VideoModel.buildActorWhereWithFilter(options.filter)
432 if (options.accountId) {
433 accountInclude.where = { id: options.accountId }
436 videoChannelInclude.include = [ accountInclude ]
439 query.include.push(videoChannelInclude)
442 if (options.followerActorId) {
443 let localVideosReq = ''
444 if (options.includeLocalVideos === true) {
445 localVideosReq = ' UNION ALL ' +
446 'SELECT "video"."id" AS "id" FROM "video" ' +
447 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
448 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
449 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
450 'WHERE "actor"."serverId" IS NULL'
453 // Force actorId to be a number to avoid SQL injections
454 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
457 [ Op.in ]: Sequelize.literal(
459 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
460 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
461 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
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 +
476 if (options.withFiles === true) {
479 [ Op.in ]: Sequelize.literal(
480 '(SELECT "videoId" FROM "videoFile")'
486 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
487 if (options.tagsAllOf || options.tagsOneOf) {
488 if (options.tagsOneOf) {
489 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
493 [ Op.in ]: Sequelize.literal(
495 'SELECT "videoId" FROM "videoTag" ' +
496 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
497 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
504 if (options.tagsAllOf) {
505 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
509 [ Op.in ]: Sequelize.literal(
511 'SELECT "videoId" FROM "videoTag" ' +
512 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
513 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' +
514 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
522 if (options.nsfw === true || options.nsfw === false) {
523 whereAnd.push({ nsfw: options.nsfw })
526 if (options.categoryOneOf) {
529 [ Op.or ]: options.categoryOneOf
534 if (options.licenceOneOf) {
537 [ Op.or ]: options.licenceOneOf
542 if (options.languageOneOf) {
543 let videoLanguages = options.languageOneOf
544 if (options.languageOneOf.find(l => l === '_unknown')) {
545 videoLanguages = videoLanguages.concat([ null ])
552 [ Op.or ]: videoLanguages
557 [ Op.in ]: Sequelize.literal(
559 'SELECT "videoId" FROM "videoCaption" ' +
560 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
569 if (options.trendingDays) {
570 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
572 query.subQuery = false
575 if (options.historyOfUser) {
577 model: UserVideoHistoryModel,
580 userId: options.historyOfUser.id
584 // Even if the relation is n:m, we know that a user only have 0..1 video history
585 // So we won't have multiple rows for the same video
586 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
587 query.subQuery = false
596 [ScopeNames.WITH_BLOCKLIST]: {
599 [ ScopeNames.WITH_THUMBNAILS ]: {
602 model: ThumbnailModel,
607 [ ScopeNames.WITH_USER_ID ]: {
610 attributes: [ 'accountId' ],
611 model: VideoChannelModel.unscoped(),
615 attributes: [ 'userId' ],
616 model: AccountModel.unscoped(),
623 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
626 model: VideoChannelModel.unscoped(),
631 exclude: [ 'privateKey', 'publicKey' ]
633 model: ActorModel.unscoped(),
637 attributes: [ 'host' ],
638 model: ServerModel.unscoped(),
642 model: AvatarModel.unscoped(),
648 model: AccountModel.unscoped(),
652 model: ActorModel.unscoped(),
654 exclude: [ 'privateKey', 'publicKey' ]
659 attributes: [ 'host' ],
660 model: ServerModel.unscoped(),
664 model: AvatarModel.unscoped(),
675 [ ScopeNames.WITH_TAGS ]: {
676 include: [ TagModel ]
678 [ ScopeNames.WITH_BLACKLISTED ]: {
681 attributes: [ 'id', 'reason', 'unfederated' ],
682 model: VideoBlacklistModel,
687 [ ScopeNames.WITH_WEBTORRENT_FILES ]: (withRedundancies = false) => {
688 let subInclude: any[] = []
690 if (withRedundancies === true) {
693 attributes: [ 'fileUrl' ],
694 model: VideoRedundancyModel.unscoped(),
703 model: VideoFileModel.unscoped(),
704 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
711 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
712 const subInclude: IncludeOptions[] = [
714 model: VideoFileModel.unscoped(),
719 if (withRedundancies === true) {
721 attributes: [ 'fileUrl' ],
722 model: VideoRedundancyModel.unscoped(),
730 model: VideoStreamingPlaylistModel.unscoped(),
731 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
738 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
741 model: ScheduleVideoUpdateModel.unscoped(),
746 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
750 attributes: [ 'currentTime' ],
751 model: UserVideoHistoryModel.unscoped(),
765 export class VideoModel extends Model<VideoModel> {
768 @Default(DataType.UUIDV4)
770 @Column(DataType.UUID)
774 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
780 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
786 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
792 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
793 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
797 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
802 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
808 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
809 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
814 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
815 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
819 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
849 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
850 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
855 commentsEnabled: boolean
859 downloadEnabled: boolean
863 waitTranscoding: boolean
867 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
878 @Default(DataType.NOW)
885 originallyPublishedAt: Date
887 @ForeignKey(() => VideoChannelModel)
891 @BelongsTo(() => VideoChannelModel, {
897 VideoChannel: VideoChannelModel
899 @BelongsToMany(() => TagModel, {
900 foreignKey: 'videoId',
901 through: () => VideoTagModel,
906 @HasMany(() => ThumbnailModel, {
914 Thumbnails: ThumbnailModel[]
916 @HasMany(() => VideoPlaylistElementModel, {
923 VideoPlaylistElements: VideoPlaylistElementModel[]
925 @HasMany(() => VideoAbuseModel, {
932 VideoAbuses: VideoAbuseModel[]
934 @HasMany(() => VideoFileModel, {
942 VideoFiles: VideoFileModel[]
944 @HasMany(() => VideoStreamingPlaylistModel, {
952 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
954 @HasMany(() => VideoShareModel, {
961 VideoShares: VideoShareModel[]
963 @HasMany(() => AccountVideoRateModel, {
970 AccountVideoRates: AccountVideoRateModel[]
972 @HasMany(() => VideoCommentModel, {
980 VideoComments: VideoCommentModel[]
982 @HasMany(() => VideoViewModel, {
989 VideoViews: VideoViewModel[]
991 @HasMany(() => UserVideoHistoryModel, {
998 UserVideoHistories: UserVideoHistoryModel[]
1000 @HasOne(() => ScheduleVideoUpdateModel, {
1007 ScheduleVideoUpdate: ScheduleVideoUpdateModel
1009 @HasOne(() => VideoBlacklistModel, {
1016 VideoBlacklist: VideoBlacklistModel
1018 @HasOne(() => VideoImportModel, {
1023 onDelete: 'set null'
1025 VideoImport: VideoImportModel
1027 @HasMany(() => VideoCaptionModel, {
1032 onDelete: 'cascade',
1034 [ 'separate' as any ]: true
1036 VideoCaptions: VideoCaptionModel[]
1039 static async sendDelete (instance: MVideoAccountLight, options) {
1040 if (instance.isOwned()) {
1041 if (!instance.VideoChannel) {
1042 instance.VideoChannel = await instance.$get('VideoChannel', {
1047 transaction: options.transaction
1048 }) as MChannelAccountDefault
1051 return sendDeleteVideo(instance, options.transaction)
1058 static async removeFiles (instance: VideoModel) {
1059 const tasks: Promise<any>[] = []
1061 logger.info('Removing files of video %s.', instance.url)
1063 if (instance.isOwned()) {
1064 if (!Array.isArray(instance.VideoFiles)) {
1065 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1068 // Remove physical files and torrents
1069 instance.VideoFiles.forEach(file => {
1070 tasks.push(instance.removeFile(file))
1071 tasks.push(instance.removeTorrent(file))
1074 // Remove playlists file
1075 tasks.push(instance.removeStreamingPlaylist())
1078 // Do not wait video deletion because we could be in a transaction
1081 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1087 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1094 return VideoModel.scope([
1095 ScopeNames.WITH_WEBTORRENT_FILES,
1096 ScopeNames.WITH_STREAMING_PLAYLISTS,
1097 ScopeNames.WITH_THUMBNAILS
1101 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1102 function getRawQuery (select: string) {
1103 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1104 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1105 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1106 'WHERE "Account"."actorId" = ' + actorId
1107 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1108 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1109 'WHERE "VideoShare"."actorId" = ' + actorId
1111 return `(${queryVideo}) UNION (${queryVideoShare})`
1114 const rawQuery = getRawQuery('"Video"."id"')
1115 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1121 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1124 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1127 { privacy: VideoPrivacy.PUBLIC },
1128 { privacy: VideoPrivacy.UNLISTED }
1133 attributes: [ 'language' ],
1134 model: VideoCaptionModel.unscoped(),
1138 attributes: [ 'id', 'url' ],
1139 model: VideoShareModel.unscoped(),
1141 // We only want videos shared by this actor
1156 attributes: [ 'id', 'url' ],
1157 model: ActorModel.unscoped()
1162 model: VideoChannelModel.unscoped(),
1166 attributes: [ 'name' ],
1167 model: AccountModel.unscoped(),
1171 attributes: [ 'id', 'url', 'followersUrl' ],
1172 model: ActorModel.unscoped(),
1178 attributes: [ 'id', 'url', 'followersUrl' ],
1179 model: ActorModel.unscoped(),
1189 return Bluebird.all([
1190 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1191 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1192 ]).then(([ rows, totals ]) => {
1193 // totals: totalVideos + totalVideoShares
1195 let totalVideoShares = 0
1196 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1197 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1199 const total = totalVideos + totalVideoShares
1207 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) {
1208 function buildBaseQuery (): FindOptions {
1212 order: getVideoSort(sort),
1215 model: VideoChannelModel,
1219 model: AccountModel,
1231 const countQuery = buildBaseQuery()
1232 const findQuery = buildBaseQuery()
1234 const findScopes = [
1235 ScopeNames.WITH_SCHEDULED_UPDATE,
1236 ScopeNames.WITH_BLACKLISTED,
1237 ScopeNames.WITH_THUMBNAILS
1240 return Promise.all([
1241 VideoModel.count(countQuery),
1242 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1243 ]).then(([ count, rows ]) => {
1251 static async listForApi (options: {
1256 includeLocalVideos: boolean,
1258 categoryOneOf?: number[],
1259 licenceOneOf?: number[],
1260 languageOneOf?: string[],
1261 tagsOneOf?: string[],
1262 tagsAllOf?: string[],
1263 filter?: VideoFilter,
1265 videoChannelId?: number,
1266 followerActorId?: number
1267 videoPlaylistId?: number,
1268 trendingDays?: number,
1269 user?: MUserAccountId,
1270 historyOfUser?: MUserId
1271 }, countVideos = true) {
1272 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1273 throw new Error('Try to filter all-local but no user has not the see all videos right')
1276 const query: FindOptions & { where?: null } = {
1277 offset: options.start,
1278 limit: options.count,
1279 order: getVideoSort(options.sort)
1282 let trendingDays: number
1283 if (options.sort.endsWith('trending')) {
1284 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1286 query.group = 'VideoModel.id'
1289 const serverActor = await getServerActor()
1291 // followerActorId === null has a meaning, so just check undefined
1292 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1294 const queryOptions = {
1296 serverAccountId: serverActor.Account.id,
1298 categoryOneOf: options.categoryOneOf,
1299 licenceOneOf: options.licenceOneOf,
1300 languageOneOf: options.languageOneOf,
1301 tagsOneOf: options.tagsOneOf,
1302 tagsAllOf: options.tagsAllOf,
1303 filter: options.filter,
1304 withFiles: options.withFiles,
1305 accountId: options.accountId,
1306 videoChannelId: options.videoChannelId,
1307 videoPlaylistId: options.videoPlaylistId,
1308 includeLocalVideos: options.includeLocalVideos,
1310 historyOfUser: options.historyOfUser,
1314 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1317 static async searchAndPopulateAccountAndServer (options: {
1318 includeLocalVideos: boolean
1323 startDate?: string // ISO 8601
1324 endDate?: string // ISO 8601
1325 originallyPublishedStartDate?: string
1326 originallyPublishedEndDate?: string
1328 categoryOneOf?: number[]
1329 licenceOneOf?: number[]
1330 languageOneOf?: string[]
1331 tagsOneOf?: string[]
1332 tagsAllOf?: string[]
1333 durationMin?: number // seconds
1334 durationMax?: number // seconds
1335 user?: MUserAccountId,
1336 filter?: VideoFilter
1340 if (options.startDate || options.endDate) {
1341 const publishedAtRange = {}
1343 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1344 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1346 whereAnd.push({ publishedAt: publishedAtRange })
1349 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1350 const originallyPublishedAtRange = {}
1352 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1353 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1355 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1358 if (options.durationMin || options.durationMax) {
1359 const durationRange = {}
1361 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1362 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1364 whereAnd.push({ duration: durationRange })
1367 const attributesInclude = []
1368 const escapedSearch = VideoModel.sequelize.escape(options.search)
1369 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1370 if (options.search) {
1371 const trigramSearch = {
1373 [ Op.in ]: Sequelize.literal(
1375 'SELECT "video"."id" FROM "video" ' +
1377 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1378 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1380 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1381 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1382 'WHERE "tag"."name" = ' + escapedSearch +
1388 if (validator.isUUID(options.search)) {
1393 uuid: options.search
1398 whereAnd.push(trigramSearch)
1401 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1404 // Cannot search on similarity if we don't have a search
1405 if (!options.search) {
1406 attributesInclude.push(
1407 Sequelize.literal('0 as similarity')
1413 include: attributesInclude
1415 offset: options.start,
1416 limit: options.count,
1417 order: getVideoSort(options.sort)
1420 const serverActor = await getServerActor()
1421 const queryOptions = {
1422 followerActorId: serverActor.id,
1423 serverAccountId: serverActor.Account.id,
1424 includeLocalVideos: options.includeLocalVideos,
1426 categoryOneOf: options.categoryOneOf,
1427 licenceOneOf: options.licenceOneOf,
1428 languageOneOf: options.languageOneOf,
1429 tagsOneOf: options.tagsOneOf,
1430 tagsAllOf: options.tagsAllOf,
1432 filter: options.filter,
1436 return VideoModel.getAvailableForApi(query, queryOptions)
1439 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1440 const where = buildWhereIdOrUUID(id)
1446 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1449 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1450 const where = buildWhereIdOrUUID(id)
1456 return VideoModel.scope([
1457 ScopeNames.WITH_THUMBNAILS,
1458 ScopeNames.WITH_BLACKLISTED
1462 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1463 const where = buildWhereIdOrUUID(id)
1469 return VideoModel.scope([
1470 ScopeNames.WITH_BLACKLISTED,
1471 ScopeNames.WITH_USER_ID,
1472 ScopeNames.WITH_THUMBNAILS
1476 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1477 const where = buildWhereIdOrUUID(id)
1480 attributes: [ 'id' ],
1485 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1488 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1489 const where = buildWhereIdOrUUID(id)
1497 return VideoModel.scope([
1498 ScopeNames.WITH_WEBTORRENT_FILES,
1499 ScopeNames.WITH_STREAMING_PLAYLISTS,
1500 ScopeNames.WITH_THUMBNAILS
1504 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1511 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1514 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1515 const query: FindOptions = {
1522 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1525 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1526 const query: FindOptions = {
1533 return VideoModel.scope([
1534 ScopeNames.WITH_ACCOUNT_DETAILS,
1535 ScopeNames.WITH_WEBTORRENT_FILES,
1536 ScopeNames.WITH_STREAMING_PLAYLISTS,
1537 ScopeNames.WITH_THUMBNAILS,
1538 ScopeNames.WITH_BLACKLISTED
1542 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1543 const where = buildWhereIdOrUUID(id)
1546 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1551 const scopes: (string | ScopeOptions)[] = [
1552 ScopeNames.WITH_TAGS,
1553 ScopeNames.WITH_BLACKLISTED,
1554 ScopeNames.WITH_ACCOUNT_DETAILS,
1555 ScopeNames.WITH_SCHEDULED_UPDATE,
1556 ScopeNames.WITH_WEBTORRENT_FILES,
1557 ScopeNames.WITH_STREAMING_PLAYLISTS,
1558 ScopeNames.WITH_THUMBNAILS
1562 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1570 static loadForGetAPI (parameters: {
1571 id: number | string,
1574 }): Bluebird<MVideoDetails> {
1575 const { id, t, userId } = parameters
1576 const where = buildWhereIdOrUUID(id)
1579 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1584 const scopes: (string | ScopeOptions)[] = [
1585 ScopeNames.WITH_TAGS,
1586 ScopeNames.WITH_BLACKLISTED,
1587 ScopeNames.WITH_ACCOUNT_DETAILS,
1588 ScopeNames.WITH_SCHEDULED_UPDATE,
1589 ScopeNames.WITH_THUMBNAILS,
1590 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1591 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1595 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1603 static async getStats () {
1604 const totalLocalVideos = await VideoModel.count({
1609 const totalVideos = await VideoModel.count()
1611 let totalLocalVideoViews = await VideoModel.sum('views', {
1616 // Sequelize could return null...
1617 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1621 totalLocalVideoViews,
1626 static incrementViews (id: number, views: number) {
1627 return VideoModel.increment('views', {
1635 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1636 // Instances only share videos
1637 const query = 'SELECT 1 FROM "videoShare" ' +
1638 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1639 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1643 type: QueryTypes.SELECT as QueryTypes.SELECT,
1644 bind: { followerActorId, videoId },
1648 return VideoModel.sequelize.query(query, options)
1649 .then(results => results.length === 1)
1652 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1655 channelId: videoChannel.id
1660 return VideoModel.update({ support: videoChannel.support }, options)
1663 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1665 attributes: [ 'id' ],
1667 channelId: videoChannel.id
1671 return VideoModel.findAll(query)
1672 .then(videos => videos.map(v => v.id))
1675 // threshold corresponds to how many video the field should have to be returned
1676 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1677 const serverActor = await getServerActor()
1678 const followerActorId = serverActor.id
1680 const scopeOptions: AvailableForListIDsOptions = {
1681 serverAccountId: serverActor.Account.id,
1683 includeLocalVideos: true,
1684 attributesType: 'none' // Don't break aggregation
1687 const query: FindOptions = {
1688 attributes: [ field ],
1691 having: Sequelize.where(
1692 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1694 order: [ (this.sequelize as any).random() ]
1697 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1699 .then(rows => rows.map(r => r[ field ]))
1702 static buildTrendingQuery (trendingDays: number) {
1706 model: VideoViewModel,
1710 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1716 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1717 if (filter && (filter === 'local' || filter === 'all-local')) {
1726 private static async getAvailableForApi (
1727 query: FindOptions & { where?: null }, // Forbid where field in query
1728 options: AvailableForListIDsOptions,
1731 const idsScope: ScopeOptions = {
1733 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1737 // Remove trending sort on count, because it uses a group by
1738 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1739 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1740 const countScope: ScopeOptions = {
1742 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1746 const [ count, ids ] = await Promise.all([
1748 ? VideoModel.scope(countScope).count(countQuery)
1749 : Promise.resolve<number>(undefined),
1751 VideoModel.scope(idsScope)
1753 .then(rows => rows.map(r => r.id))
1756 if (ids.length === 0) return { data: [], total: count }
1758 const secondQuery: FindOptions = {
1761 attributes: query.attributes,
1762 order: [ // Keep original order
1764 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1769 const apiScope: (string | ScopeOptions)[] = []
1772 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1777 ScopeNames.FOR_API, {
1779 withFiles: options.withFiles,
1780 videoPlaylistId: options.videoPlaylistId
1785 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1793 private static isPrivacyForFederation (privacy: VideoPrivacy) {
1794 return privacy === VideoPrivacy.PUBLIC || privacy === VideoPrivacy.UNLISTED
1797 static getCategoryLabel (id: number) {
1798 return VIDEO_CATEGORIES[ id ] || 'Misc'
1801 static getLicenceLabel (id: number) {
1802 return VIDEO_LICENCES[ id ] || 'Unknown'
1805 static getLanguageLabel (id: string) {
1806 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1809 static getPrivacyLabel (id: number) {
1810 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1813 static getStateLabel (id: number) {
1814 return VIDEO_STATES[ id ] || 'Unknown'
1818 return !!this.VideoBlacklist
1822 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1823 this.VideoChannel.Account.isBlocked()
1826 getQualityFileBy <T extends MVideoWithFile> (this: T, fun: (files: MVideoFile[], it: (file: MVideoFile) => number) => MVideoFile) {
1827 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1828 const file = fun(this.VideoFiles, file => file.resolution)
1830 return Object.assign(file, { Video: this })
1833 // No webtorrent files, try with streaming playlist files
1834 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1835 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1837 const file = fun(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1838 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1844 getMaxQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1845 return this.getQualityFileBy(maxBy)
1848 getMinQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1849 return this.getQualityFileBy(minBy)
1852 getWebTorrentFile <T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1853 if (Array.isArray(this.VideoFiles) === false) return undefined
1855 const file = this.VideoFiles.find(f => f.resolution === resolution)
1856 if (!file) return undefined
1858 return Object.assign(file, { Video: this })
1861 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1862 thumbnail.videoId = this.id
1864 const savedThumbnail = await thumbnail.save({ transaction })
1866 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1868 // Already have this thumbnail, skip
1869 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1871 this.Thumbnails.push(savedThumbnail)
1874 generateThumbnailName () {
1875 return this.uuid + '.jpg'
1879 if (Array.isArray(this.Thumbnails) === false) return undefined
1881 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1884 generatePreviewName () {
1885 return this.uuid + '.jpg'
1889 if (Array.isArray(this.Thumbnails) === false) return undefined
1891 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1895 return this.remote === false
1898 getWatchStaticPath () {
1899 return '/videos/watch/' + this.uuid
1902 getEmbedStaticPath () {
1903 return '/videos/embed/' + this.uuid
1906 getMiniatureStaticPath () {
1907 const thumbnail = this.getMiniature()
1908 if (!thumbnail) return null
1910 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1913 getPreviewStaticPath () {
1914 const preview = this.getPreview()
1915 if (!preview) return null
1917 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1918 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1921 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1922 return videoModelToFormattedJSON(this, options)
1925 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1926 return videoModelToFormattedDetailsJSON(this)
1929 getFormattedVideoFilesJSON (): VideoFile[] {
1930 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1931 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1934 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1935 return videoModelToActivityPubObject(this)
1938 getTruncatedDescription () {
1939 if (!this.description) return null
1941 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1942 return peertubeTruncate(this.description, { length: maxLength })
1945 getMaxQualityResolution () {
1946 const file = this.getMaxQualityFile()
1947 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1948 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1950 return getVideoFileResolution(originalFilePath)
1953 getDescriptionAPIPath () {
1954 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1957 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1958 if (!this.VideoStreamingPlaylists) return undefined
1960 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1961 playlist.Video = this
1966 setHLSPlaylist (playlist: MStreamingPlaylist) {
1967 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1969 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1970 this.VideoStreamingPlaylists = toAdd
1974 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1975 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1979 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1980 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1981 return remove(filePath)
1982 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1985 removeTorrent (videoFile: MVideoFile) {
1986 const torrentPath = getTorrentFilePath(this, videoFile)
1987 return remove(torrentPath)
1988 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1991 removeStreamingPlaylist (isRedundancy = false) {
1992 const directoryPath = getHLSDirectory(this, isRedundancy)
1994 return remove(directoryPath)
1995 .catch(err => logger.warn('Cannot delete playlist directory %s.', directoryPath, { err }))
1999 if (this.isOwned()) return false
2001 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
2004 hasPrivacyForFederation () {
2005 return VideoModel.isPrivacyForFederation(this.privacy)
2008 isNewVideo (newPrivacy: VideoPrivacy) {
2009 return this.hasPrivacyForFederation() === false && VideoModel.isPrivacyForFederation(newPrivacy) === true
2013 this.changed('updatedAt', true)
2019 return this.privacy === VideoPrivacy.PRIVATE || this.privacy === VideoPrivacy.INTERNAL || !!this.VideoBlacklist
2022 setPrivacy (newPrivacy: VideoPrivacy) {
2023 if (this.privacy === VideoPrivacy.PRIVATE && newPrivacy !== VideoPrivacy.PRIVATE) {
2024 this.publishedAt = new Date()
2027 this.privacy = newPrivacy
2031 return this.privacy === VideoPrivacy.PRIVATE ||
2032 this.privacy === VideoPrivacy.UNLISTED ||
2033 this.privacy === VideoPrivacy.INTERNAL
2036 async publishIfNeededAndSave (t: Transaction) {
2037 if (this.state !== VideoState.PUBLISHED) {
2038 this.state = VideoState.PUBLISHED
2039 this.publishedAt = new Date()
2040 await this.save({ transaction: t })
2049 if (this.isOwned()) {
2051 baseUrlHttp: WEBSERVER.URL,
2052 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2057 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2058 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2062 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2063 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2066 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2067 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2070 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2071 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2074 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2075 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2078 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2079 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2082 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2083 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2086 getBandwidthBits (videoFile: MVideoFile) {
2087 return Math.ceil((videoFile.size * 8) / this.duration)