-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyquem.js
349 lines (295 loc) · 8.19 KB
/
yquem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/*
* Yquem
* Licensed under MIT, https://opensource.org/licenses/MIT/
*/
const fs = require('fs')
const path = require('path')
const isWithinInterval = require('date-fns/isWithinInterval')
const subDays = require('date-fns/subDays')
const http = require('http')
const https = require('https')
const BASE_URL = 'http://api.betaseries.com/'
const HEADERS = {
'X-BetaSeries-Version': '3.0',
'X-BetaSeries-Key': '0b07bc22f051'
}
const VIDEO_FORMATS = ['.avi', '.mkv', '.mp4', '.webm', '.flv', '.vob', '.ogg', '.amv']
module.exports = class Yquem {
constructor(dir, fileAge = 2) {
this.dir = dir
this.fileAge = fileAge
}
run() {
return new Promise((resolve, reject) => {
const files = Yquem.getRecentFilesFromDirectory(this.dir, this.fileAge)
if (files && files.length > 0) {
const promises = files.map(async file => {
return await Yquem.getSubtitle(file)
})
Promise.all(promises)
.then(results => {
resolve(results)
})
.catch(err => {
console.log(err)
reject(err)
})
} else {
reject('No file found !')
}
})
}
// Look for subtitles files next to a specific file
static hasSubtitle(file, options = { languages: ['en'] }) {
if (file) {
const tmp = file.split('\\')
if (Array.isArray(tmp)) {
const episodePath = path.resolve(file)
const dirpath = path.dirname(episodePath)
const filename = tmp[tmp.length - 1]
const name = Yquem.getShowName(filename)
const episode = Yquem.getShowNumber(filename)
const episodeName = Yquem.buildEpisodeName(name, episode.season, episode.episode)
let results = false
// Parse inline languages options
if (options.languages && !Array.isArray(options.languages)) {
options.languages = options.languages.split(',')
options.languages = options.languages.map(i => i.trim())
}
options.languages.map(language => {
if (fs.existsSync(path.join(`${dirpath}`, `${episodeName}.${language}.srt`))) {
results = true
}
})
return results
}
}
return false
}
static async getSubtitle(file, options = { languages: ['en'] }) {
const tmp = file.split('\\')
if (Array.isArray(tmp)) {
const episodePath = path.resolve(file)
const dirpath = path.dirname(episodePath)
const filename = tmp[tmp.length - 1]
const name = Yquem.getShowName(filename)
const episode = Yquem.getShowNumber(filename)
const episodeName = Yquem.buildEpisodeName(name, episode.season, episode.episode)
let subtitles = await Yquem.getSubtitles({
name: name,
season: episode.season,
episode: episode.episode
})
if (subtitles && subtitles.length > 0) {
// Parse inline languages options
if (options.languages && !Array.isArray(options.languages)) {
options.languages = options.languages.split(',')
options.languages = options.languages.map(code => {
code = code.trim()
switch (code) {
case 'en':
return 'VO'
case 'fr':
return 'VF'
}
})
}
subtitles = subtitles.filter(subtitle => options.languages.includes(subtitle.language))
const subtitle = subtitles[0]
if (subtitle && subtitle.url) {
const fileData = await Yquem.download(subtitle.url)
if (fileData) {
let language = subtitle.language.toLowerCase()
switch (language) {
case 'vo':
language = 'en'
break
case 'vf':
language = 'fr'
break
}
const filePath = path.join(`${dirpath}`, `${episodeName}.${language}.srt`)
subtitle.file = await Yquem.writeFile(fileData, filePath)
return { file: file, subtitle: subtitle }
}
} else {
console.error(`${episodeName} : Subtitle not found !`)
}
} else {
console.error(`${episodeName} : No subtitle found !`)
}
} else {
return false
}
}
static buildEpisodeName(name, season, number) {
if (Number(number) < 10) {
number = '0' + Number(number)
}
return `${name} - ${season}x${number}`
}
static getRecentFilesFromDirectory(dir, fileAge) {
const result = []
const files = [dir]
try {
do {
const filepath = files.pop()
const stat = fs.lstatSync(filepath)
if (stat.isDirectory()) {
fs.readdirSync(filepath).forEach(f => files.push(path.join(filepath, f)))
} else if (stat.isFile()) {
if (
isWithinInterval(new Date(stat.birthtimeMs), {
start: subDays(new Date(), fileAge),
end: new Date()
})
) {
if (VIDEO_FORMATS.includes(path.extname(filepath))) {
result.push(path.resolve(filepath))
}
}
}
} while (files.length !== 0)
return result
} catch (err) {
return new Error(err)
}
}
static async download(url) {
return new Promise((resolve, reject) => {
https
.get(url, response => {
const { statusCode } = response
if (statusCode >= 400) {
reject(`[Download subtitle] Error : ${statusCode}`)
} else {
if (statusCode === 302) {
const { headers } = response
https
.get(headers.location, response => {
let data = ''
response.on('data', chunk => {
data += chunk
})
response.on('end', () => {
resolve(data)
})
})
.on('error', err => {
reject(`[Download subtitle] Error : ${err}`)
})
} else {
let data = ''
response.on('data', chunk => {
data += chunk
})
response.on('end', () => {
resolve(data)
})
}
}
})
.on('error', err => {
reject(`[Download subtitle] Error : ${err}`)
})
})
}
static async getSubtitles(options = { name: null, season: null, episode: null }) {
const resultsShow = await this.getShow(options.name)
if (resultsShow && resultsShow.shows && resultsShow.shows.length > 0) {
const show = resultsShow.shows[0]
const resultsEpisode = await this.getEpisodeByShow(show.id, `S${options.season}E${options.episode}`)
if (resultsEpisode.episode) {
const episode = resultsEpisode.episode
if (episode && episode.subtitles && episode.subtitles.length > 0) {
return episode.subtitles
} else {
console.error(`${show.title} - S${options.season}E${options.episode} : No subtitle found !`)
}
} else {
console.error(`Episode not found : "S${options.season}E${options.episode}" !`)
}
} else {
console.error(`No show found for "${options.name}" !`)
}
}
static getShowName(filename) {
if (filename) {
let name = filename.split(' - ')
return name[0].trim()
}
return null
}
static getShowNumber(filename) {
if (filename) {
var tmp = filename.split(' - ')
if (tmp) {
tmp = tmp[tmp.length - 1].trim()
tmp = tmp.split('.')
tmp = tmp[0]
tmp = tmp.split('x')
return { season: tmp[0], episode: tmp[1] }
}
}
return null
}
static getShow(title) {
return new Promise((resolve, reject) => {
http
.get(`${BASE_URL}shows/search?title=${title}`, { headers: HEADERS }, response => {
const { statusCode } = response
if (statusCode < 400) {
let data = ''
response.on('data', chunk => {
data += chunk
})
response.on('end', () => {
resolve(JSON.parse(data))
})
} else {
reject(`[Download subtitle] Error : ${statusCode}`)
}
})
.on('error', err => {
reject(`[Download subtitle] Error : ${err}`)
})
})
}
static getEpisodeByShow(id, number) {
return new Promise((resolve, reject) => {
http
.get(
`${BASE_URL}episodes/search?show_id=${id}&number=${number}&subtitles='vf'`,
{ headers: HEADERS },
response => {
const { statusCode } = response
if (statusCode < 400) {
let data = ''
response.on('data', chunk => {
data += chunk
})
response.on('end', () => {
resolve(JSON.parse(data))
})
} else {
reject(`[Download subtitle] Error : ${statusCode}`)
}
}
)
.on('error', err => {
reject(`[Download subtitle] Error : ${err}`)
})
})
}
static writeFile(data, filenamePath) {
return new Promise((resolve, reject) => {
const uData = new Uint8Array(Buffer.from(data))
fs.writeFile(filenamePath, uData, err => {
if (err) {
reject(err)
}
resolve(filenamePath)
})
})
}
}