This repository has been archived by the owner on Mar 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.js
197 lines (171 loc) · 6.19 KB
/
index.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
const EventEmitter = require("events").EventEmitter
const execFile = require("child_process").execFile;
const fs = require("fs");
const https = require("https");
const os = require("os");
const spawn = require("child_process").spawn;
const stream = require("stream");
class YoutubeDlWrap
{
constructor(binaryPath)
{
this.progressRegex = /\[download\] *(.*) of (.*) at (.*) ETA (.*) */;
this.setBinaryPath(binaryPath ? binaryPath : "youtube-dl");
}
getBinaryPath()
{
return this.binaryPath;
}
setBinaryPath(binaryPath)
{
this.binaryPath = binaryPath;
}
static downloadLatestYoutubeDl(filePath, platform = os.platform())
{
return new Promise(async (resolve, reject) =>
{
let fileName = platform == "win32" ? "youtube-dl.exe" : "youtube-dl";
if(!filePath)
filePath = "./" + fileName;
let binaryURL = "https://youtube-dl.org/downloads/latest/" + fileName;
while(binaryURL)
{
let response = await new Promise((resolveRequest, rejectRequest) =>
https.get(binaryURL, (httpResponse) => {
httpResponse.on("error", (e) => rejectRequest(e));
resolveRequest(httpResponse);
}));
if(response.headers.location)
binaryURL = response.headers.location;
else
{
binaryURL = null
response.pipe(fs.createWriteStream(filePath));
response.on("error", (e) => reject(e));
response.on("end", () => response.statusCode == 200 ? resolve(response) : reject(response));
}
}
});
}
async getExtractors()
{
let youtubeDlStdout = await this.execPromise(["--list-extractors"]);
return youtubeDlStdout.split("\n");
}
async getExtractorDescriptions()
{
let youtubeDlStdout = await this.execPromise(["--extractor-descriptions"]);
return youtubeDlStdout.split("\n");
}
async getHelp()
{
let youtubeDlStdout = await this.execPromise(["--help"]);
return youtubeDlStdout;
}
async getUserAgent()
{
let youtubeDlStdout = await this.execPromise(["--dump-user-agent"]);
return youtubeDlStdout;
}
async getVersion()
{
let youtubeDlStdout = await this.execPromise(["--version"]);
return youtubeDlStdout;
}
async getVideoInfo(youtubeDlArguments)
{
if(typeof youtubeDlArguments == "string")
youtubeDlArguments = [youtubeDlArguments];
if(!youtubeDlArguments.includes("-f") && !youtubeDlArguments.includes("--format"))
youtubeDlArguments = youtubeDlArguments.concat(["-f", "best"]);
let youtubeDlStdout = await this.execPromise(youtubeDlArguments.concat(["--dump-json"]));
try{
return JSON.parse(youtubeDlStdout);
}
catch(e){
return JSON.parse("[" + youtubeDlStdout.replace(/\n/g, ",").slice(0, -1) + "]");
}
}
setDefaultOptions(options)
{
if(!options.maxBuffer)
options.maxBuffer = 1024 * 1024 * 1024;
return options;
}
exec(youtubeDlArguments = [], options = {})
{
options = this.setDefaultOptions(options);
const execEventEmitter = new EventEmitter();
const youtubeDlProcess = spawn(this.binaryPath, youtubeDlArguments, options);
youtubeDlProcess.stdout.on("data", (data) =>
{
let stringData = data.toString();
let parsedProgress = this.parseProgress(stringData);
if(parsedProgress)
execEventEmitter.emit("progress", parsedProgress);
execEventEmitter.emit("stdout", stringData);
});
let stderrData = "";
youtubeDlProcess.stderr.on("data", (data) =>
{
let stringData = data.toString();
stderrData += stringData;
execEventEmitter.emit("stderr", stringData);
});
let processError = "";
youtubeDlProcess.on("error", (error) => {
processError = error;
});
youtubeDlProcess.on("close", (code) => {
if(code === 0)
execEventEmitter.emit("close", code);
else
execEventEmitter.emit("error", code, processError, stderrData);
});
return execEventEmitter;
}
execPromise(youtubeDlArguments = [], options = {})
{
return new Promise( (resolve, reject) =>
{
options = this.setDefaultOptions(options);
execFile(this.binaryPath, youtubeDlArguments, options, (error, stdout, stderr) =>
{
if(error)
reject({processError: error, stderr: stderr});
resolve(stdout);
});
});
}
execStream(youtubeDlArguments = [], options = {}) {
const buffer = new stream.Transform();
options = this.setDefaultOptions(options);
youtubeDlArguments = youtubeDlArguments.concat(["-o", "-"]);
buffer._transform = function (chunk,encoding, cb){
this.push(chunk);
cb();
}
const youtubeDlProcess = spawn(this.binaryPath, youtubeDlArguments, options);
youtubeDlProcess.stdout
.pipe(buffer);
[
'close', 'disconnect', 'close', 'error', 'exit', 'message', 'spawn',
].forEach(event => {
youtubeDlProcess.prependListener(event, buffer.emit.bind(buffer, event));
});
return buffer;
}
parseProgress(progressLine)
{
let progressMatch = progressLine.match(this.progressRegex);
if(progressMatch == null)
return null;
let progressObject = {};
progressObject.percent = parseFloat(progressMatch[1].replace("%", ""));
progressObject.totalSize = progressMatch[2].replace("~", "");
progressObject.currentSpeed = progressMatch[3];
progressObject.eta = progressMatch[4];
return progressObject;
}
}
module.exports = YoutubeDlWrap;