1 import { sample } from 'lodash'
2 import { FindOptions, 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 { VideoModel } from '../video/video'
36 import { VideoChannelModel } from '../video/video-channel'
37 import { VideoFileModel } from '../video/video-file'
38 import { VideoStreamingPlaylistModel } from '../video/video-streaming-playlist'
40 export enum ScopeNames {
41 WITH_VIDEO = 'WITH_VIDEO'
45 [ScopeNames.WITH_VIDEO]: {
48 model: VideoFileModel,
58 model: VideoStreamingPlaylistModel,
72 tableName: 'videoRedundancy',
75 fields: [ 'videoFileId' ]
86 export class VideoRedundancyModel extends Model {
99 @Is('VideoRedundancyFileUrl', value => throwIfNotValid(value, isUrlValid, 'fileUrl'))
100 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
104 @Is('VideoRedundancyUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
105 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
110 strategy: string // Only used by us
112 @ForeignKey(() => VideoFileModel)
116 @BelongsTo(() => VideoFileModel, {
122 VideoFile: VideoFileModel
124 @ForeignKey(() => VideoStreamingPlaylistModel)
126 videoStreamingPlaylistId: number
128 @BelongsTo(() => VideoStreamingPlaylistModel, {
134 VideoStreamingPlaylist: VideoStreamingPlaylistModel
136 @ForeignKey(() => ActorModel)
140 @BelongsTo(() => ActorModel, {
149 static async removeFile (instance: VideoRedundancyModel) {
150 if (!instance.isOwned()) return
152 if (instance.videoFileId) {
153 const videoFile = await VideoFileModel.loadWithVideo(instance.videoFileId)
155 const logIdentifier = `${videoFile.Video.uuid}-${videoFile.resolution}`
156 logger.info('Removing duplicated video file %s.', logIdentifier)
158 videoFile.Video.removeFile(videoFile, true)
159 .catch(err => logger.error('Cannot delete %s files.', logIdentifier, { err }))
162 if (instance.videoStreamingPlaylistId) {
163 const videoStreamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(instance.videoStreamingPlaylistId)
165 const videoUUID = videoStreamingPlaylist.Video.uuid
166 logger.info('Removing duplicated video streaming playlist %s.', videoUUID)
168 videoStreamingPlaylist.Video.removeStreamingPlaylistFiles(videoStreamingPlaylist, true)
169 .catch(err => logger.error('Cannot delete video streaming playlist files of %s.', videoUUID, { err }))
175 static async loadLocalByFileId (videoFileId: number): Promise<MVideoRedundancyVideo> {
176 const actor = await getServerActor()
185 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
188 static async loadLocalByStreamingPlaylistId (videoStreamingPlaylistId: number): Promise<MVideoRedundancyVideo> {
189 const actor = await getServerActor()
194 videoStreamingPlaylistId
198 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
201 static loadByIdWithVideo (id: number, transaction?: Transaction): Promise<MVideoRedundancyVideo> {
207 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
210 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoRedundancy> {
218 return VideoRedundancyModel.findOne(query)
221 static async isLocalByVideoUUIDExists (uuid: string) {
222 const actor = await getServerActor()
226 attributes: [ 'id' ],
233 model: VideoFileModel,
249 return VideoRedundancyModel.findOne(query)
253 static async getVideoSample (p: Promise<VideoModel[]>) {
255 if (rows.length === 0) return undefined
257 const ids = rows.map(r => r.id)
258 const id = sample(ids)
260 return VideoModel.loadWithFiles(id, undefined, !isTestInstance())
263 static async findMostViewToDuplicate (randomizedFactor: number) {
264 const peertubeActor = await getServerActor()
268 attributes: [ 'id', 'views' ],
269 limit: randomizedFactor,
270 order: getVideoSort('-views'),
272 privacy: VideoPrivacy.PUBLIC,
274 ...this.buildVideoIdsForDuplication(peertubeActor)
277 VideoRedundancyModel.buildServerRedundancyInclude()
281 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
284 static async findTrendingToDuplicate (randomizedFactor: number) {
285 const peertubeActor = await getServerActor()
289 attributes: [ 'id', 'views' ],
291 group: 'VideoModel.id',
292 limit: randomizedFactor,
293 order: getVideoSort('-trending'),
295 privacy: VideoPrivacy.PUBLIC,
297 ...this.buildVideoIdsForDuplication(peertubeActor)
300 VideoRedundancyModel.buildServerRedundancyInclude(),
302 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
306 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
309 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
310 const peertubeActor = await getServerActor()
314 attributes: [ 'id', 'publishedAt' ],
315 limit: randomizedFactor,
316 order: getVideoSort('-publishedAt'),
318 privacy: VideoPrivacy.PUBLIC,
323 ...this.buildVideoIdsForDuplication(peertubeActor)
326 VideoRedundancyModel.buildServerRedundancyInclude()
330 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
333 static async loadOldestLocalExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number): Promise<MVideoRedundancyVideo> {
334 const expiredDate = new Date()
335 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
337 const actor = await getServerActor()
349 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
352 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
353 const actor = await getServerActor()
354 const redundancyInclude = {
356 model: VideoRedundancyModel,
364 const queryFiles: FindOptions = {
365 include: [ redundancyInclude ]
368 const queryStreamingPlaylists: FindOptions = {
372 model: VideoModel.unscoped(),
378 model: VideoStreamingPlaylistModel.unscoped(),
389 VideoFileModel.aggregate('size', 'SUM', queryFiles),
390 VideoFileModel.aggregate('size', 'SUM', queryStreamingPlaylists)
391 ]).then(([ r1, r2 ]) => {
392 return parseAggregateResult(r1) + parseAggregateResult(r2)
396 static async listLocalExpired () {
397 const actor = await getServerActor()
408 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
411 static async listRemoteExpired () {
412 const actor = await getServerActor()
426 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
429 static async listLocalOfServer (serverId: number) {
430 const actor = await getServerActor()
431 const buildVideoInclude = () => ({
437 model: VideoChannelModel.unscoped(),
442 model: ActorModel.unscoped(),
459 model: VideoFileModel,
461 include: [ buildVideoInclude() ]
464 model: VideoStreamingPlaylistModel,
466 include: [ buildVideoInclude() ]
471 return VideoRedundancyModel.findAll(query)
474 static listForApi (options: {
478 target: VideoRedundanciesTarget
481 const { start, count, sort, target, strategy } = options
482 const redundancyWhere: WhereOptions = {}
483 const videosWhere: WhereOptions = {}
484 let redundancySqlSuffix = ''
486 if (target === 'my-videos') {
487 Object.assign(videosWhere, { remote: false })
488 } else if (target === 'remote-videos') {
489 Object.assign(videosWhere, { remote: true })
490 Object.assign(redundancyWhere, { strategy: { [Op.ne]: null } })
491 redundancySqlSuffix = ' AND "videoRedundancy"."strategy" IS NOT NULL'
495 Object.assign(redundancyWhere, { strategy: strategy })
498 const videoFilterWhere = {
506 'SELECT "videoId" FROM "videoFile" ' +
507 'INNER JOIN "videoRedundancy" ON "videoRedundancy"."videoFileId" = "videoFile".id' +
508 redundancySqlSuffix +
517 'select "videoId" FROM "videoStreamingPlaylist" ' +
518 'INNER JOIN "videoRedundancy" ON "videoRedundancy"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id' +
519 redundancySqlSuffix +
531 // /!\ On video model /!\
532 const findOptions = {
535 order: getSort(sort),
539 model: VideoFileModel,
542 model: VideoRedundancyModel.unscoped(),
544 where: redundancyWhere
550 model: VideoStreamingPlaylistModel.unscoped(),
553 model: VideoRedundancyModel.unscoped(),
555 where: redundancyWhere
558 model: VideoFileModel,
564 where: videoFilterWhere
567 // /!\ On video model /!\
568 const countOptions = {
569 where: videoFilterWhere
573 VideoModel.findAll(findOptions),
575 VideoModel.count(countOptions)
576 ]).then(([ data, total ]) => ({ total, data }))
579 static async getStats (strategy: VideoRedundancyStrategyWithManual) {
580 const actor = await getServerActor()
582 const sql = `WITH "tmp" AS ` +
584 `SELECT "videoFile"."size" AS "videoFileSize", "videoStreamingFile"."size" AS "videoStreamingFileSize", ` +
585 `"videoFile"."videoId" AS "videoFileVideoId", "videoStreamingPlaylist"."videoId" AS "videoStreamingVideoId"` +
586 `FROM "videoRedundancy" AS "videoRedundancy" ` +
587 `LEFT JOIN "videoFile" AS "videoFile" ON "videoRedundancy"."videoFileId" = "videoFile"."id" ` +
588 `LEFT JOIN "videoStreamingPlaylist" ON "videoRedundancy"."videoStreamingPlaylistId" = "videoStreamingPlaylist"."id" ` +
589 `LEFT JOIN "videoFile" AS "videoStreamingFile" ` +
590 `ON "videoStreamingPlaylist"."id" = "videoStreamingFile"."videoStreamingPlaylistId" ` +
591 `WHERE "videoRedundancy"."strategy" = :strategy AND "videoRedundancy"."actorId" = :actorId` +
594 `SELECT "videoFileVideoId" AS "videoId" FROM "tmp" ` +
595 `UNION SELECT "videoStreamingVideoId" AS "videoId" FROM "tmp" ` +
598 `COALESCE(SUM("videoFileSize"), '0') + COALESCE(SUM("videoStreamingFileSize"), '0') AS "totalUsed", ` +
599 `(SELECT COUNT("videoIds"."videoId") FROM "videoIds") AS "totalVideos", ` +
600 `COUNT(*) AS "totalVideoFiles" ` +
603 return VideoRedundancyModel.sequelize.query<any>(sql, {
604 replacements: { strategy, actorId: actor.id },
605 type: QueryTypes.SELECT
606 }).then(([ row ]) => ({
607 totalUsed: parseAggregateResult(row.totalUsed),
608 totalVideos: row.totalVideos,
609 totalVideoFiles: row.totalVideoFiles
613 static toFormattedJSONStatic (video: MVideoForRedundancyAPI): VideoRedundancy {
614 const filesRedundancies: FileRedundancyInformation[] = []
615 const streamingPlaylistsRedundancies: StreamingPlaylistRedundancyInformation[] = []
617 for (const file of video.VideoFiles) {
618 for (const redundancy of file.RedundancyVideos) {
619 filesRedundancies.push({
621 fileUrl: redundancy.fileUrl,
622 strategy: redundancy.strategy,
623 createdAt: redundancy.createdAt,
624 updatedAt: redundancy.updatedAt,
625 expiresOn: redundancy.expiresOn,
631 for (const playlist of video.VideoStreamingPlaylists) {
632 const size = playlist.VideoFiles.reduce((a, b) => a + b.size, 0)
634 for (const redundancy of playlist.RedundancyVideos) {
635 streamingPlaylistsRedundancies.push({
637 fileUrl: redundancy.fileUrl,
638 strategy: redundancy.strategy,
639 createdAt: redundancy.createdAt,
640 updatedAt: redundancy.updatedAt,
641 expiresOn: redundancy.expiresOn,
654 files: filesRedundancies,
655 streamingPlaylists: streamingPlaylistsRedundancies
661 if (this.VideoFile) return this.VideoFile.Video
663 if (this.VideoStreamingPlaylist.Video) return this.VideoStreamingPlaylist.Video
669 return !!this.strategy
672 toActivityPubObject (this: MVideoRedundancyAP): CacheFileObject {
673 if (this.VideoStreamingPlaylist) {
676 type: 'CacheFile' as 'CacheFile',
677 object: this.VideoStreamingPlaylist.Video.url,
678 expires: this.expiresOn ? this.expiresOn.toISOString() : null,
681 mediaType: 'application/x-mpegURL',
689 type: 'CacheFile' as 'CacheFile',
690 object: this.VideoFile.Video.url,
691 expires: this.expiresOn ? this.expiresOn.toISOString() : null,
694 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[this.VideoFile.extname] as any,
696 height: this.VideoFile.resolution,
697 size: this.VideoFile.size,
698 fps: this.VideoFile.fps
703 // Don't include video files we already duplicated
704 private static buildVideoIdsForDuplication (peertubeActor: MActor) {
705 const notIn = literal(
707 `SELECT "videoFile"."videoId" AS "videoId" FROM "videoRedundancy" ` +
708 `INNER JOIN "videoFile" ON "videoFile"."id" = "videoRedundancy"."videoFileId" ` +
709 `WHERE "videoRedundancy"."actorId" = ${peertubeActor.id} ` +
711 `SELECT "videoStreamingPlaylist"."videoId" AS "videoId" FROM "videoRedundancy" ` +
712 `INNER JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist"."id" = "videoRedundancy"."videoStreamingPlaylistId" ` +
713 `WHERE "videoRedundancy"."actorId" = ${peertubeActor.id} ` +
724 private static buildServerRedundancyInclude () {
727 model: VideoChannelModel.unscoped(),
732 model: ActorModel.unscoped(),
737 model: ServerModel.unscoped(),
740 redundancyAllowed: true