aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/files-cache/video-storyboards-simple-file-cache.ts
blob: 4cd96e70ce28495a9cccf38654f0673868609a8d (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
import { join } from 'path'
import { logger } from '@server/helpers/logger'
import { doRequestAndSaveToFile } from '@server/helpers/requests'
import { StoryboardModel } from '@server/models/video/storyboard'
import { FILES_CACHE } from '../../initializers/constants'
import { AbstractSimpleFileCache } from './shared/abstract-simple-file-cache'

class VideoStoryboardsSimpleFileCache extends AbstractSimpleFileCache <string> {

  private static instance: VideoStoryboardsSimpleFileCache

  private constructor () {
    super()
  }

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

  async getFilePathImpl (filename: string) {
    const storyboard = await StoryboardModel.loadWithVideoByFilename(filename)
    if (!storyboard) return undefined

    if (storyboard.Video.isOwned()) return { isOwned: true, path: storyboard.getPath() }

    return this.loadRemoteFile(storyboard.filename)
  }

  // Key is the storyboard filename
  protected async loadRemoteFile (key: string) {
    const storyboard = await StoryboardModel.loadWithVideoByFilename(key)
    if (!storyboard) return undefined

    const destPath = join(FILES_CACHE.STORYBOARDS.DIRECTORY, storyboard.filename)
    const remoteUrl = storyboard.getOriginFileUrl(storyboard.Video)

    try {
      await doRequestAndSaveToFile(remoteUrl, destPath)

      logger.debug('Fetched remote storyboard %s to %s.', remoteUrl, destPath)

      return { isOwned: false, path: destPath }
    } catch (err) {
      logger.info('Cannot fetch remote storyboard file %s.', remoteUrl, { err })

      return undefined
    }
  }
}

export {
  VideoStoryboardsSimpleFileCache
}