forked from IBM/rotisserie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
340 lines (310 loc) · 10.6 KB
/
app.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
#!/usr/bin/env node
// built-in requirements
const fs = require("fs");
const path = require("path");
// external dependencies
const express = require("express");
const request = require("request");
const Log = require("log");
const log = new Log("info");
const FFMpeg = require("fluent-ffmpeg");
const gm = require("gm").subClass({imageMagick: true});
const {spawn} = require("child_process");
// construct express app
const app = express();
// setup global list
let currentStream = {
"stream_name": "foo",
"alive": 100,
"updated": (new Date()).toJSON(),
"stream_url": "https://example.com",
};
let allStreams = [currentStream];
/**
* Ensures given filesystem directory if it does not exist.
* @param {string} dirPath - Relative or absolute path to
* desired directory.
*/
function ensureDir(dirPath) {
const parts = dirPath.split(path.sep);
const mkdirSync = function(dirPath) {
try {
fs.mkdirSync(dirPath);
} catch (err) {
if (err.code !== "EEXIST") throw err;
}
};
for (let i = 1; i <= parts.length; i++) {
mkdirSync(path.join.apply(null, parts.slice(0, i)));
}
}
/**
* Gets list of PUBG streams from Twitch API v5.
* @callback {object} body - JSON object from Twitch API call. Contains list
* of English language PUBG streams and their associated metadata.
* @param {requestCallback} callback - The callback that handles the response.
*/
function listStreams(callback) {
let clientID = process.env.clientID;
let whitelist = process.env.ROTISSERIE_WHITELIST;
let blacklist = process.env.ROTISSERIE_BLACKLIST;
let gameURL = "https://api.twitch.tv/kraken/streams?game=PLAYERUNKNOWN'S+BATTLEGROUNDS&language=en&stream_type=live&limit=20";
let options = {
url: gameURL,
headers: {
"Client-ID": clientID,
},
};
request(options, function(error, response, body) {
if (body === undefined || body === null) {
log.error("No response from Twitch.");
if (error) {
log.error(" " + error);
}
return Array([]);
}
if (error) log.error("error:", error);
log.info("statusCode:", response.statusCode);
bodyJSON = JSON.parse(body);
allAgesStreams = bodyJSON.streams.filter(function(d) {
return d.channel.mature === false;
});
if (whitelist !== null && whitelist !== undefined) {
whitelist = whitelist.split(" ");
allAgesStreams = allAgesStreams.filter(function(d) {
return whitelist.includes(d.channel.name);
});
}
if (blacklist !== null && blacklist !== undefined) {
blacklist = blacklist.split(" ");
allAgesStreams = allAgesStreams.filter(function(d) {
return !blacklist.includes(d.channel.name);
});
}
usernameList = allAgesStreams.map(function(d) {
return d.channel["display_name"];
});
log.info(usernameList);
return callback(usernameList);
});
}
/**
* Records short clip of each stream gathered in listStreams.
* @param {object} options - object of other params
* @param {string} streamName - name of stream to record.
* @param {string} clipsDir - Relative path to directory containing short
* recorded clips of each stream in streamsList.
* @return {promise} - A promise that resolves if a stream is recorded.
*/
function recordStream(options) {
return new Promise((resolve, reject) => {
log.info("recording clip of stream: " + options.streamName);
const child = spawn("livestreamer", ["--yes-run-as-root", "-Q", "-f",
"--twitch-oauth-token", process.env.token,
"twitch.tv/" + options.streamName, "720p", "-o",
options.clipsDir + options.streamName + ".mp4"]);
setTimeout(function() {
child.kill("SIGINT");
log.info("recorded stream: " + options.streamName);
resolve(options);
}, 4000);
});
}
/**
* Takes screenshots of all clips recorded in recordStreams.
* @param {object} options - object of other params
* @param {string} streamName - name of stream's clip to screenshot.
* @param {string} clipsDir - Relative path to directory containing short
* recorded clips of each stream in streamsList.
* @param {string} thumbnailsDir - Relative path to directory containing
* screenshots of each clip recorded in recordStreams.
* @return {promise} - a promise that resolves if a screenshot is taken.
*/
function takeScreenshot(options) {
return new Promise((resolve, reject) => {
if (fs.existsSync(options.clipsDir + options.streamName + ".mp4")) {
log.info("taking screenshot of stream: " + options.streamName);
new FFMpeg(options.clipsDir + options.streamName + ".mp4")
.takeScreenshots({
timestamps: [0],
folder: options.thumbnailsDir,
filename: options.streamName + ".png",
})
.on("end", function() {
resolve(options);
})
.on("error", function(err) {
fs.unlinkSync(options.clipsDir + options.streamName + ".mp4");
log.info("Deleted " + options.clipsDir
+ options.streamName + ".mp4");
reject(new Error("An error occurred: " + err.message));
});
} else {
reject(new Error("File " + options.clipsDir
+ options.streamName + ".mp4 not found."));
}
});
}
/**
* Crops all screenshots taken in takeScreenshot to just the area containing
* the number of players alive in-game.
* @param {object} options - object of other params
* @param {string} streamName - name of stream's screenshot to crop.
* @param {string} thumbnailsDir - Relative path to directory containing
* screenshots of each clip recorded in recordStream.
* @param {string} cropsDir - Relative path to directory containing cropped
* versions of all screenshots taken in takeScreenshot.
* @return {promise} - a promise which resolves if a screenshot is cropped.
*/
function cropScreenshot(options) {
return new Promise((resolve, reject) => {
log.info("cropping screenshot of stream: " + options.streamName);
if (fs.existsSync(options.thumbnailsDir + options.streamName + ".png")) {
gm(options.thumbnailsDir + options.streamName + ".png")
.crop(22, 22, 1190, 20)
.type("Grayscale")
.write(options.cropsDir + options.streamName + ".png", function(err) {
resolve(options);
if (err) reject(err);
});
log.info("cropped screenshot of: " + options.streamName);
} else {
reject(new Error(options.streamName + ": input file not found"));
}
});
}
/**
* OCR the data (via web request)
* Uses the rotisserie-ocr microservice
* @param {object} options - object of other params
* @return {promise} - a promise that is resolved if the a screenshot is ocr'd
* successfully.
*/
function ocrCroppedShot(options) {
return new Promise((resolve, reject) => {
let formData = {
image: fs.createReadStream(__dirname
+ options.cropsDir.replace(".", "")
+ options.streamName + ".png"),
};
// k8s injects the following variables
// ROTISSERIE_OCR_SERVICE_HOST=10.10.10.65
// ROTISSERIE_OCR_SERVICE_PORT=3001
let requestOptions = {
url: "http://" + process.env.ROTISSERIE_OCR_SERVICE_HOST + ":" + process.env.ROTISSERIE_OCR_SERVICE_PORT + "/process_pubg",
formData: formData,
};
request.post(requestOptions, function(err, httpResponse, body) {
if (err) {
console.error("upload failed");
reject(err);
} else {
let parsed = JSON.parse(body);
let object = {};
object.name = options.streamName;
object.alive = parsed.number;
resolve(object);
}
});
});
}
/**
* Runner for listing streams and firing up a worker for each of those streams
* to handle the stream processing.
* @param {string} cropsDir - path to directory containing cropped thumbnails
* containing the number of players alive.
*/
function updateStreamsList(cropsDir) {
// get list of twitch streams and record each one
listStreams(function(response) {
let streamsList = response;
log.info(streamsList.length);
let array = [];
let newAllStreams = [];
for (let stream in streamsList) {
let streamName = streamsList[stream];
const data = {
streamName: streamName,
clipsDir: "./streams/clips/",
thumbnailsDir: "./streams/thumbnails/",
cropsDir: "./streams/crops/",
};
recordStream(data)
.then(takeScreenshot)
.then(cropScreenshot)
.then(ocrCroppedShot)
.then(function(streamobj) {
log.info(streamobj.name + " = " + streamobj.alive + " alive.");
array.push(streamobj);
}).catch((error) => {
log.error(error.message);
});
}
setTimeout(function() {
array.sort(function(a, b) {
return a.alive - b.alive;
});
if (array.length > 0) {
log.info(array);
log.info("lowest stream: " + array[0].name);
currentStream = streamToObject(array[0]);
for (let idx in array) {
newAllStreams.push(streamToObject(array[idx]));
}
allStreams = newAllStreams;
} else {
log.error("Empty array, not switching");
}
}, 25000);
});
}
/**
Sets webpage to stream with lowest number of players alive, determined by
* getLowestStream.
* @param {object} stream - object containing name of string and number of
* players alive.
* @return {object} object - stream object containing stream metadata.
*/
function streamToObject(stream) {
object = {};
object["stream_name"] = stream.name;
object["alive"] = stream.alive;
object["stream_url"] = "https://player.twitch.tv/?channel=" + stream.name;
object["updated"] = (new Date()).toJSON();
return object;
}
/**
* Runs logic to get lowest stream and starts express app server.
*/
function main() {
const clipsDir = "./streams/clips/";
const thumbnailsDir = "./streams/thumbnails/";
const cropsDir = "./streams/crops/";
ensureDir(clipsDir);
ensureDir(thumbnailsDir);
ensureDir(cropsDir);
// init website with lowest stream.
updateStreamsList(cropsDir);
// continue searching for lowest stream every 30 seconds.
setInterval(function() {
updateStreamsList(cropsDir);
}, 30000);
// serve index.html
app.get("/", function(req, res) {
res.sendFile(__dirname + "/public/index.html");
});
// serve current leader stream object
app.get("/current", function(req, res) {
res.json(currentStream);
});
// serve all stream objects
app.get("/all", function(req, res) {
res.json(allStreams);
});
app.use(express.static("public"));
// start http server and log success
app.listen(3000, function() {
log.info("Example app listening on port 3000!");
});
}
main();