diff options
| author | Pliable Pixels <pliablepixels@gmail.com> | 2017-12-10 19:54:36 -0500 |
|---|---|---|
| committer | Pliable Pixels <pliablepixels@gmail.com> | 2017-12-10 19:54:36 -0500 |
| commit | 57b02a05bb06817eaebe8fb8afd50be21c818157 (patch) | |
| tree | a183f78a3b37cfd4881c6cbcff9e1031ac9014c5 | |
| parent | 4e552d225caa1a10ddd09c6c9a9a799eeef4d5ed (diff) | |
initial work #565
| -rw-r--r-- | angular-websocket.js | 415 | ||||
| -rw-r--r-- | config.xml | 5 | ||||
| -rw-r--r-- | package.json | 4 | ||||
| -rw-r--r-- | www/external/angular-websocket.js | 415 | ||||
| -rw-r--r-- | www/external/angular-websocket.min.js | 2 | ||||
| -rw-r--r-- | www/index.html | 8 | ||||
| -rw-r--r-- | www/js/EventServer.js | 96 | ||||
| -rwxr-xr-x | www/js/app.js | 3 | ||||
| -rw-r--r-- | www/js/controllers.js | 2 |
9 files changed, 910 insertions, 40 deletions
diff --git a/angular-websocket.js b/angular-websocket.js new file mode 100644 index 00000000..b2317cdd --- /dev/null +++ b/angular-websocket.js @@ -0,0 +1,415 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(['module', 'exports', 'angular', 'ws'], factory); + } else if (typeof exports !== "undefined") { + factory(module, exports, require('angular'), require('ws')); + } else { + var mod = { + exports: {} + }; + factory(mod, mod.exports, global.angular, global.ws); + global.angularWebsocket = mod.exports; + } +})(this, function (module, exports, _angular, ws) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _angular2 = _interopRequireDefault(_angular); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + var Socket; + + if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object' && typeof require === 'function') { + try { + + Socket = ws.Client || ws.client || ws; + } catch (e) {} + } + + // Browser + Socket = Socket || window.WebSocket || window.MozWebSocket; + + var noop = _angular2.default.noop; + var objectFreeze = Object.freeze ? Object.freeze : noop; + var objectDefineProperty = Object.defineProperty; + var isString = _angular2.default.isString; + var isFunction = _angular2.default.isFunction; + var isDefined = _angular2.default.isDefined; + var isObject = _angular2.default.isObject; + var isArray = _angular2.default.isArray; + var forEach = _angular2.default.forEach; + var arraySlice = Array.prototype.slice; + // ie8 wat + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function (elt /*, from*/) { + var len = this.length >>> 0; + var from = Number(arguments[1]) || 0; + from = from < 0 ? Math.ceil(from) : Math.floor(from); + if (from < 0) { + from += len; + } + + for (; from < len; from++) { + if (from in this && this[from] === elt) { + return from; + } + } + return -1; + }; + } + + // $WebSocketProvider.$inject = ['$rootScope', '$q', '$timeout', '$websocketBackend']; + function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { + + function $WebSocket(url, protocols, options) { + if (!options && isObject(protocols) && !isArray(protocols)) { + options = protocols; + protocols = undefined; + } + + this.protocols = protocols; + this.url = url || 'Missing URL'; + this.ssl = /(wss)/i.test(this.url); + + // this.binaryType = ''; + // this.extensions = ''; + // this.bufferedAmount = 0; + // this.trasnmitting = false; + // this.buffer = []; + + // TODO: refactor options to use isDefined + this.scope = options && options.scope || $rootScope; + this.rootScopeFailover = options && options.rootScopeFailover && true; + this.useApplyAsync = options && options.useApplyAsync || false; + this.initialTimeout = options && options.initialTimeout || 500; // 500ms + this.maxTimeout = options && options.maxTimeout || 5 * 60 * 1000; // 5 minutes + this.reconnectIfNotNormalClose = options && options.reconnectIfNotNormalClose || false; + this.binaryType = options && options.binaryType || 'blob'; + + this._reconnectAttempts = 0; + this.sendQueue = []; + this.onOpenCallbacks = []; + this.onMessageCallbacks = []; + this.onErrorCallbacks = []; + this.onCloseCallbacks = []; + + objectFreeze(this._readyStateConstants); + + if (url) { + this._connect(); + } else { + this._setInternalState(0); + } + } + + $WebSocket.prototype._readyStateConstants = { + 'CONNECTING': 0, + 'OPEN': 1, + 'CLOSING': 2, + 'CLOSED': 3, + 'RECONNECT_ABORTED': 4 + }; + + $WebSocket.prototype._normalCloseCode = 1000; + + $WebSocket.prototype._reconnectableStatusCodes = [4000]; + + $WebSocket.prototype.safeDigest = function safeDigest(autoApply) { + if (autoApply && !this.scope.$$phase) { + this.scope.$digest(); + } + }; + + $WebSocket.prototype.bindToScope = function bindToScope(scope) { + var self = this; + if (scope) { + this.scope = scope; + if (this.rootScopeFailover) { + this.scope.$on('$destroy', function () { + self.scope = $rootScope; + }); + } + } + return self; + }; + + $WebSocket.prototype._connect = function _connect(force) { + if (force || !this.socket || this.socket.readyState !== this._readyStateConstants.OPEN) { + this.socket = $websocketBackend.create(this.url, this.protocols); + this.socket.onmessage = _angular2.default.bind(this, this._onMessageHandler); + this.socket.onopen = _angular2.default.bind(this, this._onOpenHandler); + this.socket.onerror = _angular2.default.bind(this, this._onErrorHandler); + this.socket.onclose = _angular2.default.bind(this, this._onCloseHandler); + this.socket.binaryType = this.binaryType; + } + }; + + $WebSocket.prototype.fireQueue = function fireQueue() { + while (this.sendQueue.length && this.socket.readyState === this._readyStateConstants.OPEN) { + var data = this.sendQueue.shift(); + + this.socket.send(isString(data.message) || this.binaryType != 'blob' ? data.message : JSON.stringify(data.message)); + data.deferred.resolve(); + } + }; + + $WebSocket.prototype.notifyOpenCallbacks = function notifyOpenCallbacks(event) { + for (var i = 0; i < this.onOpenCallbacks.length; i++) { + this.onOpenCallbacks[i].call(this, event); + } + }; + + $WebSocket.prototype.notifyCloseCallbacks = function notifyCloseCallbacks(event) { + for (var i = 0; i < this.onCloseCallbacks.length; i++) { + this.onCloseCallbacks[i].call(this, event); + } + }; + + $WebSocket.prototype.notifyErrorCallbacks = function notifyErrorCallbacks(event) { + for (var i = 0; i < this.onErrorCallbacks.length; i++) { + this.onErrorCallbacks[i].call(this, event); + } + }; + + $WebSocket.prototype.onOpen = function onOpen(cb) { + this.onOpenCallbacks.push(cb); + return this; + }; + + $WebSocket.prototype.onClose = function onClose(cb) { + this.onCloseCallbacks.push(cb); + return this; + }; + + $WebSocket.prototype.onError = function onError(cb) { + this.onErrorCallbacks.push(cb); + return this; + }; + + $WebSocket.prototype.onMessage = function onMessage(callback, options) { + if (!isFunction(callback)) { + throw new Error('Callback must be a function'); + } + + if (options && isDefined(options.filter) && !isString(options.filter) && !(options.filter instanceof RegExp)) { + throw new Error('Pattern must be a string or regular expression'); + } + + this.onMessageCallbacks.push({ + fn: callback, + pattern: options ? options.filter : undefined, + autoApply: options ? options.autoApply : true + }); + return this; + }; + + $WebSocket.prototype._onOpenHandler = function _onOpenHandler(event) { + this._reconnectAttempts = 0; + this.notifyOpenCallbacks(event); + this.fireQueue(); + }; + + $WebSocket.prototype._onCloseHandler = function _onCloseHandler(event) { + var self = this; + if (self.useApplyAsync) { + self.scope.$applyAsync(function () { + self.notifyCloseCallbacks(event); + }); + } else { + self.notifyCloseCallbacks(event); + self.safeDigest(true); + } + if (this.reconnectIfNotNormalClose && event.code !== this._normalCloseCode || this._reconnectableStatusCodes.indexOf(event.code) > -1) { + this.reconnect(); + } + }; + + $WebSocket.prototype._onErrorHandler = function _onErrorHandler(event) { + var self = this; + if (self.useApplyAsync) { + self.scope.$applyAsync(function () { + self.notifyErrorCallbacks(event); + }); + } else { + self.notifyErrorCallbacks(event); + self.safeDigest(true); + } + }; + + $WebSocket.prototype._onMessageHandler = function _onMessageHandler(message) { + var pattern; + var self = this; + var currentCallback; + for (var i = 0; i < self.onMessageCallbacks.length; i++) { + currentCallback = self.onMessageCallbacks[i]; + pattern = currentCallback.pattern; + if (pattern) { + if (isString(pattern) && message.data === pattern) { + applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message); + } else if (pattern instanceof RegExp && pattern.exec(message.data)) { + applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message); + } + } else { + applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message); + } + } + + function applyAsyncOrDigest(callback, autoApply, args) { + args = arraySlice.call(arguments, 2); + if (self.useApplyAsync) { + self.scope.$applyAsync(function () { + callback.apply(self, args); + }); + } else { + callback.apply(self, args); + self.safeDigest(autoApply); + } + } + }; + + $WebSocket.prototype.close = function close(force) { + if (force || !this.socket.bufferedAmount) { + this.socket.close(); + } + return this; + }; + + $WebSocket.prototype.send = function send(data) { + var deferred = $q.defer(); + var self = this; + var promise = cancelableify(deferred.promise); + + if (self.readyState === self._readyStateConstants.RECONNECT_ABORTED) { + deferred.reject('Socket connection has been closed'); + } else { + self.sendQueue.push({ + message: data, + deferred: deferred + }); + self.fireQueue(); + } + + // Credit goes to @btford + function cancelableify(promise) { + promise.cancel = cancel; + var then = promise.then; + promise.then = function () { + var newPromise = then.apply(this, arguments); + return cancelableify(newPromise); + }; + return promise; + } + + function cancel(reason) { + self.sendQueue.splice(self.sendQueue.indexOf(data), 1); + deferred.reject(reason); + return self; + } + + if ($websocketBackend.isMocked && $websocketBackend.isMocked() && $websocketBackend.isConnected(this.url)) { + this._onMessageHandler($websocketBackend.mockSend()); + } + + return promise; + }; + + $WebSocket.prototype.reconnect = function reconnect() { + this.close(); + + var backoffDelay = this._getBackoffDelay(++this._reconnectAttempts); + + var backoffDelaySeconds = backoffDelay / 1000; + console.log('Reconnecting in ' + backoffDelaySeconds + ' seconds'); + + $timeout(_angular2.default.bind(this, this._connect), backoffDelay); + + return this; + }; + // Exponential Backoff Formula by Prof. Douglas Thain + // http://dthain.blogspot.co.uk/2009/02/exponential-backoff-in-distributed.html + $WebSocket.prototype._getBackoffDelay = function _getBackoffDelay(attempt) { + var R = Math.random() + 1; + var T = this.initialTimeout; + var F = 2; + var N = attempt; + var M = this.maxTimeout; + + return Math.floor(Math.min(R * T * Math.pow(F, N), M)); + }; + + $WebSocket.prototype._setInternalState = function _setInternalState(state) { + if (Math.floor(state) !== state || state < 0 || state > 4) { + throw new Error('state must be an integer between 0 and 4, got: ' + state); + } + + // ie8 wat + if (!objectDefineProperty) { + this.readyState = state || this.socket.readyState; + } + this._internalConnectionState = state; + + forEach(this.sendQueue, function (pending) { + pending.deferred.reject('Message cancelled due to closed socket connection'); + }); + }; + + // Read only .readyState + if (objectDefineProperty) { + objectDefineProperty($WebSocket.prototype, 'readyState', { + get: function get() { + return this._internalConnectionState || this.socket.readyState; + }, + set: function set() { + throw new Error('The readyState property is read-only'); + } + }); + } + + return function (url, protocols, options) { + return new $WebSocket(url, protocols, options); + }; + } + + // $WebSocketBackendProvider.$inject = ['$log']; + function $WebSocketBackendProvider($log) { + this.create = function create(url, protocols) { + var match = /wss?:\/\//.exec(url); + + if (!match) { + throw new Error('Invalid url provided'); + } + + if (protocols) { + return new Socket(url, protocols); + } + + return new Socket(url); + }; + + this.createWebSocketBackend = function createWebSocketBackend(url, protocols) { + $log.warn('Deprecated: Please use .create(url, protocols)'); + return this.create(url, protocols); + }; + } + + _angular2.default.module('ngWebSocket', []).factory('$websocket', ['$rootScope', '$q', '$timeout', '$websocketBackend', $WebSocketProvider]).factory('WebSocket', ['$rootScope', '$q', '$timeout', 'WebsocketBackend', $WebSocketProvider]).service('$websocketBackend', ['$log', $WebSocketBackendProvider]).service('WebSocketBackend', ['$log', $WebSocketBackendProvider]); + + _angular2.default.module('angular-websocket', ['ngWebSocket']); + + exports.default = _angular2.default.module('ngWebSocket'); + module.exports = exports['default']; +});
\ No newline at end of file @@ -1,5 +1,5 @@ <?xml version='1.0' encoding='utf-8'?> -<widget android-packageName="com.pliablepixels.zmninja_pro" id="com.pliablepixels.zmninjapro" ios-CFBundleIdentifier="com.pliablepixels.zmninja-pro" version="1.2.510" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> +<widget android-packageName="com.pliablepixels.zmninja_pro" id="com.pliablepixels.zmninjapro" ios-CFBundleIdentifier="com.pliablepixels.zmninja-pro" version="1.2.512" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> <name>zmNinja</name> <description> High performance ZoneMinder client @@ -9,6 +9,7 @@ </author> <content src="index.html" /> <access launch-external="yes" origin="mailto:*" /> + <access allows-arbitrary-loads-for-media="true" allows-arbitrary-loads-in-web-content="true" allows-local-networking="true" origin="*" /> <allow-intent href="mailto:*" /> <allow-navigation href="*" /> <preference name="AndroidPersistentFileLocation" value="Compatibility" /> @@ -100,8 +101,8 @@ </platform> <icon src="resources/android/icon/drawable-xhdpi-icon.png" /> <preference name="SplashShowOnlyFirstTime" value="false" /> - <engine name="ios" spec="4.5.4" /> <engine name="android" spec="^6.3.0" /> + <engine name="ios" spec="4.5.4" /> <plugin name="com.telerik.plugins.nativepagetransitions" spec="^0.6.5" /> <plugin name="cordova-library-helper" spec="^1.0.4"> <variable name="PHOTO_LIBRARY_USAGE_DESCRIPTION" value="Save media to your Camera Roll" /> diff --git a/package.json b/package.json index 07e37e6e..b54dbe0a 100644 --- a/package.json +++ b/package.json @@ -4,8 +4,8 @@ "displayName": "zmNinja", "cordova": { "platforms": [ - "ios", - "android" + "android", + "ios" ], "plugins": { "com.telerik.plugins.nativepagetransitions": {}, diff --git a/www/external/angular-websocket.js b/www/external/angular-websocket.js new file mode 100644 index 00000000..b2317cdd --- /dev/null +++ b/www/external/angular-websocket.js @@ -0,0 +1,415 @@ +(function (global, factory) { + if (typeof define === "function" && define.amd) { + define(['module', 'exports', 'angular', 'ws'], factory); + } else if (typeof exports !== "undefined") { + factory(module, exports, require('angular'), require('ws')); + } else { + var mod = { + exports: {} + }; + factory(mod, mod.exports, global.angular, global.ws); + global.angularWebsocket = mod.exports; + } +})(this, function (module, exports, _angular, ws) { + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _angular2 = _interopRequireDefault(_angular); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; + }; + + var Socket; + + if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object' && typeof require === 'function') { + try { + + Socket = ws.Client || ws.client || ws; + } catch (e) {} + } + + // Browser + Socket = Socket || window.WebSocket || window.MozWebSocket; + + var noop = _angular2.default.noop; + var objectFreeze = Object.freeze ? Object.freeze : noop; + var objectDefineProperty = Object.defineProperty; + var isString = _angular2.default.isString; + var isFunction = _angular2.default.isFunction; + var isDefined = _angular2.default.isDefined; + var isObject = _angular2.default.isObject; + var isArray = _angular2.default.isArray; + var forEach = _angular2.default.forEach; + var arraySlice = Array.prototype.slice; + // ie8 wat + if (!Array.prototype.indexOf) { + Array.prototype.indexOf = function (elt /*, from*/) { + var len = this.length >>> 0; + var from = Number(arguments[1]) || 0; + from = from < 0 ? Math.ceil(from) : Math.floor(from); + if (from < 0) { + from += len; + } + + for (; from < len; from++) { + if (from in this && this[from] === elt) { + return from; + } + } + return -1; + }; + } + + // $WebSocketProvider.$inject = ['$rootScope', '$q', '$timeout', '$websocketBackend']; + function $WebSocketProvider($rootScope, $q, $timeout, $websocketBackend) { + + function $WebSocket(url, protocols, options) { + if (!options && isObject(protocols) && !isArray(protocols)) { + options = protocols; + protocols = undefined; + } + + this.protocols = protocols; + this.url = url || 'Missing URL'; + this.ssl = /(wss)/i.test(this.url); + + // this.binaryType = ''; + // this.extensions = ''; + // this.bufferedAmount = 0; + // this.trasnmitting = false; + // this.buffer = []; + + // TODO: refactor options to use isDefined + this.scope = options && options.scope || $rootScope; + this.rootScopeFailover = options && options.rootScopeFailover && true; + this.useApplyAsync = options && options.useApplyAsync || false; + this.initialTimeout = options && options.initialTimeout || 500; // 500ms + this.maxTimeout = options && options.maxTimeout || 5 * 60 * 1000; // 5 minutes + this.reconnectIfNotNormalClose = options && options.reconnectIfNotNormalClose || false; + this.binaryType = options && options.binaryType || 'blob'; + + this._reconnectAttempts = 0; + this.sendQueue = []; + this.onOpenCallbacks = []; + this.onMessageCallbacks = []; + this.onErrorCallbacks = []; + this.onCloseCallbacks = []; + + objectFreeze(this._readyStateConstants); + + if (url) { + this._connect(); + } else { + this._setInternalState(0); + } + } + + $WebSocket.prototype._readyStateConstants = { + 'CONNECTING': 0, + 'OPEN': 1, + 'CLOSING': 2, + 'CLOSED': 3, + 'RECONNECT_ABORTED': 4 + }; + + $WebSocket.prototype._normalCloseCode = 1000; + + $WebSocket.prototype._reconnectableStatusCodes = [4000]; + + $WebSocket.prototype.safeDigest = function safeDigest(autoApply) { + if (autoApply && !this.scope.$$phase) { + this.scope.$digest(); + } + }; + + $WebSocket.prototype.bindToScope = function bindToScope(scope) { + var self = this; + if (scope) { + this.scope = scope; + if (this.rootScopeFailover) { + this.scope.$on('$destroy', function () { + self.scope = $rootScope; + }); + } + } + return self; + }; + + $WebSocket.prototype._connect = function _connect(force) { + if (force || !this.socket || this.socket.readyState !== this._readyStateConstants.OPEN) { + this.socket = $websocketBackend.create(this.url, this.protocols); + this.socket.onmessage = _angular2.default.bind(this, this._onMessageHandler); + this.socket.onopen = _angular2.default.bind(this, this._onOpenHandler); + this.socket.onerror = _angular2.default.bind(this, this._onErrorHandler); + this.socket.onclose = _angular2.default.bind(this, this._onCloseHandler); + this.socket.binaryType = this.binaryType; + } + }; + + $WebSocket.prototype.fireQueue = function fireQueue() { + while (this.sendQueue.length && this.socket.readyState === this._readyStateConstants.OPEN) { + var data = this.sendQueue.shift(); + + this.socket.send(isString(data.message) || this.binaryType != 'blob' ? data.message : JSON.stringify(data.message)); + data.deferred.resolve(); + } + }; + + $WebSocket.prototype.notifyOpenCallbacks = function notifyOpenCallbacks(event) { + for (var i = 0; i < this.onOpenCallbacks.length; i++) { + this.onOpenCallbacks[i].call(this, event); + } + }; + + $WebSocket.prototype.notifyCloseCallbacks = function notifyCloseCallbacks(event) { + for (var i = 0; i < this.onCloseCallbacks.length; i++) { + this.onCloseCallbacks[i].call(this, event); + } + }; + + $WebSocket.prototype.notifyErrorCallbacks = function notifyErrorCallbacks(event) { + for (var i = 0; i < this.onErrorCallbacks.length; i++) { + this.onErrorCallbacks[i].call(this, event); + } + }; + + $WebSocket.prototype.onOpen = function onOpen(cb) { + this.onOpenCallbacks.push(cb); + return this; + }; + + $WebSocket.prototype.onClose = function onClose(cb) { + this.onCloseCallbacks.push(cb); + return this; + }; + + $WebSocket.prototype.onError = function onError(cb) { + this.onErrorCallbacks.push(cb); + return this; + }; + + $WebSocket.prototype.onMessage = function onMessage(callback, options) { + if (!isFunction(callback)) { + throw new Error('Callback must be a function'); + } + + if (options && isDefined(options.filter) && !isString(options.filter) && !(options.filter instanceof RegExp)) { + throw new Error('Pattern must be a string or regular expression'); + } + + this.onMessageCallbacks.push({ + fn: callback, + pattern: options ? options.filter : undefined, + autoApply: options ? options.autoApply : true + }); + return this; + }; + + $WebSocket.prototype._onOpenHandler = function _onOpenHandler(event) { + this._reconnectAttempts = 0; + this.notifyOpenCallbacks(event); + this.fireQueue(); + }; + + $WebSocket.prototype._onCloseHandler = function _onCloseHandler(event) { + var self = this; + if (self.useApplyAsync) { + self.scope.$applyAsync(function () { + self.notifyCloseCallbacks(event); + }); + } else { + self.notifyCloseCallbacks(event); + self.safeDigest(true); + } + if (this.reconnectIfNotNormalClose && event.code !== this._normalCloseCode || this._reconnectableStatusCodes.indexOf(event.code) > -1) { + this.reconnect(); + } + }; + + $WebSocket.prototype._onErrorHandler = function _onErrorHandler(event) { + var self = this; + if (self.useApplyAsync) { + self.scope.$applyAsync(function () { + self.notifyErrorCallbacks(event); + }); + } else { + self.notifyErrorCallbacks(event); + self.safeDigest(true); + } + }; + + $WebSocket.prototype._onMessageHandler = function _onMessageHandler(message) { + var pattern; + var self = this; + var currentCallback; + for (var i = 0; i < self.onMessageCallbacks.length; i++) { + currentCallback = self.onMessageCallbacks[i]; + pattern = currentCallback.pattern; + if (pattern) { + if (isString(pattern) && message.data === pattern) { + applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message); + } else if (pattern instanceof RegExp && pattern.exec(message.data)) { + applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message); + } + } else { + applyAsyncOrDigest(currentCallback.fn, currentCallback.autoApply, message); + } + } + + function applyAsyncOrDigest(callback, autoApply, args) { + args = arraySlice.call(arguments, 2); + if (self.useApplyAsync) { + self.scope.$applyAsync(function () { + callback.apply(self, args); + }); + } else { + callback.apply(self, args); + self.safeDigest(autoApply); + } + } + }; + + $WebSocket.prototype.close = function close(force) { + if (force || !this.socket.bufferedAmount) { + this.socket.close(); + } + return this; + }; + + $WebSocket.prototype.send = function send(data) { + var deferred = $q.defer(); + var self = this; + var promise = cancelableify(deferred.promise); + + if (self.readyState === self._readyStateConstants.RECONNECT_ABORTED) { + deferred.reject('Socket connection has been closed'); + } else { + self.sendQueue.push({ + message: data, + deferred: deferred + }); + self.fireQueue(); + } + + // Credit goes to @btford + function cancelableify(promise) { + promise.cancel = cancel; + var then = promise.then; + promise.then = function () { + var newPromise = then.apply(this, arguments); + return cancelableify(newPromise); + }; + return promise; + } + + function cancel(reason) { + self.sendQueue.splice(self.sendQueue.indexOf(data), 1); + deferred.reject(reason); + return self; + } + + if ($websocketBackend.isMocked && $websocketBackend.isMocked() && $websocketBackend.isConnected(this.url)) { + this._onMessageHandler($websocketBackend.mockSend()); + } + + return promise; + }; + + $WebSocket.prototype.reconnect = function reconnect() { + this.close(); + + var backoffDelay = this._getBackoffDelay(++this._reconnectAttempts); + + var backoffDelaySeconds = backoffDelay / 1000; + console.log('Reconnecting in ' + backoffDelaySeconds + ' seconds'); + + $timeout(_angular2.default.bind(this, this._connect), backoffDelay); + + return this; + }; + // Exponential Backoff Formula by Prof. Douglas Thain + // http://dthain.blogspot.co.uk/2009/02/exponential-backoff-in-distributed.html + $WebSocket.prototype._getBackoffDelay = function _getBackoffDelay(attempt) { + var R = Math.random() + 1; + var T = this.initialTimeout; + var F = 2; + var N = attempt; + var M = this.maxTimeout; + + return Math.floor(Math.min(R * T * Math.pow(F, N), M)); + }; + + $WebSocket.prototype._setInternalState = function _setInternalState(state) { + if (Math.floor(state) !== state || state < 0 || state > 4) { + throw new Error('state must be an integer between 0 and 4, got: ' + state); + } + + // ie8 wat + if (!objectDefineProperty) { + this.readyState = state || this.socket.readyState; + } + this._internalConnectionState = state; + + forEach(this.sendQueue, function (pending) { + pending.deferred.reject('Message cancelled due to closed socket connection'); + }); + }; + + // Read only .readyState + if (objectDefineProperty) { + objectDefineProperty($WebSocket.prototype, 'readyState', { + get: function get() { + return this._internalConnectionState || this.socket.readyState; + }, + set: function set() { + throw new Error('The readyState property is read-only'); + } + }); + } + + return function (url, protocols, options) { + return new $WebSocket(url, protocols, options); + }; + } + + // $WebSocketBackendProvider.$inject = ['$log']; + function $WebSocketBackendProvider($log) { + this.create = function create(url, protocols) { + var match = /wss?:\/\//.exec(url); + + if (!match) { + throw new Error('Invalid url provided'); + } + + if (protocols) { + return new Socket(url, protocols); + } + + return new Socket(url); + }; + + this.createWebSocketBackend = function createWebSocketBackend(url, protocols) { + $log.warn('Deprecated: Please use .create(url, protocols)'); + return this.create(url, protocols); + }; + } + + _angular2.default.module('ngWebSocket', []).factory('$websocket', ['$rootScope', '$q', '$timeout', '$websocketBackend', $WebSocketProvider]).factory('WebSocket', ['$rootScope', '$q', '$timeout', 'WebsocketBackend', $WebSocketProvider]).service('$websocketBackend', ['$log', $WebSocketBackendProvider]).service('WebSocketBackend', ['$log', $WebSocketBackendProvider]); + + _angular2.default.module('angular-websocket', ['ngWebSocket']); + + exports.default = _angular2.default.module('ngWebSocket'); + module.exports = exports['default']; +});
\ No newline at end of file diff --git a/www/external/angular-websocket.min.js b/www/external/angular-websocket.min.js new file mode 100644 index 00000000..0d82580f --- /dev/null +++ b/www/external/angular-websocket.min.js @@ -0,0 +1,2 @@ +!function(e,t){if("function"==typeof define&&define.amd)define(["module","exports","angular","ws"],t);else if("undefined"!=typeof exports)t(module,exports,require("angular"),require("ws"));else{var o={exports:{}};t(o,o.exports,e.angular,e.ws),e.angularWebsocket=o.exports}}(this,function(e,t,o,n){"use strict";function s(e){return e&&e.__esModule?e:{"default":e}}function r(e,t,o,n){function s(t,o,n){n||!k(o)||C(o)||(n=o,o=void 0),this.protocols=o,this.url=t||"Missing URL",this.ssl=/(wss)/i.test(this.url),this.scope=n&&n.scope||e,this.rootScopeFailover=n&&n.rootScopeFailover&&!0,this.useApplyAsync=n&&n.useApplyAsync||!1,this.initialTimeout=n&&n.initialTimeout||500,this.maxTimeout=n&&n.maxTimeout||3e5,this.reconnectIfNotNormalClose=n&&n.reconnectIfNotNormalClose||!1,this.binaryType=n&&n.binaryType||"blob",this._reconnectAttempts=0,this.sendQueue=[],this.onOpenCallbacks=[],this.onMessageCallbacks=[],this.onErrorCallbacks=[],this.onCloseCallbacks=[],f(this._readyStateConstants),t?this._connect():this._setInternalState(0)}return s.prototype._readyStateConstants={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3,RECONNECT_ABORTED:4},s.prototype._normalCloseCode=1e3,s.prototype._reconnectableStatusCodes=[4e3],s.prototype.safeDigest=function(e){e&&!this.scope.$$phase&&this.scope.$digest()},s.prototype.bindToScope=function(t){var o=this;return t&&(this.scope=t,this.rootScopeFailover&&this.scope.$on("$destroy",function(){o.scope=e})),o},s.prototype._connect=function(e){!e&&this.socket&&this.socket.readyState===this._readyStateConstants.OPEN||(this.socket=n.create(this.url,this.protocols),this.socket.onmessage=c["default"].bind(this,this._onMessageHandler),this.socket.onopen=c["default"].bind(this,this._onOpenHandler),this.socket.onerror=c["default"].bind(this,this._onErrorHandler),this.socket.onclose=c["default"].bind(this,this._onCloseHandler),this.socket.binaryType=this.binaryType)},s.prototype.fireQueue=function(){for(;this.sendQueue.length&&this.socket.readyState===this._readyStateConstants.OPEN;){var e=this.sendQueue.shift();this.socket.send(d(e.message)||"blob"!=this.binaryType?e.message:JSON.stringify(e.message)),e.deferred.resolve()}},s.prototype.notifyOpenCallbacks=function(e){for(var t=0;t<this.onOpenCallbacks.length;t++)this.onOpenCallbacks[t].call(this,e)},s.prototype.notifyCloseCallbacks=function(e){for(var t=0;t<this.onCloseCallbacks.length;t++)this.onCloseCallbacks[t].call(this,e)},s.prototype.notifyErrorCallbacks=function(e){for(var t=0;t<this.onErrorCallbacks.length;t++)this.onErrorCallbacks[t].call(this,e)},s.prototype.onOpen=function(e){return this.onOpenCallbacks.push(e),this},s.prototype.onClose=function(e){return this.onCloseCallbacks.push(e),this},s.prototype.onError=function(e){return this.onErrorCallbacks.push(e),this},s.prototype.onMessage=function(e,t){if(!y(e))throw new Error("Callback must be a function");if(t&&b(t.filter)&&!d(t.filter)&&!(t.filter instanceof RegExp))throw new Error("Pattern must be a string or regular expression");return this.onMessageCallbacks.push({fn:e,pattern:t?t.filter:void 0,autoApply:t?t.autoApply:!0}),this},s.prototype._onOpenHandler=function(e){this._reconnectAttempts=0,this.notifyOpenCallbacks(e),this.fireQueue()},s.prototype._onCloseHandler=function(e){var t=this;t.useApplyAsync?t.scope.$applyAsync(function(){t.notifyCloseCallbacks(e)}):(t.notifyCloseCallbacks(e),t.safeDigest(!0)),(this.reconnectIfNotNormalClose&&e.code!==this._normalCloseCode||this._reconnectableStatusCodes.indexOf(e.code)>-1)&&this.reconnect()},s.prototype._onErrorHandler=function(e){var t=this;t.useApplyAsync?t.scope.$applyAsync(function(){t.notifyErrorCallbacks(e)}):(t.notifyErrorCallbacks(e),t.safeDigest(!0))},s.prototype._onMessageHandler=function(e){function t(e,t,o){o=m.call(arguments,2),s.useApplyAsync?s.scope.$applyAsync(function(){e.apply(s,o)}):(e.apply(s,o),s.safeDigest(t))}for(var o,n,s=this,r=0;r<s.onMessageCallbacks.length;r++)n=s.onMessageCallbacks[r],o=n.pattern,o?d(o)&&e.data===o?t(n.fn,n.autoApply,e):o instanceof RegExp&&o.exec(e.data)&&t(n.fn,n.autoApply,e):t(n.fn,n.autoApply,e)},s.prototype.close=function(e){return!e&&this.socket.bufferedAmount||this.socket.close(),this},s.prototype.send=function(e){function o(e){e.cancel=s;var t=e.then;return e.then=function(){var e=t.apply(this,arguments);return o(e)},e}function s(t){return i.sendQueue.splice(i.sendQueue.indexOf(e),1),r.reject(t),i}var r=t.defer(),i=this,a=o(r.promise);return i.readyState===i._readyStateConstants.RECONNECT_ABORTED?r.reject("Socket connection has been closed"):(i.sendQueue.push({message:e,deferred:r}),i.fireQueue()),n.isMocked&&n.isMocked()&&n.isConnected(this.url)&&this._onMessageHandler(n.mockSend()),a},s.prototype.reconnect=function(){this.close();var e=this._getBackoffDelay(++this._reconnectAttempts),t=e/1e3;return console.log("Reconnecting in "+t+" seconds"),o(c["default"].bind(this,this._connect),e),this},s.prototype._getBackoffDelay=function(e){var t=Math.random()+1,o=this.initialTimeout,n=2,s=e,r=this.maxTimeout;return Math.floor(Math.min(t*o*Math.pow(n,s),r))},s.prototype._setInternalState=function(e){if(Math.floor(e)!==e||0>e||e>4)throw new Error("state must be an integer between 0 and 4, got: "+e);h||(this.readyState=e||this.socket.readyState),this._internalConnectionState=e,g(this.sendQueue,function(e){e.deferred.reject("Message cancelled due to closed socket connection")})},h&&h(s.prototype,"readyState",{get:function(){return this._internalConnectionState||this.socket.readyState},set:function(){throw new Error("The readyState property is read-only")}}),function(e,t,o){return new s(e,t,o)}}function i(e){this.create=function(e,t){var o=/wss?:\/\//.exec(e);if(!o)throw new Error("Invalid url provided");return t?new a(e,t):new a(e)},this.createWebSocketBackend=function(t,o){return e.warn("Deprecated: Please use .create(url, protocols)"),this.create(t,o)}}Object.defineProperty(t,"__esModule",{value:!0});var a,c=s(o),l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};if("object"===("undefined"==typeof t?"undefined":l(t))&&"function"==typeof require)try{a=n.Client||n.client||n}catch(u){}a=a||window.WebSocket||window.MozWebSocket;var p=c["default"].noop,f=Object.freeze?Object.freeze:p,h=Object.defineProperty,d=c["default"].isString,y=c["default"].isFunction,b=c["default"].isDefined,k=c["default"].isObject,C=c["default"].isArray,g=c["default"].forEach,m=Array.prototype.slice;Array.prototype.indexOf||(Array.prototype.indexOf=function(e){var t=this.length>>>0,o=Number(arguments[1])||0;for(o=0>o?Math.ceil(o):Math.floor(o),0>o&&(o+=t);t>o;o++)if(o in this&&this[o]===e)return o;return-1}),c["default"].module("ngWebSocket",[]).factory("$websocket",["$rootScope","$q","$timeout","$websocketBackend",r]).factory("WebSocket",["$rootScope","$q","$timeout","WebsocketBackend",r]).service("$websocketBackend",["$log",i]).service("WebSocketBackend",["$log",i]),c["default"].module("angular-websocket",["ngWebSocket"]),t["default"]=c["default"].module("ngWebSocket"),e.exports=t["default"]}); +//# sourceMappingURL=angular-websocket.min.js.map diff --git a/www/index.html b/www/index.html index cf7728bf..bc79ad6d 100644 --- a/www/index.html +++ b/www/index.html @@ -7,7 +7,7 @@ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover"> - <meta http-equiv="Content-Security-Policy" content="img-src * blob: android-webview-video-poster: cdvphotolibrary: 'self' data: ws: wss://*; default-src * blob: 'self' gap: wss: ws: data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src * http: https: ws: wss://*;"> + <meta http-equiv="Content-Security-Policy" content="img-src * blob: android-webview-video-poster: cdvphotolibrary: 'self' data: ws: wss://*; default-src * blob: 'self' gap: wss: ws: data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src * http: https: ws: wss:;"> @@ -68,7 +68,11 @@ <script src="external/moment-timezone-with-data.min.js"></script> <script src="external/angular-ios9-uiwebview.patch.js"></script> <script src="external/ionRadio.min.js"></script> - <script src="external/ng-websocket.min.js"></script> + + <!--<script src="external/ng-websocket.min.js"></script>--> + <script src="external/angular-websocket.js"></script> + + <script src="external/uri.min.js"></script> <script src="external/angular-carousel.min.js"></script> <script src="external/ion-pullup.min.js"></script> diff --git a/www/js/EventServer.js b/www/js/EventServer.js index c07a3e06..2eacf653 100644 --- a/www/js/EventServer.js +++ b/www/js/EventServer.js @@ -17,12 +17,14 @@ angular.module('zmApp.controllers') var localNotificationId = 0; var firstError = true; + var pushInited = false; //-------------------------------------------------------------------------- // called when the websocket is opened //-------------------------------------------------------------------------- function openHandshake() { + NVRDataModel.log ("Inside openHandshake"); var loginData = NVRDataModel.getLogin(); if (loginData.isUseEventServer == false || loginData.eventServer == "") { @@ -30,11 +32,15 @@ angular.module('zmApp.controllers') return; } - NVRDataModel.log("openHandshake: Websocket open"); - ws.$emit('auth', + NVRDataModel.log("openHandshake: Websocket open, sending Auth"); + ws.send( { - user: loginData.username, - password: loginData.password + event:'auth', + data: { + user: loginData.username, + password: loginData.password + } + }); if ($rootScope.apnsToken != '') @@ -52,14 +58,17 @@ angular.module('zmApp.controllers') if (1) { //console.log ("HANDSHAKE MESSAGE WITH "+$rootScope.monstring); - ws.$emit('push', + ws.send( { - type: 'token', - platform: plat, - token: $rootScope.apnsToken, - monlist:$rootScope.monstring, - intlist:$rootScope.intstring, - state: pushstate + event:'push', + data :{ + type: 'token', + platform: plat, + token: $rootScope.apnsToken, + monlist:$rootScope.monstring, + intlist:$rootScope.intstring, + state: pushstate + } }); } } @@ -89,7 +98,7 @@ angular.module('zmApp.controllers') } //if (!$rootScope.apnsToken) - pushInit(); + if (!pushInited) pushInit(); if (typeof ws !== 'undefined') { @@ -99,20 +108,24 @@ angular.module('zmApp.controllers') } NVRDataModel.log("Initializing Websocket with URL " + - loginData.eventServer + " , will connect later..."); - ws = $websocket.$new( + loginData.eventServer ); + /* ws = $websocket.$new( { url: loginData.eventServer, reconnect: true, reconnectInterval: 60000, lazy: true - }); + });*/ + + ws = $websocket(loginData.eventServer,{reconnectIfNotNormalClose: true}); + ws.onOpen(openHandshake); // Transmit auth information to server - ws.$on('$open', openHandshake); + // ws.$on('$open', openHandshake); NVRDataModel.debug("Setting up websocket error handler"); - ws.$on('$error', function(e) + //ws.$on('$error', function(e) + ws.onError(function (e) { // we don't need this check as I changed reconnect interval to 60s @@ -126,21 +139,33 @@ angular.module('zmApp.controllers') }, 3000); // leave 3 seconds for transitions firstError = false; lastEventServerCheck = Date.now(); + ws.close(); + ws = undefined; + + // NVRDataModel.log ("Will try to reconnect in 10 sec.."); + // $timeout ( init, 10000 ); } //console.log ("VALUE TIME " + lastEventServerCheck); //console.log ("NOW TIME " + Date.now()); }); - ws.$on('$close', function() + ws.onClose( function () + // ws.$on('$close', function() { NVRDataModel.log("Websocket closed"); + ws = undefined; }); // Handles responses back from ZM ES - ws.$on('$message', function(str) + ws.onMessage (function (str) + // ws.$on('$message', function(str) { + if (str.isTrusted) { + NVRDataModel.log ("Got isTrusted="+str.isTrusted); + return; + } NVRDataModel.log("Real-time event: " + JSON.stringify(str)); // Error messages @@ -150,7 +175,7 @@ angular.module('zmApp.controllers') if (str.reason == 'APNSDISABLED') { - ws.$close(); + ws.close(); NVRDataModel.displayBanner('error', ['Event Server: APNS disabled'], 2000, 6000); $rootScope.apnsToken = ""; } @@ -261,10 +286,11 @@ angular.module('zmApp.controllers') if (typeof ws === 'undefined') return; - ws.$close(); - ws.$un('open'); - ws.$un('close'); - ws.$un('message'); + // ws.$close(); + ws.close(); + // ws.$un('open'); + // ws.$un('close'); + // ws.$un('message'); ws = undefined; } @@ -292,7 +318,12 @@ angular.module('zmApp.controllers') return; } - if (ws.$status() == ws.$CLOSED) + ws.send({ + 'event':type, + 'data': obj + }); + + /*if (ws.$status() == ws.$CLOSED) { NVRDataModel.log("Websocket was closed, trying to re-open"); ws.$un('$open'); @@ -313,11 +344,11 @@ angular.module('zmApp.controllers') }); } - else + else* { - ws.$emit(type, obj); + ws.send(type, obj); // console.log("sending " + type + " " + JSON.stringify(obj)); - } + }*/ } @@ -337,11 +368,11 @@ angular.module('zmApp.controllers') if (typeof ws !== 'undefined') { - if (ws.$status() != ws.$CLOSED) + /*(if (ws.$status() != ws.$CLOSED) { NVRDataModel.debug("Closing open websocket as event server was disabled"); ws.$close(); - } + }*/ } return; @@ -360,11 +391,11 @@ angular.module('zmApp.controllers') // c) The network died // Seems to me in all cases we should give re-open a shot - if (ws.$status() == ws.$CLOSED) + /*if (ws.$status() == ws.$CLOSED) { NVRDataModel.log("Websocket was closed, trying to re-open"); ws.$open(); - } + }*/ } @@ -431,6 +462,7 @@ angular.module('zmApp.controllers') push.on('registration', function(data) { + pushInited = true; NVRDataModel.debug("Push Notification registration ID received: " + JSON.stringify(data)); $rootScope.apnsToken = data.registrationId; diff --git a/www/js/app.js b/www/js/app.js index a4fafc9e..892fc3d3 100755 --- a/www/js/app.js +++ b/www/js/app.js @@ -29,7 +29,8 @@ angular.module('zmApp', [ 'jett.ionic.scroll.sista', 'uk.ac.soton.ecs.videogular.plugins.cuepoints', 'dcbImgFallback', - 'ngImageAppear' + 'ngImageAppear', + 'angular-websocket' ]) diff --git a/www/js/controllers.js b/www/js/controllers.js index 5321384b..0f4d3976 100644 --- a/www/js/controllers.js +++ b/www/js/controllers.js @@ -4,7 +4,7 @@ -angular.module('zmApp.controllers', ['ionic', 'ionic.utils', 'ngCordova', 'ng-mfb', 'angularCircularNavigation', 'jett.ionic.content.banner', 'ionic-pullup', 'ngWebsocket']) +angular.module('zmApp.controllers', ['ionic', 'ionic.utils', 'ngCordova', 'ng-mfb', 'angularCircularNavigation', 'jett.ionic.content.banner', 'ionic-pullup']) .controller('zmApp.BaseController', function ($scope, $ionicSideMenuDelegate, $ionicPlatform, $timeout, $rootScope) { $scope.openMenu = function () { |
