2
1

captions-utils.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { join } from 'path'
  2. import { CONFIG } from '../initializers'
  3. import { VideoCaptionModel } from '../models/video/video-caption'
  4. import * as srt2vtt from 'srt-to-vtt'
  5. import { createReadStream, createWriteStream, remove, move } from 'fs-extra'
  6. async function moveAndProcessCaptionFile (physicalFile: { filename: string, path: string }, videoCaption: VideoCaptionModel) {
  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 { // 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. }