videos-caption-cache.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 { fetchRemoteVideoStaticFile } from '../activitypub'
  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. // FIXME: use URL
  36. const remoteStaticPath = videoCaption.getCaptionStaticPath()
  37. const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.getCaptionName())
  38. await fetchRemoteVideoStaticFile(video, remoteStaticPath, destPath)
  39. return { isOwned: false, path: destPath }
  40. }
  41. }
  42. export {
  43. VideosCaptionCache
  44. }