Upgrade sequelize
[oweals/peertube.git] / server / lib / files-cache / abstract-video-static-file-cache.ts
1 import { createWriteStream, remove } from 'fs-extra'
2 import { logger } from '../../helpers/logger'
3 import { VideoModel } from '../../models/video/video'
4 import { fetchRemoteVideoStaticFile } from '../activitypub'
5 import * as memoizee from 'memoizee'
6
7 type GetFilePathResult = { isOwned: boolean, path: string } | undefined
8
9 export abstract class AbstractVideoStaticFileCache <T> {
10
11   getFilePath: (params: T) => Promise<GetFilePathResult>
12
13   abstract getFilePathImpl (params: T): Promise<GetFilePathResult>
14
15   // Load and save the remote file, then return the local path from filesystem
16   protected abstract loadRemoteFile (key: string): Promise<GetFilePathResult>
17
18   init (max: number, maxAge: number) {
19     this.getFilePath = memoizee(this.getFilePathImpl, {
20       maxAge,
21       max,
22       promise: true,
23       dispose: (result: GetFilePathResult) => {
24         if (result.isOwned !== true) {
25           remove(result.path)
26             .then(() => logger.debug('%s removed from %s', result.path, this.constructor.name))
27             .catch(err => logger.error('Cannot remove %s from cache %s.', result.path, this.constructor.name, { err }))
28         }
29       }
30     })
31   }
32
33   protected saveRemoteVideoFileAndReturnPath (video: VideoModel, remoteStaticPath: string, destPath: string) {
34     return new Promise<string>((res, rej) => {
35       const req = fetchRemoteVideoStaticFile(video, remoteStaticPath, rej)
36
37       const stream = createWriteStream(destPath)
38
39       req.pipe(stream)
40          .on('error', (err) => rej(err))
41          .on('finish', () => res(destPath))
42     })
43   }
44 }