1 import { AbstractScheduler } from './abstract-scheduler'
2 import { CONFIG, JOB_TTL, REDUNDANCY, SCHEDULER_INTERVALS_MS } from '../../initializers'
3 import { logger } from '../../helpers/logger'
4 import { VideoRedundancyStrategy, VideosRedundancy } from '../../../shared/models/redundancy'
5 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
6 import { VideoFileModel } from '../../models/video/video-file'
7 import { downloadWebTorrentVideo } from '../../helpers/webtorrent'
8 import { join } from 'path'
9 import { rename } from 'fs-extra'
10 import { getServerActor } from '../../helpers/utils'
11 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
12 import { VideoModel } from '../../models/video/video'
13 import { getVideoCacheFileActivityPubUrl } from '../activitypub/url'
14 import { isTestInstance } from '../../helpers/core-utils'
16 export class VideosRedundancyScheduler extends AbstractScheduler {
18 private static instance: AbstractScheduler
19 private executing = false
21 protected schedulerIntervalMs = CONFIG.REDUNDANCY.VIDEOS.CHECK_INTERVAL
23 private constructor () {
28 if (this.executing) return
32 for (const obj of CONFIG.REDUNDANCY.VIDEOS.STRATEGIES) {
34 const videoToDuplicate = await this.findVideoToDuplicate(obj)
35 if (!videoToDuplicate) continue
37 const videoFiles = videoToDuplicate.VideoFiles
38 videoFiles.forEach(f => f.Video = videoToDuplicate)
40 if (await this.isTooHeavy(obj.strategy, videoFiles, obj.size)) {
41 if (!isTestInstance()) logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
45 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, obj.strategy)
47 await this.createVideoRedundancy(obj.strategy, videoFiles)
49 logger.error('Cannot run videos redundancy %s.', obj.strategy, { err })
53 await this.removeExpired()
55 this.executing = false
58 static get Instance () {
59 return this.instance || (this.instance = new this())
62 private async removeExpired () {
63 const expired = await VideoRedundancyModel.listAllExpired()
65 for (const m of expired) {
66 logger.info('Removing expired video %s from our redundancy system.', this.buildEntryLogId(m))
71 logger.error('Cannot remove %s video from our redundancy system.', this.buildEntryLogId(m))
76 private findVideoToDuplicate (cache: VideosRedundancy) {
77 if (cache.strategy === 'most-views') {
78 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
81 if (cache.strategy === 'trending') {
82 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
85 if (cache.strategy === 'recently-added') {
86 const minViews = cache.minViews
87 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
91 private async createVideoRedundancy (strategy: VideoRedundancyStrategy, filesToDuplicate: VideoFileModel[]) {
92 const serverActor = await getServerActor()
94 for (const file of filesToDuplicate) {
95 const existing = await VideoRedundancyModel.loadByFileId(file.id)
97 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', file.Video.url, file.resolution, strategy)
99 existing.expiresOn = this.buildNewExpiration()
100 await existing.save()
102 await sendUpdateCacheFile(serverActor, existing)
106 // We need more attributes and check if the video still exists
107 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(file.Video.id)
110 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy)
112 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
113 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
115 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, JOB_TTL['video-import'])
117 const destPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
118 await rename(tmpPath, destPath)
120 const createdModel = await VideoRedundancyModel.create({
121 expiresOn: new Date(Date.now() + REDUNDANCY.VIDEOS.EXPIRES_AFTER_MS),
122 url: getVideoCacheFileActivityPubUrl(file),
123 fileUrl: video.getVideoFileUrl(file, CONFIG.WEBSERVER.URL),
125 videoFileId: file.id,
126 actorId: serverActor.id
128 createdModel.VideoFile = file
130 await sendCreateCacheFile(serverActor, createdModel)
134 private async isTooHeavy (strategy: VideoRedundancyStrategy, filesToDuplicate: VideoFileModel[], maxSizeArg: number) {
135 const maxSize = maxSizeArg - this.getTotalFileSizes(filesToDuplicate)
137 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(strategy)
139 return totalDuplicated > maxSize
142 private buildNewExpiration () {
143 return new Date(Date.now() + REDUNDANCY.VIDEOS.EXPIRES_AFTER_MS)
146 private buildEntryLogId (object: VideoRedundancyModel) {
147 return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
150 private getTotalFileSizes (files: VideoFileModel[]) {
151 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
153 return files.reduce(fileReducer, 0)