-
Notifications
You must be signed in to change notification settings - Fork 9
/
Stream.js
89 lines (78 loc) · 2.23 KB
/
Stream.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
const { spawn, exec } = require('child_process');
const EventEmitter = require('events').EventEmitter;
const fs = require('fs-extra');
const kill = require('tree-kill');
class Streamlink extends EventEmitter {
constructor(stream) {
super();
this.stream = stream;
}
output(loc) {
this.outputLoc = loc;
return this;
}
quality(qual) {
this.qual = qual;
return this;
}
isLive(done) {
exec('streamlink -j ' + this.stream, (err, stdout, stderr) => {
var json = JSON.parse(stdout);
if (json.error);
else {
this.qualities = Object.keys(json['streams']);
done(true);
}
});
}
start(done) {
if (this.outputLoc && fs.existsSync(this.outputLoc)) {
this.emit('err', 'File already exists.');
return this;
}
this.isLive(live => {
if (!live) {
this.emit('err', 'Is not live.');
return;
}
var args = [];
if (this.outputLoc) {
args.push('-o');
args.push(this.outputLoc);
}
args.push(this.stream);
args.push(this.qual || 'best');
this.startTime = Math.floor(Date.now() / 1000);
this.live = spawn('streamlink', args);
this.live.stdout.on('data', (d) => {
this.emit('log', d.toString());
});
this.live.on('close', (code, st) => this.end(code, st));
});
return this;
}
live() {
return this;
}
end(code, st) {
console.log(code, st);
var endO = {
exitCode: code,
duration: Math.floor(Date.now() / 1000) - this.startTime,
output: this.outputLoc,
startTime: this.startTime,
stream: this.stream
};
this.emit('end', endO);
if (this.live) kill(this.live.pid);
return endO;
}
getQualities() {
this.isLive(live => {
this.emit('quality', this.qualities);
return this;
});
this.emit('err', 'Stream is not live.');
}
}
module.exports = Streamlink;