forked from horacio9a/mfc-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
770 lines (602 loc) · 25.1 KB
/
Copy pathmain.js
File metadata and controls
770 lines (602 loc) · 25.1 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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
// MyFreeCams Recorder v.1.0.9
'use strict';
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var mvAsync = Promise.promisify(require('mv'));
var mkdirp = require('mkdirp');
var moment = require('moment');
var colors = require('colors');
var yaml = require('js-yaml');
var path = require('path');
var spawn = require('child_process').spawn;
var HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher();
var http = require('http');
var WebSocketClient = require('websocket').client;
var bhttp = require('bhttp');
var _ = require('underscore');
var config = yaml.safeLoad(fs.readFileSync('config.yml', 'utf8'));
config.captureDirectory = config.captureDirectory || 'C:/Videos/MFC';
config.createModelDirectory = config.createModelDirectory || false;
config.directoryFormat = config.directoryFormat || 'id+nm';
config.dateFormat = config.dateFormat || 'DDMMYYYY-HHmmss';
config.downloadProgram = config.downloadProgram || 'ls';
config.modelScanInterval = config.modelScanInterval || 30;
config.minFileSizeMb = config.minFileSizeMb || 0;
config.port = config.port || 8888;
config.debug = config.debug || true;
config.includeModels = Array.isArray(config.includeModels) ? config.includeModels : [];
config.excludeModels = Array.isArray(config.excludeModels) ? config.excludeModels : [];
config.deleteModels = Array.isArray(config.deleteModels) ? config.deleteModels : [];
config.includeUids = Array.isArray(config.includeUids) ? config.includeUids : [];
config.excludeUids = Array.isArray(config.excludeUids) ? config.excludeUids : [];
config.deleteUids = Array.isArray(config.deleteUids) ? config.deleteUids : [];
var captureDirectory = path.resolve(config.captureDirectory);
var minFileSize = config.minFileSizeMb * 1048576;
function getCurrentDateTime() {
return moment().format(config.dateFormat);
};
function getCurrentTime() {
return moment().format('HH:mm:ss');
};
function printMsg(msg) {
console.log(colors.gray(`[` + getCurrentTime() + `]`), msg);
};
function printErrorMsg(msg) {
console.log(colors.gray(`[` + getCurrentTime() + `]`), colors.red(`[ERROR]`), msg);
};
function printDebugMsg(msg) {
if (config.debug && msg) {
console.log(colors.gray(`[` + getCurrentTime() + `]`), colors.magenta(`[DEBUG]`), msg);
};
};
function getTimestamp() {
return Math.floor(new Date().getTime() / 1000);
};
function dumpModelsCurrentlyCapturing() {
_.each(modelsCurrentlyCapturing, function(m) {
printMsg(`>>> ${colors.cyan(m.filename)} @ ${colors.yellow(config.downloadProgram)} recording <<<`);
});
};
function getUid(nm) {
var onlineModel = _.findWhere(onlineModels, {nm: nm});
return _.isUndefined(onlineModel) ? false : onlineModel.uid;
}
function remove(value, array) {
var idx = array.indexOf(value);
if (idx != -1) {
array.splice(idx, 1);
}
}
// returns true, if the mode has been changed
function setMode(uid, mode) {
var configModel = _.findWhere(config.models, {uid: uid});
if (_.isUndefined(configModel)) {
config.models.push({uid: uid, mode: mode});
return true;
} else if (configModel.mode != mode) {
configModel.mode = mode;
return true;
}
return false;
}
function getFileno() {
return new Promise(function(resolve, reject) {
var client = new WebSocketClient();
client.on('connectFailed', function(err) {
reject(err);
});
client.on('connect', function(connection) {
connection.on('error', function(err) {
reject(err);
});
connection.on('message', function(message) {
if (message.type === 'utf8') {
var parts = /%22opts%22:([0-9]*),%22respkey%22:([0-9]*),%22serv%22:([0-9]*),%22type%22:([0-9]*)\}/.exec(message.utf8Data);
if (parts && parts[1] && parts[2] && parts[3] && parts[4]) {
connection.close();
resolve(`respkey=${parts[2]}&type=${parts[4]}&opts=${parts[1]}&serv=${parts[3]}`);
}
}
});
connection.sendUTF("hello fcserver\n\0");
connection.sendUTF("1 0 0 20071025 0 guest:guest\n\0");
});
var servers = ["xchat20","xchat22","xchat23","xchat24","xchat25","xchat26","xchat27","xchat28","xchat29","xchat39",
"xchat62","xchat63","xchat64","xchat65","xchat66","xchat67","xchat68","xchat69","xchat70","xchat71",
"xchat72","xchat73","xchat74","xchat75","xchat76","xchat77","xchat78","xchat79","xchat80","xchat81",
"xchat83","xchat84","xchat85","xchat86","xchat87","xchat88","xchat89","xchat91","xchat94","xchat95",
"xchat96","xchat97","xchat98","xchat99","xchat100","xchat101","xchat102","xchat103","xchat104","xchat105",
"xchat106","xchat108","xchat109","xchat111","xchat100","xchat101","xchat102","xchat103","xchat104","xchat105",
"xchat106","xchat108","xchat109","xchat111","xchat112","xchat113","xchat114","xchat115","xchat116","xchat118",
"xchat119","xchat120","xchat121","xchat122","xchat123","xchat124","xchat125","xchat126","xchat127",
"ychat30","ychat31","ychat32","ychat33"];
var server = _.sample(servers); // pick a random chat server
printDebugMsg(`>>> ${colors.gray(`Start searching new models on server`)} ${colors.green(server)} <<<`);
client.connect('ws://' + server + '.myfreecams.com:8080/fcsl','','http://' + server + '.myfreecams.com:8080',{Cookie: 'company_id=3149; guest_welcome=1; history=7411522,5375294'})
}).timeout(20000); // 20 secs
}
function getOnlineModels(fileno) {
var url = `http://www.myfreecams.com/php/FcwExtResp.php?${fileno}`;
// printDebugMsg(`>>> ${colors.gray(fileno)} <<<`);
return Promise
.try(function() {
return session.get(url);
})
.then(function(response) {
onlineModels = [];
try {
var data = JSON.parse(response.body.toString('utf8'));
var m;
for (var i = 1; i < data.rdata.length; i += 1) {
m = data.rdata[i];
onlineModels.push({
nm: m[0],
sid:m[1],
uid:m[2],
vs:m[3],
pid:m[4],
lv:m[5],
camserv:m[6],
phase:m[7],
creation:m[11],
photos:m[14],
blurb:m[15],
new_model:m[16],
missmfc:m[17],
camscore:m[18],
continent: m[19],
flags:m[20],
rank:m[21],
rc:m[22],
topic:m[23]
});
}
} catch (err) {
throw new Error(`Failed to parse data.`);
}
printMsg(`${colors.green(onlineModels.length)} models online.`);
})
.timeout(20000); // 20 secs
};
function selectMyModels() {
return Promise
.try(function() {
printDebugMsg(`${config.models.length} models in ${colors.yellow(`config.`)}`);
// to include the model only knowing her name, we need to know her uid,
// if we could not find model's uid in array of online models we skip this model till the next iteration
config.includeModels = _.filter(config.includeModels, function(nm) {
var uid = getUid(nm);
if (uid === false) {
return true; // keep the model till the next iteration
}
config.includeUids.push(uid);
dirty = true;
});
config.excludeModels = _.filter(config.excludeModels, function(nm) {
var uid = getUid(nm);
if (uid === false) {
return true; // keep the model till the next iteration
}
config.excludeUids.push(uid);
dirty = true;
});
config.deleteModels = _.filter(config.deleteModels, function(nm) {
var uid = getUid(nm);
if (uid === false) {
return true; // keep the model till the next iteration
}
config.deleteUids.push(uid);
dirty = true;
});
_.each(config.includeUids, function(uid) {
dirty = setMode(uid, 1) || dirty;
});
config.includeUids = [];
_.each(config.excludeUids, function(uid) {
dirty = setMode(uid, 0) || dirty;
});
config.excludeUids = [];
_.each(config.deleteUids, function(uid) {
dirty = setMode(uid, -1) || dirty;
});
config.deleteUids = [];
// remove duplicates
if (dirty) {
config.models = _.uniq(config.models, function(m) {
return m.uid;
});
}
var myModels = [];
_.each(config.models, function(configModel) {
var onlineModel = _.findWhere(onlineModels, {uid: configModel.uid});
if (!_.isUndefined(onlineModel)) {
// if the model does not have a name in config.models we use her name by default
if (!configModel.nm) {
configModel.nm = onlineModel.nm;
dirty = true;
}
onlineModel.mode = configModel.mode;
if (onlineModel.mode == 1) {
if (onlineModel.vs === 0) {
myModels.push(onlineModel);
} else if (onlineModel.vs === 2) {
printMsg(colors.green(`${onlineModel.nm} ${colors.cyan(`is Away.`)}`));
} else if (onlineModel.vs === 12) {
printMsg(colors.green(`${onlineModel.nm} ${colors.cyan(`is in Private.`)}`));
} else if (onlineModel.vs === 13) {
printMsg(colors.green(`${onlineModel.nm} ${colors.cyan(`is in Group Show.`)}`));
} else if (onlineModel.vs === 14) {
printMsg(colors.green(`${onlineModel.nm} ${colors.cyan(`is in Club Show.`)}`));
} else if (onlineModel.vs === 90) {
printMsg(colors.green(`${onlineModel.nm} ${colors.cyan(`is Cam Off.`)}`));
}
}
}
});
printDebugMsg(`${myModels.length} model(s) to recording.`);
if (dirty) {
printDebugMsg(`Save changes in ${colors.yellow('config.')}`);
fs.writeFileSync('config.yml', yaml.safeDump(config), 'utf8');
dirty = false;
}
return myModels;
});
}
function createCaptureProcess(model) {
var modelCurrentlyCapturing = _.findWhere(modelsCurrentlyCapturing, {uid: model.uid});
if (!_.isUndefined(modelCurrentlyCapturing)) {
return; // resolve immediately
}
if ((model.camserv) < 840) {
printDebugMsg(colors.green(model.nm) + (colors.cyan(` is NO MOBILE FEED - Exclude or Delete this model`)));
return;} // resolve immediately
if (model.phase == 'a') {
printDebugMsg(colors.green(model.nm) + (colors.cyan(` is HD model - use v.3.0.9 for recording HD models`)));
return;} // resolve immediately
var fileFormat;
if (config.downloadProgram == 'ls') {
fileFormat = 'mp4'}
if (config.downloadProgram == 'sl') {
fileFormat = 'mp4'}
if (config.downloadProgram == 'ff-ts') {
fileFormat = 'ts'}
if (config.downloadProgram == 'ff-flv') {
fileFormat = 'flv'}
if (config.downloadProgram == 'hls') {
fileFormat = 'mp4'}
if (config.downloadProgram == 'rtmp') {
fileFormat = 'flv'}
var dlProgram;
if (config.downloadProgram == 'ls') {
dlProgram = config.livestreamer}
if (config.downloadProgram == 'sl') {
dlProgram = config.streamlink}
if (config.downloadProgram == 'ff-ts') {
dlProgram = config.ffmpeg}
if (config.downloadProgram == 'ff-flv') {
dlProgram = config.ffmpeg}
if (config.downloadProgram == 'hls') {
dlProgram = config.hlsdl}
if (config.downloadProgram == 'rtmp') {
dlProgram = config.mfcd}
printMsg(colors.green(model.nm) + ` now online >>> Starting ${colors.yellow(config.downloadProgram)} recording <<<`);
return Promise
.try(function() {
var filename = model.nm + '_MFC_' + getCurrentDateTime() + '.' + fileFormat;
var modelDir;
if (config.directoryFormat == 'id+nm') {
modelDir = model.uid + '_' + model.nm}
if (config.directoryFormat == 'id') {
modelDir = (model.uid).toString()}
if (config.directoryFormat == 'nm') {
modelDir = model.nm}
if (config.directoryFormat == 'nm+id') {
modelDir = model.nm + '_' + model.uid}
function mkdir(dir) {
mkdirp(dir, err => {
if (err) {
printErrorMsg(err);
process.exit(1);
}
});
}
var src = path.join(captureDirectory, filename);
var roomId = 100000000 + model.uid;
var sdUrl = `http://video${model.camserv - 500}.myfreecams.com:1935/NxServer/ngrp:mfc_${roomId}.f4v_mobile/playlist.m3u8?nc=${Date.now()}`;
var captureProcess;
if (config.downloadProgram == 'ls') {
captureProcess = spawn(dlProgram, ['-Q','hlsvariant://' + sdUrl,'best','--stream-sorting-excludes=>950p,>1500k','-o', src])};
if (config.downloadProgram == 'sl') {
captureProcess = spawn(dlProgram, ['-Q','hls://' + sdUrl,'best','--stream-sorting-excludes=>950p,>1500k','-o', src])};
if (config.downloadProgram == 'ff-ts') {
captureProcess = spawn(dlProgram, ['-hide_banner','-v','fatal','-i',sdUrl,'-map','0:1','-map','0:2','-c','copy','-vsync','2','-r','60','-b:v','500k', src])};
if (config.downloadProgram == 'ff-flv') {
captureProcess = spawn(dlProgram, ['-hide_banner','-v','fatal','-i',sdUrl,'-c:v','copy','-map','0:1','-map','0:2','-c:a','aac','-b:a','192k','-ar','32000', src])};
if (config.downloadProgram == 'hls') {
captureProcess = spawn(dlProgram, [sdUrl,'-b','-q','-o', src])};
if (config.downloadProgram == 'rtmp') {
captureProcess = spawn(dlProgram, [model.nm, src])};
captureProcess.stdout.on('data', function(data) {
printMsg(data.toString());
});
captureProcess.stderr.on('data', function(data) {
printMsg(data.toString());
});
captureProcess.on('close', function(code) {
printMsg(`${colors.green(model.nm)} <<< stopped recording.`);
var modelCurrentlyCapturing = _.findWhere(modelsCurrentlyCapturing, {
pid: captureProcess.pid});
if (!_.isUndefined(modelCurrentlyCapturing)) {
var modelIndex = modelsCurrentlyCapturing.indexOf(modelCurrentlyCapturing);
if (modelIndex !== -1) {
modelsCurrentlyCapturing.splice(modelIndex, 1);
}};
var dst = config.createModelDirectory
? path.join(captureDirectory, modelDir, filename)
: src;
fs.statAsync(src)
// if the file is big enough we keep it otherwise we delete it
.then(stats => (stats.size <= minFileSize) ? fs.unlinkAsync(src) : mvAsync(src, dst, { mkdirp: true }))
.catch(err => {
if (err.code !== 'ENOENT') {
printErrorMsg(`[` + colors.green(model.nm) + `] ` + err.toString());
}
});
});
if (!!captureProcess.pid) {
modelsCurrentlyCapturing.push({
nm: model.nm,
uid: model.uid,
filename: filename,
captureProcess: captureProcess,
pid: captureProcess.pid,
checkAfter: getTimestamp() + 180, // we are gonna check the process after 3 min
size: 0
});
}
})
.catch(function(err) {
printErrorMsg(`[` + colors.green(model.nm) + `] ` + err.toString());
});
}
function checkCaptureProcess(model) {
var onlineModel = _.findWhere(onlineModels, {uid: model.uid});
if (!_.isUndefined(onlineModel)) {
if (onlineModel.mode == 1) {
onlineModel.capturing = true;
} else if (!!model.captureProcess) {
// if the model has been excluded or deleted we stop capturing process and resolve immediately
printDebugMsg(colors.green(model.nm) + ` <<< has to be stopped.`);
model.captureProcess.kill();
return;
}
}
// if this is not the time to check the process then we resolve immediately
if (model.checkAfter > getTimestamp()) {
return;
}
return fs
.statAsync(path.join(captureDirectory, model.filename))
.then(function(stats) {
printDebugMsg(colors.green(model.nm) + ` @ ` + colors.cyan((stats.size/1048576).toFixed(2)) + ` MB >>> recording in progress <<<`);
// we check the process every 10 minutes since its start,
// if the size of the file has not changed for the last 10 min, we kill the process
if (stats.size - model.size > 0) {
model.checkAfter = getTimestamp() + 180; // 3 minutes
model.size = stats.size;
} else if (!!model.captureProcess) {
// we assume that onClose will do all clean up for us
printErrorMsg(`[` + colors.green(model.nm) + `] Process is dead.`);
model.captureProcess.kill();
} else {
// suppose here we should forcefully remove the model from modelsCurrentlyCapturing
// because her captureProcess is unset, but let's leave this as is
}
})
.catch(function(err) {
if (err.code == 'ENOENT') {
// do nothing, file does not exists,
// this is kind of impossible case, however, probably there should be some code to "clean up" the process
} else {
printErrorMsg('[' + colors.green(model.nm) + '] ' + err.toString());
}
});
}
function mainLoop() {
Promise
.try(function() {
return getFileno();
})
.then(function(fileno) {
return getOnlineModels(fileno);
})
.then(function() {
return selectMyModels();
})
.then(function(myModels) {
return Promise.all(myModels.map(createCaptureProcess));
})
.then(function() {
return Promise.all(modelsCurrentlyCapturing.map(checkCaptureProcess));
})
.then(function() {
models = onlineModels;
})
.catch(function(err) {
printErrorMsg(err);
})
.finally(function() {
dumpModelsCurrentlyCapturing();
printDebugMsg(`>>> ${colors.gray(`Will search for new models in ${config.modelScanInterval} seconds ...`)} <<<`);
setTimeout(mainLoop, config.modelScanInterval * 1000);
});
}
var session = bhttp.session();
var models = new Array();
var onlineModels = new Array();
var modelsCurrentlyCapturing = new Array();
// convert the list of models to the new format
var dirty = false;
if (config.models.length > 0) {
config.models = config.models.map(function(m) {
if (typeof m === 'number') { // then this "simple" uid
m = {uid: m, include: 1};
dirty = true;
} else if (_.isUndefined(m.mode)) { // if there is no mode field this old version
m.mode = !m.excluded ? 1 : 0;
dirty = true;
}
return m;
});
}
if (dirty) {printDebugMsg(`Save changes in ${colors.yellow(`config.`)}`); // then there were some changes in the list of models
fs.writeFileSync('config.yml', yaml.safeDump(config), 0, 'utf8');
dirty = false}
mainLoop();
dispatcher.onGet('/', (req, res) => {
fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('Not Found');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data, 'utf-8');
}
});
});
dispatcher.onGet('/favicon.ico', (req, res) => {
fs.readFile(path.join(__dirname, 'favicon.ico'), (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'image/x-icon' });
res.end('Not Found');
} else {
res.writeHead(200, { 'Content-Type': 'image/x-icon' });
res.end(data);
}
});
});
// return an array of online models
dispatcher.onGet('/models', (req, res) => {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(models));
});
// when we include the model we only "express our intention" to do so,
// in fact the model will be included in the config only with the next iteration of mainLoop
dispatcher.onGet('/models/include', function(req, res) {
if (req.params && req.params.uid) {
var uid = parseInt(req.params.uid, 10);
if (!isNaN(uid)) {
printDebugMsg(`${colors.green(uid)}${colors.cyan(` >>> include >>>`)}`);
// before we include the model we check that the model is not in our "to exclude" or "to delete" lists
remove(req.params.nm, config.excludeUids);
remove(req.params.nm, config.deleteUids);
config.includeUids.push(uid);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({uid: uid})); // this will be sent back to the browser
var model = _.findWhere(models, {uid: uid});
if (!_.isUndefined(model)) {
model.nextMode = 1;
}
return;
}
} else if (req.params && req.params.nm) {
printDebugMsg(`${colors.green(req.params.nm)}${colors.cyan(` >>> include >>>`)}`);
// before we include the model we check that the model is not in our "to exclude" or "to delete" lists
remove(req.params.nm, config.excludeModels);
remove(req.params.nm, config.deleteModels);
config.includeModels.push(req.params.nm);
dirty = true;
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({nm: req.params.nm})); // this will be sent back to the browser
var model = _.findWhere(models, {nm: req.params.nm});
if (!_.isUndefined(model)) {
model.nextMode = 1;
}
return;
}
res.writeHead(422, {'Content-Type': 'application/json'});
res.end(JSON.stringify({error: 'Invalid request'}));
});
// whenever we exclude the model we only "express our intention" to do so,
// in fact the model will be exclude from config only with the next iteration of mainLoop
dispatcher.onGet('/models/exclude', function(req, res) {
if (req.params && req.params.uid) {
var uid = parseInt(req.params.uid, 10);
if (!isNaN(uid)) {
printDebugMsg(`${colors.green(uid)}${colors.cyan(` <<< exclude <<<`)}`);
// before we exclude the model we check that the model is not in our "to include" or "to delete" lists
remove(req.params.nm, config.includeUids);
remove(req.params.nm, config.deleteUids);
config.excludeUids.push(uid);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({uid: uid})); // this will be sent back to the browser
var model = _.findWhere(models, {uid: uid});
if (!_.isUndefined(model)) {
model.nextMode = 0;
}
return;
}
} else if (req.params && req.params.nm) {
printDebugMsg(`${colors.green(req.params.nm)}${colors.cyan(` <<< exclude <<<`)}`);
// before we exclude the model we check that the model is not in our "to include" or "to delete" lists
remove(req.params.nm, config.includeModels);
remove(req.params.nm, config.deleteModels);
config.excludeModels.push(req.params.nm);
dirty = true;
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({nm: req.params.nm})); // this will be sent back to the browser
var model = _.findWhere(models, {nm: req.params.nm});
if (!_.isUndefined(model)) {
model.nextMode = 0;
}
return;
}
res.writeHead(422, {'Content-Type': 'application/json'});
res.end(JSON.stringify({error: `Invalid request.`}));
});
// whenever we delete the model we only "express our intention" to do so,
// in fact the model will be markd as "deleted" in config only with the next iteration of mainLoop
dispatcher.onGet('/models/delete', function(req, res) {
if (req.params && req.params.uid) {
var uid = parseInt(req.params.uid, 10);
if (!isNaN(uid)) {
printDebugMsg(`${colors.green(uid)}${colors.red(` >>> delete <<<`)}`);
// before we exclude the model we check that the model is not in our "to include" or "to exclude" lists
remove(req.params.nm, config.includeUids);
remove(req.params.nm, config.excludeUids);
config.deleteUids.push(uid);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({uid: uid})); // this will be sent back to the browser
var model = _.findWhere(models, {uid: uid});
if (!_.isUndefined(model)) {
model.nextMode = -1;
}
return;
}
} else if (req.params && req.params.nm) {
printDebugMsg(`${colors.green(req.params.nm)}${colors.red(` >>> delete <<<`)}`);
// before we exclude the model we check that the model is not in our "include" or "exclude" lists
remove(req.params.nm, config.includeModels);
remove(req.params.nm, config.excludeModels);
config.deleteModels.push(req.params.nm);
dirty = true;
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({nm: req.params.nm})); // this will be sent back to the browser
var model = _.findWhere(models, {nm: req.params.nm});
if (!_.isUndefined(model)) {
model.nextMode = -1;
}
return;
}
res.writeHead(422, {'Content-Type': 'application/json'});
res.end(JSON.stringify({error: `Invalid request.`}));
});
dispatcher.onError(function(req, res) {
res.writeHead(404);
});
http.createServer((req, res) => {
dispatcher.dispatch(req, res);
}).listen(config.port, () => {
printMsg(`Server listening on: ` + colors.green(`0.0.0.0:` + config.port));
});