]>
Commit | Line | Data |
---|---|---|
ce32426b | 1 | // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js |
299474e8 | 2 | // We rewrote it to avoid sync calls |
ce32426b C |
3 | |
4 | import { AbstractScheduler } from './abstract-scheduler' | |
5 | import { SCHEDULER_INTERVALS_MS } from '../../initializers' | |
6 | import { logger } from '../../helpers/logger' | |
7 | import * as request from 'request' | |
8 | import { createWriteStream, writeFile } from 'fs' | |
9 | import { join } from 'path' | |
10 | import { root } from '../../helpers/core-utils' | |
11 | ||
12 | export class YoutubeDlUpdateScheduler extends AbstractScheduler { | |
13 | ||
14 | private static instance: AbstractScheduler | |
15 | ||
16 | protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.youtubeDLUpdate | |
17 | ||
18 | private constructor () { | |
19 | super() | |
20 | } | |
21 | ||
22 | async execute () { | |
23 | const binDirectory = join(root(), 'node_modules', 'youtube-dl', 'bin') | |
24 | const bin = join(binDirectory, 'youtube-dl') | |
25 | const detailsPath = join(binDirectory, 'details') | |
26 | const url = 'https://yt-dl.org/downloads/latest/youtube-dl' | |
27 | ||
28 | request.get(url, { followRedirect: false }, (err, res) => { | |
29 | if (err) { | |
30 | logger.error('Cannot update youtube-dl.', { err }) | |
31 | return | |
32 | } | |
33 | ||
34 | if (res.statusCode !== 302) { | |
35 | logger.error('youtube-dl update error: did not get redirect for the latest version link. Status %d', res.statusCode) | |
36 | return | |
37 | } | |
38 | ||
39 | const url = res.headers.location | |
40 | const downloadFile = request.get(url) | |
41 | const newVersion = /yt-dl\.org\/downloads\/(\d{4}\.\d\d\.\d\d(\.\d)?)\/youtube-dl/.exec(url)[1] | |
42 | ||
43 | downloadFile.on('response', res => { | |
44 | if (res.statusCode !== 200) { | |
45 | logger.error('Cannot update youtube-dl: new version response is not 200, it\'s %d.', res.statusCode) | |
46 | return | |
47 | } | |
48 | ||
49 | downloadFile.pipe(createWriteStream(bin, { mode: 493 })) | |
50 | }) | |
51 | ||
52 | downloadFile.on('error', err => logger.error('youtube-dl update error.', { err })) | |
53 | ||
54 | downloadFile.on('end', () => { | |
55 | const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' }) | |
56 | writeFile(detailsPath, details, { encoding: 'utf8' }, err => { | |
57 | if (err) { | |
58 | logger.error('youtube-dl update error: cannot write details.', { err }) | |
59 | return | |
60 | } | |
61 | ||
62 | logger.info('youtube-dl updated to version %s.', newVersion) | |
63 | }) | |
64 | }) | |
65 | ||
66 | }) | |
67 | } | |
68 | ||
69 | static get Instance () { | |
70 | return this.instance || (this.instance = new this()) | |
71 | } | |
72 | } |