2
1

videos-caption-cache.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { join } from 'path'
  2. import { FILES_CACHE } from '../../initializers/constants'
  3. import { VideoModel } from '../../models/video/video'
  4. import { VideoCaptionModel } from '../../models/video/video-caption'
  5. import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
  6. import { CONFIG } from '../../initializers/config'
  7. import { logger } from '../../helpers/logger'
  8. import { doRequestAndSaveToFile } from '@server/helpers/requests'
  9. type GetPathParam = { videoId: string, language: string }
  10. class VideosCaptionCache extends AbstractVideoStaticFileCache <GetPathParam> {
  11. private static readonly KEY_DELIMITER = '%'
  12. private static instance: VideosCaptionCache
  13. private constructor () {
  14. super()
  15. }
  16. static get Instance () {
  17. return this.instance || (this.instance = new this())
  18. }
  19. async getFilePathImpl (params: GetPathParam) {
  20. const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(params.videoId, params.language)
  21. if (!videoCaption) return undefined
  22. if (videoCaption.isOwned()) return { isOwned: true, path: join(CONFIG.STORAGE.CAPTIONS_DIR, videoCaption.getCaptionName()) }
  23. const key = params.videoId + VideosCaptionCache.KEY_DELIMITER + params.language
  24. return this.loadRemoteFile(key)
  25. }
  26. protected async loadRemoteFile (key: string) {
  27. logger.debug('Loading remote caption file %s.', key)
  28. const [ videoId, language ] = key.split(VideosCaptionCache.KEY_DELIMITER)
  29. const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(videoId, language)
  30. if (!videoCaption) return undefined
  31. if (videoCaption.isOwned()) throw new Error('Cannot load remote caption of owned video.')
  32. // Used to fetch the path
  33. const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
  34. if (!video) return undefined
  35. const remoteUrl = videoCaption.getFileUrl(video)
  36. const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.getCaptionName())
  37. await doRequestAndSaveToFile({ uri: remoteUrl }, destPath)
  38. return { isOwned: false, path: destPath }
  39. }
  40. }
  41. export {
  42. VideosCaptionCache
  43. }