-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmythtv.js
1425 lines (1208 loc) · 50 KB
/
mythtv.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
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var _ = require("underscore");
var http = require('http');
var path = require('path');
var net = require('net');
var fs = require('fs');
var mdns = require('mdns');
var async = require('async');
var xml2js = require('xml2js');
var mxutils = require("./mxutils");
var mythprotocol = require("./mythtv/mythprotocol");
var frontends = new (require("./mythtv/frontends"));
// ////////////////////////////////////////////////////////////////////////
// Helpers
// ////////////////////////////////////////////////////////////////////////
var traitOrder = {
Bookmarked : 1,
CutList : 2,
Movie : 3,
Preserved : 4,
Watched : 5,
Unwatched : 6,
Deleted : 7
};
var slashPattern = new RegExp("[/]");
function titleCompare (t1,t2) {
if (t1.substr(0,4) === "The ") t1 = t1.substr(4);
if (t2.substr(0,4) === "The ") t2 = t2.substr(4);
var t1lc = t1.toLowerCase(), t2lc = t2.toLowerCase();
return t1lc > t2lc ? 1 : t1lc < t2lc ? -1 : t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
}
function episodeCompare (t1,t2) {
var t1Val = !!t1.Airdate ? t1.Airdate : (t1.StartTime || t1.SubTitle || t1.FileName);
var t2Val = !!t2.Airdate ? t2.Airdate : (t2.StartTime || t2.SubTitle || t2.FileName);
return t1Val === t2Val
? (t1.StartTime > t2.StartTime ? -1 : 1)
: (t1Val > t2Val ? -1 : 1);
}
function videoCompare (v1,v2) {
var t1 = v1.Title.toLowerCase();
var t2 = v2.Title.toLowerCase();
if (t1.substr(0,4) === "the ") t1 = t1.substr(4);
if (t2.substr(0,4) === "the ") t2 = t2.substr(4);
return t1 === t2 ? 0 : (t1 < t2 ? -1 : 1);
}
function traitCompare(t1,t2) {
return traitOrder[t1] < traitOrder[t2] ? -1 : 1;
}
function stringCompare (g1,g2) {
return g1.toLowerCase() > g2.toLowerCase() ? 1 : -1;
}
function FormatAirdate(airdate) {
var d = new Date(airdate.substr(0,4), airdate.substr(5,2)-1, airdate.substr(8,2));
return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][d.getDay()]
+ ", "
+ ["January","February","March","April","May","June","July",
"August","September","October","November","December"][d.getMonth()]
+ " " + d.getDate() + ", " + d.getFullYear();
}
// ////////////////////////////////////////////////////////////////////////
// Globals
// ////////////////////////////////////////////////////////////////////////
var backends = [ ];
module.exports = function(args) {
var myth = {
isUp : false, // true = BE has announced itself on bonjour
//connected : false, // obsolete: true = we're connected to BE's event socket
connectPending : false,
bonjour : undefined
};
var backendProtocol;
var backend = {
events : new mythprotocol(),
lock : new mythprotocol(),
host : "127.0.0.1",
customHost : false,
hostName : "localhost", // for settings queries
port : 6544,
protocolPort : 6543,
method : 'GET',
headers : { 'content-type': 'text/plain',
'connection': 'keep-alive',
'accept': 'application/json' },
// for adapting to service api changes
ContentAPI : 1.32
};
var viewButtons = {
Programs : [ ],
Properties : [ ],
About : [
{
Class : "mx-About",
href : "/about",
recGroup : "overview",
Title : "Overview"
},
{
Class : "mx-About",
href : "/about",
recGroup : "terms",
Title : "Terms & Credits"
},
{
Class : "mx-About",
href : "/about",
recGroup : "gplv3",
Title : "GPLv3"
}
]
};
var byRecGroup = { "All" : [ ], "Default" : [ ] };
var byFilename = { };
var byChanId = { };
var sortedTitles = { };
var groupNames = [ ];
var traitNames = [ ];
var fileHasStream = { };
var streamToFilename = { };
var byVideoFolder = { };
var byVideoId = [ ];
if (process.env["MX_HOST"]) {
backend.host = process.env["MX_HOST"];
backend.customHost = true;
}
if (!!args && args.host) {
backend.host = args.host;
backend.customHost = true;
}
function serviceRequest(options, callback) {
var allOptions = { };
Object.keys(backend).forEach(function (option) {
allOptions[option] = backend[option];
});
Object.keys(options).forEach(function (option) {
allOptions[option] = options[option];
});
var req = http.request(allOptions, function (reply) {
var response = "";
reply.setEncoding('utf8');
reply.on('data', function (chunk) {
response += chunk;
//response += chunk.substr(0, chunk.length-2);
});
reply.on('end', function () {
callback(response);
});
});
req.end();
}
function reqJSON (options, callback) {
serviceRequest(options, function (reply) {
response = reply.replace(/[\r\n]/g, "");
var jsObject;
try {
jsObject = JSON.parse(response);
} catch (err) {
log.info("reqJSON got an error reply: " + response);
log.info(options.path);
if (response.length > 0) {
// probably we got back an error xml, convert and
// flatten. For some reason myth sends two copies of
// the error so first reduce it back to one error
var errXML = "<?" + response.split(/<[?]/)[1];
jsObject = mxutils.xmlStringToObject(errXML).detail;
} else {
jsObject = {
errorCode : "ServerError",
errorDescription : "MythTV sent back an empty response"
};
}
jsObject.url = "http://" + options.host + ":" + options.port + options.path;
}
callback(jsObject);
})
}
function reqXML (options, callback) {
// some services are XML only (&*^&%&^%$^%$%$#@@!@)
serviceRequest(options, function (reply) {
response = reply.replace(/[\r\n]/g, "");
var jsObject;
try {
var parser = new xml2js.Parser();
parser.parseString(response, function (err, jsObject) {
callback(jsObject);
});
} catch (err) {
log.info("reqXML got an error reply");
log.info(jsObject);
}
})
}
function toUTCString(localTs) {
if (backendProtocol > "74")
return localTs.getFullYear() + "-" + ("0" + (localTs.getMonth()+1)).substr(-2) + "-" + ("0" + localTs.getDate()).substr(-2) + "T" + ("0" + localTs.getHours()).substr(-2) + ":" + ("0" + localTs.getMinutes()).substr(-2) + ":" + ("0" + localTs.getSeconds()).substr(-2);
else
return localTs.getUTCFullYear() + "-" + ("0" + (localTs.getUTCMonth()+1)).substr(-2) + "-" + ("0" + localTs.getUTCDate()).substr(-2) + "T" + ("0" + localTs.getUTCHours()).substr(-2) + ":" + ("0" + localTs.getUTCMinutes()).substr(-2) + ":" + ("0" + localTs.getUTCSeconds()).substr(-2);
}
function localFromUTCString(utcString) {
if (backendProtocol > "74")
return utcString;
var utc = new Date();
utc.setUTCFullYear(Number(utcString.substr(0,4)),
Number(utcString.substr(5,2))-1,
Number(utcString.substr(8,2)));
utc.setUTCHours(Number(utcString.substr(11,2)),
Number(utcString.substr(14,2)),
Number(utcString.substr(17,2)));
return utc.getFullYear() + "-" + ("0" + (utc.getMonth()+1)).substr(-2) + "-" + ("0" + utc.getDate()).substr(-2) + "T" + ("0" + utc.getHours()).substr(-2) + ":" + ("0" + utc.getMinutes()).substr(-2) + ":" + ("0" + utc.getSeconds()).substr(-2);
}
function getChanKey(arg1, arg2) {
if (typeof(arg1) === "object")
return arg1.Channel.ChanId + ' ' + localFromUTCString(arg1.Recording.StartTs);
else
return arg1 + ' ' + arg2;
}
// ////////////////////////////////////////////////////////////////////////
// backend locking
// ////////////////////////////////////////////////////////////////////////
var backendLock = (function () {
// we lock the backend when:
// - first client connects & myth is up
// - myth comes up and we have > 0 clients
// we unlock when:
// - last client connects & myth is up
// - myth goes down (really a flag change)
var aClientIsConnected = false;
var lockBackend = function () {
if (!backend.lock.isConnected() && !process.env["MX_PASSIVE"]) {
backend.lock.connect({
host : backend.host,
clientName : "MythExpress.BackendLock",
mode : backend.events.Playback,
eventMode : backend.events.NoEvents
});
log.info("Backend locked");
}
}
var unlockBackend = function () {
if (backend.lock.isConnected()) {
backend.lock.disconnect();
log.info("Backend unlocked");
}
}
// backend status we do automatically while client presence
// via explicit calls
backend.events.on("connect", function () {
myth.isUp = true;
if (aClientIsConnected)
lockBackend();
});
backend.events.on("close", function () {
myth.isUp = false;
});
return {
clientConnect : function () {
if (!aClientIsConnected) {
aClientIsConnected = true;
if (myth.isUp)
lockBackend();
}
},
noClientsLeft : function () {
if (myth.isUp)
unlockBackend();
aClientIsConnected = false;
}
};
})();
// ////////////////////////////////////////////////////////////////////////
// events to the browser
// ////////////////////////////////////////////////////////////////////////
var eventSocket = (function() {
var wss = args.websocket;
var wssClients = [ ];
function blast(msg, client) {
var msgStr = JSON.stringify(msg);
var allClients = typeof(client) === "undefined";
var byIndex = typeof(client) === "number";
var byCookie = typeof(client) === "string";
if (allClients) log.info('blast ' + msgStr);
else log.info('blast ' + msgStr + " (" + client + ")");
wssClients.forEach(function (webSocket, idx) {
if (webSocket.readyState === args.ws.OPEN) {
if (allClients) webSocket.send(msgStr);
if (byIndex && idx == client) webSocket.send(msgStr);
if (byCookie && webSocket.mxCookie === client) webSocket.send(msgStr);
}
});
wssClients = _.filter(wssClients, function (client) {
return client.readyState != args.ws.CLOSED;
});
}
var recChange = { };
var inReset = false;
var recordingsWereReset = false;
var shutdownSeconds = -1;
var vidChange = false;
var recGroupsChanged = false;
var changeAPI = {
blast : blast,
resettingRecordings : function (startingReset) {
if (inReset && !startingReset)
recordingsWereReset = true;
inReset = startingReset;
},
isDoingReset : function () {
return inReset;
},
recordingChange : function (change) {
if (!inReset) {
if (!change.title)
change.title = "*";
if (!recChange[change.group])
recChange[change.group] = { };
recChange[change.group][change.title] = true;
}
},
videoChange : function () {
vidChange = true;
},
recGroupChange : function (grp) {
recGroupsChanged = true;
},
groupsDidChange : function () {
return recGroupsChanged;
},
frontendChange : function (feList, clientNum) {
blast({ Frontends : feList }, clientNum);
},
groupChanges : function () {
return recChange;
},
sendChanges : function () {
if (!inReset) {
if (recordingsWereReset) {
blast({ Recordings : true, Reset : true });
recordingsWereReset = false;
} else {
var rc = recChange;
var grpList = [ ];
for (var grp in recChange) {
var titleList = [ ];
for (var title in recChange[grp]) {
blast({ Recordings : true, Group : grp, Title : title});
titleList.push(title);
}
titleList.forEach(function (title) { delete rc[grp][title]; });
}
grpList.slice(2).forEach(function (grp) { if (rc[grp].length == 0) delete rc[grp]; });
}
if (recGroupsChanged) {
blast({ RecordingGroups : true });
recGroupsChanged = false;
}
}
if (vidChange) {
blast({ Videos : true });
vidChange = false;
}
},
alertShutdown : function (seconds, clientNum) {
shutdownSeconds = seconds;
if (seconds > 0) {
blast({ Alert : true, Category : "Servers", Class : "Alert",
Message : myth.bonjour.name + " will shut down in " + seconds + " seconds"},
clientNum);
} else if (seconds == 0) {
blast({ Alert : true, Category : "Servers", Class : "Alert",
Message : myth.bonjour.name + " has commenced shutdown"},
clientNum);
} else {
blast({ Alert : true, Category : "Servers", Class : "Alert", Decay : 5,
Message : "Shutdown cancelled" });
}
},
alertOffline : function (clientNum) {
blast({ Alert : true, Category : "Servers", Class : "Alert",
Message : "MythTV" + " is offline"},
clientNum);
},
alertConnecting : function (clientNum) {
blast({ Alert : true, Category : "Servers", Class : "Info",
Message : "MythExpress is loading from " + myth.bonjour.name },
clientNum);
},
alertConnected : function () {
blast({ Alert : true, Category : "Servers", Cancel : true });
},
alertConnection : function (clientNum) {
blast({ Alert : true, Category : "Servers", Class : "Info", Decay : 5,
Message : "Connected to " + myth.bonjour.fullname },
clientNum);
},
alertProtocol : function (protocol) {
blast({ Alert : true, Category : "Servers", Class : "Alert",
Message : myth.bonjour.fullname + " uses unrecognized protocol '" + protocol + "'" });
},
alertNoServers : function (clientNum) {
blast({ Alert : true, Category : "Servers", Class : "Alert",
Message : "There is no MythTV server available" },
clientNum);
}
};
wss.on("connection", function(ws) {
ws.on("close", function () {
var clientsRemaining = false;
wssClients.forEach(function (webSocket, idx) {
if (webSocket.readyState !== args.ws.CLOSED)
clientsRemaining = true;
});
if (!clientsRemaining)
backendLock.noClientsLeft();
log.info('ws client closed');
});
ws.on("error", function (error) {
log.info("WebSocket error:");
log.info(error);
});
ws.on("message", function (message) {
var msg = JSON.parse(message);
if (msg.hasOwnProperty("Cookie")) {
ws.mxCookie = msg.Cookie;
ws.mxPing = new Date();
}
else if (msg.hasOwnProperty("Pong")) {
ws.mxPing = new Date();
log.info(" Pong " + msg.Pong);
}
});
wssClients.push(ws);
log.info('new client (' + wssClients.length + ')');
backendLock.clientConnect();
var clientNum = wssClients.length-1;
changeAPI.frontendChange(frontends.FrontendList(), clientNum);
if (false && backends.length == 0)
changeAPI.alertNoServers(clientNum);
else if (!myth.isUp)
changeAPI.alertOffline(clientNum);
else if (myth.connectPending)
changeAPI.alertConnecting(clientNum);
else if (backend.events.isConnected())
changeAPI.alertConnected(clientNum);
else if (shutdownSeconds >= 0)
changeAPI.alertShutdown(shutdownSeconds, clientNum);
});
wss.on("error", function (error) {
log.info("WebSocketServer error:");
log.info(error);
});
var webSocketReaper = setInterval(function() {
if (wssClients.length > 0) {
var blastTime = new Date();
blast({ Ping: Date().toString() });
// terminate non-responders after two minutes
setTimeout(function () {
wssClients.forEach(function (webSocket, idx) {
if (webSocket.mxPing.getTime() < blastTime.getTime()) {
webSocket.terminate();
}
});
}, 180 * 1000);
}
}, 3600 * 1000);
return changeAPI;
})();
// ////////////////////////////////////////////////////////////////////////
// data model maintenance
// ////////////////////////////////////////////////////////////////////////
function updateStreamExistence(streamInfoList) {
// we don't get notifications of stream create/deletes so we
// compensate by calling this function anytime we're
// requesting a list of streams in other contexts
Object.keys(fileHasStream).forEach(function (fileName) {
delete fileHasStream[fileName];
});
streamInfoList.LiveStreamInfos.forEach(function (stream) {
var fileName = stream.SourceFile.split("/").pop();
fileHasStream[fileName] = true;
fileHasStream[stream.SourceFile] = true;
streamToFilename[stream.Id] = { FileName : fileName, SourceFile : stream.SourceFile };
});
log.info("Stream flags updated");
}
function addRecordingToRecGroup (recording, recGroup) {
if (!byRecGroup.hasOwnProperty(recGroup)) {
byRecGroup[recGroup] = { };
eventSocket.recGroupChange(recGroup);
}
var groupRecordings = byRecGroup[recGroup];
if (!byRecGroup[recGroup].hasOwnProperty(recording.Title)) {
byRecGroup[recGroup][recording.Title] = [ ];
eventSocket.recordingChange({ group : recGroup});
}
eventSocket.recordingChange({ group : recGroup, title : recording.Title});
byRecGroup[recGroup][recording.Title].push(recording);
}
function delRecordingFromRecGroup (recording, recGroup) {
if (byRecGroup.hasOwnProperty(recGroup) && byRecGroup[recGroup].hasOwnProperty(recording.Title)) {
var found = false
var episodes = _.filter(byRecGroup[recGroup][recording.Title], function (episode) {
var match = episode.FileName === recording.FileName;
found |= match;
return !match;
});
byRecGroup[recGroup][recording.Title] = episodes;
if (found) {
eventSocket.recordingChange({ group : recGroup, title : recording.Title});
if (episodes.length < 2) {
eventSocket.recordingChange({ group : recGroup });
if (episodes.length == 0) {
log.info('that was the last episode');
delete byRecGroup[recGroup][recording.Title];
if (Object.keys(byRecGroup[recGroup]).length == 0) {
log.info('delete rec group ' + recGroup);
delete byRecGroup[recGroup];
eventSocket.recGroupChange(recGroup);
}
}
}
}
}
}
function assignProperties(program) {
var mx = { recGroups : { }, traits : { } };
var flags = backend.events.getProgramFlags(program.ProgramFlags);
if (program.Recording.RecGroup === "Deleted") {
mx.traits.Deleted = true;
} else {
mx.recGroups.All = true;
if (program.Recording.hasOwnProperty("RecGroup"))
mx.recGroups[program.Recording.RecGroup] = true;
if (flags.BookmarkSet) mx.traits.Bookmarked = true;
if (flags.HasCutlist) mx.traits.CutList = true;
if (flags.Preserved) mx.traits.Preserved = true;
if (flags.Watched) mx.traits.Watched = true;
else mx.traits.Unwatched = true;
if (program.hasOwnProperty("ProgramId") && program.ProgramId.length > 0 && program.ProgramId.substr(0,2) === "MV") mx.traits.Movie = true;
}
program.ProgramFlags_ = flags;
program.mx = mx;
program.AirdateFormatted = program.Airdate ? FormatAirdate(program.Airdate) : "";
}
function emptyProgram (fileName) {
var empty = {
Title : "",
StartTime : undefined,
ProgramFlags : 0,
Recording : { RecGroup : undefined },
FileName : fileName
};
assignProperties(empty);
return empty;
}
var doLog = false;
function applyProgramUpdate(newProg) {
var oldProg = { }, isExistingProgram;
if (isExistingProgram = byFilename.hasOwnProperty(newProg.FileName)) {
mxutils.copyProperties(byFilename[newProg.FileName], oldProg);
mxutils.copyProperties(newProg, byFilename[newProg.FileName]);
newProg = byFilename[newProg.FileName];
} else {
oldProg = emptyProgram();
byFilename[newProg.FileName] = newProg;
byChanId[getChanKey(newProg)] = newProg.FileName;
//log.info(getChanKey(newProg) + " = " + newProg.Title + " / " + newProg.SubTitle);
}
assignProperties(newProg);
var oldGroups = Object.keys(oldProg.mx.recGroups).concat(Object.keys(oldProg.mx.traits));
var newGroups = Object.keys(newProg.mx.recGroups).concat(Object.keys(newProg.mx.traits));
var oldMap = { }, newMap = { };
oldGroups.forEach(function (group) { oldMap[group] = true; });
newGroups.forEach(function (group) { newMap[group] = true; });
if (oldProg.Title != newProg.Title) {
// remove from all groups under the old title and
// readd under the new title
if (doLog) log.info(' title change ' + oldProg.title + " => " + newProg.Title
+ " (" + newProg.FileName + ")");
if (isExistingProgram) {
oldGroups.forEach(function (group) {
if (doLog) log.info(' del from ' + group);
delRecordingFromRecGroup(oldProg, group);
});
}
newGroups.forEach(function (group) {
if (doLog) log.info(' add from ' + group);
addRecordingToRecGroup(newProg, group);
});
} else {
// remove from groups not appearing in the new and
// add to groups that weren't in the old list
//log.info("old groups / new groups for existing prog? " + isExistingProgram);
//log.info(oldGroups);
//log.info(newGroups);
oldGroups.forEach(function (group) {
if (!newMap.hasOwnProperty(group)) {
if (doLog) log.info(' del from ' + group);
delRecordingFromRecGroup(oldProg, group);
}
});
newGroups.forEach(function (group) {
if (!oldMap.hasOwnProperty(group)) {
if (doLog) log.info(' add from ' + group);
addRecordingToRecGroup(newProg, group);
}
});
}
}
// new update events can come before we've processed the GetRecorded request
var pendingRetrieves = { };
function takeAndAddRecording(recording, override) {
var chanKey = getChanKey(recording);
if (override || !pendingRetrieves.hasOwnProperty(chanKey)) {
doLog = true;
applyProgramUpdate(recording);
doLog = false;
delete pendingRetrieves[chanKey];
} else log.info(" ignored due to pending retrieve");
}
function retrieveAndAddRecording (recordedId) {
log.info('retrieveAndAddRecording /Dvr/GetRecorded?RecordedId=' + recordedId);
reqJSON(
{
path : '/Dvr/GetRecorded?RecordedId=' + recordedId
},
function (response) {
//log.info('retrieveAndAddRecording');
//log.info(response);
takeAndAddRecording(response.Program, true);
});
};
function deleteByChanId (chanKey) {
if (byChanId.hasOwnProperty(chanKey)) {
var fileName = byChanId[chanKey];
log.info(" chanKey " + chanKey + " maps to " + fileName);
if (byFilename.hasOwnProperty(fileName)) {
var prog = byFilename[fileName];
log.info("deleted dangling program " + prog.Title + " " + prog.StartTime);
if (prog.hasOwnProperty("mx")) {
for (var group in prog.mx.recGroups) {
if (doLog) log.info(' del from ' + group);
delRecordingFromRecGroup(prog, group);
};
for (var flag in prog.mx.ProgramFlags_) {
if (prog.mx.ProgramFlags_[flag]) {
if (doLog) log.info(' del from ' + group);
delRecordingFromRecGroup(prog, group);
}
};
} else {
// clean out any possible straggler records
var prog = emptyProgram(fileName);
groupNames.concat(trainNames).forEach(function (group) {
delRecordingFromRecGroup(emptyProgram, group);
});
}
delete byFilename[fileName];
}
// get rid of stranded streams here until the BE does it
var operation = backend.ContentAPI < 1.33 ? "GetFilteredLiveStreamList" : "GetLiveStreamList";
reqJSON({ path : "/Content/" + operation + "?FileName=" + fileName },
function (reply) {
console.log("/Content/" + operation + "?FileName=" + fileName);
console.log(reply);
reply.LiveStreamInfoList.LiveStreamInfos.forEach(function (stream) {
log.info("remove stream " + stream.Id);
reqJSON({ path : "/Content/RemoveLiveStream?Id=" + stream.Id },
function (reply) { }
);
});
}
);
delete byChanId[chanKey];
}
// else {
// log.info("no entry for " + chanKey + " but");
// Object.keys(byChanId).forEach(function (chKey) {
// if (chKey.substr(0,4) === chanKey.substr(0,4))
// log.info(" " + chKey);
// });
// }
}
function updateStructures() {
var pendingChanges = eventSocket.groupChanges();
for (var group in pendingChanges) {
if (byRecGroup.hasOwnProperty(group)) {
for (var title in pendingChanges[group]) {
if (title === "*") {
sortedTitles[group] = Object.keys(byRecGroup[group]).sort(titleCompare);
} else {
if (byRecGroup[group].hasOwnProperty(title)) {
byRecGroup[group][title].sort(episodeCompare);
}
}
}
} else {
if (sortedTitles.hasOwnProperty(group)) {
delete sortedTitles[group];
}
}
}
if (eventSocket.groupsDidChange()) {
groupNames.length = 0;
traitNames.length = 0;
for (var group in byRecGroup) {
if (traitOrder.hasOwnProperty(group)) {
traitNames.push(group);
} else if (group !== "Default" && group !== "Recordings" && group !== "All") {
groupNames.push(group);
}
};
groupNames.sort(stringCompare);
if (groupNames.length > 1) {
groupNames.unshift("Default");
groupNames.unshift("All");
} else {
groupNames.unshift("Recordings");
}
traitNames.sort(traitCompare);
viewButtons.Programs.length = 0;
viewButtons.Properties.length = 0;
groupNames.forEach(function (groupName) {
viewButtons.Programs.push({
Class : "mx-RecGroup",
href : "/recordings",
recGroup : groupName,
Title : groupName
});
});
viewButtons.Programs.push({
Class : "mx-Videos",
href : "/videos",
Title : "Videos"
});
viewButtons.Programs.push({
Class : "mx-Streams",
href : "/streams",
Title : "Streams"
});
traitNames.forEach(function (traitName) {
viewButtons.Properties.push({
Class : "mx-RecGroup",
href : "/properties",
recGroup : traitName,
Title : traitName
});
});
viewButtons.Properties.push({
Class : "mx-Streams",
href : "/streams",
Title : "Streams"
});
}
}
function resetVideoList() {
Object.keys(byVideoFolder).forEach(function (folder) {
delete byVideoFolder[folder];
});
byVideoId.length = 0;
byVideoFolder["/"] = { Title : "Videos", List : [ ] };
}
function loadVideoList(callback) {
reqJSON(
{ path : '/Video/GetVideoList' },
function (videos) {
videos.VideoMetadataInfoList.VideoMetadataInfos.forEach(function (video) {
video.ReleaseDateFormatted = video.ReleaseDate ? FormatAirdate(video.ReleaseDate) : "";
byVideoId[video.Id] = video;
byFilename[video.FileName] = video;
var curPath = "";
var curList = byVideoFolder["/"];
path.dirname(video.FileName).split(slashPattern).forEach(function (folder) {
if (folder !== ".") {
var newPath = curPath + "/" + folder;
var newList = byVideoFolder[newPath];
if (!newList) {
newList = { Title : folder, List : [ ], VideoFolder : newPath };
byVideoFolder[newPath] = newList;
curList.List.push(newList);
}
curPath = newPath;
curList = newList;
}
});
curList.List.push(video);
});
Object.keys(byVideoFolder).forEach(function (path) {
byVideoFolder[path].List.sort(videoCompare);
});
callback();
});
}
var initializingModel = false;
function initModel () {
if (initializingModel)
return;
initializingModel = true;
async.auto({
alertClients : function (finished) {
eventSocket.alertConnecting();
eventSocket.resettingRecordings(true);
finished(null);
},
getServerPort : function (finished) {
finished(null);
},
resetStructures : [
"alertClients",
function (finished) {
Object.keys(sortedTitles).forEach(function (group) {
delete sortedTitles[group];
});
Object.keys(byRecGroup).forEach(function (group) {
delete byRecGroup[group];
});
byRecGroup.All = [ ];
byRecGroup.Default = [ ];
byRecGroup.Recordings = byRecGroup.Default; // an alias for when we have only one group
Object.keys(byFilename).forEach(function (fileName) {
delete byFilename[fileName];
});
resetVideoList();
finished(null);
}
],
detectStreamedRecordings : function (finished) {
reqJSON(
{
path : "/Content/GetLiveStreamList"
},
function (reply) {
updateStreamExistence(reply.LiveStreamInfoList);
finished(null);
});
},
loadRecordings : [
"resetStructures",
function (finished) {
reqJSON(
{ path : "/Dvr/GetRecordedList" },
function (pl) {
pl.ProgramList.Programs.forEach(function (prog) {
applyProgramUpdate(prog);
});
Object.keys(byRecGroup).forEach(function (group) {
sortedTitles[group] = Object.keys(byRecGroup[group]).sort(titleCompare);
Object.keys(byRecGroup[group]).forEach(function (title) {
byRecGroup[group][title].sort(episodeCompare);
});
log.info(group + ' ' + Object.keys(byRecGroup[group]).length);
});
finished(null);
});
}],