73b6d166d978915da7de8b0dcffbceb5d49a3f71
[oweals/peertube.git] / server / helpers / captions-utils.ts
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/typings/models'
6
7 async function moveAndProcessCaptionFile (physicalFile: { filename: string, path: string }, videoCaption: MVideoCaptionFormattable) {
8   const videoCaptionsDir = CONFIG.STORAGE.CAPTIONS_DIR
9   const destination = join(videoCaptionsDir, videoCaption.getCaptionName())
10
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
19   // This is important in case if there is another attempt in the retry process
20   physicalFile.filename = videoCaption.getCaptionName()
21   physicalFile.path = destination
22 }
23
24 // ---------------------------------------------------------------------------
25
26 export {
27   moveAndProcessCaptionFile
28 }
29
30 // ---------------------------------------------------------------------------
31
32 function convertSrtToVtt (source: string, destination: string) {
33   return new Promise((res, rej) => {
34     const file = createReadStream(source)
35     const converter = srt2vtt()
36     const writer = createWriteStream(destination)
37
38     for (const s of [ file, converter, writer ]) {
39       s.on('error', err => rej(err))
40     }
41
42     return file.pipe(converter)
43                .pipe(writer)
44                .on('finish', () => res())
45   })
46 }