Skip to content

Commit

Permalink
fix(#1): 重构字幕下载逻辑
Browse files Browse the repository at this point in the history
  • Loading branch information
techmovie committed Aug 18, 2022
1 parent 00ef3f7 commit e6a4994
Show file tree
Hide file tree
Showing 3 changed files with 337 additions and 553 deletions.
31 changes: 26 additions & 5 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const axios = require('axios')
const fs = require('fs')
const vtt2srt = require('node-vtt-to-srt')

class VideoDownloader {
constructor (config) {
Expand Down Expand Up @@ -33,14 +32,15 @@ class VideoDownloader {
const fileName = `${chapterNumber}-${title}.${subtitle.language}`
console.log(`开始下载:${fileName}.vtt`)
await this.downloadFile(subtitle.link, `${fileName}.vtt`)
console.log('vtt转srt')
console.log('vtt转srt...')
try {
fs.createReadStream(`${fileName}.vtt`)
.pipe(vtt2srt())
.pipe(fs.createWriteStream(`${folderName}/${fileName}.srt`))
const source = fs.readFileSync(`${fileName}.vtt`, 'UTF-8')
const srt = this.vtt2srt(source)
fs.writeFileSync(`${folderName}/${fileName}.srt`, srt, 'UTF-8')
console.log(`格式转换成功,删除${fileName}.vtt`)
fs.unlinkSync(`${fileName}.vtt`)
} catch (error) {
console.log(error.message)
console.log(`${fileName}.vtt 格式转换失败`)
}
}
Expand Down Expand Up @@ -113,6 +113,27 @@ class VideoDownloader {
writer.on('error', reject)
})
}

vtt2srt (source) {
const vttRemoval = /(WEBVTT\s+)(\d{2}:)/mg
const itemMatcher = /((\d{2}:)?\d{2}:\d{2})\.(\d{3}\s+)-->\s+((\d{2}:)?\d{2}:\d{2})\.(\d{3}\s*)/mg
const separator = '\n'
let srtString = source.replace(vttRemoval, '$2')
let lineCounter = 0
srtString = srtString.replace(itemMatcher, function (match) {
lineCounter++
return lineCounter + separator + match.replace(itemMatcher, (match, p1, p2, p3, p4, p5, p6) => {
if (p1.split(':').length === 2) {
p1 = '00:' + p1
}
if (p4.split(':').length === 2) {
p4 = '00:' + p4
}
return `${p1},${p3} --> ${p4},${p6}`
})
})
return srtString
}
}

exports.VideoDownloader = VideoDownloader
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.21.1",
"node-vtt-to-srt": "^1.0.1"
"axios": "^0.21.1"
},
"devDependencies": {
"eslint": "^7.30.0",
Expand Down
Loading

0 comments on commit e6a4994

Please sign in to comment.