aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/cache/videos-preview-cache.ts
blob: 0eb43efcc03dc10c7aab65a929b1e64bfa2f1734 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import * as asyncLRU from 'async-lru'
import { createWriteStream } from 'fs'
import { join } from 'path'
import { logger, unlinkPromise } from '../../helpers'
import { CACHE, CONFIG } from '../../initializers'
import { VideoModel } from '../../models/video/video'
import { fetchRemoteVideoPreview } from '../activitypub'

class VideosPreviewCache {

  private static instance: VideosPreviewCache

  private lru

  private constructor () { }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }

  init (max: number) {
    this.lru = new asyncLRU({
      max,
      load: (key, cb) => {
        this.loadPreviews(key)
          .then(res => cb(null, res))
          .catch(err => cb(err))
      }
    })

    this.lru.on('evict', (obj: { key: string, value: string }) => {
      unlinkPromise(obj.value).then(() => logger.debug('%s evicted from VideosPreviewCache', obj.value))
    })
  }

  async getPreviewPath (key: string) {
    const video = await VideoModel.loadByUUID(key)
    if (!video) return undefined

    if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())

    return new Promise<string>((res, rej) => {
      this.lru.get(key, (err, value) => {
        err ? rej(err) : res(value)
      })
    })
  }

  private async loadPreviews (key: string) {
    const video = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(key)
    if (!video) return undefined

    if (video.isOwned()) throw new Error('Cannot load preview of owned video.')

    const res = await this.saveRemotePreviewAndReturnPath(video)

    return res
  }

  private saveRemotePreviewAndReturnPath (video: VideoModel) {
    const req = fetchRemoteVideoPreview(video)

    return new Promise<string>((res, rej) => {
      const path = join(CACHE.DIRECTORIES.PREVIEWS, video.getPreviewName())
      const stream = createWriteStream(path)

      req.pipe(stream)
         .on('finish', () => res(path))
         .on('error', (err) => rej(err))
    })
  }
}

export {
  VideosPreviewCache
}