videos-preview-cache.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { join } from 'path'
  2. import { FILES_CACHE } from '../../initializers/constants'
  3. import { VideoModel } from '../../models/video/video'
  4. import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
  5. import { doRequestAndSaveToFile } from '@server/helpers/requests'
  6. class VideosPreviewCache extends AbstractVideoStaticFileCache <string> {
  7. private static instance: VideosPreviewCache
  8. private constructor () {
  9. super()
  10. }
  11. static get Instance () {
  12. return this.instance || (this.instance = new this())
  13. }
  14. async getFilePathImpl (videoUUID: string) {
  15. const video = await VideoModel.loadByUUID(videoUUID)
  16. if (!video) return undefined
  17. if (video.isOwned()) return { isOwned: true, path: video.getPreview().getPath() }
  18. return this.loadRemoteFile(videoUUID)
  19. }
  20. protected async loadRemoteFile (key: string) {
  21. const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(key)
  22. if (!video) return undefined
  23. if (video.isOwned()) throw new Error('Cannot load remote preview of owned video.')
  24. const preview = video.getPreview()
  25. const destPath = join(FILES_CACHE.PREVIEWS.DIRECTORY, preview.filename)
  26. const remoteUrl = preview.getFileUrl(video)
  27. await doRequestAndSaveToFile({ uri: remoteUrl }, destPath)
  28. return { isOwned: false, path: destPath }
  29. }
  30. }
  31. export {
  32. VideosPreviewCache
  33. }