1 import { sample } from 'lodash'
2 import { col, FindOptions, fn, 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'
39 import { forEachSeries } from 'async'
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 loadLocalByStreamingPlaylistId (videoStreamingPlaylistId: number): Promise<MVideoRedundancyVideo> {
190 const actor = await getServerActor()
195 videoStreamingPlaylistId
199 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
202 static loadByIdWithVideo (id: number, transaction?: Transaction): Promise<MVideoRedundancyVideo> {
208 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
211 static loadByUrl (url: string, transaction?: Transaction): Promise<MVideoRedundancy> {
219 return VideoRedundancyModel.findOne(query)
222 static async isLocalByVideoUUIDExists (uuid: string) {
223 const actor = await getServerActor()
227 attributes: [ 'id' ],
234 model: VideoFileModel,
250 return VideoRedundancyModel.findOne(query)
254 static async getVideoSample (p: Promise<VideoModel[]>) {
256 if (rows.length === 0) return undefined
258 const ids = rows.map(r => r.id)
259 const id = sample(ids)
261 return VideoModel.loadWithFiles(id, undefined, !isTestInstance())
264 static async findMostViewToDuplicate (randomizedFactor: number) {
265 const peertubeActor = await getServerActor()
269 attributes: [ 'id', 'views' ],
270 limit: randomizedFactor,
271 order: getVideoSort('-views'),
273 privacy: VideoPrivacy.PUBLIC,
275 ...this.buildVideoIdsForDuplication(peertubeActor)
278 VideoRedundancyModel.buildServerRedundancyInclude()
282 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
285 static async findTrendingToDuplicate (randomizedFactor: number) {
286 const peertubeActor = await getServerActor()
290 attributes: [ 'id', 'views' ],
292 group: 'VideoModel.id',
293 limit: randomizedFactor,
294 order: getVideoSort('-trending'),
296 privacy: VideoPrivacy.PUBLIC,
298 ...this.buildVideoIdsForDuplication(peertubeActor)
301 VideoRedundancyModel.buildServerRedundancyInclude(),
303 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
307 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
310 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
311 const peertubeActor = await getServerActor()
315 attributes: [ 'id', 'publishedAt' ],
316 limit: randomizedFactor,
317 order: getVideoSort('-publishedAt'),
319 privacy: VideoPrivacy.PUBLIC,
324 ...this.buildVideoIdsForDuplication(peertubeActor)
327 VideoRedundancyModel.buildServerRedundancyInclude()
331 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
334 static async loadOldestLocalExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number): Promise<MVideoRedundancyVideo> {
335 const expiredDate = new Date()
336 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
338 const actor = await getServerActor()
350 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
353 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
354 const actor = await getServerActor()
355 const redundancyInclude = {
357 model: VideoRedundancyModel,
365 const queryFiles: FindOptions = {
366 include: [ redundancyInclude ]
369 const queryStreamingPlaylists: FindOptions = {
373 model: VideoModel.unscoped(),
379 model: VideoStreamingPlaylistModel.unscoped(),
390 VideoFileModel.aggregate('size', 'SUM', queryFiles),
391 VideoFileModel.aggregate('size', 'SUM', queryStreamingPlaylists)
392 ]).then(([ r1, r2 ]) => {
393 return parseAggregateResult(r1) + parseAggregateResult(r2)
397 static async listLocalExpired () {
398 const actor = await getServerActor()
409 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
412 static async listRemoteExpired () {
413 const actor = await getServerActor()
427 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
430 static async listLocalOfServer (serverId: number) {
431 const actor = await getServerActor()
432 const buildVideoInclude = () => ({
438 model: VideoChannelModel.unscoped(),
443 model: ActorModel.unscoped(),
460 model: VideoFileModel,
462 include: [ buildVideoInclude() ]
465 model: VideoStreamingPlaylistModel,
467 include: [ buildVideoInclude() ]
472 return VideoRedundancyModel.findAll(query)
475 static listForApi (options: {
479 target: VideoRedundanciesTarget
482 const { start, count, sort, target, strategy } = options
483 const redundancyWhere: WhereOptions = {}
484 const videosWhere: WhereOptions = {}
485 let redundancySqlSuffix = ''
487 if (target === 'my-videos') {
488 Object.assign(videosWhere, { remote: false })
489 } else if (target === 'remote-videos') {
490 Object.assign(videosWhere, { remote: true })
491 Object.assign(redundancyWhere, { strategy: { [Op.ne]: null } })
492 redundancySqlSuffix = ' AND "videoRedundancy"."strategy" IS NOT NULL'
496 Object.assign(redundancyWhere, { strategy: strategy })
499 const videoFilterWhere = {
507 'SELECT "videoId" FROM "videoFile" ' +
508 'INNER JOIN "videoRedundancy" ON "videoRedundancy"."videoFileId" = "videoFile".id' +
509 redundancySqlSuffix +
518 'select "videoId" FROM "videoStreamingPlaylist" ' +
519 'INNER JOIN "videoRedundancy" ON "videoRedundancy"."videoStreamingPlaylistId" = "videoStreamingPlaylist".id' +
520 redundancySqlSuffix +
532 // /!\ On video model /!\
533 const findOptions = {
536 order: getSort(sort),
540 model: VideoFileModel,
543 model: VideoRedundancyModel.unscoped(),
545 where: redundancyWhere
551 model: VideoStreamingPlaylistModel.unscoped(),
554 model: VideoRedundancyModel.unscoped(),
556 where: redundancyWhere
559 model: VideoFileModel,
565 where: videoFilterWhere
568 // /!\ On video model /!\
569 const countOptions = {
570 where: videoFilterWhere
574 VideoModel.findAll(findOptions),
576 VideoModel.count(countOptions)
577 ]).then(([ data, total ]) => ({ total, data }))
580 static async getStats (strategy: VideoRedundancyStrategyWithManual) {
581 const actor = await getServerActor()
583 const sql = `WITH "tmp" AS ` +
585 `SELECT "videoFile"."size" AS "videoFileSize", "videoStreamingFile"."size" AS "videoStreamingFileSize", ` +
586 `"videoFile"."videoId" AS "videoFileVideoId", "videoStreamingPlaylist"."videoId" AS "videoStreamingVideoId"` +
587 `FROM "videoRedundancy" AS "videoRedundancy" ` +
588 `LEFT JOIN "videoFile" AS "videoFile" ON "videoRedundancy"."videoFileId" = "videoFile"."id" ` +
589 `LEFT JOIN "videoStreamingPlaylist" ON "videoRedundancy"."videoStreamingPlaylistId" = "videoStreamingPlaylist"."id" ` +
590 `LEFT JOIN "videoFile" AS "videoStreamingFile" ` +
591 `ON "videoStreamingPlaylist"."id" = "videoStreamingFile"."videoStreamingPlaylistId" ` +
592 `WHERE "videoRedundancy"."strategy" = :strategy AND "videoRedundancy"."actorId" = :actorId` +
595 `SELECT "videoFileVideoId" AS "videoId" FROM "tmp" ` +
596 `UNION SELECT "videoStreamingVideoId" AS "videoId" FROM "tmp" ` +
599 `COALESCE(SUM("videoFileSize"), '0') + COALESCE(SUM("videoStreamingFileSize"), '0') AS "totalUsed", ` +
600 `(SELECT COUNT("videoIds"."videoId") FROM "videoIds") AS "totalVideos", ` +
601 `COUNT(*) AS "totalVideoFiles" ` +
604 return VideoRedundancyModel.sequelize.query<any>(sql, {
605 replacements: { strategy, actorId: actor.id },
606 type: QueryTypes.SELECT
607 }).then(([ row ]) => ({
608 totalUsed: parseAggregateResult(row.totalUsed),
609 totalVideos: row.totalVideos,
610 totalVideoFiles: row.totalVideoFiles
614 static toFormattedJSONStatic (video: MVideoForRedundancyAPI): VideoRedundancy {
615 const filesRedundancies: FileRedundancyInformation[] = []
616 const streamingPlaylistsRedundancies: StreamingPlaylistRedundancyInformation[] = []
618 for (const file of video.VideoFiles) {
619 for (const redundancy of file.RedundancyVideos) {
620 filesRedundancies.push({
622 fileUrl: redundancy.fileUrl,
623 strategy: redundancy.strategy,
624 createdAt: redundancy.createdAt,
625 updatedAt: redundancy.updatedAt,
626 expiresOn: redundancy.expiresOn,
632 for (const playlist of video.VideoStreamingPlaylists) {
633 const size = playlist.VideoFiles.reduce((a, b) => a + b.size, 0)
635 for (const redundancy of playlist.RedundancyVideos) {
636 streamingPlaylistsRedundancies.push({
638 fileUrl: redundancy.fileUrl,
639 strategy: redundancy.strategy,
640 createdAt: redundancy.createdAt,
641 updatedAt: redundancy.updatedAt,
642 expiresOn: redundancy.expiresOn,
655 files: filesRedundancies,
656 streamingPlaylists: streamingPlaylistsRedundancies
662 if (this.VideoFile) return this.VideoFile.Video
664 if (this.VideoStreamingPlaylist.Video) return this.VideoStreamingPlaylist.Video
670 return !!this.strategy
673 toActivityPubObject (this: MVideoRedundancyAP): CacheFileObject {
674 if (this.VideoStreamingPlaylist) {
677 type: 'CacheFile' as 'CacheFile',
678 object: this.VideoStreamingPlaylist.Video.url,
679 expires: this.expiresOn ? this.expiresOn.toISOString() : null,
682 mediaType: 'application/x-mpegURL',
690 type: 'CacheFile' as 'CacheFile',
691 object: this.VideoFile.Video.url,
692 expires: this.expiresOn ? this.expiresOn.toISOString() : null,
695 mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[this.VideoFile.extname] as any,
697 height: this.VideoFile.resolution,
698 size: this.VideoFile.size,
699 fps: this.VideoFile.fps
704 // Don't include video files we already duplicated
705 private static buildVideoIdsForDuplication (peertubeActor: MActor) {
706 const notIn = literal(
708 `SELECT "videoFile"."videoId" AS "videoId" FROM "videoRedundancy" ` +
709 `INNER JOIN "videoFile" ON "videoFile"."id" = "videoRedundancy"."videoFileId" ` +
710 `WHERE "videoRedundancy"."actorId" = ${peertubeActor.id} ` +
712 `SELECT "videoStreamingPlaylist"."videoId" AS "videoId" FROM "videoRedundancy" ` +
713 `INNER JOIN "videoStreamingPlaylist" ON "videoStreamingPlaylist"."id" = "videoRedundancy"."videoStreamingPlaylistId" ` +
714 `WHERE "videoRedundancy"."actorId" = ${peertubeActor.id} ` +
725 private static buildServerRedundancyInclude () {
728 model: VideoChannelModel.unscoped(),
733 model: ActorModel.unscoped(),
738 model: ServerModel.unscoped(),
741 redundancyAllowed: true