summaryrefslogtreecommitdiff
path: root/www/js/EventServer.js
blob: b9182b6fc5efecec1cde45bc417c11d32bfbff39 (plain)
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
/* 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', ['ZMDataModel', '$rootScope', '$websocket', '$ionicPopup', '$timeout', '$q', 'zm', '$ionicPlatform', '$cordovaMedia', function
    (ZMDataModel, $rootScope, $websocket, $ionicPopup, $timeout, $q, zm, $ionicPlatform, $cordovaMedia) {


        var ws;

        var localNotificationId = 0;


        //--------------------------------------------------------------------------
        // used to compare versions of event server 
        //--------------------------------------------------------------------------

        //credit: https://gist.github.com/alexey-bass/1115557

        function versionCompare(left, right) {
            if (typeof left + typeof right != 'stringstring')
                return false;

            var a = left.split('.');
            var b = right.split('.');
            var i = 0;
            var len = Math.max(a.length, b.length);

            for (; i < len; i++) {
                if ((a[i] && !b[i] && parseInt(a[i]) > 0) || (parseInt(a[i]) > parseInt(b[i]))) {
                    return 1;
                } else if ((b[i] && !a[i] && parseInt(b[i]) > 0) || (parseInt(a[i]) < parseInt(b[i]))) {
                    return -1;
                }
            }

            return 0;
        }


        //--------------------------------------------------------------------------
        // called when the websocket is opened
        //--------------------------------------------------------------------------
        function openHandshake() {
            var loginData = ZMDataModel.getLogin();
            if (loginData.isUseEventServer == "0" || loginData.eventServer == "") {
                ZMDataModel.zmLog("openHandShake: no event server");
                return;
            }

            ZMDataModel.zmLog("openHandshake: Websocket open");
            ws.$emit('auth', {
                user: loginData.username,
                password: loginData.password
            });

            if ($rootScope.apnsToken != '') {
                var plat = $ionicPlatform.is('ios') ? 'ios' : 'android';
                var ld = ZMDataModel.getLogin();
                var pushstate = "enabled";
                if (ld.disablePush == "1")
                    pushstate = "disabled";

                ZMDataModel.zmDebug("openHandShake: state of push is " + pushstate);
                ws.$emit('push', {
                    type: 'token',
                    platform: plat,
                    token: $rootScope.apnsToken,
                    state: pushstate
                });
            }

        }



        //--------------------------------------------------------------------------
        // Called once at app start. Does a lazy definition of websockets open
        //--------------------------------------------------------------------------
        function init() {
            $rootScope.isAlarm = 0;
            $rootScope.alarmCount = "0";

            var d = $q.defer();

            var loginData = ZMDataModel.getLogin();

            if (loginData.isUseEventServer == '0' || !loginData.eventServer) {
                ZMDataModel.zmLog("No Event Server present. Not initializing");
                d.reject("false");
                return d.promise;
            }

            if (!$rootScope.apnsToken)
                pushInit();



            if (typeof ws !== 'undefined') {
                ZMDataModel.zmDebug("Event server already initialized");
                d.resolve("true");
                return d.promise;
            }


            ZMDataModel.zmLog("Initializing Websocket with URL " +
                loginData.eventServer + " , will connect later...");
            ws = $websocket.$new({
                url: loginData.eventServer,
                reconnect: true,
                reconnectInterval: 5000,
                lazy: true
            });



            // Transmit auth information to server              
            ws.$on('$open', openHandshake);

            ws.$on('$close', function () {
                ZMDataModel.zmLog("Websocket closed");

            });

            // Handles responses back from ZM ES

            ws.$on('$message', function (str) {
                ZMDataModel.zmLog("Real-time event: " + JSON.stringify(str));
                

                // Error messages
                if (str.status != 'Success') {
                    ZMDataModel.zmLog("Event Error: " + JSON.stringify(str));

                    if (str.reason == 'APNSDISABLED') {
                        ws.$close();
                        ZMDataModel.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 (versionCompare(str.version, zm.minEventServerVersion) == -1) {
                        $ionicPopup.alert({
                            title: 'Event Server version not supported',
                            template: 'You are running version ' + str.version + ". Please upgrade to " +
                                zm.minEventServerVersion
                        });
                    }

                }




                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 = "Latest Alarms: ";
                        $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
                    {
                        ZMDataModel.zmDebug("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 + ")");
                        localNotText = localNotText + str.events[iter].Name + ",";
                        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 (!ZMDataModel.isBackground()) {
                        
                        //emit alarm details - this is when received over websockets
                        $rootScope.$emit('alarm',{message:listOfMonitors});
                        
                        if (str.supplementary != 'true')
                        {
                        
                            ZMDataModel.zmDebug("App is in foreground, displaying banner");
                            if (eventsToDisplay.length > 0) {

                                if (eventsToDisplay.length == 1) {
                                    console.log("Single Display: " + eventsToDisplay[0]);
                                    ZMDataModel.displayBanner('alarm', [eventsToDisplay[0]], 5000, 5000);
                                } else {
                                    ZMDataModel.displayBanner('alarm', eventsToDisplay, 
                                                              5000, 5000 * eventsToDisplay.length);
                                }

                            }
                        }
                    }

                    

                } //end of success handler





            });
            d.resolve("true");
            return (d.promise);

        }
        
        function disconnect()
        {
            ZMDataModel.zmLog("Disconnecting and deleting Event Server socket...");
            
             if (typeof ws === 'undefined') 
                 return;
             
            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
        //--------------------------------------------------------------------------
        function sendMessage(type, obj, isForce) {
            var ld = ZMDataModel.getLogin();
            if (ld.isUseEventServer == "0" && isForce!=1) {
                ZMDataModel.zmDebug("Not sending WSS message as event server is off");
                return;
            }


            if (typeof ws === 'undefined') {
                ZMDataModel.zmDebug("Event server not initalized, not sending message");
                return;
            }


            if (ws.$status() == ws.$CLOSED) {
                ZMDataModel.zmLog("Websocket was closed, trying to re-open");
                ws.$un('$open');
                //ws.$on ('$open', openHandshake);
                ws.$open();


                ws.$on('$open', openHandshake, function () {

                    console.log(" sending " + type + " " +
                        JSON.stringify(obj));
                    ws.$emit(type, obj);

                    ws.$un('$open');
                    ws.$on('$open', openHandshake);


                });


            } else {
                ws.$emit(type, obj);
                console.log("sending " + type + " " + JSON.stringify(obj));
            }



        }

        //--------------------------------------------------------------------------
        // Called each time we resume 
        //--------------------------------------------------------------------------
        function refresh() {
            var loginData = ZMDataModel.getLogin();

            if ((!loginData.eventServer) || (loginData.isUseEventServer == "0")) {
                ZMDataModel.zmLog("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) {
                        ZMDataModel.zmDebug("Closing open websocket as event server was disabled");
                        ws.$close();
                    }
                }

                return;
            }

            if (typeof ws === 'undefined') {
                ZMDataModel.zmDebug("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) {
                ZMDataModel.zmLog("Websocket was closed, trying to re-open");
                ws.$open();
            }


        }

        function pushInit() {
            ZMDataModel.zmLog("Setting up push registration");
            var push;
            var mediasrc;
            var media;


            var plat = $ionicPlatform.is('ios') ? 'ios' : 'android';


            if ($rootScope.platformOS == 'desktop')
            {
                ZMDataModel.zmLog ("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": "true"
                        }
                    }

                );

            } else {
                mediasrc = "/android_asset/www/sounds/blop.mp3";
                push = PushNotification.init(

                    {
                        "android": {
                            "senderID": zm.gcmSenderId,
                            "icon": "ic_stat_notification"
                        }
                    }

                );

            }

            console.log("*********** MEDIA BLOG IS " + mediasrc);
            media = $cordovaMedia.newMedia(mediasrc);
            /* var push = PushNotification.init(
                         { "android": 
                          {"senderID":zm.gcmSenderId,
                           "icon":"ic_stat_notification"
                          }
                         },
                          
                          { "ios": 
                          {"alert": "true", 
                           "badge": "true", 
                           "sound": "true"}
                         }  
                          
                     );*/





            push.on('registration', function (data) {
                ZMDataModel.zmDebug("Push Notification registration ID received: " + JSON.stringify(data));
                $rootScope.apnsToken = data.registrationId;

                var plat = $ionicPlatform.is('ios') ? 'ios' : 'android';
                var ld = ZMDataModel.getLogin();
                var pushstate = "enabled";
                if (ld.disablePush == '1')
                    pushstate = "disabled";

                sendMessage('push', {
                    type: 'token',
                    platform: plat,
                    token: $rootScope.apnsToken,
                    state: pushstate
                });


            });


            push.on('notification', function (data) {

                var ld = ZMDataModel.getLogin();
                if (ld.isUseEventServer == "0") {
                    ZMDataModel.zmDebug("received push notification, but event server disabled. Not acting on it");
                    return;
                }
                console.log("************* PUSH RECEIVED ******************");
                console.log(JSON.stringify(data));

                // data.message,
                // data.title,
                // data.count,
                // data.sound,
                // data.image,
                // data.additionalData



                if (data.additionalData.foreground == false) {
                    // This means push notification tap in background

                    ZMDataModel.zmDebug("**** NOTIFICATION TAPPED SETTING TAPPED TO 1 ****");
                    $rootScope.alarmCount = "0";
                    $rootScope.isAlarm = 0;
                    $rootScope.tappedNotification = 1;
                } else {
                    
                    // this flag honors the HW mute button. Go figure
                    // http://ilee.co.uk/phonegap-plays-sound-on-mute/
                    media.play({ playAudioWhenScreenIsLocked : false });
                    
    
                    var str = data.message;
                    // console.log ("***STRING: " + str + " " +str.status);
                    var eventsToDisplay = [];

                    /*console.log ("PUSH IS " + JSON.stringify(str.events));
                    var alarmtext = "";
                    for (var iter=0; iter<str.events.length; iter++)
                    {
                          // lets stack the display so they don't overwrite
                        console.log ("PUSHING " + str.events[iter].Name+": new event ("+str.events[iter].EventId+")"); 
                        
                        var evtstr  = str.events[iter].Name+": new event ("+str.events[iter].EventId+")";
                       eventsToDisplay.push(evtstr);
                        
                    }*/


                    ZMDataModel.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) {
                console.log("************* PUSH ERROR ******************");
            });
        }

        return {
            refresh: refresh,
            init: init,
            sendMessage: sendMessage,
            pushInit: pushInit,
            disconnect: disconnect

        };


}]);