1 import { sample } from 'lodash'
2 import { literal, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
16 } from 'sequelize-typescript'
17 import { getServerActor } from '@server/models/application/application'
18 import { MActor, MVideoForRedundancyAPI, MVideoRedundancy, MVideoRedundancyAP, MVideoRedundancyVideo } from '@server/types/models'
19 import { VideoRedundanciesTarget } from '@shared/models/redundancy/video-redundancies-filters.model'
21 FileRedundancyInformation,
22 StreamingPlaylistRedundancyInformation,
24 } from '@shared/models/redundancy/video-redundancy.model'
25 import { CacheFileObject, VideoPrivacy } from '../../../shared'
26 import { VideoRedundancyStrategy, VideoRedundancyStrategyWithManual } from '../../../shared/models/redundancy'
27 import { isTestInstance } from '../../helpers/core-utils'
28 import { isActivityPubUrlValid, isUrlValid } from '../../helpers/custom-validators/activitypub/misc'
29 import { logger } from '../../helpers/logger'
30 import { CONFIG } from '../../initializers/config'
31 import { CONSTRAINTS_FIELDS, MIMETYPES } from '../../initializers/constants'
32 import { ActorModel } from '../activitypub/actor'
33 import { ServerModel } from '../server/server'
34 import { getSort, getVideoSort, parseAggregateResult, throwIfNotValid } from '../utils'
35 import { ScheduleVideoUpdateModel } from '../video/schedule-video-update'
36 import { VideoModel } from '../video/video'
37 import { VideoChannelModel } from '../video/video-channel'
38 import { VideoFileModel } from '../video/video-file'
39 import { VideoStreamingPlaylistModel } from '../video/video-streaming-playlist'
41 export enum ScopeNames {
42 WITH_VIDEO = 'WITH_VIDEO'
46 [ScopeNames.WITH_VIDEO]: {
49 model: VideoFileModel,
59 model: VideoStreamingPlaylistModel,
73 tableName: 'videoRedundancy',
76 fields: [ 'videoFileId' ]
87 export class VideoRedundancyModel extends Model {
100 @Is('VideoRedundancyFileUrl', value => throwIfNotValid(value, isUrlValid, 'fileUrl'))
101 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
105 @Is('VideoRedundancyUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
106 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
111 strategy: string // Only used by us
113 @ForeignKey(() => VideoFileModel)
117 @BelongsTo(() => VideoFileModel, {
123 VideoFile: VideoFileModel
125 @ForeignKey(() => VideoStreamingPlaylistModel)
127 videoStreamingPlaylistId: number
129 @BelongsTo(() => VideoStreamingPlaylistModel, {
135 VideoStreamingPlaylist: VideoStreamingPlaylistModel
137 @ForeignKey(() => ActorModel)
141 @BelongsTo(() => ActorModel, {
150 static async removeFile (instance: VideoRedundancyModel) {
151 if (!instance.isOwned()) return
153 if (instance.videoFileId) {
154 const videoFile = await VideoFileModel.loadWithVideo(instance.videoFileId)
156 const logIdentifier = `${videoFile.Video.uuid}-${videoFile.resolution}`
157 logger.info('Removing duplicated video file %s.', logIdentifier)
159 videoFile.Video.removeFile(videoFile, true)
160 .catch(err => logger.error('Cannot delete %s files.', logIdentifier, { err }))
163 if (instance.videoStreamingPlaylistId) {
164 const videoStreamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(instance.videoStreamingPlaylistId)
166 const videoUUID = videoStreamingPlaylist.Video.uuid
167 logger.info('Removing duplicated video streaming playlist %s.', videoUUID)
169 videoStreamingPlaylist.Video.removeStreamingPlaylistFiles(videoStreamingPlaylist, true)
170 .catch(err => logger.error('Cannot delete video streaming playlist files of %s.', videoUUID, { err }))
176 static async loadLocalByFileId (videoFileId: number): Promise<MVideoRedundancyVideo> {
177 const actor = await getServerActor()
186 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
189 static async listLocalByVideoId (videoId: number): Promise<MVideoRedundancyVideo[]> {
190 const actor = await getServerActor()
192 const queryStreamingPlaylist = {
198 model: VideoStreamingPlaylistModel.unscoped(),
202 model: VideoModel.unscoped(),
219 model: VideoFileModel,
235 VideoRedundancyModel.findAll(queryStreamingPlaylist),
236 VideoRedundancyModel.findAll(queryFiles)
237 ]).then(([ r1, r2 ]) => r1.concat(r2))
240 static async loadLocalByStreamingPlaylistId (videoStreamingPlaylistId: number): Promise<MVideoRedundancyVideo> {
241 const actor = await getServerActor()
246 videoStreamingPlaylistId
250 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
253 static loadByIdWithVideo (id: number, transaction?: Transaction): Promise<MVideoRedundancyVideo> {
259 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
262 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoRedundancy> {
270 return VideoRedundancyModel.findOne(query)
273 static async isLocalByVideoUUIDExists (uuid: string) {
274 const actor = await getServerActor()
278 attributes: [ 'id' ],
285 model: VideoFileModel,
301 return VideoRedundancyModel.findOne(query)
305 static async getVideoSample (p: Promise<VideoModel[]>) {
307 if (rows.length === 0) return undefined
309 const ids = rows.map(r => r.id)
310 const id = sample(ids)
312 return VideoModel.loadWithFiles(id, undefined, !isTestInstance())
315 static async findMostViewToDuplicate (randomizedFactor: number) {
316 const peertubeActor = await getServerActor()
320 attributes: [ 'id', 'views' ],
321 limit: randomizedFactor,
322 order: getVideoSort('-views'),
324 privacy: VideoPrivacy.PUBLIC,
326 ...this.buildVideoIdsForDuplication(peertubeActor)
329 VideoRedundancyModel.buildServerRedundancyInclude()
333 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
336 static async findTrendingToDuplicate (randomizedFactor: number) {
337 const peertubeActor = await getServerActor()
341 attributes: [ 'id', 'views' ],
343 group: 'VideoModel.id',
344 limit: randomizedFactor,
345 order: getVideoSort('-trending'),
347 privacy: VideoPrivacy.PUBLIC,
349 ...this.buildVideoIdsForDuplication(peertubeActor)
352 VideoRedundancyModel.buildServerRedundancyInclude(),
354 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
358 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
361 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
362 const peertubeActor = await getServerActor()
366 attributes: [ 'id', 'publishedAt' ],
367 limit: randomizedFactor,
368 order: getVideoSort('-publishedAt'),
370 privacy: VideoPrivacy.PUBLIC,
375 ...this.buildVideoIdsForDuplication(peertubeActor)
378 VideoRedundancyModel.buildServerRedundancyInclude(),
380 // Required by publishedAt sort
382 model: ScheduleVideoUpdateModel.unscoped(),
388 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
391 static async loadOldestLocalExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number): Promise<MVideoRedundancyVideo> {
392 const expiredDate = new Date()
393 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
395 const actor = await getServerActor()
407 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
410 static async listLocalExpired () {
411 const actor = await getServerActor()
422 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
425 static async listRemoteExpired () {
426 const actor = await getServerActor()
440 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
443 static async listLocalOfServer (serverId: number) {
444 const actor = await getServerActor()
445 const buildVideoInclude = () => ({
451 model: VideoChannelModel.unscoped(),
456 model: ActorModel.unscoped(),
473 model: VideoFileModel,
475 include: [ buildVideoInclude() ]
478 model: VideoStreamingPlaylistModel,
480 include: [ buildVideoInclude() ]
485 return VideoRedundancyModel.findAll(query)
488 static listForApi (options: {
492 target: VideoRedundanciesTarget
495 const { start, count, sort, target, strategy } = options
496 const redundancyWhere: WhereOptions = {}
497 const videosWhere: WhereOptions = {}
498 let redundancySqlSuffix = ''
500 if (target === 'my-videos') {
501 Object.assign(videosWhere, { remote: false })
502 } else if (target === 'remote-videos') {
503 Object.assign(videosWhere, { remote: true })
504 Object.assign(redundancyWhere, { strategy: { [Op.ne]: null } })
505 redundancySqlSuffix = ' AND "videoRedundancy"."strategy" IS NOT NULL'
509 Object.assign(redundancyWhere, { strategy: strategy })
512 const videoFilterWhere = {
520 'SELECT "videoId" FROM "videoFile" ' +
521 'INNER JOIN "videoRedundancy" ON "videoRedundancy"."videoFileId" = "videoFile".id' +
522 redundancySqlSuffix +
531 'select "videoId" FROM "videoStreamingPlaylist" ' +
532 'INNER JOIN "videoRedundancy" ON "videoRedundancy"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id' +
533 redundancySqlSuffix +
545 // /!\ On video model /!\
546 const findOptions = {
549 order: getSort(sort),
553 model: VideoFileModel,
556 model: VideoRedundancyModel.unscoped(),
558 where: redundancyWhere
564 model: VideoStreamingPlaylistModel.unscoped(),
567 model: VideoRedundancyModel.unscoped(),
569 where: redundancyWhere
572 model: VideoFileModel,
578 where: videoFilterWhere
581 // /!\ On video model /!\
582 const countOptions = {
583 where: videoFilterWhere
587 VideoModel.findAll(findOptions),
589 VideoModel.count(countOptions)
590 ]).then(([ data, total ]) => ({ total, data }))
593 static async getStats (strategy: VideoRedundancyStrategyWithManual) {
594 const actor = await getServerActor()
596 const sql = `WITH "tmp" AS ` +
598 `SELECT "videoFile"."size" AS "videoFileSize", "videoStreamingFile"."size" AS "videoStreamingFileSize", ` +
599 `"videoFile"."videoId" AS "videoFileVideoId", "videoStreamingPlaylist"."videoId" AS "videoStreamingVideoId"` +
600 `FROM "videoRedundancy" AS "videoRedundancy" ` +
601 `LEFT JOIN "videoFile" AS "videoFile" ON "videoRedundancy"."videoFileId" = "videoFile"."id" ` +
602 `LEFT JOIN "videoStreamingPlaylist" ON "videoRedundancy"."videoStreamingPlaylistId" = "videoStreamingPlaylist"."id" ` +
603 `LEFT JOIN "videoFile" AS "videoStreamingFile" ` +
604 `ON "videoStreamingPlaylist"."id" = "videoStreamingFile"."videoStreamingPlaylistId" ` +
605 `WHERE "videoRedundancy"."strategy" = :strategy AND "videoRedundancy"."actorId" = :actorId` +
608 `SELECT "videoFileVideoId" AS "videoId" FROM "tmp" ` +
609 `UNION SELECT "videoStreamingVideoId" AS "videoId" FROM "tmp" ` +
612 `COALESCE(SUM("videoFileSize"), '0') + COALESCE(SUM("videoStreamingFileSize"), '0') AS "totalUsed", ` +
613 `(SELECT COUNT("videoIds"."videoId") FROM "videoIds") AS "totalVideos", ` +
614 `COUNT(*) AS "totalVideoFiles" ` +
617 return VideoRedundancyModel.sequelize.query<any>(sql, {
618 replacements: { strategy, actorId: actor.id },
619 type: QueryTypes.SELECT
620 }).then(([ row ]) => ({
621 totalUsed: parseAggregateResult(row.totalUsed),
622 totalVideos: row.totalVideos,
623 totalVideoFiles: row.totalVideoFiles
627 static toFormattedJSONStatic (video: MVideoForRedundancyAPI): VideoRedundancy {
628 const filesRedundancies: FileRedundancyInformation[] = []
629 const streamingPlaylistsRedundancies: StreamingPlaylistRedundancyInformation[] = []
631 for (const file of video.VideoFiles) {
632 for (const redundancy of file.RedundancyVideos) {
633 filesRedundancies.push({
635 fileUrl: redundancy.fileUrl,
636 strategy: redundancy.strategy,
637 createdAt: redundancy.createdAt,
638 updatedAt: redundancy.updatedAt,
639 expiresOn: redundancy.expiresOn,
645 for (const playlist of video.VideoStreamingPlaylists) {
646 const size = playlist.VideoFiles.reduce((a, b) => a + b.size, 0)
648 for (const redundancy of playlist.RedundancyVideos) {
649 streamingPlaylistsRedundancies.push({
651 fileUrl: redundancy.fileUrl,
652 strategy: redundancy.strategy,
653 createdAt: redundancy.createdAt,
654 updatedAt: redundancy.updatedAt,
655 expiresOn: redundancy.expiresOn,
668 files: filesRedundancies,
669 streamingPlaylists: streamingPlaylistsRedundancies
675 if (this.VideoFile?.Video) return this.VideoFile.Video
677 if (this.VideoStreamingPlaylist?.Video) return this.VideoStreamingPlaylist.Video
683 return !!this.strategy
686 toActivityPubObject (this: MVideoRedundancyAP): CacheFileObject {
687 if (this.VideoStreamingPlaylist) {
690 type: 'CacheFile' as 'CacheFile',
691 object: this.VideoStreamingPlaylist.Video.url,
692 expires: this.expiresOn ? this.expiresOn.toISOString() : null,
695 mediaType: 'application/x-mpegURL',
703 type: 'CacheFile' as 'CacheFile',
704 object: this.VideoFile.Video.url,
705 expires: this.expiresOn ? this.expiresOn.toISOString() : null,
708 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[this.VideoFile.extname] as any,
710 height: this.VideoFile.resolution,
711 size: this.VideoFile.size,
712 fps: this.VideoFile.fps
717 // Don't include video files we already duplicated
718 private static buildVideoIdsForDuplication (peertubeActor: MActor) {
719 const notIn = literal(
721 `SELECT "videoFile"."videoId" AS "videoId" FROM "videoRedundancy" ` +
722 `INNER JOIN "videoFile" ON "videoFile"."id" = "videoRedundancy"."videoFileId" ` +
723 `WHERE "videoRedundancy"."actorId" = ${peertubeActor.id} ` +
725 `SELECT "videoStreamingPlaylist"."videoId" AS "videoId" FROM "videoRedundancy" ` +
726 `INNER JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist"."id" = "videoRedundancy"."videoStreamingPlaylistId" ` +
727 `WHERE "videoRedundancy"."actorId" = ${peertubeActor.id} ` +
738 private static buildServerRedundancyInclude () {
741 model: VideoChannelModel.unscoped(),
746 model: ActorModel.unscoped(),
751 model: ServerModel.unscoped(),
754 redundancyAllowed: true