1 // Thanks: https://github.com/przemyslawpluta/node-youtube-dl/blob/master/lib/downloader.js
2 // Use rewrote it to avoid sync calls
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'
12 export class YoutubeDlUpdateScheduler extends AbstractScheduler {
14 private static instance: AbstractScheduler
16 protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.youtubeDLUpdate
18 private constructor () {
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'
28 request.get(url, { followRedirect: false }, (err, res) => {
30 logger.error('Cannot update youtube-dl.', { err })
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)
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]
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)
49 downloadFile.pipe(createWriteStream(bin, { mode: 493 }))
52 downloadFile.on('error', err => logger.error('youtube-dl update error.', { err }))
54 downloadFile.on('end', () => {
55 const details = JSON.stringify({ version: newVersion, path: bin, exec: 'youtube-dl' })
56 writeFile(detailsPath, details, { encoding: 'utf8' }, err => {
58 logger.error('youtube-dl update error: cannot write details.', { err })
62 logger.info('youtube-dl updated to version %s.', newVersion)
69 static get Instance () {
70 return this.instance || (this.instance = new this())