]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/helpers/captions-utils.ts
Prevent caption listing of private videos
[github/Chocobozzz/PeerTube.git] / server / helpers / captions-utils.ts
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
9 async function moveAndProcessCaptionFile (physicalFile: { filename: string, path: string }, videoCaption: MVideoCaption) {
10 const videoCaptionsDir = CONFIG.STORAGE.CAPTIONS_DIR
11 const destination = join(videoCaptionsDir, videoCaption.filename)
12
13 // Convert this srt file to vtt
14 if (physicalFile.path.endsWith('.srt')) {
15 await convertSrtToVtt(physicalFile.path, destination)
16 await remove(physicalFile.path)
17 } else if (physicalFile.path !== destination) { // Just move the vtt file
18 await move(physicalFile.path, destination, { overwrite: true })
19 }
20
21 // This is important in case if there is another attempt in the retry process
22 physicalFile.filename = videoCaption.filename
23 physicalFile.path = destination
24 }
25
26 // ---------------------------------------------------------------------------
27
28 export {
29 moveAndProcessCaptionFile
30 }
31
32 // ---------------------------------------------------------------------------
33
34 function convertSrtToVtt (source: string, destination: string) {
35 const fixVTT = new Transform({
36 transform: (chunk, _encoding, cb) => {
37 let block: string = chunk.toString()
38
39 block = block.replace(/(\d\d:\d\d:\d\d)(\s)/g, '$1.000$2')
40 .replace(/(\d\d:\d\d:\d\d),(\d)(\s)/g, '$1.00$2$3')
41 .replace(/(\d\d:\d\d:\d\d),(\d\d)(\s)/g, '$1.0$2$3')
42
43 return cb(undefined, block)
44 }
45 })
46
47 return pipelinePromise(
48 createReadStream(source),
49 srt2vtt(),
50 fixVTT,
51 createWriteStream(destination)
52 )
53 }