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 { RecentlyAddedStrategy, VideoRedundancyStrategy, VideosRedundancy } from '../../../shared/models/redundancy'
5 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
6 import { VideoFileModel } from '../../models/video/video-file'
7 import { sortBy } from 'lodash'
8 import { downloadWebTorrentVideo } from '../../helpers/webtorrent'
9 import { join } from 'path'
10 import { rename } from 'fs-extra'
11 import { getServerActor } from '../../helpers/utils'
12 import { sendCreateCacheFile, sendUpdateCacheFile } from '../activitypub/send'
13 import { VideoModel } from '../../models/video/video'
14 import { getVideoCacheFileActivityPubUrl } from '../activitypub/url'
15 import { removeVideoRedundancy } from '../redundancy'
16 import { isTestInstance } from '../../helpers/core-utils'
18 export class VideosRedundancyScheduler extends AbstractScheduler {
20 private static instance: AbstractScheduler
21 private executing = false
23 protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.videosRedundancy
25 private constructor () {
30 if (this.executing) return
34 for (const obj of CONFIG.REDUNDANCY.VIDEOS) {
36 const videoToDuplicate = await this.findVideoToDuplicate(obj)
37 if (!videoToDuplicate) continue
39 const videoFiles = videoToDuplicate.VideoFiles
40 videoFiles.forEach(f => f.Video = videoToDuplicate)
42 if (await this.isTooHeavy(obj.strategy, videoFiles, obj.size)) {
43 if (!isTestInstance()) logger.info('Video %s is too big for our cache, skipping.', videoToDuplicate.url)
47 logger.info('Will duplicate video %s in redundancy scheduler "%s".', videoToDuplicate.url, obj.strategy)
49 await this.createVideoRedundancy(obj.strategy, videoFiles)
51 logger.error('Cannot run videos redundancy %s.', obj.strategy, { err })
55 const expired = await VideoRedundancyModel.listAllExpired()
57 for (const m of expired) {
58 logger.info('Removing expired video %s from our redundancy system.', this.buildEntryLogId(m))
63 logger.error('Cannot remove %s video from our redundancy system.', this.buildEntryLogId(m))
67 this.executing = false
70 static get Instance () {
71 return this.instance || (this.instance = new this())
74 private findVideoToDuplicate (cache: VideosRedundancy) {
75 if (cache.strategy === 'most-views') {
76 return VideoRedundancyModel.findMostViewToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
79 if (cache.strategy === 'trending') {
80 return VideoRedundancyModel.findTrendingToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR)
83 if (cache.strategy === 'recently-added') {
84 const minViews = cache.minViews
85 return VideoRedundancyModel.findRecentlyAddedToDuplicate(REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR, minViews)
89 private async createVideoRedundancy (strategy: VideoRedundancyStrategy, filesToDuplicate: VideoFileModel[]) {
90 const serverActor = await getServerActor()
92 for (const file of filesToDuplicate) {
93 const existing = await VideoRedundancyModel.loadByFileId(file.id)
95 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', file.Video.url, file.resolution, strategy)
97 existing.expiresOn = this.buildNewExpiration()
100 await sendUpdateCacheFile(serverActor, existing)
104 // We need more attributes and check if the video still exists
105 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(file.Video.id)
108 logger.info('Duplicating %s - %d in videos redundancy with "%s" strategy.', video.url, file.resolution, strategy)
110 const { baseUrlHttp, baseUrlWs } = video.getBaseUrls()
111 const magnetUri = video.generateMagnetUri(file, baseUrlHttp, baseUrlWs)
113 const tmpPath = await downloadWebTorrentVideo({ magnetUri }, JOB_TTL['video-import'])
115 const destPath = join(CONFIG.STORAGE.VIDEOS_DIR, video.getVideoFilename(file))
116 await rename(tmpPath, destPath)
118 const createdModel = await VideoRedundancyModel.create({
119 expiresOn: new Date(Date.now() + REDUNDANCY.VIDEOS.EXPIRES_AFTER_MS),
120 url: getVideoCacheFileActivityPubUrl(file),
121 fileUrl: video.getVideoFileUrl(file, CONFIG.WEBSERVER.URL),
123 videoFileId: file.id,
124 actorId: serverActor.id
126 createdModel.VideoFile = file
128 await sendCreateCacheFile(serverActor, createdModel)
132 private async isTooHeavy (strategy: VideoRedundancyStrategy, filesToDuplicate: VideoFileModel[], maxSizeArg: number) {
133 const maxSize = maxSizeArg - this.getTotalFileSizes(filesToDuplicate)
135 const totalDuplicated = await VideoRedundancyModel.getTotalDuplicated(strategy)
137 return totalDuplicated > maxSize
140 private buildNewExpiration () {
141 return new Date(Date.now() + REDUNDANCY.VIDEOS.EXPIRES_AFTER_MS)
144 private buildEntryLogId (object: VideoRedundancyModel) {
145 return `${object.VideoFile.Video.url}-${object.VideoFile.resolution}`
148 private getTotalFileSizes (files: VideoFileModel[]) {
149 const fileReducer = (previous: number, current: VideoFileModel) => previous + current.size
151 return files.reduce(fileReducer, 0)