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
|
/* jshint -W041 */
/* jslint browser: true*/
/* global cordova,StatusBar,angular,console */
// core app start stuff
angular.module('zmApp', [
'ionic',
'tc.chartjs',
'zmApp.controllers',
'fileLogger',
])
//------------------------------------------------------------------
// this directive will be load any time an image completes loading
// via img tags where this directive is added (I am using this in
// events and mionitor view to show a loader while the image is
// downloading from ZM
//------------------------------------------------------------------
.directive('imageonload', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind('load', function () {
//call the function that was passed
scope.$apply(attrs.imageonload);
});
}
};
})
//------------------------------------------------------------------
// In Android, HTTP requests seem to get stuck once in a while
// It may be a crosswalk issue.
// To tackle this gracefully, I've set up a global interceptor
// If the HTTP request does not complete in 15 seconds, it cancels
// That way the user can try again, and won't get stuck
// Also remember you need to add it to .config
//------------------------------------------------------------------
.factory('timeoutHttpIntercept', function ($rootScope, $q) {
return {
'request': function (config) {
if ( !(config.url.indexOf("/api/states/change/") > -1 ||
config.url.indexOf("getDiskPercent.json") > -1 ))
{
config.timeout = 15000;
}
else
{
//console.log ("HTTP INTERCEPT:Skipping HTTP timeout for "+config.url);
}
return config;
}
};
})
//-----------------------------------------------------------------
// This service automatically logs into ZM at periodic intervals
//------------------------------------------------------------------
.factory('zmAutoLogin', function($interval, ZMDataModel, $http) {
var zmAutoLoginHandle;
function doLogin()
{
console.log ("**** ZM AUTO LOGIN CALLED");
ZMDataModel.zmLog("zmAutologin timer started");
var loginData = ZMDataModel.getLogin();
$http({
method:'POST',
url:loginData.url + '/index.php',
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
},
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" +
encodeURIComponent(obj[p]));
var foo = str.join("&");
//console.log("****RETURNING " + foo);
return foo;
},
data: {
username:loginData.username,
password:loginData.password,
action:"login",
view:"console"
}
})
.success(function(data)
{
console.log ("**** ZM Login OK");
ZMDataModel.zmLog("zmAutologin successfully logged into Zoneminder");
})
.error(function(error)
{
console.log ("**** ZM Login FAILED");
ZMDataModel.zmLog ("zmAutologin Error " + JSON.stringify(error), "error");
});
}
function start()
{
$interval.cancel(zmAutoLoginHandle);
doLogin();
zmAutoLoginHandle = $interval(function()
{
doLogin();
},5*60*1000); // Auto login every 5 minutes
// PHP timeout is around 10 minutes
// should be ok?
}
function stop()
{
$interval.cancel(zmAutoLoginHandle);
ZMDataModel.zmLog("Cancelling zmAutologin timer");
}
return {
start: start,
stop: stop
};
})
/* For future use - does not work with img src intercepts
.factory ('httpAuthIntercept', function ($rootScope, $q)
{
return {
requestError: function (response) {
console.log ("**** REJECT REQUEST: "+JSON.stringify(response));
return $q.reject(response);
},
responseError: function (response) {
console.log ("**** REJECT RESPONSE: "+JSON.stringify(response));
return $q.reject(response);
},
response: function (response)
{
console.log("*******RESPONSE with status: "+response.status+"****************");
if (response.status == 500)
{
console.log ("**** RESPONSE: "+JSON.stringify(response));
}
return (response);
}
};
})
*/
//------------------------------------------------------------------
// First run in ionic
//------------------------------------------------------------------
.run(function ($ionicPlatform, $ionicPopup, $rootScope, $state, ZMDataModel, $cordovaSplashscreen, $http, $interval, zmAutoLogin, $fileLogger,$timeout)
{
ZMDataModel.init();
var loginData = ZMDataModel.getLogin();
if (ZMDataModel.isLoggedIn()) {
ZMDataModel.zmLog ("User is logged in");
console.log("VALID CREDENTIALS. Grabbing Monitors");
ZMDataModel.getMonitors(0);
}
// this works reliably on both Android and iOS. The "onorientation" seems to reverse w/h in Android. Go figure.
// http://stackoverflow.com/questions/1649086/detect-rotation-of-android-phone-in-the-browser-with-javascript
var checkOrientation = function () {
var pixelRatio = window.devicePixelRatio || 1;
$rootScope.devWidth = ((window.innerWidth > 0) ? window.innerWidth : screen.width);
$rootScope.devHeight = ((window.innerHeight > 0) ? window.innerHeight : screen.height);
console.log("********NEW Computed Dev Width & Height as" + $rootScope.devWidth + "*" + $rootScope.devHeight);
//ZMDataModel.zmLog("Device orientation change: "+$rootScope.devWidth + "*" + $rootScope.devHeight);
};
window.addEventListener("resize", checkOrientation, false);
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
var requireLogin = toState.data.requireLogin;
if (ZMDataModel.isLoggedIn()) {
console.log("State transition is authorized");
return;
}
if (requireLogin) {
console.log("**** STATE from " + "**** STATE TO " + toState.name);
$ionicPopup.alert({
title: "Credentials Required",
template: "Please provide your ZoneMinder credentials"
});
// for whatever reason, .go was resulting in digest loops.
// if you don't prevent, states will stack
event.preventDefault();
$state.transitionTo('login');
}
});
$ionicPlatform.ready(function () {
// generates and error in desktops but works fine
ZMDataModel.zmLog("Device is ready");
console.log("**** DEVICE READY ***");
$fileLogger.checkFile().then(function(resp) {
if (parseInt(resp.size) > 50000)
{
console.log ("Deleting old log file as it exceeds 50K bytes");
$fileLogger.deleteLogfile().then(function()
{
console.log('Logfile deleted');
});
}
else
{
console.log ("Log file size is " + resp.size + " bytes");
}
});
$fileLogger.setStorageFilename('zmNinjaLog.txt');
setTimeout(function () {
if (window.cordova)
{
$cordovaSplashscreen.hide();
}
}, 1500);
var pixelRatio = window.devicePixelRatio || 1;
$rootScope.devWidth = ((window.innerWidth > 0) ? window.innerWidth : screen.width);
$rootScope.devHeight = ((window.innerHeight > 0) ? window.innerHeight : screen.height);
console.log("********Computed Dev Width & Height as" + $rootScope.devWidth + "*" + $rootScope.devHeight);
// What I noticed is when I moved the app to the device
// the montage screens were not redrawn after resuming from background mode
// Everything was fine if I switched back to the montage screen
// so as a global hack I'm just reloading the current state if you switch
// from foreground to background and back
document.addEventListener("resume", function () {
console.log("****The application is resuming from the background");
ZMDataModel.zmLog("App is resuming from background");
$rootScope.rand = Math.floor((Math.random() * 100000) + 1);
console.log("** generated Random of " + $rootScope.rand);
$state.go($state.current, {}, {
reload: true
});
zmAutoLogin.stop(); //safety
zmAutoLogin.start();
}, false);
document.addEventListener("pause", function () {
console.log("****The application is going into background");
ZMDataModel.zmLog("App is going into background");
zmAutoLogin.stop();
}, false);
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
}); //platformReady
// lets POST so we get a session ID right hre
//console.log ("Setting up POST LOGIN timer");
zmAutoLogin.start();
}) //run
//------------------------------------------------------------------
// Route configuration
//------------------------------------------------------------------
// My route map connecting menu options to their respective templates and controllers
.config(function ($stateProvider, $urlRouterProvider, $httpProvider) {
// If you do this, Allow Origin can't be *
//$httpProvider.defaults.withCredentials = true;
$httpProvider.interceptors.push('timeoutHttpIntercept');
//$httpProvider.interceptors.push('httpAuthIntercept');
$stateProvider
.state('login', {
data: {
requireLogin: false
},
url: "/login",
templateUrl: "templates/login.html",
controller: 'zmApp.LoginCtrl',
});
$stateProvider
.state('help', {
data: {
requireLogin: false
},
url: "/help",
templateUrl: "templates/help.html",
controller: 'zmApp.HelpCtrl',
})
.state('monitors', {
data: {
requireLogin: true
},
resolve: {
message: function (ZMDataModel) {
console.log("Inside app.montage resolve");
return ZMDataModel.getMonitors(0);
}
},
url: "/monitors",
templateUrl: "templates/monitors.html",
controller: 'zmApp.MonitorCtrl',
})
.state('events', {
data: {
requireLogin: true
},
resolve: {
message: function (ZMDataModel) {
console.log("Inside app.events resolve");
return ZMDataModel.getMonitors(0);
}
},
url: "/events/:id",
templateUrl: "templates/events.html",
controller: 'zmApp.EventCtrl',
})
.state('events-graphs', {
data: {
requireLogin: true
},
url: "/events-graphs",
templateUrl: "templates/events-graphs.html",
controller: 'zmApp.EventsGraphsCtrl',
})
.state('state', {
data: {
requireLogin: true
},
url: "/state",
templateUrl: "templates/state.html",
controller: 'zmApp.StateCtrl',
})
.state('devoptions', {
data: {
requireLogin: true
},
url: "/devoptions",
templateUrl: "templates/devoptions.html",
controller: 'zmApp.DevOptionsCtrl',
})
.state('log', {
data: {
requireLogin: false
},
url: "/log",
templateUrl: "templates/log.html",
controller: 'zmApp.LogCtrl',
})
.state('montage', {
data: {
requireLogin: true
},
resolve: {
message: function (ZMDataModel) {
console.log("Inside app.montage resolve");
return ZMDataModel.getMonitors(0);
}
},
url: "/montage",
templateUrl: "templates/montage.html",
controller: 'zmApp.MontageCtrl',
params: {minimal:false, isRefresh:false}
});
// if none of the above states are matched, use this as the fallback
var defaultState = "/montage";
//var defaultState = "/login";
// as it turns out I can't really inject a factory in config the normal way
// FIXME: In future, read up http://stackoverflow.com/questions/15937267/inject-service-in-app-config
//var defaultState = (ZMDataModel.isLoggedIn())? "/monitors":"/login";
//$urlRouterProvider.otherwise(defaultState);
// https://github.com/angular-ui/ui-router/issues/600
// If I start using the urlRouterProvider above and the
// first state is monitors it goes into a digest loop.
$urlRouterProvider.otherwise(function ($injector, $location) {
var $state = $injector.get("$state");
$state.go("montage");
});
}); //config
|