1 import { AbstractScheduler } from './abstract-scheduler'
2 import { CONFIG, REDUNDANCY, VIDEO_IMPORT_TIMEOUT } from '../../initializers'
3 import { logger } from '../../helpers/logger'
4 import { 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 { getVideoCacheFileActivityPubUrl } from '../activitypub/url'
13 import { removeVideoRedundancy } from '../redundancy'
14 import { getOrCreateVideoAndAccountAndChannel } from '../activitypub'
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) {
33 logger.info('Running redundancy scheduler for strategy %s.', obj.strategy)
36 const videoToDuplicate = await this.findVideoToDuplicate(obj)
37 if (!videoToDuplicate) continue
39 const videoFiles = videoToDuplicate.VideoFiles
40 videoFiles.forEach(f => f.Video = videoToDuplicate)
42 await this.purgeCacheIfNeeded(obj, videoFiles)
44 if (await this.isTooHeavy(obj, videoFiles)) {
45 logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
49 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, obj.strategy)
51 await this.createVideoRedundancy(obj, videoFiles)
53 logger.error('Cannot run videos redundancy %s.', obj.strategy, { err })
57 await this.extendsLocalExpiration()
59 await this.purgeRemoteExpired()
61 this.executing = false
64 static get Instance () {
65 return this.instance || (this.instance = new this())
68 private async extendsLocalExpiration () {
69 const expired = await VideoRedundancyModel.listLocalExpired()
71 for (const redundancyModel of expired) {
73 await this.extendsOrDeleteRedundancy(redundancyModel)
75 logger.error('Cannot extend expiration of %s video from our redundancy system.', this.buildEntryLogId(redundancyModel))
80 private async extendsOrDeleteRedundancy (redundancyModel: VideoRedundancyModel) {
81 // Refresh the video, maybe it was deleted
82 const video = await this.loadAndRefreshVideo(redundancyModel.VideoFile.Video.url)
85 logger.info('Destroying existing redundancy %s, because the associated video does not exist anymore.', redundancyModel.url)
87 await redundancyModel.destroy()
91 const redundancy = CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.find(s => s.strategy === redundancyModel.strategy)
92 await this.extendsExpirationOf(redundancyModel, redundancy.minLifetime)
95 private async purgeRemoteExpired () {
96 const expired = await VideoRedundancyModel.listRemoteExpired()
98 for (const redundancyModel of expired) {
100 await removeVideoRedundancy(redundancyModel)
102 logger.error('Cannot remove redundancy %s from our redundancy system.', this.buildEntryLogId(redundancyModel))
107 private findVideoToDuplicate (cache: VideosRedundancy) {
108 if (cache.strategy === 'most-views') {
109 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
112 if (cache.strategy === 'trending') {
113 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
116 if (cache.strategy === 'recently-added') {
117 const minViews = cache.minViews
118 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
122 private async createVideoRedundancy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
123 const serverActor = await getServerActor()
125 for (const file of filesToDuplicate) {
126 const video = await this.loadAndRefreshVideo(file.Video.url)
128 const existingRedundancy = await VideoRedundancyModel.loadLocalByFileId(file.id)
129 if (existingRedundancy) {
130 await this.extendsOrDeleteRedundancy(existingRedundancy)
136 logger.info('Video %s we want to duplicate does not existing anymore, skipping.', file.Video.url)
141 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, redundancy.strategy)
143 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
144 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
146 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, VIDEO_IMPORT_TIMEOUT)
148 const destPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
149 await rename(tmpPath, destPath)
151 const createdModel = await VideoRedundancyModel.create({
152 expiresOn: this.buildNewExpiration(redundancy.minLifetime),
153 url: getVideoCacheFileActivityPubUrl(file),
154 fileUrl: video.getVideoFileUrl(file, CONFIG.WEBSERVER.URL),
155 strategy: redundancy.strategy,
156 videoFileId: file.id,
157 actorId: serverActor.id
159 createdModel.VideoFile = file
161 await sendCreateCacheFile(serverActor, createdModel)
163 logger.info('Duplicated %s - %d -> %s.', video.url, file.resolution, createdModel.url)
167 private async extendsExpirationOf (redundancy: VideoRedundancyModel, expiresAfterMs: number) {
168 logger.info('Extending expiration of %s.', redundancy.url)
170 const serverActor = await getServerActor()
172 redundancy.expiresOn = this.buildNewExpiration(expiresAfterMs)
173 await redundancy.save()
175 await sendUpdateCacheFile(serverActor, redundancy)
178 private async purgeCacheIfNeeded (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
179 while (this.isTooHeavy(redundancy, filesToDuplicate)) {
180 const toDelete = await VideoRedundancyModel.loadOldestLocalThatAlreadyExpired(redundancy.strategy, redundancy.minLifetime)
181 if (!toDelete) return
183 await removeVideoRedundancy(toDelete)
187 private async isTooHeavy (redundancy: VideosRedundancy, filesToDuplicate: VideoFileModel[]) {
188 const maxSize = redundancy.size - this.getTotalFileSizes(filesToDuplicate)
190 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(redundancy.strategy)
192 return totalDuplicated > maxSize
195 private buildNewExpiration (expiresAfterMs: number) {
196 return new Date(Date.now() + expiresAfterMs)
199 private buildEntryLogId (object: VideoRedundancyModel) {
200 return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
203 private getTotalFileSizes (files: VideoFileModel[]) {
204 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
206 return files.reduce(fileReducer, 0)
209 private async loadAndRefreshVideo (videoUrl: string) {
210 // We need more attributes and check if the video still exists
211 const getVideoOptions = {
212 videoObject: videoUrl,
213 syncParam: { likes: false, dislikes: false, shares: false, comments: false, thumbnail: false, refreshVideo: true },
214 fetchType: 'all' as 'all'
216 const { video } = await getOrCreateVideoAndAccountAndChannel(getVideoOptions)