-
Notifications
You must be signed in to change notification settings - Fork 1
/
MMG2CoreAPI.js
1615 lines (1276 loc) · 42.8 KB
/
MMG2CoreAPI.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
//jshint esversion:10
// _________ ____________ ____ ____
// / __ \ / / ./ | / |
// / / ) ' _______/ ./ |/ |
// / /__/ / ./ |
// / ( ./ |
// / _ \____/ ,. ,. |
// / / ) , / | / | |
// /_____/ ;____/ \_____________/ |____/ |_______|
// R E M O T E C O N D I T I O N M O N I T O R I N G
// Part of the DVR Group
//
// TITLE: MMG2 Core API Class
//
// AUTHOR(S): Gary Ott ([email protected])
//
// DATE: August 2022 ~ August 2023
//
//
// (C) DVR Ltd 2023
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
const
https = require("https"),
EventEmitter = require("events"),
WebSocket = require("ws"),
AUTH_ERROR = "Authentication failure.",
WS_STATE = {
CLOSED: 0,
CLOSING: 1,
OPEN: 2,
OPENING: 3,
RECONN: 4
},
CRUD_TYPES = {
CREATE: 1,
READ: 2,
UPDATE: 3,
DELETE: 4
},
DATA_SETS = {
USERS: 1,
USERGROUPS: 2,
TEMPLATES: 8,
SITE_ICONS: 9,
SITES: 3,
LOCATIONS: 4,
BOM_ENTRIES: 5,
STATUS: 6,
REPORTS: 7,
SCHEDULES: 8,
DEPLOYABLE: 9,
UNDEPLOYABLE: 10,
ALARMS: 11,
PREPAY_CODES: 12,
CONTROL_HISTORY: 13
},
noop = () => {};
//PRIVATE METHODS FOR JobQueue
//============================
const
JQ_beginJob = (pVars) => {
///Starts a new job if possible.
let
getCompleteFunction = (j) => {
return () => {
//Called by the job to notify JobQueue of completion.
if (j.completed) {
throw new Error("Job completed multiple times.");
}
j.completed = true;
pVars.queue.splice(pVars.queue.indexOf(j), 1);
pVars.activeJobs -= 1;
pVars.queueLength -= 1;
pVars.completed += 1;
if ((pVars.queueLength === 0) && (pVars.activeJobs === 0)) {
if (pVars.onCompleteQueue) {
pVars.onCompleteQueue();
}
}
else {
JQ_beginJob(pVars);
}
};
},
getAbortFunction = () => {
return (about) => {
if (!pVars.aborted) {
pVars.aborted = true;
if (pVars.onAbortQueue) {
pVars.onAbortQueue(about);
}
}
};
},
h_startWithoutCallStack = (job) => {
return () => {
job.run(job.context, getCompleteFunction(job), getAbortFunction());
};
};
while (pVars.started && (!pVars.aborted) && (pVars.activeJobs < pVars.concurrentLimit) && (pVars.activeJobs < pVars.queueLength)) {
setTimeout(h_startWithoutCallStack(pVars.queue[pVars.activeJobs]), 0);
pVars.activeJobs += 1;
}
};
class JobQueue {
constructor() {
this._private = {
activeJobs: 0, //Number of jobs currently running.
queueLength: 0, //Current number of items in queue
enqueued: 0, //Number of jobs that have been added to the queue.
completed: 0, //Number of jobs that have been added to the queue.
queue: [], //The list of jobs in the queue.
aborted: false, //Current state
started: false, //Current state
//Settings
concurrentLimit: 0, //Maximum number of jobs that may run simutaniously.
onCompleteQueue: 0, //Called everytime the queue is completely empty.
onAbortQueue: 0 //Called when a job aborts the whole queue.
};
}
enqueue(job, context) {
let pVars = this._private;
pVars.queue.push({
context: context,
run: job,
completed: false
});
pVars.enqueued += 1;
pVars.queueLength += 1;
if (pVars.started) {
//Cause job to start if within limits.
JQ_beginJob(pVars);
}
}
setLimit(newValue) {
if ((newValue === undefined) || (newValue < 1) || (isNaN(newValue))) {
throw new Error("JobQueue: Invalid value for limit.");
}
this._private.concurrentLimit = newValue;
}
start() {
let pVars = this._private;
if (pVars.started) {
throw new Error("JobQueue: Cannot start a job queue that is already running.");
}
pVars.started = true;
if (pVars.queueLength > 0) {
JQ_beginJob(pVars);
}
else if (pVars.onCompleteQueue) {
pVars.onCompleteQueue();
}
}
// pause() {
// this._private.started = false;
// }
// getStats() {
// let pVars = this._private;
// return {
// activeJobs: pVars.activeJobs,
// enqueued: pVars.enqueued,
// limit: pVars.concurrentLimit,
// queueLength: pVars.queueLength,
// completedJobs: pVars.completed
// };
// }
onAbort(newValue) {
this._private.onAbortQueue = newValue;
}
onComplete(newValue) {
this._private.onCompleteQueue = newValue;
}
}
//PRIVATE METHODS FOR MMG2CoreAPI
//===============================
const
COREcheckTimer = (self) => {
var timeNow = Date.now(),
a = 0,
runAgain = false,
request = null,
timeoutAfter = 0,
nextTimeout = timeNow + (24 * 60 * 60 * 1000);
for (a = self.sentWebSocketRequests.length - 1; a >= 0; a -= 1) {
request = self.sentWebSocketRequests[a];
if ((request.context) && (request.context.timeout)) {
timeoutAfter = request.context.timeout;
}
else {
timeoutAfter = self.timeout;
}
if ((request.ts.getTime() + timeoutAfter) < timeNow) {
self.sentWebSocketRequests.splice(a, 1); //This line MUST go before the following or it is
//possible that checkTimer is called again resulting
//in the same job being timed out multiple times and
//getting an error from request.complete()
//Bug fix, 30.11.2018, Gary
if (request.context.onFailure) {
request.context.onFailure(0);
}
request.complete();
}
else if (request.ts.getTime() + timeoutAfter < nextTimeout) {
nextTimeout = (request.ts.getTime() + timeoutAfter);
runAgain = true;
}
}
if (self.timer) {
clearTimeout(self.timer);
}
if (runAgain) {
self.timer = setTimeout(COREcheckTimer, nextTimeout - timeNow, self);
}
},
COREgetLDMConfig = (dataSet, params) => {
switch (dataSet) {
case DATA_SETS.USERS:
return {
idField: "userID", //Uniqueness of this field within the data
//object is enforced. New data overwrites old
//data.
subscribeTopics: ["SRV/users"],
//List of topics to subscribe to for new
//messages from other users.
createAPI: "/API/createUser", //API to call to create a new entry.
readAPI: "/API/getUsers", //API to call to obtain initial data set.
updateAPI: "/API/updateUser", //API to call to update an entry.
readAPIArrayField: "users",
};
case DATA_SETS.USERGROUPS:
return {
idField: "groupID", //Uniqueness of this field within the data
//object is enforced. New data overwrites old
//data.
subscribeTopics: ["SRV/usergroups"],
//List of topics to subscribe to for new
//messages from other users.
createAPI: "/API/createUserGroup", //API to call to create a new entry.
readAPI: "/API/getUserGroups", //API to call to obtain initial data set.
updateAPI: "/API/updateUserGroup", //API to call to update an entry.
deleteAPI: "/API/deleteUserGroup", //API to call to delete an entry.
readAPIArrayField: "groups"
};
case DATA_SETS.TEMPLATES:
return {
idField: "templateID", //Uniqueness of this field within the data object is enforced. New data overwrites old data.
subscribeTopics: ["SRV/templates"], //List of topics to subscribe to for new messages from other users.
createAPI: "/API/setup/createTemplate", //API to call to create a new entry.
readAPI: "/API/setup/getTemplates", //API to call to obtain initial data set.
updateAPI: "/API/setup/updateTemplate", //API to call to update an entry.
deleteAPI: "/API/setup/deleteTemplate", //API to call to delete an entry.
readAPIArrayField: "templates"
};
case DATA_SETS.SITE_ICONS:
return {
idField: "siteIconID", //Uniqueness of this field within the data object is enforced. New data overwrites old data.
subscribeTopics: ["SRV/siteIcons/" + params.locationID], //List of topics to subscribe to for new messages from other users.
readAPI: "/API/setup/getSiteIcons", //API to call to obtain initial data set.
readAPIArrayField: "templates" // needs to match the returnAs in messageMap
};
case DATA_SETS.SITES:
return {
subscribeTopics: ["SRV/sites"],
idField: "locationID",
readAPIArrayField: "sites",
readAPI: "/API/setup/getSites"
};
case DATA_SETS.REPORTS:
return {
idField: "reportID",
subscribeTopics: ["SRV/report/" + params.locationID],
readAPI: "/API/report/getScheduledReports",
deleteAPI: "/API/report/deleteReport",
readAPIArrayField: "report"
};
case DATA_SETS.SCHEDULES:
return {
idField: "scheduleID",
subscribeTopics: ["SRV/schedule/" + params.locationID],
createAPI: "/API/schedule/createSchedule",
readAPI: "/API/schedule/getScheduleList",
updateAPI: "/API/schedule/updateSchedule",
deleteAPI: "/API/schedule/deleteSchedule",
readAPIArrayField: "schedule",
};
case DATA_SETS.DEPLOYABLE:
return {
idField: "undeployedID",
subscribeTopics: ["SRV/deployable/" + params.locationID],
readAPI: "/API/asset/getDeployable",
readAPIArrayField: "deployable"
};
case DATA_SETS.UNDEPLOYABLE:
return {
idField: "undeployedID",
subscribeTopics: ["SRV/undeployable/" + params.locationID],
readAPI: "/API/asset/getUndeployable",
readAPIArrayField: "undeployable"
};
case DATA_SETS.ALARMS:
return {
idField: "alarmID", //Uniqueness of this field within the data object is enforced. New data overwrites old data.
subscribeTopics: ["SRV/alarms/" + params.locationID], //List of topics to subscribe to for new messages from other users.
readAPI: "/API/monitor/getAlarms", //API to call to obtain initial data set.
readAPIArrayField: "alarms", // needs to match the returnAs in messageMap
};
case DATA_SETS.LOCATIONS:
return {
subscribeTopics: ["SRV/locations/" + params.locationID],
idField: "locationID",
readAPIArrayField: "locations",
createAPI: "/API/setup/createLocation",
readAPI: "/API/setup/getLocations",
updateAPI: "/API/setup/updateLocation",
deleteAPI: "/API/setup/deleteLocation"
};
case DATA_SETS.BOM_ENTRIES:
return {
idField: "lineID",
readAPIArrayField: "bom",
createAPI: "/API/setup/createBOMExtra",
readAPI: "/API/setup/getBOMExtra",
updateAPI: "/API/setup/updateBOMExtra",
deleteAPI: "/API/setup/deleteBOMExtra",
subscribeTopics: ["SRV/bom/" + params.locationID]
};
case DATA_SETS.STATUS:
console.log("DATA_SETS.STATUS not supported (yet?).");
return {
idField: "locationID",
readAPIArrayField: "status",
readAPI: "/API/monitor/getStatus",
subscribeTopics: []
};
case DATA_SETS.PREPAY_CODES:
return {
idField: "code",
subscribeTopics: ["SRV/prepayCodes/" + params.service],
createAPI: "/API/prePay/createCode",
readAPI: "/API/prePay/getCodes",
deleteAPI: "/API/prePay/revokeCode",
readAPIArrayField: "codes"
};
case DATA_SETS.CONTROL_HISTORY:
return {
idField: "instructionID",
subscribeTopics: ["SRV/control/" + params.locationID],
readAPI: "/API/deviceControl/getControlHistory",
readAPIArrayField: "history"
};
}
},
COREsendPing = (self) => {
if ((self.authenticated) || (self.useKey)) {
if ((self.primaryWebSocket) && (self.primaryWebSocketState === WS_STATE.OPEN)) {
self.primaryWebSocket.send(JSON.stringify({
type: "PING" //Heartbeat
}));
}
else if (!self.useKey) {
let
request = https.request(
{
host: self.options.domain,
path: "/heartbeat",
method: "GET"
},
noop
);
request.end();
}
self.hbTimer = setTimeout(COREsendPing, self.heartbeatInterval, self);
}
else {
self.hbTimer = null;
}
},
COREopenPrimaryWebSocket = (self) => {
var subscribe = () => {
self.webSocketPushHandlers.forEach((pushHandler) => {
console.log("Subscribing to " + pushHandler.topic);
self.primaryWebSocket.send(JSON.stringify({
type: "SUB",
topic: pushHandler.topic
}));
});
},
onOpen = (err, socket) => {
var
pingCycle = () => {
///Repeatedly ping the server until we get a response.
//The longer the outage, the longer the interval between requests up to a maximum
//of 12 seconds. A random element prevents all clients pinging the server at the
//exact same moment following a breif hiccup.
self.reconnectAttempts += 1;
setTimeout(() => {
console.log("Pinging server...");
var
request = https.request(
{
host: self.options.domain,
path: "/ping",
method: "GET"
},
(res) => {
if (res.statusCode !== 200) {
pingCycle();
return;
}
console.log("Server alive!");
//Success! It is possible to communicate with the server but we can't
//assume the server will recognise our authentication token. We need
//to reauthenticate before we can re-open the web socket.
if (self.authenticated) {
self.logOn(
() => {
//Successfully reauthenticated.
//Now try connecting to the websocket again...
self.myJobQueue.enqueue(COREmakeWebSocketConnection, context);
},
pingCycle
);
}
else {
self.primaryWebSocketState = WS_STATE.CLOSED;
self.emit("error", new Error("Unable to reauthenticate following a connection break."));
}
}
);
request.on("error", pingCycle);
request.end();
}, Math.min(1000 * self.reconnectAttempts, 10000) + (Math.random() * 2000));
};
if (err) {
//Socket and close are undefined.
//We don't need to remove the job from HRQ.
//At this point, an existing websocket dropped out and our first attempt to reconnect
//resulted in this error. The error message doesn't tell us the HTTP status code so we
//don't know if the server restarted for some reason of if the internet connection
//flaked on us. What is really disappointing is that the message in the console window
//will show us the cause but we can't determine the reason from code.
if (console && console.log) {
console.error("The websocket connection encountered an error.");
console.error(err);
}
self.primaryWebSocketState = WS_STATE.RECONN;
//pingCycle() will keep pinging the server until it gets a 200 OK.
pingCycle();
return;
}
self.emit("connectionRestore");
self.primaryWebSocket = socket;
self.primaryWebSocketState = WS_STATE.OPEN;
self.reconnectAttempts = 0;
socket.on("close", () => {
self.primaryWebSocket = undefined;
if (self.primaryWebSocketState === WS_STATE.CLOSING) {
//Intentional close on log off
self.primaryWebSocketState = WS_STATE.CLOSED;
}
else {
self.primaryWebSocketState = WS_STATE.RECONN;
self.myJobQueue.enqueue(COREmakeWebSocketConnection, context);
}
});
subscribe();
self.pendingWebSocketRequests.forEach((request) => {
self.request(request);
});
self.pendingWebSocketRequests = [];
},
onMessage = (message) => {
///Decide what action to take when a message comes in through the primary web socket connection.
var a = 0,
msg;
try {
msg = JSON.parse(message);
if (!msg.type || ((msg.type !== "PONG") && (msg.data === undefined))) {
if ((msg.state === "ERROR") && (typeof msg.additional === "string") && (msg.additional.indexOf("Not logged in") > -1)) {
if (self.authenticated) {
console.log("wut?");
}
return;
}
else {
self.emit("error", new Error("Received message in unrecognised format."));
}
}
}
catch(e) {
self.emit("error", new Error("Unable to understand message from server."));
console.log(e);
// console.log(message);
return;
}
if (msg.type === "RES") {
//Response to a request.
for (a = self.sentWebSocketRequests.length - 1; a >= 0; a -= 1) {
if (self.sentWebSocketRequests[a].id === msg.id) {
if (msg.code < 300) {
//Hopefully a 200 OK
self.sentWebSocketRequests[a].context.onSuccess(msg.data);
self.sentWebSocketRequests[a].complete();
}
else {
//Ah, crap.
//Get and immediately invoke a fail handler function.
COREgetFailHandler.call(self, self.sentWebSocketRequests[a].context, self.sentWebSocketRequests[a].complete)({
status: msg.code,
additional: msg.additional || (msg.data ? msg.data.additional : undefined)
});
}
//Clean up
self.sentWebSocketRequests.splice(a, 1);
break;
}
}
}
else if (msg.type === "PUB") {
//Information published to a topic we have previously subscribed to.
for (a = self.webSocketPushHandlers.length - 1; a >= 0; a -= 1) {
if (self.webSocketPushHandlers[a].topic === msg.topic) {
self.webSocketPushHandlers[a].handler(msg.data);
//Do not break here. There can be multiple registered handlers.
}
}
}
else if (msg.type === "PONG") {
console.log("PONG message received.");
}
else {
console.log("Message type not recognised:", message);
}
},
context = {
url: "wss://" + self.options.domain + "/API/primary",
debug: "primary",
onOpen: onOpen,
onMessage: onMessage,
self: self,
key: self.token
};
self.primaryWebSocketState = WS_STATE.OPENING;
self.myJobQueue.enqueue(COREmakeWebSocketConnection, context);
},
COREgetFailHandler = (context, complete) => {
return function(status) {
if (status.status === 401) {
lo.logOff(); //Will return without doing anything if not currently in a logged in state.
if (context.onFailure) {
context.onFailure(status.status, status.additional);
}
complete();
return;
}
if (context.critical) {
switch (status.status) {
case -1: //Deliberate fall through
case 0:
//Timeout, internet connection break, etc.
if (context.onFailure) {
context.onFailure(status.status, status.additional);
}
break;
case 400:
//This really ought to be caused by a client side bug and should never happen in a production system.
throw new Error("400 - Bad Request (" + context.resource + ")");
//console.log(context.params);
//case 401: Already handled above
// break;
case 403:
//The client IP has been blocked or the client side software has a bug in that it did not
//restrict the user from attempting something they're not permitted to do.
throw new Error("403 - Forbidden (" + context.resource + ")");
case 404:
//The client side or server side software has a bug (e.g. a mis-spelt URL)
throw new Error("404 - File not found (" + context.resource + ")");
case 405:
throw new Error("405 - Method not allowed (" + context.resource + ")");
case 429:
//Too many requests (should never happen as jobqueue implemented to prevent it).
if (context.onFailure) {
context.onFailure(status.status, status.additional);
}
break;
case 500:
throw new Error("500 - Internal server error in " + context.resource);
default:
throw new Error("Unrecognised error condition (" + status.status + ") while retrieving " + context.resource + "\n\n" + (status.statusText ? status.statusText : ""));
}
}
else {
if (context.onFailure) {
context.onFailure(status.status, status.additional);
}
}
complete();
};
},
//JOBS THAT CAN BE ENQUEUED IN the JOB QUEUE:
COREmakeWebSocketConnection = (context, complete, abort) => { //jshint ignore:line
var
webSocket,
opened = false,
completed = false,
id = Math.random();
// console.log("key: ", context.key);
if (context.key.trim().startsWith("token")) {
webSocket = new WebSocket(
context.url,
{
headers: {
cookie: context.self.token
}
}
);
}
else {
webSocket = new WebSocket(
context.url + "?api_key=" + encodeURIComponent(context.key)
);
}
webSocket.on("open", () => {
console.log("Socket opened: ", id);
opened = true;
context.onOpen(null, webSocket);
});
webSocket.on("message", context.onMessage);
webSocket.on("close", () => {
console.log("Socket closed: ", id);
if (!completed) {
completed = true;
complete();
}
});
webSocket.on("error", (err) => {
if (!opened) {
context.onOpen(err);
if (!completed) {
completed = true;
complete();
}
}
else {
console.log("Websocket error", id);
COREmakeWebSocketConnection(context, complete, abort);
}
});
},
COREmakeWsRequest = (context, complete) => {
///Makes a requests for a resource by the Primary WebSocket.
if (context.self.primaryWebSocket) {
context.self.lastIDRequest += 1;
context.self.sentWebSocketRequests.push({
id: context.self.lastIDRequest,
context: context,
complete: complete,
ts: new Date()
});
context.self.primaryWebSocket.send(JSON.stringify({
type: "REQ", //Request
id: context.self.lastIDRequest,
resource: context.resource,
params: context.params
}));
}
else {
console.log("Boo");
}
COREcheckTimer(context.self);
},
COREmakeHttpRequest = (context, complete, abort) => { //jshint ignore:line
///Makes a requests for a resource by normal HTTP
//We never actually want to call abort since jobs maybe entirely disperate.
var url = HTTPS_URL + context.resource;
if (context.params) {
url += "?" + $httpParamSerializer(context.params);
}
var httpRequest = https.request({
});
httpRequest.end();
$http(
Object.merge(
{
//Defaults
method: "GET",
url: url
},
context.options
)
).then(
(returnData) => {
context.onSuccess(returnData);
complete();
},
COREgetFailHandler.call(this, context, complete, abort)
);
};
class MMG2CoreAPI extends EventEmitter {
static version = "0.2"; //jshint ignore:line
static DATA_SETS = DATA_SETS;
static CRUD_TYPES = CRUD_TYPES;
//==========================================
constructor(opts) {
super();
super.constructor();
this.options = opts;
this.token = null;
this.useKey = false;
this.primaryWebSocket = null;
this.primaryWebSocketState = WS_STATE.CLOSED;
this.webSocketPushHandlers = []; //List of callback functions to handle published messages.
this.authenticated = false;
this.myJobQueue = new JobQueue();
this.queueStarted = false;
this.reconnectAttempts = 0;
this.sentWebSocketRequests = []; //Requests awaiting a response.
this.pendingWebSocketRequests = []; //Requests waiting for the websocket to open before sending.
this.lastIDRequest = 0; //Simple ID number to match request with response.
this.timeout = 30000; //30 second default timeout
this.timer = null;
this.heartbeatInterval = 50000; //(14 * 60 * 1000), //14 minutes
this.hbTimer = null;
}
setKey(key) {
if (this.authenticated) {
throw new Error("Cannot set API key if already using a sesson.");
}
this.token = key;
this.useKey = true;
if (!this.hbTimer) {
this.hbTimer = setTimeout(COREsendPing, this.heartbeatInterval, this);
}
}
logOn(onSuccess, onFailure) {
var logOnRequest;
if (this.useKey) {
throw new Error("No point in starting a session after setting API key.");
}
console.log("Attempting to log in to " + this.options.domain + " as '" + this.options.username + "'....");
logOnRequest = https.request(
{
host: this.options.domain,
path: "/API/logOn.js" +
"?un=" + encodeURIComponent(this.options.username) +
"&pw=" + encodeURIComponent(this.options.password),
method: "GET"
},
(res) => {
this.authenticated = (res.statusCode === 200);
if (this.authenticated) {
this.token = res.headers["set-cookie"][0].split(";")[0];
onSuccess();
}
else {
onFailure(new Error(AUTH_ERROR));
}
}
);
logOnRequest.end();
if (!this.hbTimer) {
this.hbTimer = setTimeout(COREsendPing, this.heartbeatInterval, this);
}
}
logOff(onSuccess, onFailure) {
if ((this.primaryWebSocketState === WS_STATE.OPENING) || (this.primaryWebSocketState === WS_STATE.OPEN)) {
//this.primaryWebSocketState shall be set to CLOSED by the 'close' event handler.
//Setting this.primaryWebSocketState to CLOSING causes the 'close' event handler not to attempt to reconnect.
this.primaryWebSocketState = WS_STATE.CLOSING;
this.primaryWebSocket.close();