1 import * as Bluebird from 'bluebird'
2 import { maxBy } 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') {
351 const privacyWhere = {
352 // Always list public videos
353 privacy: VideoPrivacy.PUBLIC,
354 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
357 state: VideoState.PUBLISHED
361 state: VideoState.TO_TRANSCODE,
362 waitTranscoding: false
368 whereAnd.push(privacyWhere)
371 if (options.videoPlaylistId) {
374 model: VideoPlaylistElementModel.unscoped(),
377 videoPlaylistId: options.videoPlaylistId
381 query.subQuery = false
384 if (options.filter || options.accountId || options.videoChannelId) {
385 const videoChannelInclude: IncludeOptions = {
387 model: VideoChannelModel.unscoped(),
391 if (options.videoChannelId) {
392 videoChannelInclude.where = {
393 id: options.videoChannelId
397 if (options.filter || options.accountId) {
398 const accountInclude: IncludeOptions = {
400 model: AccountModel.unscoped(),
404 if (options.filter) {
405 accountInclude.include = [
408 model: ActorModel.unscoped(),
410 where: VideoModel.buildActorWhereWithFilter(options.filter)
415 if (options.accountId) {
416 accountInclude.where = { id: options.accountId }
419 videoChannelInclude.include = [ accountInclude ]
422 query.include.push(videoChannelInclude)
425 if (options.followerActorId) {
426 let localVideosReq = ''
427 if (options.includeLocalVideos === true) {
428 localVideosReq = ' UNION ALL ' +
429 'SELECT "video"."id" AS "id" FROM "video" ' +
430 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
431 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
432 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
433 'WHERE "actor"."serverId" IS NULL'
436 // Force actorId to be a number to avoid SQL injections
437 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
440 [ Op.in ]: Sequelize.literal(
442 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
443 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
444 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
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 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
451 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
459 if (options.withFiles === true) {
462 [ Op.in ]: Sequelize.literal(
463 '(SELECT "videoId" FROM "videoFile")'
469 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
470 if (options.tagsAllOf || options.tagsOneOf) {
471 if (options.tagsOneOf) {
472 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
476 [ Op.in ]: Sequelize.literal(
478 'SELECT "videoId" FROM "videoTag" ' +
479 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
480 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
487 if (options.tagsAllOf) {
488 const tagsAllOfLower = options.tagsAllOf.map(t => t.toLowerCase())
492 [ Op.in ]: Sequelize.literal(
494 'SELECT "videoId" FROM "videoTag" ' +
495 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
496 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsAllOfLower) + ')' +
497 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
505 if (options.nsfw === true || options.nsfw === false) {
506 whereAnd.push({ nsfw: options.nsfw })
509 if (options.categoryOneOf) {
512 [ Op.or ]: options.categoryOneOf
517 if (options.licenceOneOf) {
520 [ Op.or ]: options.licenceOneOf
525 if (options.languageOneOf) {
526 let videoLanguages = options.languageOneOf
527 if (options.languageOneOf.find(l => l === '_unknown')) {
528 videoLanguages = videoLanguages.concat([ null ])
535 [ Op.or ]: videoLanguages
540 [ Op.in ]: Sequelize.literal(
542 'SELECT "videoId" FROM "videoCaption" ' +
543 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
552 if (options.trendingDays) {
553 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
555 query.subQuery = false
558 if (options.historyOfUser) {
560 model: UserVideoHistoryModel,
563 userId: options.historyOfUser.id
567 // Even if the relation is n:m, we know that a user only have 0..1 video history
568 // So we won't have multiple rows for the same video
569 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
570 query.subQuery = false
579 [ScopeNames.WITH_BLOCKLIST]: {
582 [ ScopeNames.WITH_THUMBNAILS ]: {
585 model: ThumbnailModel,
590 [ ScopeNames.WITH_USER_ID ]: {
593 attributes: [ 'accountId' ],
594 model: VideoChannelModel.unscoped(),
598 attributes: [ 'userId' ],
599 model: AccountModel.unscoped(),
606 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
609 model: VideoChannelModel.unscoped(),
614 exclude: [ 'privateKey', 'publicKey' ]
616 model: ActorModel.unscoped(),
620 attributes: [ 'host' ],
621 model: ServerModel.unscoped(),
625 model: AvatarModel.unscoped(),
631 model: AccountModel.unscoped(),
635 model: ActorModel.unscoped(),
637 exclude: [ 'privateKey', 'publicKey' ]
642 attributes: [ 'host' ],
643 model: ServerModel.unscoped(),
647 model: AvatarModel.unscoped(),
658 [ ScopeNames.WITH_TAGS ]: {
659 include: [ TagModel ]
661 [ ScopeNames.WITH_BLACKLISTED ]: {
664 attributes: [ 'id', 'reason', 'unfederated' ],
665 model: VideoBlacklistModel,
670 [ ScopeNames.WITH_WEBTORRENT_FILES ]: (withRedundancies = false) => {
671 let subInclude: any[] = []
673 if (withRedundancies === true) {
676 attributes: [ 'fileUrl' ],
677 model: VideoRedundancyModel.unscoped(),
686 model: VideoFileModel.unscoped(),
687 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
694 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
695 const subInclude: IncludeOptions[] = [
697 model: VideoFileModel.unscoped(),
702 if (withRedundancies === true) {
704 attributes: [ 'fileUrl' ],
705 model: VideoRedundancyModel.unscoped(),
713 model: VideoStreamingPlaylistModel.unscoped(),
714 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
721 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
724 model: ScheduleVideoUpdateModel.unscoped(),
729 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
733 attributes: [ 'currentTime' ],
734 model: UserVideoHistoryModel.unscoped(),
748 export class VideoModel extends Model<VideoModel> {
751 @Default(DataType.UUIDV4)
753 @Column(DataType.UUID)
757 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
763 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
769 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
775 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
776 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
780 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
785 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
791 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
792 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
797 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
798 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
802 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
832 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
833 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
838 commentsEnabled: boolean
842 downloadEnabled: boolean
846 waitTranscoding: boolean
850 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
861 @Default(DataType.NOW)
868 originallyPublishedAt: Date
870 @ForeignKey(() => VideoChannelModel)
874 @BelongsTo(() => VideoChannelModel, {
880 VideoChannel: VideoChannelModel
882 @BelongsToMany(() => TagModel, {
883 foreignKey: 'videoId',
884 through: () => VideoTagModel,
889 @HasMany(() => ThumbnailModel, {
897 Thumbnails: ThumbnailModel[]
899 @HasMany(() => VideoPlaylistElementModel, {
906 VideoPlaylistElements: VideoPlaylistElementModel[]
908 @HasMany(() => VideoAbuseModel, {
915 VideoAbuses: VideoAbuseModel[]
917 @HasMany(() => VideoFileModel, {
925 VideoFiles: VideoFileModel[]
927 @HasMany(() => VideoStreamingPlaylistModel, {
935 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
937 @HasMany(() => VideoShareModel, {
944 VideoShares: VideoShareModel[]
946 @HasMany(() => AccountVideoRateModel, {
953 AccountVideoRates: AccountVideoRateModel[]
955 @HasMany(() => VideoCommentModel, {
963 VideoComments: VideoCommentModel[]
965 @HasMany(() => VideoViewModel, {
972 VideoViews: VideoViewModel[]
974 @HasMany(() => UserVideoHistoryModel, {
981 UserVideoHistories: UserVideoHistoryModel[]
983 @HasOne(() => ScheduleVideoUpdateModel, {
990 ScheduleVideoUpdate: ScheduleVideoUpdateModel
992 @HasOne(() => VideoBlacklistModel, {
999 VideoBlacklist: VideoBlacklistModel
1001 @HasOne(() => VideoImportModel, {
1006 onDelete: 'set null'
1008 VideoImport: VideoImportModel
1010 @HasMany(() => VideoCaptionModel, {
1015 onDelete: 'cascade',
1017 [ 'separate' as any ]: true
1019 VideoCaptions: VideoCaptionModel[]
1022 static async sendDelete (instance: MVideoAccountLight, options) {
1023 if (instance.isOwned()) {
1024 if (!instance.VideoChannel) {
1025 instance.VideoChannel = await instance.$get('VideoChannel', {
1030 transaction: options.transaction
1031 }) as MChannelAccountDefault
1034 return sendDeleteVideo(instance, options.transaction)
1041 static async removeFiles (instance: VideoModel) {
1042 const tasks: Promise<any>[] = []
1044 logger.info('Removing files of video %s.', instance.url)
1046 if (instance.isOwned()) {
1047 if (!Array.isArray(instance.VideoFiles)) {
1048 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1051 // Remove physical files and torrents
1052 instance.VideoFiles.forEach(file => {
1053 tasks.push(instance.removeFile(file))
1054 tasks.push(instance.removeTorrent(file))
1057 // Remove playlists file
1058 tasks.push(instance.removeStreamingPlaylist())
1061 // Do not wait video deletion because we could be in a transaction
1064 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1070 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1077 return VideoModel.scope([
1078 ScopeNames.WITH_WEBTORRENT_FILES,
1079 ScopeNames.WITH_STREAMING_PLAYLISTS,
1080 ScopeNames.WITH_THUMBNAILS
1084 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1085 function getRawQuery (select: string) {
1086 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1087 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1088 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1089 'WHERE "Account"."actorId" = ' + actorId
1090 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1091 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1092 'WHERE "VideoShare"."actorId" = ' + actorId
1094 return `(${queryVideo}) UNION (${queryVideoShare})`
1097 const rawQuery = getRawQuery('"Video"."id"')
1098 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1104 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1107 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1110 { privacy: VideoPrivacy.PUBLIC },
1111 { privacy: VideoPrivacy.UNLISTED }
1116 attributes: [ 'language' ],
1117 model: VideoCaptionModel.unscoped(),
1121 attributes: [ 'id', 'url' ],
1122 model: VideoShareModel.unscoped(),
1124 // We only want videos shared by this actor
1139 attributes: [ 'id', 'url' ],
1140 model: ActorModel.unscoped()
1145 model: VideoChannelModel.unscoped(),
1149 attributes: [ 'name' ],
1150 model: AccountModel.unscoped(),
1154 attributes: [ 'id', 'url', 'followersUrl' ],
1155 model: ActorModel.unscoped(),
1161 attributes: [ 'id', 'url', 'followersUrl' ],
1162 model: ActorModel.unscoped(),
1172 return Bluebird.all([
1173 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1174 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1175 ]).then(([ rows, totals ]) => {
1176 // totals: totalVideos + totalVideoShares
1178 let totalVideoShares = 0
1179 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1180 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1182 const total = totalVideos + totalVideoShares
1190 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) {
1191 function buildBaseQuery (): FindOptions {
1195 order: getVideoSort(sort),
1198 model: VideoChannelModel,
1202 model: AccountModel,
1214 const countQuery = buildBaseQuery()
1215 const findQuery = buildBaseQuery()
1217 const findScopes = [
1218 ScopeNames.WITH_SCHEDULED_UPDATE,
1219 ScopeNames.WITH_BLACKLISTED,
1220 ScopeNames.WITH_THUMBNAILS
1223 return Promise.all([
1224 VideoModel.count(countQuery),
1225 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1226 ]).then(([ count, rows ]) => {
1234 static async listForApi (options: {
1239 includeLocalVideos: boolean,
1241 categoryOneOf?: number[],
1242 licenceOneOf?: number[],
1243 languageOneOf?: string[],
1244 tagsOneOf?: string[],
1245 tagsAllOf?: string[],
1246 filter?: VideoFilter,
1248 videoChannelId?: number,
1249 followerActorId?: number
1250 videoPlaylistId?: number,
1251 trendingDays?: number,
1252 user?: MUserAccountId,
1253 historyOfUser?: MUserId
1254 }, countVideos = true) {
1255 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1256 throw new Error('Try to filter all-local but no user has not the see all videos right')
1259 const query: FindOptions & { where?: null } = {
1260 offset: options.start,
1261 limit: options.count,
1262 order: getVideoSort(options.sort)
1265 let trendingDays: number
1266 if (options.sort.endsWith('trending')) {
1267 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1269 query.group = 'VideoModel.id'
1272 const serverActor = await getServerActor()
1274 // followerActorId === null has a meaning, so just check undefined
1275 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1277 const queryOptions = {
1279 serverAccountId: serverActor.Account.id,
1281 categoryOneOf: options.categoryOneOf,
1282 licenceOneOf: options.licenceOneOf,
1283 languageOneOf: options.languageOneOf,
1284 tagsOneOf: options.tagsOneOf,
1285 tagsAllOf: options.tagsAllOf,
1286 filter: options.filter,
1287 withFiles: options.withFiles,
1288 accountId: options.accountId,
1289 videoChannelId: options.videoChannelId,
1290 videoPlaylistId: options.videoPlaylistId,
1291 includeLocalVideos: options.includeLocalVideos,
1293 historyOfUser: options.historyOfUser,
1297 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1300 static async searchAndPopulateAccountAndServer (options: {
1301 includeLocalVideos: boolean
1306 startDate?: string // ISO 8601
1307 endDate?: string // ISO 8601
1308 originallyPublishedStartDate?: string
1309 originallyPublishedEndDate?: string
1311 categoryOneOf?: number[]
1312 licenceOneOf?: number[]
1313 languageOneOf?: string[]
1314 tagsOneOf?: string[]
1315 tagsAllOf?: string[]
1316 durationMin?: number // seconds
1317 durationMax?: number // seconds
1318 user?: MUserAccountId,
1319 filter?: VideoFilter
1323 if (options.startDate || options.endDate) {
1324 const publishedAtRange = {}
1326 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1327 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1329 whereAnd.push({ publishedAt: publishedAtRange })
1332 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1333 const originallyPublishedAtRange = {}
1335 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1336 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1338 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1341 if (options.durationMin || options.durationMax) {
1342 const durationRange = {}
1344 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1345 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1347 whereAnd.push({ duration: durationRange })
1350 const attributesInclude = []
1351 const escapedSearch = VideoModel.sequelize.escape(options.search)
1352 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1353 if (options.search) {
1354 const trigramSearch = {
1356 [ Op.in ]: Sequelize.literal(
1358 'SELECT "video"."id" FROM "video" ' +
1360 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1361 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1363 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1364 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1365 'WHERE "tag"."name" = ' + escapedSearch +
1371 if (validator.isUUID(options.search)) {
1376 uuid: options.search
1381 whereAnd.push(trigramSearch)
1384 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1387 // Cannot search on similarity if we don't have a search
1388 if (!options.search) {
1389 attributesInclude.push(
1390 Sequelize.literal('0 as similarity')
1396 include: attributesInclude
1398 offset: options.start,
1399 limit: options.count,
1400 order: getVideoSort(options.sort)
1403 const serverActor = await getServerActor()
1404 const queryOptions = {
1405 followerActorId: serverActor.id,
1406 serverAccountId: serverActor.Account.id,
1407 includeLocalVideos: options.includeLocalVideos,
1409 categoryOneOf: options.categoryOneOf,
1410 licenceOneOf: options.licenceOneOf,
1411 languageOneOf: options.languageOneOf,
1412 tagsOneOf: options.tagsOneOf,
1413 tagsAllOf: options.tagsAllOf,
1415 filter: options.filter,
1419 return VideoModel.getAvailableForApi(query, queryOptions)
1422 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1423 const where = buildWhereIdOrUUID(id)
1429 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1432 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1433 const where = buildWhereIdOrUUID(id)
1439 return VideoModel.scope([
1440 ScopeNames.WITH_THUMBNAILS,
1441 ScopeNames.WITH_BLACKLISTED
1445 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1446 const where = buildWhereIdOrUUID(id)
1452 return VideoModel.scope([
1453 ScopeNames.WITH_BLACKLISTED,
1454 ScopeNames.WITH_USER_ID,
1455 ScopeNames.WITH_THUMBNAILS
1459 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1460 const where = buildWhereIdOrUUID(id)
1463 attributes: [ 'id' ],
1468 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1471 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1472 const where = buildWhereIdOrUUID(id)
1480 return VideoModel.scope([
1481 ScopeNames.WITH_WEBTORRENT_FILES,
1482 ScopeNames.WITH_STREAMING_PLAYLISTS,
1483 ScopeNames.WITH_THUMBNAILS
1487 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1494 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1497 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1498 const query: FindOptions = {
1505 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1508 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1509 const query: FindOptions = {
1516 return VideoModel.scope([
1517 ScopeNames.WITH_ACCOUNT_DETAILS,
1518 ScopeNames.WITH_WEBTORRENT_FILES,
1519 ScopeNames.WITH_STREAMING_PLAYLISTS,
1520 ScopeNames.WITH_THUMBNAILS,
1521 ScopeNames.WITH_BLACKLISTED
1525 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1526 const where = buildWhereIdOrUUID(id)
1529 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1534 const scopes: (string | ScopeOptions)[] = [
1535 ScopeNames.WITH_TAGS,
1536 ScopeNames.WITH_BLACKLISTED,
1537 ScopeNames.WITH_ACCOUNT_DETAILS,
1538 ScopeNames.WITH_SCHEDULED_UPDATE,
1539 ScopeNames.WITH_WEBTORRENT_FILES,
1540 ScopeNames.WITH_STREAMING_PLAYLISTS,
1541 ScopeNames.WITH_THUMBNAILS
1545 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1553 static loadForGetAPI (parameters: {
1554 id: number | string,
1557 }): Bluebird<MVideoDetails> {
1558 const { id, t, userId } = parameters
1559 const where = buildWhereIdOrUUID(id)
1562 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1567 const scopes: (string | ScopeOptions)[] = [
1568 ScopeNames.WITH_TAGS,
1569 ScopeNames.WITH_BLACKLISTED,
1570 ScopeNames.WITH_ACCOUNT_DETAILS,
1571 ScopeNames.WITH_SCHEDULED_UPDATE,
1572 ScopeNames.WITH_THUMBNAILS,
1573 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1574 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1578 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1586 static async getStats () {
1587 const totalLocalVideos = await VideoModel.count({
1592 const totalVideos = await VideoModel.count()
1594 let totalLocalVideoViews = await VideoModel.sum('views', {
1599 // Sequelize could return null...
1600 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1604 totalLocalVideoViews,
1609 static incrementViews (id: number, views: number) {
1610 return VideoModel.increment('views', {
1618 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1619 // Instances only share videos
1620 const query = 'SELECT 1 FROM "videoShare" ' +
1621 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1622 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1626 type: QueryTypes.SELECT as QueryTypes.SELECT,
1627 bind: { followerActorId, videoId },
1631 return VideoModel.sequelize.query(query, options)
1632 .then(results => results.length === 1)
1635 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1638 channelId: videoChannel.id
1643 return VideoModel.update({ support: videoChannel.support }, options)
1646 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1648 attributes: [ 'id' ],
1650 channelId: videoChannel.id
1654 return VideoModel.findAll(query)
1655 .then(videos => videos.map(v => v.id))
1658 // threshold corresponds to how many video the field should have to be returned
1659 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1660 const serverActor = await getServerActor()
1661 const followerActorId = serverActor.id
1663 const scopeOptions: AvailableForListIDsOptions = {
1664 serverAccountId: serverActor.Account.id,
1666 includeLocalVideos: true,
1667 attributesType: 'none' // Don't break aggregation
1670 const query: FindOptions = {
1671 attributes: [ field ],
1674 having: Sequelize.where(
1675 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1677 order: [ (this.sequelize as any).random() ]
1680 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1682 .then(rows => rows.map(r => r[ field ]))
1685 static buildTrendingQuery (trendingDays: number) {
1689 model: VideoViewModel,
1693 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1699 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1700 if (filter && (filter === 'local' || filter === 'all-local')) {
1709 private static async getAvailableForApi (
1710 query: FindOptions & { where?: null }, // Forbid where field in query
1711 options: AvailableForListIDsOptions,
1714 const idsScope: ScopeOptions = {
1716 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1720 // Remove trending sort on count, because it uses a group by
1721 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1722 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1723 const countScope: ScopeOptions = {
1725 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1729 const [ count, ids ] = await Promise.all([
1731 ? VideoModel.scope(countScope).count(countQuery)
1732 : Promise.resolve<number>(undefined),
1734 VideoModel.scope(idsScope)
1736 .then(rows => rows.map(r => r.id))
1739 if (ids.length === 0) return { data: [], total: count }
1741 const secondQuery: FindOptions = {
1744 attributes: query.attributes,
1745 order: [ // Keep original order
1747 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1752 const apiScope: (string | ScopeOptions)[] = []
1755 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1760 ScopeNames.FOR_API, {
1762 withFiles: options.withFiles,
1763 videoPlaylistId: options.videoPlaylistId
1768 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1776 static getCategoryLabel (id: number) {
1777 return VIDEO_CATEGORIES[ id ] || 'Misc'
1780 static getLicenceLabel (id: number) {
1781 return VIDEO_LICENCES[ id ] || 'Unknown'
1784 static getLanguageLabel (id: string) {
1785 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1788 static getPrivacyLabel (id: number) {
1789 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1792 static getStateLabel (id: number) {
1793 return VIDEO_STATES[ id ] || 'Unknown'
1797 return !!this.VideoBlacklist
1801 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1802 this.VideoChannel.Account.isBlocked()
1805 getMaxQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1806 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1807 const file = maxBy(this.VideoFiles, file => file.resolution)
1809 return Object.assign(file, { Video: this })
1812 // No webtorrent files, try with streaming playlist files
1813 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1814 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1816 const file = maxBy(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1817 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1823 getWebTorrentFile <T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1824 if (Array.isArray(this.VideoFiles) === false) return undefined
1826 const file = this.VideoFiles.find(f => f.resolution === resolution)
1827 if (!file) return undefined
1829 return Object.assign(file, { Video: this })
1832 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1833 thumbnail.videoId = this.id
1835 const savedThumbnail = await thumbnail.save({ transaction })
1837 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1839 // Already have this thumbnail, skip
1840 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1842 this.Thumbnails.push(savedThumbnail)
1845 generateThumbnailName () {
1846 return this.uuid + '.jpg'
1850 if (Array.isArray(this.Thumbnails) === false) return undefined
1852 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1855 generatePreviewName () {
1856 return this.uuid + '.jpg'
1860 if (Array.isArray(this.Thumbnails) === false) return undefined
1862 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1866 return this.remote === false
1869 getWatchStaticPath () {
1870 return '/videos/watch/' + this.uuid
1873 getEmbedStaticPath () {
1874 return '/videos/embed/' + this.uuid
1877 getMiniatureStaticPath () {
1878 const thumbnail = this.getMiniature()
1879 if (!thumbnail) return null
1881 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1884 getPreviewStaticPath () {
1885 const preview = this.getPreview()
1886 if (!preview) return null
1888 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1889 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1892 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1893 return videoModelToFormattedJSON(this, options)
1896 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1897 return videoModelToFormattedDetailsJSON(this)
1900 getFormattedVideoFilesJSON (): VideoFile[] {
1901 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1902 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1905 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1906 return videoModelToActivityPubObject(this)
1909 getTruncatedDescription () {
1910 if (!this.description) return null
1912 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1913 return peertubeTruncate(this.description, { length: maxLength })
1916 getMaxQualityResolution () {
1917 const file = this.getMaxQualityFile()
1918 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1919 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1921 return getVideoFileResolution(originalFilePath)
1924 getDescriptionAPIPath () {
1925 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1928 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1929 if (!this.VideoStreamingPlaylists) return undefined
1931 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1932 playlist.Video = this
1937 setHLSPlaylist (playlist: MStreamingPlaylist) {
1938 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1940 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1941 this.VideoStreamingPlaylists = toAdd
1945 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1946 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1950 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1951 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1952 return remove(filePath)
1953 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1956 removeTorrent (videoFile: MVideoFile) {
1957 const torrentPath = getTorrentFilePath(this, videoFile)
1958 return remove(torrentPath)
1959 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1962 removeStreamingPlaylist (isRedundancy = false) {
1963 const directoryPath = getHLSDirectory(this, isRedundancy)
1965 return remove(directoryPath)
1966 .catch(err => logger.warn('Cannot delete playlist directory %s.', directoryPath, { err }))
1970 if (this.isOwned()) return false
1972 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1976 this.changed('updatedAt', true)
1981 async publishIfNeededAndSave (t: Transaction) {
1982 if (this.state !== VideoState.PUBLISHED) {
1983 this.state = VideoState.PUBLISHED
1984 this.publishedAt = new Date()
1985 await this.save({ transaction: t })
1994 if (this.isOwned()) {
1996 baseUrlHttp: WEBSERVER.URL,
1997 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
2002 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
2003 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
2007 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
2008 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2011 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2012 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2015 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2016 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2019 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2020 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2023 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2024 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2027 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2028 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2031 getBandwidthBits (videoFile: MVideoFile) {
2032 return Math.ceil((videoFile.size * 8) / this.duration)