captions-utils.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { join } from 'path'
  2. import { CONFIG } from '../initializers/config'
  3. import * as srt2vtt from 'srt-to-vtt'
  4. import { createReadStream, createWriteStream, move, remove } from 'fs-extra'
  5. import { MVideoCaptionFormattable } from '@server/types/models'
  6. async function moveAndProcessCaptionFile (physicalFile: { filename: string, path: string }, videoCaption: MVideoCaptionFormattable) {
  7. const videoCaptionsDir = CONFIG.STORAGE.CAPTIONS_DIR
  8. const destination = join(videoCaptionsDir, videoCaption.getCaptionName())
  9. // Convert this srt file to vtt
  10. if (physicalFile.path.endsWith('.srt')) {
  11. await convertSrtToVtt(physicalFile.path, destination)
  12. await remove(physicalFile.path)
  13. } else if (physicalFile.path !== destination) { // Just move the vtt file
  14. await move(physicalFile.path, destination, { overwrite: true })
  15. }
  16. // This is important in case if there is another attempt in the retry process
  17. physicalFile.filename = videoCaption.getCaptionName()
  18. physicalFile.path = destination
  19. }
  20. // ---------------------------------------------------------------------------
  21. export {
  22. moveAndProcessCaptionFile
  23. }
  24. // ---------------------------------------------------------------------------
  25. function convertSrtToVtt (source: string, destination: string) {
  26. return new Promise((res, rej) => {
  27. const file = createReadStream(source)
  28. const converter = srt2vtt()
  29. const writer = createWriteStream(destination)
  30. for (const s of [ file, converter, writer ]) {
  31. s.on('error', err => rej(err))
  32. }
  33. return file.pipe(converter)
  34. .pipe(writer)
  35. .on('finish', () => res())
  36. })
  37. }