captions-utils.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { createReadStream, createWriteStream, move, remove } from 'fs-extra'
  2. import { join } from 'path'
  3. import srt2vtt from 'srt-to-vtt'
  4. import { Transform } from 'stream'
  5. import { MVideoCaption } from '@server/types/models'
  6. import { CONFIG } from '../initializers/config'
  7. import { pipelinePromise } from './core-utils'
  8. async function moveAndProcessCaptionFile (physicalFile: { filename: string, path: string }, videoCaption: MVideoCaption) {
  9. const videoCaptionsDir = CONFIG.STORAGE.CAPTIONS_DIR
  10. const destination = join(videoCaptionsDir, videoCaption.filename)
  11. // Convert this srt file to vtt
  12. if (physicalFile.path.endsWith('.srt')) {
  13. await convertSrtToVtt(physicalFile.path, destination)
  14. await remove(physicalFile.path)
  15. } else if (physicalFile.path !== destination) { // Just move the vtt file
  16. await move(physicalFile.path, destination, { overwrite: true })
  17. }
  18. // This is important in case if there is another attempt in the retry process
  19. physicalFile.filename = videoCaption.filename
  20. physicalFile.path = destination
  21. }
  22. // ---------------------------------------------------------------------------
  23. export {
  24. moveAndProcessCaptionFile
  25. }
  26. // ---------------------------------------------------------------------------
  27. function convertSrtToVtt (source: string, destination: string) {
  28. const fixVTT = new Transform({
  29. transform: (chunk, _encoding, cb) => {
  30. let block: string = chunk.toString()
  31. block = block.replace(/(\d\d:\d\d:\d\d)(\s)/g, '$1.000$2')
  32. .replace(/(\d\d:\d\d:\d\d),(\d)(\s)/g, '$1.00$2$3')
  33. .replace(/(\d\d:\d\d:\d\d),(\d\d)(\s)/g, '$1.0$2$3')
  34. return cb(undefined, block)
  35. }
  36. })
  37. return pipelinePromise(
  38. createReadStream(source),
  39. srt2vtt(),
  40. fixVTT,
  41. createWriteStream(destination)
  42. )
  43. }