Repository navigation
Expand file tree
/
Copy pathMain.hx
More file actions
405 lines (366 loc) · 14.3 KB
/
Copy pathMain.hx
File metadata and controls
405 lines (366 loc) · 14.3 KB
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import DateTools;
import sys.io.File;
import sys.FileSystem;
import sys.thread.Thread;
import haxe.Timer;
import haxe.Http;
import haxe.Json;
import src.ProcessRecording;
import src.Recording;
import src.Config;
import src.Util;
import src.Types;
using StringTools;
using Std;
// Color codes in terminal
final COLOR_RESET = "\033[m";
final COLOR_RED = "\033[38;5;1m";
final COLOR_GREEN = "\033[38;5;2m";
// currentlyWatchedStreamers is the array of the streamers names that are currently watched, without modifiers because this list is passed to the twitch api
var currentlyWatchedStreamers:Array<String> = [];
// status contains infos about watched streamers
var status:Array<StreamerStatus> = [];
class Main {
static macro function getDefine(key:String):haxe.macro.Expr {
return macro $v{haxe.macro.Context.definedValue(key)};
}
static macro function getBuildTime() {
return macro $v{DateTools.format(Date.now(), "%Y-%m-%d at %H:%M:%S")};
}
static public function main() {
var version = getDefine("version");
var buildDate = getBuildTime();
Sys.println('Starting streamscope v${version == null ? " dev" : version} built on $buildDate');
// check if no path for the list of streamers to watch is supplied
if (Sys.args()[0] == null) return Sys.println("No path selected for the list of streamers to record.");
var listPath = Sys.args()[0];
// generate config if it does not exist
if (!FileSystem.exists("./config.json")) {
var configToWrite = File.write("./config.json");
configToWrite.writeString(freshConfig);
configToWrite.close();
Sys.println("Generated a new configuration file (config.json), you need to check and tweak the values in it before using streamscope.");
if (FileSystem.exists(listPath)) Sys.exit(0); // don't exit yet if we need to create the list.txt file
}
// generate streamers list if it does not exist
if (!FileSystem.exists(listPath)) {
File.write(listPath);
Sys.println("Generated an empty text file (list.txt) where the streamer names you want to record should be entered (1 per line).");
Sys.exit(0);
}
// parse config
try {
config = Json.parse(File.getContent("./config.json"));
} catch (e) {
Sys.println('Invalid configuration file: $e');
Sys.exit(1);
}
// check config values
for (path in [config.temp_path, config.processed_path, config.problematic_path]) {
if (!FileSystem.exists(path)) {
try {
FileSystem.createDirectory(path);
Sys.println('Created directory: $path');
} catch (e) {
return Sys.println('Failed to create directory: $path');
}
}
}
if (!Std.isOfType(config.twitch_id, String)
|| !Std.isOfType(config.twitch_secret, String)
|| config.twitch_id == ""
|| config.twitch_secret == "") {
Sys.println('Missing Twitch ID and/or secret in the config');
Sys.exit(1);
}
// check that required external tools are available
if (!isCommandAvailable("streamlink", "--version")) return Sys.println("streamlink is not installed or not in PATH.");
if (!isCommandAvailable("ffmpeg", "-version")) return Sys.println("ffmpeg is not installed or not in PATH.");
// check and process leftover streams in another thread
Thread.create(checkLeftovers);
refreshStreamers(listPath);
Sys.println("Getting Twitch client credentials...");
var credentials = getAccessToken();
if (credentials == "ERROR") {
Sys.println("Failed to get Twitch client credentials after all attempts, exiting.");
Sys.exit(1);
}
if (config.debug) trace('The Twitch access token is $credentials');
Sys.println("Got Twitch credentials!");
// main loop
var timer = new Timer(config.query_time * 1000);
timer.run = () -> {
refreshStreamers(listPath);
var twitchResponse = checkStreamersOnline(currentlyWatchedStreamers, credentials);
// twitch response array values:
// {status: "OK", ...}: List of online streamers, empty if nobody is online
// {status: "ERR_UNKNOWN"}: Unknown error
// {status: "ERR_REGEN_CREDS"}: Need to regen the credentials, got status 401
if (twitchResponse.contains({status: "ERR_REGEN_CREDS"})) {
Sys.println("Got error 401, need to regen the credentials.");
var newCredentials = getAccessToken();
if (newCredentials != "ERROR") {
credentials = newCredentials;
if (config.debug) trace('The regenerated Twitch access token is $credentials');
Sys.println("Regenerated Twitch credentials!");
} else {
Sys.println("Failed to regenerate Twitch credentials after all attempts.");
}
} else if (twitchResponse.contains({status: "ERR_UNKNOWN"})) {
Sys.println('Got an unknown error when fetching online streamers, retrying in ${config.query_time} seconds.');
} else {
// onlineStreamersNames is used to set online/offline status of the streamers in the loop
var onlineStreamersNames:Array<String> = [];
for (streamer in twitchResponse) {
onlineStreamersNames.push(streamer.user_login.toLowerCase());
for (streamerStatus in status) {
if (streamerStatus.streamer_input_username.toLowerCase() == streamer.user_login) {
if (streamerStatus.online == false) {
// if streamer just got online we start recording
streamerStatus.streamer_username = streamer.user_login;
streamerStatus.streamer_display_name = streamer.user_name;
streamerStatus.online = true;
// using UTC date
var now = Date.now();
streamerStatus.recording_since = '${now.getFullYear()}-${toTwoDigits(now.getUTCMonth() + 1)}-${toTwoDigits(now.getUTCDate())} ${toTwoDigits(now.getUTCHours())}:${toTwoDigits(now.getUTCMinutes())}:${toTwoDigits(now.getUTCSeconds())}';
streamerStatus.title = streamer.title;
streamerStatus.started_at = streamer.started_at;
streamerStatus.game_id = streamer.game_id;
streamerStatus.game_name = streamer.game_name;
streamerStatus.language = streamer.language;
streamerStatus.tag_ids = streamer.tag_ids;
streamerStatus.is_mature = streamer.is_mature;
var filename:String = startRecording(streamerStatus);
// getting the filename here to be able to send it to updateStreamInfo() when the title of the stream changes for example
streamerStatus.filename = filename;
break;
} else {
// if the streamer is already online
var path = '${config.processed_path}/${streamer.user_login}';
if (streamer.title.toString() != streamerStatus.title.toString()) {
updateStreamInfo("title", streamer.title, streamerStatus.filename, path);
streamerStatus.title = streamer.title;
}
if (streamer.game_id.toString() != streamerStatus.game_id.toString()) {
updateStreamInfo("game_id", streamer.game_id, streamerStatus.filename, path);
streamerStatus.game_id = streamer.game_id;
}
if (streamer.game_name.toString() != streamerStatus.game_name.toString()) {
updateStreamInfo("game_name", streamer.game_name, streamerStatus.filename, path);
streamerStatus.game_name = streamer.game_name;
}
break;
}
}
}
}
// mark streamers that went offline and handle cleanup
for (streamerStatus in status) {
if (streamerStatus.online == true) {
if (!onlineStreamersNames.contains(streamerStatus.streamer_username.toLowerCase())) {
streamerStatus.online = false;
if (streamerStatus.chat_thread != null) {
streamerStatus.chat_thread.sendMessage("end");
streamerStatus.chat_thread = null;
}
// streamlink thread will exit on its own after the process ends
streamerStatus.streamlink_thread = null;
}
}
}
// log current status for watched streamers
Sys.println('\n--- ${Date.now().toString()} ---');
if (status.length == 0) {
Sys.println('Nobody to watch for!');
}
for (streamer in status) {
if (streamer.online) {
var streamingSince = '${streamer.started_at.split("T")[0]} ${streamer.started_at.split("T")[1].replace("Z", "")}';
var log = '${streamer.streamer_username}: ${COLOR_GREEN}ONLINE${COLOR_RESET} since ${streamingSince}, currently on ${streamer.game_name} - ';
if (streamer.chat_only) {
log += 'Recording chat since ${streamer.recording_since}';
} else {
if (streamlinkProcesses.exists(streamer.streamer_username)) {
log += 'Recording since ${streamer.recording_since}';
} else if (!streamer.was_online) {
log += 'Not recording (starting up)';
} else {
log += 'Not recording (process may have been killed)';
}
}
Sys.println(log);
} else {
if (streamlinkProcesses.exists(streamer.streamer_username)) {
Sys.println('${streamer.streamer_input_username}: ${COLOR_RED}OFFLINE${COLOR_RESET} - Waiting for streamlink to stop...');
} else {
Sys.println('${streamer.streamer_input_username}: ${COLOR_RED}OFFLINE${COLOR_RESET}');
}
}
}
// newline
Sys.println('');
// update was_online for next tick
for (streamerStatus in status) {
streamerStatus.was_online = streamerStatus.online;
}
}
}
}
/**
* Get a Twitch OAuth access token
* @return "ERROR" or the access token itself
*/
static public function getAccessToken():String {
var maxRetries = 5;
for (attempt in 0...maxRetries) {
var result:String = null;
var twitch = new Http('https://id.twitch.tv/oauth2/token?client_id=${config.twitch_id}&client_secret=${config.twitch_secret}&grant_type=client_credentials');
twitch.onData = s -> result = Json.parse(s).access_token;
twitch.onError = e -> {
Sys.println('Error when trying to get the Twitch client credentials: $e');
result = "ERROR";
};
twitch.request(true);
if (result != "ERROR") return result;
if (attempt < maxRetries - 1) {
Sys.println('Failed to get Twitch client credentials, retrying in 10 seconds... (${attempt + 1}/$maxRetries)');
Sys.sleep(10);
}
}
return "ERROR";
}
/**
* Check if the input streamers list are online on Twitch
* @param streamers the array of streamers to check for
* @param credentials Twitch access token
* @return Array of online streamers with the data twitch sends us
*/
static public function checkStreamersOnline(streamers:Array<String>, credentials:String):Array<OnlineStreamer> {
var streamersQuery = "";
for (streamer in streamers) {
if (streamersQuery == "") {
streamersQuery += '?user_login=$streamer';
} else {
streamersQuery += '&user_login=$streamer';
}
}
var result:Array<OnlineStreamer> = [];
var twitch = new Http('https://api.twitch.tv/helix/streams$streamersQuery');
twitch.addHeader("Client-ID", config.twitch_id);
twitch.addHeader("Authorization", 'Bearer $credentials');
twitch.onData = data -> {
// here twitch sends us an array of objects in the data property of the online streamers.
// offline streamers aren't present in there.
var streamersInfo:Array<{
id:String,
user_id:String,
user_login:String,
user_name:String,
game_id:String,
game_name:String,
title:String,
started_at:String,
language:String,
tag_ids:String,
is_mature:String
}> = Json.parse(data).data;
for (streamerInfo in streamersInfo) {
result.push({
status: "OK",
stream_id: streamerInfo.id,
user_id: streamerInfo.user_id,
user_login: streamerInfo.user_login,
user_name: streamerInfo.user_name,
game_id: streamerInfo.game_id,
game_name: streamerInfo.game_name,
title: streamerInfo.title,
started_at: streamerInfo.started_at,
language: streamerInfo.language,
tag_ids: streamerInfo.tag_ids,
is_mature: streamerInfo.is_mature
});
}
}
twitch.onError = data -> {
if (data == "Http Error #401") {
result = [{status: "ERR_REGEN_CREDS"}];
} else {
Sys.println('Unknown error when trying to fetch online streamers: $data');
result = [{status: "ERR_UNKNOWN"}];
}
}
twitch.request();
return result;
}
/**
* Checks if the streamers list file changed (to call when starting the app and for each loop iteration)
* @param listPath path of the list to check for
*/
static public function refreshStreamers(listPath) {
var newWatchedStreamers:Array<String> = [];
var lines = File.getContent(listPath).split("\n");
// filter comments and empty lines (iterate in reverse to safely remove while iterating)
var i = lines.length - 1;
while (i >= 0) {
var line = lines[i];
if (line.startsWith("//") || line.trim() == "") lines.remove(line);
i--;
}
// find streamers to start watching
// every line here is a streamer name in the list, eventually with modifiers (eg chat:streamer) (NOT IMPLEMENTED)
for (line in lines) {
var isChatOnly = line.split(":")[0] == "chat" ? true : false;
var streamerInputUsername = isChatOnly ? line.split(":")[1] : line;
newWatchedStreamers.push(streamerInputUsername);
if (!currentlyWatchedStreamers.contains(streamerInputUsername)) {
Sys.println('Starting to watch for $streamerInputUsername');
status.push({
streamer_input_username: streamerInputUsername,
streamer_username: "",
streamer_display_name: "",
online: false,
was_online: false,
chat_only: isChatOnly,
recording_since: "",
filename: "",
title: "",
started_at: "",
game_id: "",
game_name: "",
language: "",
tag_ids: "",
is_mature: ""
});
}
}
// find streamers to stop watching
for (streamer in currentlyWatchedStreamers) {
if (!newWatchedStreamers.contains(streamer)) {
for (watchedStreamer in status) {
if (watchedStreamer.streamer_input_username == streamer) {
if (watchedStreamer.online == true) {
Sys.println('Stopping recording for $streamer.');
killStreamlink(watchedStreamer);
if (watchedStreamer.chat_thread != null) {
watchedStreamer.chat_thread.sendMessage("end");
watchedStreamer.chat_thread = null;
}
watchedStreamer.streamlink_thread = null;
} else {
Sys.println('Stopping to watch for $streamer.');
}
status.remove(watchedStreamer);
break;
}
}
}
}
currentlyWatchedStreamers = newWatchedStreamers;
}
static public function isCommandAvailable(command:String, versionFlag:String):Bool {
var process = new sys.io.Process(command, [versionFlag]);
var exitCode = process.exitCode(true);
process.close();
return exitCode == 0;
}
}