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
|
/* jshint -W041 */
/* jslint browser: true*/
/* global cordova,StatusBar,angular,console ,PushNotification*/
//--------------------------------------------------------------------------
// This factory interacts with the ZM Event Server
// over websockets and is responsible for rendering real time notifications
//--------------------------------------------------------------------------
angular.module('zmApp.controllers')
.factory('EventServer', ['NVRDataModel', '$rootScope', '$websocket', '$ionicPopup', '$timeout', '$q', 'zm', '$ionicPlatform', '$cordovaMedia', '$translate', function (NVRDataModel, $rootScope, $websocket, $ionicPopup, $timeout, $q, zm, $ionicPlatform, $cordovaMedia, $translate) {
var ws;
var localNotificationId = 0;
var pushInited = false;
var isTimerOn = false;
//--------------------------------------------------------------------------
// called when the websocket is opened
//--------------------------------------------------------------------------
function handleOpen(event) {
NVRDataModel.debug ("WebSocket open called with:"+JSON.stringify(event.data));
var loginData = NVRDataModel.getLogin();
NVRDataModel.log("openHandshake: Websocket open, sending Auth");
sendMessage("auth",
{
user: loginData.username,
password: loginData.password
});
if ($rootScope.apnsToken != '') {
var plat = $ionicPlatform.is('ios') ? 'ios' : 'android';
var ld = NVRDataModel.getLogin();
var pushstate = "enabled";
if (ld.disablePush == true)
pushstate = "disabled";
NVRDataModel.debug("openHandShake: state of push is " + pushstate);
// let's do this only if disabled. If enabled, I suppose registration
// will be called?
//if (ld.disablePush)
//console.log ("HANDSHAKE MESSAGE WITH "+$rootScope.monstring);
sendMessage ("push", {
type: 'token',
platform: plat,
token: $rootScope.apnsToken,
monlist: $rootScope.monstring,
intlist: $rootScope.intstring,
state: pushstate
});
}
}
function handleClose(event) {
console.log ("*********** WEBSOCKET CLOSE CALLED WITH "+JSON.stringify(event.data));
if (!isTimerOn) {
NVRDataModel.log("Will try to reconnect in 10 sec..");
$timeout(init, 10000);
isTimerOn = true;
}
}
function handleError(event) {
console.log ("*********** WEBSOCKET CLOSE CALLED WITH "+JSON.stringify(event.data));
//return;
if (!isTimerOn) {
NVRDataModel.log("Will try to reconnect in 10 sec..");
$timeout(init, 10000);
isTimerOn = true;
}
}
function handleMessage(smsg) {
//NVRDataModel.debug ("Websocket received message:"+smsg);
str = JSON.parse(smsg);
NVRDataModel.debug("Real-time event: " + JSON.stringify(str));
// Error messages
if (str.status != 'Success') {
NVRDataModel.log("Event Error: " + JSON.stringify(str));
if (str.reason == 'APNSDISABLED') {
console.log ("FORCE CLOSING");
ws.close();
NVRDataModel.displayBanner('error', ['Event Server: APNS disabled'], 2000, 6000);
$rootScope.apnsToken = "";
}
}
if (str.status == 'Success' && (str.event == 'auth')) {
if (str.version == undefined)
str.version = "0.1";
if (NVRDataModel.versionCompare(str.version, zm.minEventServerVersion) == -1) {
$rootScope.zmPopup = $ionicPopup.alert({
title: $translate.instant('kEventServerVersionTitle'),
template: $translate.instant('kEventServerVersionBody1') + " " + str.version + ". " + $translate.instant('kEventServerVersionBody2') + " " +
zm.minEventServerVersion,
okText: $translate.instant('kButtonOk'),
cancelText: $translate.instant('kButtonCancel'),
});
}
}
if (str.status == 'Success' && str.event == 'alarm') // new events
{
var localNotText;
// ZMN specific hack for Event Server
if (str.supplementary != 'true') {
new Audio('sounds/blop.mp3').play();
localNotText = "";
$rootScope.isAlarm = 1;
// Show upto a max of 99 when it comes to display
// so aesthetics are maintained
if ($rootScope.alarmCount == "99") {
$rootScope.alarmCount = "99+";
}
if ($rootScope.alarmCount != "99+") {
$rootScope.alarmCount = (parseInt($rootScope.alarmCount) + 1).toString();
}
} else {
NVRDataModel.debug("received supplementary event information over websockets");
}
var eventsToDisplay = [];
var listOfMonitors = [];
for (var iter = 0; iter < str.events.length; iter++) {
// lets stack the display so they don't overwrite
//eventsToDisplay.push(str.events[iter].Name + ": latest new alarm (" + str.events[iter].EventId + ")");
var txt = str.events[iter].EventId;
if (str.events[iter].Cause) {
txt = str.events[iter].Cause;
}
eventsToDisplay.push(str.events[iter].Name + ": " + txt);
localNotText = localNotText + str.events[iter].Name + ": " + txt + ",";
listOfMonitors.push(str.events[iter].MonitorId);
}
localNotText = localNotText.substring(0, localNotText.length - 1);
// if we are in background, do a local notification, else do an in app display
if (!NVRDataModel.isBackground()) {
//emit alarm details - this is when received over websockets
$rootScope.$broadcast('alarm', {
message: listOfMonitors
});
if (str.supplementary != 'true') {
NVRDataModel.debug("App is in foreground, displaying banner");
if (eventsToDisplay.length > 0) {
if (eventsToDisplay.length == 1) {
//console.log("Single Display: " + eventsToDisplay[0]);
NVRDataModel.displayBanner('alarm', [eventsToDisplay[0]], 5000, 5000);
} else {
NVRDataModel.displayBanner('alarm', eventsToDisplay,
5000, 5000 * eventsToDisplay.length);
}
}
}
}
}
}
//--------------------------------------------------------------------------
// Called once at app start. Does a lazy definition of websockets open
//--------------------------------------------------------------------------
function init() {
$rootScope.isAlarm = 0;
$rootScope.alarmCount = "0";
isTimerOn = false;
var d = $q.defer();
var loginData = NVRDataModel.getLogin();
if (loginData.isUseEventServer == false || !loginData.eventServer) {
NVRDataModel.log("No Event Server present. Not initializing");
d.reject("false");
return d.promise;
}
NVRDataModel.log("Initializing Websocket with URL " +
loginData.eventServer);
ws = new WebSocket(loginData.eventServer);
ws.onopen = function (event) {
handleOpen(event);
if (!pushInited) { NVRDataModel.debug ("Initializing FCM push"); pushInit();}
d.resolve("true");
return;
};
ws.onclose = function (event) {
handleClose(event);
d.reject ("error");
return;
};
ws.onerror = function (event) {
handleError(event);
d.reject ("error");
return;
};
ws.onmessage = function (event) {
var smsg = event.data;
handleMessage (smsg);
};
/*
ws.onMessage(function (str)
// ws.$on('$message', function(str)
{
str = JSON.parse(str.data);
//console.log ("FULL MESSAGE="+JSON.stringify(str.data));
NVRDataModel.debug("Real-time event: " + JSON.stringify(str));
// Error messages
if (str.status != 'Success') {
NVRDataModel.log("Event Error: " + JSON.stringify(str));
if (str.reason == 'APNSDISABLED') {
ws.close();
NVRDataModel.displayBanner('error', ['Event Server: APNS disabled'], 2000, 6000);
$rootScope.apnsToken = "";
}
}
if (str.status == 'Success' && (str.event == 'auth')) {
if (str.version == undefined)
str.version = "0.1";
if (NVRDataModel.versionCompare(str.version, zm.minEventServerVersion) == -1) {
$rootScope.zmPopup = $ionicPopup.alert({
title: $translate.instant('kEventServerVersionTitle'),
template: $translate.instant('kEventServerVersionBody1') + " " + str.version + ". " + $translate.instant('kEventServerVersionBody2') + " " +
zm.minEventServerVersion,
okText: $translate.instant('kButtonOk'),
cancelText: $translate.instant('kButtonCancel'),
});
}
}
if (str.status == 'Success' && str.event == 'alarm') // new events
{
var localNotText;
// ZMN specific hack for Event Server
if (str.supplementary != 'true') {
new Audio('sounds/blop.mp3').play();
localNotText = "";
$rootScope.isAlarm = 1;
// Show upto a max of 99 when it comes to display
// so aesthetics are maintained
if ($rootScope.alarmCount == "99") {
$rootScope.alarmCount = "99+";
}
if ($rootScope.alarmCount != "99+") {
$rootScope.alarmCount = (parseInt($rootScope.alarmCount) + 1).toString();
}
} else {
NVRDataModel.debug("received supplementary event information over websockets");
}
var eventsToDisplay = [];
var listOfMonitors = [];
for (var iter = 0; iter < str.events.length; iter++) {
// lets stack the display so they don't overwrite
//eventsToDisplay.push(str.events[iter].Name + ": latest new alarm (" + str.events[iter].EventId + ")");
var txt = str.events[iter].EventId;
if (str.events[iter].Cause) {
txt = str.events[iter].Cause;
}
eventsToDisplay.push(str.events[iter].Name + ": " + txt);
localNotText = localNotText + str.events[iter].Name + ": " + txt + ",";
listOfMonitors.push(str.events[iter].MonitorId);
}
localNotText = localNotText.substring(0, localNotText.length - 1);
// if we are in background, do a local notification, else do an in app display
if (!NVRDataModel.isBackground()) {
//emit alarm details - this is when received over websockets
$rootScope.$broadcast('alarm', {
message: listOfMonitors
});
if (str.supplementary != 'true') {
NVRDataModel.debug("App is in foreground, displaying banner");
if (eventsToDisplay.length > 0) {
if (eventsToDisplay.length == 1) {
//console.log("Single Display: " + eventsToDisplay[0]);
NVRDataModel.displayBanner('alarm', [eventsToDisplay[0]], 5000, 5000);
} else {
NVRDataModel.displayBanner('alarm', eventsToDisplay,
5000, 5000 * eventsToDisplay.length);
}
}
}
}
} //end of success handler
});
*/
return (d.promise);
}
function disconnect() {
if (typeof ws === 'undefined') {
NVRDataModel.log("Event server socket is empty, nothing to disconnect");
return;
}
NVRDataModel.log("Clearing error/close cbk, disconnecting and deleting Event Server socket...");
// ws.$close();
ws.onmessage = null;
ws.close();
// ws.$un('open');
// ws.$un('close');
// ws.$un('message');
ws = undefined;
}
//--------------------------------------------------------------------------
// Send an arbitrary object to the Event Serve
// currently planned to use it for device token
// isForce =1 when you need to send the message even
// if config says ES is off. This may happen when
// you turn off ES and then we need sendMessage to
// let ZMES know not to send us messages
//--------------------------------------------------------------------------
function sendMessage(type, obj, isForce) {
var ld = NVRDataModel.getLogin();
if (ld.isUseEventServer == false && isForce != 1) {
NVRDataModel.debug("Not sending WSS message as event server is off");
return;
}
if (typeof ws === 'undefined') {
NVRDataModel.debug("Event server not initalized, not sending message");
return;
}
// console.log (">>>>>>>>>>>>>>>>>EVENT SERVER SENDING: type="+type+" DATA="+JSON.stringify(obj));
var msg = {
'event': type,
'data': obj
};
var jmsg = JSON.stringify(msg);
NVRDataModel.debug ("~~~~ sendMessage: Sending->"+jmsg);
ws.send(jmsg);
}
//--------------------------------------------------------------------------
// Called each time we resume
//--------------------------------------------------------------------------
function refresh() {
var loginData = NVRDataModel.getLogin();
if ((!loginData.eventServer) || (loginData.isUseEventServer == false)) {
NVRDataModel.log("No Event Server configured, skipping refresh");
// Let's also make sure that if the socket was open
// we close it - this may happen if you disable it after using it
if (typeof ws !== 'undefined') {
/*(if (ws.$status() != ws.$CLOSED)
{
NVRDataModel.debug("Closing open websocket as event server was disabled");
ws.$close();
}*/
}
return;
}
if (typeof ws === 'undefined') {
NVRDataModel.debug("Calling websocket init");
init();
}
// refresh is called when
// The following situations will close the socket
// a) In iOS the client went to background -- we should reconnect
// b) The Event Server died
// c) The network died
// Seems to me in all cases we should give re-open a shot
/*if (ws.$status() == ws.$CLOSED)
{
NVRDataModel.log("Websocket was closed, trying to re-open");
ws.$open();
}*/
}
function pushInit() {
NVRDataModel.log(">>>Setting up push registration");
var push;
var mediasrc;
var media;
var ld = NVRDataModel.getLogin();
var plat = $ionicPlatform.is('ios') ? 'ios' : 'android';
if ($rootScope.platformOS == 'desktop') {
NVRDataModel.log("Desktop instance, not setting up push. Websockets only, I hope");
return;
}
if (plat == 'ios') {
mediasrc = "sounds/blop.mp3";
push = PushNotification.init(
{
"ios": {
"alert": "true",
"badge": "true",
"sound": ld.soundOnPush,
//"sound": "true",
"clearBadge": "true",
//"fcmSandbox": "true"
}
}
);
} else {
mediasrc = "/android_asset/www/sounds/blop.mp3";
var android_media_file = "blop";
push = PushNotification.init(
{
"android": {
// "senderID": zm.gcmSenderId,
"icon": "ic_stat_notification",
sound: "true",
vibrate: ld.vibrateOnPush
//"sound": android_media_file
}
}
);
}
// console.log("*********** MEDIA BLOG IS " + mediasrc);
media = $cordovaMedia.newMedia(mediasrc);
push.on('registration', function (data) {
pushInited = true;
NVRDataModel.debug("Push Notification registration ID received: " + JSON.stringify(data));
$rootScope.apnsToken = data.registrationId;
var plat = $ionicPlatform.is('ios') ? 'ios' : 'android';
var ld = NVRDataModel.getLogin();
var pushstate = "enabled";
if (ld.disablePush == true)
pushstate = "disabled";
// now at this stage, if this is a first registration
// zmeventserver will have no record of this token
// so we need to make sure we send it a legit list of
// monitors otherwise users will get notifications for monitors
// their login is not supposed to see. Refer #391
var monstring = '';
var intstring = '';
NVRDataModel.getMonitors()
.then(function (succ) {
var mon = succ;
if (ld.eventServerMonitors != '') {
// load previous monlist and intlist
// so we don't overwrite
monstring = ld.eventServerMonitors;
intstring = ld.eventServerInterval;
NVRDataModel.debug("loading saved monitor list and interval of " + monstring + ">>" + intstring);
} else { // build new list
for (var i = 0; i < mon.length; i++) {
monstring = monstring + mon[i].Monitor.Id + ",";
intstring = intstring + '0,';
}
if (monstring.charAt(monstring.length - 1) == ',')
monstring = monstring.substr(0, monstring.length - 1);
if (intstring.charAt(intstring.length - 1) == ',')
intstring = intstring.substr(0, intstring.length - 1);
}
//console.log ("WUTPUT SENDING REG WITH "+monstring);
$rootScope.monstring = monstring;
$rootScope.intstring = intstring;
sendMessage('push', {
type: 'token',
platform: plat,
token: $rootScope.apnsToken,
monlist: monstring,
intlist: intstring,
state: pushstate
}, 1);
},
function (err) {
NVRDataModel.log("Could not get monitors, can't send push reg");
});
});
push.on('notification', function (data) {
$ionicPlatform.ready(function () {
NVRDataModel.debug("received push notification");
var ld = NVRDataModel.getLogin();
if (ld.isUseEventServer == false) {
NVRDataModel.debug("received push notification, but event server disabled. Not acting on it");
return;
}
if (data.additionalData.foreground == false) {
// This means push notification tap in background
NVRDataModel.debug("*** PUSH NOTFN.>>>>" + JSON.stringify(data));
// set tappedMid to monitor
//*** PUSH DATA>>>>{"sound":"blop","message":"Alarms: Basement (2854) ","additionalData":{"mid":"2","coldstart":false,"collapse_key":"do_not_collapse","foreground":false}}
if (data.additionalData.dismissed != undefined || data.additionalData.coldstart == true || $rootScope.platformOS == 'ios') // user tapped on notification
// in iOS case, since content-av is not there this notification won't be called unless you tap
{
NVRDataModel.debug("Notification Tapped");
$rootScope.alarmCount = "0";
$rootScope.isAlarm = 0;
$rootScope.tappedNotification = 1;
var mid;
var eid;
// we are using FCM on IOS too
/* if ($rootScope.platformOS == 'ios') {
mid = data.additionalData.gcm.notification.mid;
eid = data.additionalData.gcm.notification.eid;
}
else {*/
mid = data.additionalData.mid;
eid = data.additionalData.eid;
// }
// if Multiple mids, take the first one
var mi = mid.indexOf(',');
if (mi > 0) {
mid = mid.slice(0, mi);
}
mid = parseInt(mid);
$rootScope.tappedMid = mid;
$rootScope.tappedEid = eid;
NVRDataModel.log("Push notification: Tapped Monitor taken as:" + $rootScope.tappedMid);
if ($rootScope.platformOS == 'ios') {
NVRDataModel.debug("iOS only: clearing background push");
push.finish(function () {
NVRDataModel.debug("processing of push data is finished");
});
}
} else {
NVRDataModel.debug("App started via icon, not notification");
$rootScope.tappedNotification = 0;
$rootScope.tappedEid = 0;
$rootScope.tappedMid = 0;
}
// keep this emit not broadcast
// see Portal latch for reason
$rootScope.$emit('process-push');
} else // app is foreground
{
// this flag honors the HW mute button. Go figure
// http://ilee.co.uk/phonegap-plays-sound-on-mute/
NVRDataModel.debug("--> *** PUSH IN FOREGROUND");
$rootScope.tappedNotification = 0;
$rootScope.tappedEid = 0;
$rootScope.tappedMid = 0;
if (ld.soundOnPush) {
media.play({
playAudioWhenScreenIsLocked: false
});
}
var str = data.message;
// console.log ("***STRING: " + str + " " +str.status);
var eventsToDisplay = [];
NVRDataModel.displayBanner('alarm', [str], 0, 5000 * eventsToDisplay.length);
$rootScope.isAlarm = 1;
// Show upto a max of 99 when it comes to display
// so aesthetics are maintained
if ($rootScope.alarmCount == "99") {
$rootScope.alarmCount = "99+";
}
if ($rootScope.alarmCount != "99+") {
$rootScope.alarmCount = (parseInt($rootScope.alarmCount) + 1).toString();
}
}
});
});
push.on('error', function (e) {
NVRDataModel.debug("Push error: " + JSON.stringify(e));
// console.log("************* PUSH ERROR ******************");
});
}
return {
refresh: refresh,
init: init,
sendMessage: sendMessage,
pushInit: pushInit,
disconnect: disconnect
};
}]);
|