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'
62 HLS_REDUNDANCY_DIRECTORY,
63 HLS_STREAMING_PLAYLIST_DIRECTORY,
66 STATIC_DOWNLOAD_PATHS,
74 } from '../../initializers/constants'
75 import { sendDeleteVideo } from '../../lib/activitypub/send'
76 import { AccountModel } from '../account/account'
77 import { AccountVideoRateModel } from '../account/account-video-rate'
78 import { ActorModel } from '../activitypub/actor'
79 import { AvatarModel } from '../avatar/avatar'
80 import { ServerModel } from '../server/server'
82 buildBlockedAccountSQL,
83 buildTrigramSearchIndex,
86 createSimilarityAttribute,
91 import { TagModel } from './tag'
92 import { VideoAbuseModel } from './video-abuse'
93 import { ScopeNames as VideoChannelScopeNames, SummaryOptions, VideoChannelModel } from './video-channel'
94 import { VideoCommentModel } from './video-comment'
95 import { VideoFileModel } from './video-file'
96 import { VideoShareModel } from './video-share'
97 import { VideoTagModel } from './video-tag'
98 import { ScheduleVideoUpdateModel } from './schedule-video-update'
99 import { VideoCaptionModel } from './video-caption'
100 import { VideoBlacklistModel } from './video-blacklist'
101 import { remove } from 'fs-extra'
102 import { VideoViewModel } from './video-views'
103 import { VideoRedundancyModel } from '../redundancy/video-redundancy'
105 videoFilesModelToFormattedJSON,
106 VideoFormattingJSONOptions,
107 videoModelToActivityPubObject,
108 videoModelToFormattedDetailsJSON,
109 videoModelToFormattedJSON
110 } from './video-format-utils'
111 import { UserVideoHistoryModel } from '../account/user-video-history'
112 import { VideoImportModel } from './video-import'
113 import { VideoStreamingPlaylistModel } from './video-streaming-playlist'
114 import { VideoPlaylistElementModel } from './video-playlist-element'
115 import { CONFIG } from '../../initializers/config'
116 import { ThumbnailModel } from './thumbnail'
117 import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type'
118 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
121 MChannelAccountDefault,
124 MStreamingPlaylistFilesVideo,
128 MVideoAccountLightBlacklistAllFiles,
133 MVideoFormattableDetails,
138 MVideoThumbnailBlacklist,
142 } from '../../typings/models'
143 import { MVideoFile, MVideoFileStreamingPlaylistVideo } from '../../typings/models/video/video-file'
144 import { MThumbnail } from '../../typings/models/video/thumbnail'
145 import { VideoFile } from '@shared/models/videos/video-file.model'
146 import { getTorrentFileName, getTorrentFilePath, getVideoFilename, getVideoFilePath, getHLSDirectory } from '@server/lib/video-paths'
148 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
149 const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [
150 buildTrigramSearchIndex('video_name_trigram', 'name'),
152 { fields: [ 'createdAt' ] },
153 { fields: [ 'publishedAt' ] },
154 { fields: [ 'duration' ] },
155 { fields: [ 'views' ] },
156 { fields: [ 'channelId' ] },
158 fields: [ 'originallyPublishedAt' ],
160 originallyPublishedAt: {
166 fields: [ 'category' ], // We don't care videos with an unknown category
174 fields: [ 'licence' ], // We don't care videos with an unknown licence
182 fields: [ 'language' ], // We don't care videos with an unknown language
190 fields: [ 'nsfw' ], // Most of the videos are not NSFW
196 fields: [ 'remote' ], // Only index local videos
211 export enum ScopeNames {
212 AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS',
214 WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS',
215 WITH_TAGS = 'WITH_TAGS',
216 WITH_WEBTORRENT_FILES = 'WITH_WEBTORRENT_FILES',
217 WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE',
218 WITH_BLACKLISTED = 'WITH_BLACKLISTED',
219 WITH_BLOCKLIST = 'WITH_BLOCKLIST',
220 WITH_USER_HISTORY = 'WITH_USER_HISTORY',
221 WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS',
222 WITH_USER_ID = 'WITH_USER_ID',
223 WITH_THUMBNAILS = 'WITH_THUMBNAILS'
226 export type ForAPIOptions = {
229 videoPlaylistId?: number
233 withAccountBlockerIds?: number[]
236 export type AvailableForListIDsOptions = {
237 serverAccountId: number
238 followerActorId: number
239 includeLocalVideos: boolean
241 attributesType?: 'none' | 'id' | 'all'
244 categoryOneOf?: number[]
246 licenceOneOf?: number[]
247 languageOneOf?: string[]
254 videoChannelId?: number
256 videoPlaylistId?: number
258 trendingDays?: number
259 user?: MUserAccountId
260 historyOfUser?: MUserId
262 baseWhere?: WhereOptions[]
266 [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => {
267 const query: FindOptions = {
270 model: VideoChannelModel.scope({
272 VideoChannelScopeNames.SUMMARY, {
274 withAccountBlockerIds: options.withAccountBlockerIds
281 attributes: [ 'type', 'filename' ],
282 model: ThumbnailModel,
291 [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken
296 if (options.withFiles === true) {
298 model: VideoFileModel.unscoped(),
303 if (options.videoPlaylistId) {
305 model: VideoPlaylistElementModel.unscoped(),
308 videoPlaylistId: options.videoPlaylistId
315 [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => {
316 const whereAnd = options.baseWhere ? options.baseWhere : []
318 const query: FindOptions = {
323 const attributesType = options.attributesType || 'id'
325 if (attributesType === 'id') query.attributes = [ 'id' ]
326 else if (attributesType === 'none') query.attributes = [ ]
330 [ Op.notIn ]: Sequelize.literal(
331 '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")'
336 if (options.serverAccountId) {
339 [ Op.notIn ]: Sequelize.literal(
341 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' +
342 buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) +
350 // Only list public/published videos
351 if (!options.filter || options.filter !== 'all-local') {
352 const privacyWhere = {
353 // Always list public videos
354 privacy: VideoPrivacy.PUBLIC,
355 // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding
358 state: VideoState.PUBLISHED
362 state: VideoState.TO_TRANSCODE,
363 waitTranscoding: false
369 whereAnd.push(privacyWhere)
372 if (options.videoPlaylistId) {
375 model: VideoPlaylistElementModel.unscoped(),
378 videoPlaylistId: options.videoPlaylistId
382 query.subQuery = false
385 if (options.filter || options.accountId || options.videoChannelId) {
386 const videoChannelInclude: IncludeOptions = {
388 model: VideoChannelModel.unscoped(),
392 if (options.videoChannelId) {
393 videoChannelInclude.where = {
394 id: options.videoChannelId
398 if (options.filter || options.accountId) {
399 const accountInclude: IncludeOptions = {
401 model: AccountModel.unscoped(),
405 if (options.filter) {
406 accountInclude.include = [
409 model: ActorModel.unscoped(),
411 where: VideoModel.buildActorWhereWithFilter(options.filter)
416 if (options.accountId) {
417 accountInclude.where = { id: options.accountId }
420 videoChannelInclude.include = [ accountInclude ]
423 query.include.push(videoChannelInclude)
426 if (options.followerActorId) {
427 let localVideosReq = ''
428 if (options.includeLocalVideos === true) {
429 localVideosReq = ' UNION ALL ' +
430 'SELECT "video"."id" AS "id" FROM "video" ' +
431 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
432 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
433 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
434 'WHERE "actor"."serverId" IS NULL'
437 // Force actorId to be a number to avoid SQL injections
438 const actorIdNumber = parseInt(options.followerActorId.toString(), 10)
441 [ Op.in ]: Sequelize.literal(
443 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' +
444 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
445 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
447 'SELECT "video"."id" AS "id" FROM "video" ' +
448 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' +
449 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' +
450 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' +
451 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' +
452 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
460 if (options.withFiles === true) {
463 [ Op.in ]: Sequelize.literal(
464 '(SELECT "videoId" FROM "videoFile")'
470 // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN()
471 if (options.tagsAllOf || options.tagsOneOf) {
472 if (options.tagsOneOf) {
473 const tagsOneOfLower = options.tagsOneOf.map(t => t.toLowerCase())
477 [ Op.in ]: Sequelize.literal(
479 'SELECT "videoId" FROM "videoTag" ' +
480 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
481 'WHERE lower("tag"."name") IN (' + createSafeIn(VideoModel, tagsOneOfLower) + ')' +
488 if (options.tagsAllOf) {
489 const tagsAllOfLower = options.tagsAllOf.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, tagsAllOfLower) + ')' +
498 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + tagsAllOfLower.length +
506 if (options.nsfw === true || options.nsfw === false) {
507 whereAnd.push({ nsfw: options.nsfw })
510 if (options.categoryOneOf) {
513 [ Op.or ]: options.categoryOneOf
518 if (options.licenceOneOf) {
521 [ Op.or ]: options.licenceOneOf
526 if (options.languageOneOf) {
527 let videoLanguages = options.languageOneOf
528 if (options.languageOneOf.find(l => l === '_unknown')) {
529 videoLanguages = videoLanguages.concat([ null ])
536 [ Op.or ]: videoLanguages
541 [ Op.in ]: Sequelize.literal(
543 'SELECT "videoId" FROM "videoCaption" ' +
544 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' +
553 if (options.trendingDays) {
554 query.include.push(VideoModel.buildTrendingQuery(options.trendingDays))
556 query.subQuery = false
559 if (options.historyOfUser) {
561 model: UserVideoHistoryModel,
564 userId: options.historyOfUser.id
568 // Even if the relation is n:m, we know that a user only have 0..1 video history
569 // So we won't have multiple rows for the same video
570 // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel
571 query.subQuery = false
580 [ScopeNames.WITH_BLOCKLIST]: {
583 [ ScopeNames.WITH_THUMBNAILS ]: {
586 model: ThumbnailModel,
591 [ ScopeNames.WITH_USER_ID ]: {
594 attributes: [ 'accountId' ],
595 model: VideoChannelModel.unscoped(),
599 attributes: [ 'userId' ],
600 model: AccountModel.unscoped(),
607 [ ScopeNames.WITH_ACCOUNT_DETAILS ]: {
610 model: VideoChannelModel.unscoped(),
615 exclude: [ 'privateKey', 'publicKey' ]
617 model: ActorModel.unscoped(),
621 attributes: [ 'host' ],
622 model: ServerModel.unscoped(),
626 model: AvatarModel.unscoped(),
632 model: AccountModel.unscoped(),
636 model: ActorModel.unscoped(),
638 exclude: [ 'privateKey', 'publicKey' ]
643 attributes: [ 'host' ],
644 model: ServerModel.unscoped(),
648 model: AvatarModel.unscoped(),
659 [ ScopeNames.WITH_TAGS ]: {
660 include: [ TagModel ]
662 [ ScopeNames.WITH_BLACKLISTED ]: {
665 attributes: [ 'id', 'reason', 'unfederated' ],
666 model: VideoBlacklistModel,
671 [ ScopeNames.WITH_WEBTORRENT_FILES ]: (withRedundancies = false) => {
672 let subInclude: any[] = []
674 if (withRedundancies === true) {
677 attributes: [ 'fileUrl' ],
678 model: VideoRedundancyModel.unscoped(),
687 model: VideoFileModel.unscoped(),
688 separate: true, // We may have multiple files, having multiple redundancies so let's separate this join
695 [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => {
696 const subInclude: IncludeOptions[] = [
698 model: VideoFileModel.unscoped(),
703 if (withRedundancies === true) {
705 attributes: [ 'fileUrl' ],
706 model: VideoRedundancyModel.unscoped(),
714 model: VideoStreamingPlaylistModel.unscoped(),
715 separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join
722 [ ScopeNames.WITH_SCHEDULED_UPDATE ]: {
725 model: ScheduleVideoUpdateModel.unscoped(),
730 [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => {
734 attributes: [ 'currentTime' ],
735 model: UserVideoHistoryModel.unscoped(),
749 export class VideoModel extends Model<VideoModel> {
752 @Default(DataType.UUIDV4)
754 @Column(DataType.UUID)
758 @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name'))
764 @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true))
770 @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true))
776 @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true))
777 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max))
781 @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy'))
786 @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean'))
792 @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true))
793 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max))
798 @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true))
799 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max))
803 @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration'))
833 @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
834 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max))
839 commentsEnabled: boolean
843 downloadEnabled: boolean
847 waitTranscoding: boolean
851 @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state'))
862 @Default(DataType.NOW)
869 originallyPublishedAt: Date
871 @ForeignKey(() => VideoChannelModel)
875 @BelongsTo(() => VideoChannelModel, {
881 VideoChannel: VideoChannelModel
883 @BelongsToMany(() => TagModel, {
884 foreignKey: 'videoId',
885 through: () => VideoTagModel,
890 @HasMany(() => ThumbnailModel, {
898 Thumbnails: ThumbnailModel[]
900 @HasMany(() => VideoPlaylistElementModel, {
907 VideoPlaylistElements: VideoPlaylistElementModel[]
909 @HasMany(() => VideoAbuseModel, {
916 VideoAbuses: VideoAbuseModel[]
918 @HasMany(() => VideoFileModel, {
926 VideoFiles: VideoFileModel[]
928 @HasMany(() => VideoStreamingPlaylistModel, {
936 VideoStreamingPlaylists: VideoStreamingPlaylistModel[]
938 @HasMany(() => VideoShareModel, {
945 VideoShares: VideoShareModel[]
947 @HasMany(() => AccountVideoRateModel, {
954 AccountVideoRates: AccountVideoRateModel[]
956 @HasMany(() => VideoCommentModel, {
964 VideoComments: VideoCommentModel[]
966 @HasMany(() => VideoViewModel, {
973 VideoViews: VideoViewModel[]
975 @HasMany(() => UserVideoHistoryModel, {
982 UserVideoHistories: UserVideoHistoryModel[]
984 @HasOne(() => ScheduleVideoUpdateModel, {
991 ScheduleVideoUpdate: ScheduleVideoUpdateModel
993 @HasOne(() => VideoBlacklistModel, {
1000 VideoBlacklist: VideoBlacklistModel
1002 @HasOne(() => VideoImportModel, {
1007 onDelete: 'set null'
1009 VideoImport: VideoImportModel
1011 @HasMany(() => VideoCaptionModel, {
1016 onDelete: 'cascade',
1018 [ 'separate' as any ]: true
1020 VideoCaptions: VideoCaptionModel[]
1023 static async sendDelete (instance: MVideoAccountLight, options) {
1024 if (instance.isOwned()) {
1025 if (!instance.VideoChannel) {
1026 instance.VideoChannel = await instance.$get('VideoChannel', {
1031 transaction: options.transaction
1032 }) as MChannelAccountDefault
1035 return sendDeleteVideo(instance, options.transaction)
1042 static async removeFiles (instance: VideoModel) {
1043 const tasks: Promise<any>[] = []
1045 logger.info('Removing files of video %s.', instance.url)
1047 if (instance.isOwned()) {
1048 if (!Array.isArray(instance.VideoFiles)) {
1049 instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[]
1052 // Remove physical files and torrents
1053 instance.VideoFiles.forEach(file => {
1054 tasks.push(instance.removeFile(file))
1055 tasks.push(instance.removeTorrent(file))
1058 // Remove playlists file
1059 tasks.push(instance.removeStreamingPlaylist())
1062 // Do not wait video deletion because we could be in a transaction
1065 logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err })
1071 static listLocal (): Bluebird<MVideoWithAllFiles[]> {
1078 return VideoModel.scope([
1079 ScopeNames.WITH_WEBTORRENT_FILES,
1080 ScopeNames.WITH_STREAMING_PLAYLISTS,
1081 ScopeNames.WITH_THUMBNAILS
1085 static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) {
1086 function getRawQuery (select: string) {
1087 const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' +
1088 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
1089 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' +
1090 'WHERE "Account"."actorId" = ' + actorId
1091 const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' +
1092 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
1093 'WHERE "VideoShare"."actorId" = ' + actorId
1095 return `(${queryVideo}) UNION (${queryVideoShare})`
1098 const rawQuery = getRawQuery('"Video"."id"')
1099 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
1105 order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings
1108 [ Op.in ]: Sequelize.literal('(' + rawQuery + ')')
1111 { privacy: VideoPrivacy.PUBLIC },
1112 { privacy: VideoPrivacy.UNLISTED }
1117 attributes: [ 'language' ],
1118 model: VideoCaptionModel.unscoped(),
1122 attributes: [ 'id', 'url' ],
1123 model: VideoShareModel.unscoped(),
1125 // We only want videos shared by this actor
1140 attributes: [ 'id', 'url' ],
1141 model: ActorModel.unscoped()
1146 model: VideoChannelModel.unscoped(),
1150 attributes: [ 'name' ],
1151 model: AccountModel.unscoped(),
1155 attributes: [ 'id', 'url', 'followersUrl' ],
1156 model: ActorModel.unscoped(),
1162 attributes: [ 'id', 'url', 'followersUrl' ],
1163 model: ActorModel.unscoped(),
1173 return Bluebird.all([
1174 VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query),
1175 VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT })
1176 ]).then(([ rows, totals ]) => {
1177 // totals: totalVideos + totalVideoShares
1179 let totalVideoShares = 0
1180 if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10)
1181 if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10)
1183 const total = totalVideos + totalVideoShares
1191 static listUserVideosForApi (accountId: number, start: number, count: number, sort: string) {
1192 function buildBaseQuery (): FindOptions {
1196 order: getVideoSort(sort),
1199 model: VideoChannelModel,
1203 model: AccountModel,
1215 const countQuery = buildBaseQuery()
1216 const findQuery = buildBaseQuery()
1218 const findScopes = [
1219 ScopeNames.WITH_SCHEDULED_UPDATE,
1220 ScopeNames.WITH_BLACKLISTED,
1221 ScopeNames.WITH_THUMBNAILS
1224 return Promise.all([
1225 VideoModel.count(countQuery),
1226 VideoModel.scope(findScopes).findAll<MVideoForUser>(findQuery)
1227 ]).then(([ count, rows ]) => {
1235 static async listForApi (options: {
1240 includeLocalVideos: boolean,
1242 categoryOneOf?: number[],
1243 licenceOneOf?: number[],
1244 languageOneOf?: string[],
1245 tagsOneOf?: string[],
1246 tagsAllOf?: string[],
1247 filter?: VideoFilter,
1249 videoChannelId?: number,
1250 followerActorId?: number
1251 videoPlaylistId?: number,
1252 trendingDays?: number,
1253 user?: MUserAccountId,
1254 historyOfUser?: MUserId
1255 }, countVideos = true) {
1256 if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) {
1257 throw new Error('Try to filter all-local but no user has not the see all videos right')
1260 const query: FindOptions & { where?: null } = {
1261 offset: options.start,
1262 limit: options.count,
1263 order: getVideoSort(options.sort)
1266 let trendingDays: number
1267 if (options.sort.endsWith('trending')) {
1268 trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS
1270 query.group = 'VideoModel.id'
1273 const serverActor = await getServerActor()
1275 // followerActorId === null has a meaning, so just check undefined
1276 const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id
1278 const queryOptions = {
1280 serverAccountId: serverActor.Account.id,
1282 categoryOneOf: options.categoryOneOf,
1283 licenceOneOf: options.licenceOneOf,
1284 languageOneOf: options.languageOneOf,
1285 tagsOneOf: options.tagsOneOf,
1286 tagsAllOf: options.tagsAllOf,
1287 filter: options.filter,
1288 withFiles: options.withFiles,
1289 accountId: options.accountId,
1290 videoChannelId: options.videoChannelId,
1291 videoPlaylistId: options.videoPlaylistId,
1292 includeLocalVideos: options.includeLocalVideos,
1294 historyOfUser: options.historyOfUser,
1298 return VideoModel.getAvailableForApi(query, queryOptions, countVideos)
1301 static async searchAndPopulateAccountAndServer (options: {
1302 includeLocalVideos: boolean
1307 startDate?: string // ISO 8601
1308 endDate?: string // ISO 8601
1309 originallyPublishedStartDate?: string
1310 originallyPublishedEndDate?: string
1312 categoryOneOf?: number[]
1313 licenceOneOf?: number[]
1314 languageOneOf?: string[]
1315 tagsOneOf?: string[]
1316 tagsAllOf?: string[]
1317 durationMin?: number // seconds
1318 durationMax?: number // seconds
1319 user?: MUserAccountId,
1320 filter?: VideoFilter
1324 if (options.startDate || options.endDate) {
1325 const publishedAtRange = {}
1327 if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate
1328 if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate
1330 whereAnd.push({ publishedAt: publishedAtRange })
1333 if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) {
1334 const originallyPublishedAtRange = {}
1336 if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate
1337 if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate
1339 whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange })
1342 if (options.durationMin || options.durationMax) {
1343 const durationRange = {}
1345 if (options.durationMin) durationRange[ Op.gte ] = options.durationMin
1346 if (options.durationMax) durationRange[ Op.lte ] = options.durationMax
1348 whereAnd.push({ duration: durationRange })
1351 const attributesInclude = []
1352 const escapedSearch = VideoModel.sequelize.escape(options.search)
1353 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
1354 if (options.search) {
1358 [ Op.in ]: Sequelize.literal(
1360 'SELECT "video"."id" FROM "video" ' +
1362 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' +
1363 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' +
1365 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' +
1366 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' +
1367 'WHERE "tag"."name" = ' + escapedSearch +
1374 attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search))
1377 // Cannot search on similarity if we don't have a search
1378 if (!options.search) {
1379 attributesInclude.push(
1380 Sequelize.literal('0 as similarity')
1386 include: attributesInclude
1388 offset: options.start,
1389 limit: options.count,
1390 order: getVideoSort(options.sort)
1393 const serverActor = await getServerActor()
1394 const queryOptions = {
1395 followerActorId: serverActor.id,
1396 serverAccountId: serverActor.Account.id,
1397 includeLocalVideos: options.includeLocalVideos,
1399 categoryOneOf: options.categoryOneOf,
1400 licenceOneOf: options.licenceOneOf,
1401 languageOneOf: options.languageOneOf,
1402 tagsOneOf: options.tagsOneOf,
1403 tagsAllOf: options.tagsAllOf,
1405 filter: options.filter,
1409 return VideoModel.getAvailableForApi(query, queryOptions)
1412 static load (id: number | string, t?: Transaction): Bluebird<MVideoThumbnail> {
1413 const where = buildWhereIdOrUUID(id)
1419 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1422 static loadWithBlacklist (id: number | string, t?: Transaction): Bluebird<MVideoThumbnailBlacklist> {
1423 const where = buildWhereIdOrUUID(id)
1429 return VideoModel.scope([
1430 ScopeNames.WITH_THUMBNAILS,
1431 ScopeNames.WITH_BLACKLISTED
1435 static loadWithRights (id: number | string, t?: Transaction): Bluebird<MVideoWithRights> {
1436 const where = buildWhereIdOrUUID(id)
1442 return VideoModel.scope([
1443 ScopeNames.WITH_BLACKLISTED,
1444 ScopeNames.WITH_USER_ID,
1445 ScopeNames.WITH_THUMBNAILS
1449 static loadOnlyId (id: number | string, t?: Transaction): Bluebird<MVideoIdThumbnail> {
1450 const where = buildWhereIdOrUUID(id)
1453 attributes: [ 'id' ],
1458 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1461 static loadWithFiles (id: number | string, t?: Transaction, logging?: boolean): Bluebird<MVideoWithAllFiles> {
1462 const where = buildWhereIdOrUUID(id)
1470 return VideoModel.scope([
1471 ScopeNames.WITH_WEBTORRENT_FILES,
1472 ScopeNames.WITH_STREAMING_PLAYLISTS,
1473 ScopeNames.WITH_THUMBNAILS
1477 static loadByUUID (uuid: string): Bluebird<MVideoThumbnail> {
1484 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options)
1487 static loadByUrl (url: string, transaction?: Transaction): Bluebird<MVideoThumbnail> {
1488 const query: FindOptions = {
1495 return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query)
1498 static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction): Bluebird<MVideoAccountLightBlacklistAllFiles> {
1499 const query: FindOptions = {
1506 return VideoModel.scope([
1507 ScopeNames.WITH_ACCOUNT_DETAILS,
1508 ScopeNames.WITH_WEBTORRENT_FILES,
1509 ScopeNames.WITH_STREAMING_PLAYLISTS,
1510 ScopeNames.WITH_THUMBNAILS,
1511 ScopeNames.WITH_BLACKLISTED
1515 static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number): Bluebird<MVideoFullLight> {
1516 const where = buildWhereIdOrUUID(id)
1519 order: [ [ 'Tags', 'name', 'ASC' ] ] as any,
1524 const scopes: (string | ScopeOptions)[] = [
1525 ScopeNames.WITH_TAGS,
1526 ScopeNames.WITH_BLACKLISTED,
1527 ScopeNames.WITH_ACCOUNT_DETAILS,
1528 ScopeNames.WITH_SCHEDULED_UPDATE,
1529 ScopeNames.WITH_WEBTORRENT_FILES,
1530 ScopeNames.WITH_STREAMING_PLAYLISTS,
1531 ScopeNames.WITH_THUMBNAILS
1535 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1543 static loadForGetAPI (parameters: {
1544 id: number | string,
1547 }): Bluebird<MVideoDetails> {
1548 const { id, t, userId } = parameters
1549 const where = buildWhereIdOrUUID(id)
1552 order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings
1557 const scopes: (string | ScopeOptions)[] = [
1558 ScopeNames.WITH_TAGS,
1559 ScopeNames.WITH_BLACKLISTED,
1560 ScopeNames.WITH_ACCOUNT_DETAILS,
1561 ScopeNames.WITH_SCHEDULED_UPDATE,
1562 ScopeNames.WITH_THUMBNAILS,
1563 { method: [ ScopeNames.WITH_WEBTORRENT_FILES, true ] },
1564 { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] }
1568 scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] })
1576 static async getStats () {
1577 const totalLocalVideos = await VideoModel.count({
1582 const totalVideos = await VideoModel.count()
1584 let totalLocalVideoViews = await VideoModel.sum('views', {
1589 // Sequelize could return null...
1590 if (!totalLocalVideoViews) totalLocalVideoViews = 0
1594 totalLocalVideoViews,
1599 static incrementViews (id: number, views: number) {
1600 return VideoModel.increment('views', {
1608 static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) {
1609 // Instances only share videos
1610 const query = 'SELECT 1 FROM "videoShare" ' +
1611 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' +
1612 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' +
1616 type: QueryTypes.SELECT as QueryTypes.SELECT,
1617 bind: { followerActorId, videoId },
1621 return VideoModel.sequelize.query(query, options)
1622 .then(results => results.length === 1)
1625 static bulkUpdateSupportField (videoChannel: MChannel, t: Transaction) {
1628 channelId: videoChannel.id
1633 return VideoModel.update({ support: videoChannel.support }, options)
1636 static getAllIdsFromChannel (videoChannel: MChannelId): Bluebird<number[]> {
1638 attributes: [ 'id' ],
1640 channelId: videoChannel.id
1644 return VideoModel.findAll(query)
1645 .then(videos => videos.map(v => v.id))
1648 // threshold corresponds to how many video the field should have to be returned
1649 static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) {
1650 const serverActor = await getServerActor()
1651 const followerActorId = serverActor.id
1653 const scopeOptions: AvailableForListIDsOptions = {
1654 serverAccountId: serverActor.Account.id,
1656 includeLocalVideos: true,
1657 attributesType: 'none' // Don't break aggregation
1660 const query: FindOptions = {
1661 attributes: [ field ],
1664 having: Sequelize.where(
1665 Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold }
1667 order: [ (this.sequelize as any).random() ]
1670 return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] })
1672 .then(rows => rows.map(r => r[ field ]))
1675 static buildTrendingQuery (trendingDays: number) {
1679 model: VideoViewModel,
1683 [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays)
1689 private static buildActorWhereWithFilter (filter?: VideoFilter) {
1690 if (filter && (filter === 'local' || filter === 'all-local')) {
1699 private static async getAvailableForApi (
1700 query: FindOptions & { where?: null }, // Forbid where field in query
1701 options: AvailableForListIDsOptions,
1704 const idsScope: ScopeOptions = {
1706 ScopeNames.AVAILABLE_FOR_LIST_IDS, options
1710 // Remove trending sort on count, because it uses a group by
1711 const countOptions = Object.assign({}, options, { trendingDays: undefined })
1712 const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined })
1713 const countScope: ScopeOptions = {
1715 ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions
1719 const [ count, ids ] = await Promise.all([
1721 ? VideoModel.scope(countScope).count(countQuery)
1722 : Promise.resolve<number>(undefined),
1724 VideoModel.scope(idsScope)
1726 .then(rows => rows.map(r => r.id))
1729 if (ids.length === 0) return { data: [], total: count }
1731 const secondQuery: FindOptions = {
1734 attributes: query.attributes,
1735 order: [ // Keep original order
1737 ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ')
1742 const apiScope: (string | ScopeOptions)[] = []
1745 apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] })
1750 ScopeNames.FOR_API, {
1752 withFiles: options.withFiles,
1753 videoPlaylistId: options.videoPlaylistId
1758 const rows = await VideoModel.scope(apiScope).findAll(secondQuery)
1766 static getCategoryLabel (id: number) {
1767 return VIDEO_CATEGORIES[ id ] || 'Misc'
1770 static getLicenceLabel (id: number) {
1771 return VIDEO_LICENCES[ id ] || 'Unknown'
1774 static getLanguageLabel (id: string) {
1775 return VIDEO_LANGUAGES[ id ] || 'Unknown'
1778 static getPrivacyLabel (id: number) {
1779 return VIDEO_PRIVACIES[ id ] || 'Unknown'
1782 static getStateLabel (id: number) {
1783 return VIDEO_STATES[ id ] || 'Unknown'
1787 return !!this.VideoBlacklist
1791 return (this.VideoChannel.Account.Actor.Server && this.VideoChannel.Account.Actor.Server.isBlocked()) ||
1792 this.VideoChannel.Account.isBlocked()
1795 getMaxQualityFile <T extends MVideoWithFile> (this: T): MVideoFileVideo | MVideoFileStreamingPlaylistVideo {
1796 if (Array.isArray(this.VideoFiles) && this.VideoFiles.length !== 0) {
1797 const file = maxBy(this.VideoFiles, file => file.resolution)
1799 return Object.assign(file, { Video: this })
1802 // No webtorrent files, try with streaming playlist files
1803 if (Array.isArray(this.VideoStreamingPlaylists) && this.VideoStreamingPlaylists.length !== 0) {
1804 const streamingPlaylistWithVideo = Object.assign(this.VideoStreamingPlaylists[0], { Video: this })
1806 const file = maxBy(streamingPlaylistWithVideo.VideoFiles, file => file.resolution)
1807 return Object.assign(file, { VideoStreamingPlaylist: streamingPlaylistWithVideo })
1813 getWebTorrentFile <T extends MVideoWithFile> (this: T, resolution: number): MVideoFileVideo {
1814 if (Array.isArray(this.VideoFiles) === false) return undefined
1816 const file = this.VideoFiles.find(f => f.resolution === resolution)
1817 if (!file) return undefined
1819 return Object.assign(file, { Video: this })
1822 async addAndSaveThumbnail (thumbnail: MThumbnail, transaction: Transaction) {
1823 thumbnail.videoId = this.id
1825 const savedThumbnail = await thumbnail.save({ transaction })
1827 if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = []
1829 // Already have this thumbnail, skip
1830 if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return
1832 this.Thumbnails.push(savedThumbnail)
1835 generateThumbnailName () {
1836 return this.uuid + '.jpg'
1840 if (Array.isArray(this.Thumbnails) === false) return undefined
1842 return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE)
1845 generatePreviewName () {
1846 return this.uuid + '.jpg'
1850 if (Array.isArray(this.Thumbnails) === false) return undefined
1852 return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW)
1856 return this.remote === false
1859 getWatchStaticPath () {
1860 return '/videos/watch/' + this.uuid
1863 getEmbedStaticPath () {
1864 return '/videos/embed/' + this.uuid
1867 getMiniatureStaticPath () {
1868 const thumbnail = this.getMiniature()
1869 if (!thumbnail) return null
1871 return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename)
1874 getPreviewStaticPath () {
1875 const preview = this.getPreview()
1876 if (!preview) return null
1878 // We use a local cache, so specify our cache endpoint instead of potential remote URL
1879 return join(LAZY_STATIC_PATHS.PREVIEWS, preview.filename)
1882 toFormattedJSON (this: MVideoFormattable, options?: VideoFormattingJSONOptions): Video {
1883 return videoModelToFormattedJSON(this, options)
1886 toFormattedDetailsJSON (this: MVideoFormattableDetails): VideoDetails {
1887 return videoModelToFormattedDetailsJSON(this)
1890 getFormattedVideoFilesJSON (): VideoFile[] {
1891 const { baseUrlHttp, baseUrlWs } = this.getBaseUrls()
1892 return videoFilesModelToFormattedJSON(this, baseUrlHttp, baseUrlWs, this.VideoFiles)
1895 toActivityPubObject (this: MVideoAP): VideoTorrentObject {
1896 return videoModelToActivityPubObject(this)
1899 getTruncatedDescription () {
1900 if (!this.description) return null
1902 const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
1903 return peertubeTruncate(this.description, { length: maxLength })
1906 getMaxQualityResolution () {
1907 const file = this.getMaxQualityFile()
1908 const videoOrPlaylist = file.getVideoOrStreamingPlaylist()
1909 const originalFilePath = getVideoFilePath(videoOrPlaylist, file)
1911 return getVideoFileResolution(originalFilePath)
1914 getDescriptionAPIPath () {
1915 return `/api/${API_VERSION}/videos/${this.uuid}/description`
1918 getHLSPlaylist (): MStreamingPlaylistFilesVideo {
1919 if (!this.VideoStreamingPlaylists) return undefined
1921 const playlist = this.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
1922 playlist.Video = this
1927 setHLSPlaylist (playlist: MStreamingPlaylist) {
1928 const toAdd = [ playlist ] as [ VideoStreamingPlaylistModel ]
1930 if (Array.isArray(this.VideoStreamingPlaylists) === false || this.VideoStreamingPlaylists.length === 0) {
1931 this.VideoStreamingPlaylists = toAdd
1935 this.VideoStreamingPlaylists = this.VideoStreamingPlaylists
1936 .filter(s => s.type !== VideoStreamingPlaylistType.HLS)
1940 removeFile (videoFile: MVideoFile, isRedundancy = false) {
1941 const filePath = getVideoFilePath(this, videoFile, isRedundancy)
1942 return remove(filePath)
1943 .catch(err => logger.warn('Cannot delete file %s.', filePath, { err }))
1946 removeTorrent (videoFile: MVideoFile) {
1947 const torrentPath = getTorrentFilePath(this, videoFile)
1948 return remove(torrentPath)
1949 .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err }))
1952 removeStreamingPlaylist (isRedundancy = false) {
1953 const directoryPath = getHLSDirectory(this, isRedundancy)
1955 return remove(directoryPath)
1956 .catch(err => logger.warn('Cannot delete playlist directory %s.', directoryPath, { err }))
1960 if (this.isOwned()) return false
1962 return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL)
1966 this.changed('updatedAt', true)
1971 async publishIfNeededAndSave (t: Transaction) {
1972 if (this.state !== VideoState.PUBLISHED) {
1973 this.state = VideoState.PUBLISHED
1974 this.publishedAt = new Date()
1975 await this.save({ transaction: t })
1984 if (this.isOwned()) {
1986 baseUrlHttp: WEBSERVER.URL,
1987 baseUrlWs: WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT
1992 baseUrlHttp: REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host,
1993 baseUrlWs: REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host
1997 getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) {
1998 return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
2001 getTorrentUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2002 return baseUrlHttp + STATIC_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2005 getTorrentDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2006 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + getTorrentFileName(this, videoFile)
2009 getVideoFileUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2010 return baseUrlHttp + STATIC_PATHS.WEBSEED + getVideoFilename(this, videoFile)
2013 getVideoRedundancyUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2014 return baseUrlHttp + STATIC_PATHS.REDUNDANCY + getVideoFilename(this, videoFile)
2017 getVideoFileDownloadUrl (videoFile: MVideoFile, baseUrlHttp: string) {
2018 return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + getVideoFilename(this, videoFile)
2021 getBandwidthBits (videoFile: MVideoFile) {
2022 return Math.ceil((videoFile.size * 8) / this.duration)