// DYMICO_TRANSPILER_V=v2-cleanroom1 source=gs-in-dymico runtime=dymicoAsset cacheTier=mem console.log("[DYMICO_TRANSPILER_V=v2-cleanroom1 source=gs-in-dymico runtime=dymicoAsset cacheTier=mem]"); if (typeof gs === "undefined" || typeof gs.mc !== "function") { /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function() { var gs = function(obj) { if (obj instanceof gs) return obj; if (!(this instanceof gs)) return new gs(obj); }; var root = this; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = gs; } exports.gs = gs; } else { root.gs = gs; } //Fails gs.fails = false; //Local console gs.consoleData = ''; //If true and console is available, all output will go through console gs.consoleOutput = true; //If true and console is available, some methods will show info on console gs.consoleInfo = false; var globalMetaClass = {}; //Categories var categories = []; // Mixins var mixins = []; var mixinsObjects = []; //Delegate var delegates = []; //Static this var aStT = null; //@Delegate var mapAddDelegate = {}; gs.myCategories = {}; ///////////////////////////////////////////////////////////////// // assert and println ///////////////////////////////////////////////////////////////// gs.assert = function(value) { if(value === false) { gs.fails = true; var message = 'Assert Fails! - '; if (arguments.length == 2 && arguments[1] !== null) { message = arguments[1] + ' - '; } gs.println(message + value); } }; //Function that used for print and println in groovy gs.println = function(value) { if (gs.consoleOutput) { console.log(value); } else { if (gs.consoleData !== "") { gs.consoleData = gs.consoleData + "\n"; } gs.consoleData = gs.consoleData + value; } }; gs.printNashorn = function(value) { print(value); }; //TODO We don't know if a function is constructor, atm if function name starts with uppercase, it is function isConstructor(name, func) { return name[0] == name[0].toUpperCase(); } function isFunction(f) { return typeof(f) === "function"; } function getterSetterRemove(name) { return name.charAt(3).toLowerCase() + name.slice(4); } ///////////////////////////////////////////////////////////////// // Class functions ///////////////////////////////////////////////////////////////// function BaseClass() { }; gs.BaseClass = BaseClass; //gs.baseClass = { //The with function, with is a reserved word in JavaScript BaseClass.prototype.clazz = {}; BaseClass.prototype.withz = function(closure) { return closure.apply(this, closure.arguments); }, BaseClass.prototype.getProperties = function() { var result = gs.map(), ob; for (ob in this) { if (isFunction(this[ob]) && ob.startsWith('get') && this[ob].length == 0 && ob !== 'getProperties' && ob !== 'getMethods' && ob !== 'getMetaClass') { result.add(getterSetterRemove(ob), this[ob]()); } else if (!isFunction(this[ob]) && ob != 'clazz' && ob.indexOf('__') < 0) { result.add(ob, this[ob]); } } return result; }; BaseClass.prototype.getMethods = function() { var result = gs.list([]), ob; for (ob in this) { if (isFunction(this[ob])) { if (!isObjectProperty(ob) && !(isConstructor(ob, this[ob]))) { var item = { name: ob }; result.add(item); } } } return result; }; BaseClass.prototype.invokeMethod = function(name, values) { var i, newArgs = []; if (values) { for (i=0; i < values.length; i++) { newArgs[i] = values[i]; } } var f = this[name]; return f.apply(this, newArgs); }; BaseClass.prototype.constructor = function() { return this; }; BaseClass.prototype.asType = function(type) { if (hasFunc(type, 'gSaT')) { type.gSaT(this); } return this; }; BaseClass.prototype.withTraits = function() { var i; for (i = 0; i < arguments.length; i++) { arguments[i].gSaT(this); } return this; }; BaseClass.prototype.getClass = function() { return this.clazz; }; BaseClass.prototype.getMetaClass = function() { return gs.metaClass(this); }; function applyBaseClassFunctions(item) { item.asType = BaseClass.prototype.asType; } function isObjectProperty(name) { return ['clazz','gSdefaultValue','leftShift', 'minus','plus','equals','toString', 'clone','withz','getProperties','getStatic', 'getClass', 'getMetaClass', 'getMethods','invokeMethod','constructor', 'asType', 'withTraits'].indexOf(name) >= 0; } function isJsArray(array) { return array['clazz'] === undefined } gs.expando = function() { var object = gs.init('Expando'); object.constructorWithMap = function(map) { gs.passMapToObject(map, this); return this;}; if (arguments.length == 1) {object.constructorWithMap(arguments[0]); } return object; }; gs.expandoMetaClass = function() { var object = gs.init('ExpandoMetaClass'); object.initialize = function() { return this; }; return object; }; function expandWithMetaClass(item, objectName) { if (globalMetaClass && globalMetaClass[objectName]) { var obj, map = globalMetaClass[objectName]; for (obj in map) { //Static methods var staticMap = map.getStatic(); if (staticMap) { var objStatic; for (objStatic in staticMap) { if (objStatic != 'gSparent') { //console.log('Adding static->'+objStatic); item[obj] = staticMap[objStatic]; } } } //Non static methods and properties item[obj] = map[obj]; } } return item; } gs.init = function(name) { return expandWithMetaClass(new BaseClass(), name); }; function createClassNames(item, items) { var number = items.length, i, container; for (i = 0; i < number ; i++) { if (i === 0) { container = {}; item.clazz = container; } container.name = items[i]; container.simpleName = getSimpleName(items[i]); if (i < number) { container.superclass = {}; container = container.superclass; } } } function getSimpleName(name) { var pos = name.indexOf("."); while (pos >= 0) { name = name.substring(pos + 1); pos = name.indexOf("."); } return name; } ///////////////////////////////////////////////////////////////// // set - as Set and HashSet from groovy ///////////////////////////////////////////////////////////////// gs.set = function(value) { var object; if (arguments.length === 0) { object = gs.list([]); } else { object = value; } createClassNames(object, ['java.util.HashSet']); object.isSet = true; object.withz = function(closure) { return interceptClosureCall(closure, this); }; object.add = function(item) { if (!(this.contains(item))) { this.push(item); return this; } else { return false; } }; object.addAll = function(elements) { if (elements instanceof Array) { var i, fails = false; //Check if items not in set for (i = 0; !fails && i < elements.length; i++) { if (this.contains(elements[i])) { fails = true; } } if (fails) { return false; } else { //All ok, we add items to the set for (i = 0; i < elements.length; i++) { this.add(elements[i]); } } } return this; }; object.equals = function(other) { if (!(other instanceof Array) || other.length != this.length || !(other.isSet)) { return false; } else { var i, result = true; for (i = 0; i < this.length && result; i++) { if (!(other.contains(this[i]))) { result = false; } } return result; } }; object.toList = function() { var i, list = []; for (i = 0; i < this.length; i++) { list[i] = this[i]; } return gs.list(list); }; object.plus = function(other) { var result = gs.set(); result.addAll(this); if (other instanceof Array) { var i; for (i = 0; i < other.length; i++) { if (!(result.contains(other[i]))) { result.add(other[i]); } } } return result; }; object.minus = function(other) { var result = gs.set(); result.addAll(this); if (other instanceof Array) { var i; for (i = 0;i < other.length; i++) { if (result.contains(other[i])) { result.remove(other[i]); } } } return result; }; object.remove = function(value) { var index = this.indexOf(value); if (index >= 0) { this.splice(index, 1); return true; } else { return false; } }; return object; }; ///////////////////////////////////////////////////////////////// // map - [:] from groovy ///////////////////////////////////////////////////////////////// function isMapProperty(name) { return isObjectProperty(name) || ['any','collect', 'collectEntries','collectMany','countBy','dropWhile', 'each','eachWithIndex','every','find','findAll', 'findResult','findResults','get','getAt','groupBy', 'inject','intersect','max','min', 'putAll','putAt','reverseEach', 'clear', 'sort','spread','subMap','add','take','takeWhile', 'withDefault','count','drop','keySet', 'put','size','isEmpty','remove','containsKey', 'containsValue','values'].indexOf(name) >= 0; } gs.map = function() { var gSobject = new GsGroovyMap(); expandWithMetaClass(gSobject, 'LinkedHashMap'); applyBaseClassFunctions(gSobject); if (arguments.length == 1 && arguments[0] instanceof Object) { gs.passMapToObject(arguments[0], gSobject); } return gSobject; }; function GsGroovyMap() {} GsGroovyMap.prototype.clazz = { name: 'java.util.LinkedHashMap', simpleName: 'LinkedHashMap', superclass: { name: 'java.util.HashMap', simpleName: 'HashMap'}}; GsGroovyMap.prototype.gSdefaultValue = null; GsGroovyMap.prototype.withz = BaseClass.prototype.withz; GsGroovyMap.prototype.add = function(key, value) { if (key == "spreadMap") { //We insert items of the map, from spread operator var ob; for (ob in value) { if (!isMapProperty(ob)) { this[ob] = value[ob]; } } } else { this[key] = value; } return this; }; GsGroovyMap.prototype.put = function(key,value) { return this.add(key,value); }; GsGroovyMap.prototype.leftShift = function(key,value) { if (arguments.length == 1) { return this.plus(arguments[0]); } else { return this.add(key,value); } }; GsGroovyMap.prototype.putAt = function(key,value) { this.put(key,value); }; GsGroovyMap.prototype.size = function() { var number = 0,ob; for (ob in this) { if (!isMapProperty(ob)) { number++; } } return number; }; GsGroovyMap.prototype.isEmpty = function() { return (this.size() === 0); }; GsGroovyMap.prototype.remove = function(key) { if (this[key]) { delete this[key]; } }; GsGroovyMap.prototype.each = function(closure) { var ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; //Nice, number of arguments in length property if (f.length == 1) { closure({key: ob, value: this[ob]}); } if (f.length == 2) { closure(ob,this[ob]); } } } }; GsGroovyMap.prototype.count = function(closure) { var number = 0, ob; for (ob in this) { if (!isMapProperty(ob)) { if (closure.length == 1) { if (closure({key: ob, value: this[ob]})) { number++; } } if (closure.length == 2) { if (closure(ob, this[ob])) { number++; } } } } return number; }; GsGroovyMap.prototype.any = function(closure) { var ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; if (f.length == 1) { if (closure({key:ob, value: this[ob]})) { return true; } } if (f.length == 2) { if (closure(ob, this[ob])) { return true; } } } } return false; }; GsGroovyMap.prototype.every = function(closure) { var ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; if (f.length == 1) { if (!closure({key: ob, value: this[ob]})) { return false; } } if (f.length == 2) { if (!closure(ob, this[ob])) { return false; } } } } return true; }; GsGroovyMap.prototype.find = function(closure) { var ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; if (f.length == 1) { var entry = {key: ob, value: this[ob]}; if (closure(entry)) { return entry; } } if (f.length == 2) { if (closure(ob, this[ob])) { return {key: ob, value: this[ob]}; } } } } return null; }; GsGroovyMap.prototype.dropWhile = function(closure) { var result = gs.map(), ob; for (ob in this) { if (!isMapProperty(ob)) { var entry = {key: ob, value: this[ob]}; var f = arguments[0]; if (f.length == 1) { if (!closure(entry)) { result.add(entry.key, entry.value); } } if (f.length == 2) { if (!closure(entry.key, entry.value)) { result.add(entry.key, entry.value); } } } } return result; }; GsGroovyMap.prototype.drop = function(number) { var result = gs.map(), ob, count = 0; for (ob in this) { if (!isMapProperty(ob)) { count ++; if (count > number) { result.add(ob, this[ob]); } } } return result; }; GsGroovyMap.prototype.findAll = function(closure) { var result = gs.map(), ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; if (f.length == 1) { var entry = {key: ob, value: this[ob]}; if (closure(entry)) { result.add(entry.key, entry.value); } } if (f.length == 2) { if (closure(ob, this[ob])) { result.add(ob, this[ob]); } } } } return result; }; GsGroovyMap.prototype.collect = function(closure) { var result = gs.list([]), ob; for (ob in this) { if (!isMapProperty(ob)) { var f = arguments[0]; if (f.length==1) { result.add(closure({key:ob, value:this[ob]})); } if (f.length==2) { result.add(closure(ob,this[ob])); } } } if (result.size()>0) { return result; } else { return null; } }; GsGroovyMap.prototype.containsKey = function(key) { if (this[key] === undefined || this[key] === null) { return false; } else { return true; } }; GsGroovyMap.prototype.containsValue = function(value) { var ob, gotIt = false; for (ob in this) { if (!isMapProperty(ob)) { if (gs.equals(this[ob],value)) { gotIt = true; break; } } } return gotIt; }; GsGroovyMap.prototype.get = function(key, defaultValue) { if (!this.containsKey(key)) { this[key] = defaultValue; } return this[key]; }; GsGroovyMap.prototype.toString = function() { var items = ''; this.each (function(key,value) { items = items + key+': '+value+' ,'; }); return '[' + items + ']'; }; GsGroovyMap.prototype.equals = function(otherMap) { var result = true, ob; for (ob in this) { if (!isMapProperty(ob)) { if (!gs.equals(this[ob],otherMap[ob])) { result = false; } } } return result; }; GsGroovyMap.prototype.keySet = function() { var result = gs.list([]), ob; for (ob in this) { if (!isMapProperty(ob)) { result.add(ob); } } return result; }; GsGroovyMap.prototype.values = function() { var result = gs.list([]), ob; for (ob in this) { if (!isMapProperty(ob)) { result.add(this[ob]); } } return result; }; GsGroovyMap.prototype.withDefault = function(closure) { this.gSdefaultValue = closure; return this; }; GsGroovyMap.prototype.inject = function(initial,closure) { var ob; for (ob in this) { if (!isMapProperty(ob)) { if (closure.length == 2) { var entry = {key:ob, value:this[ob]}; initial = closure(initial, entry); } if (closure.length == 3) { initial = closure(initial, ob, this[ob]); } } } return initial; }; GsGroovyMap.prototype.putAll = function (items) { if (items instanceof Array) { var i; for (i=0;i= 0; i--) { interceptClosureCall(closure, this[i]); } return this; }; Array.prototype.eachWithIndex = function(closure,index) { for (index=0; index < this.length; index++) { closure(this[index], index); } return this; }; Array.prototype.any = function(closure) { var i; for (i = 0;i < this.length; i++) { if (closure(this[i])) { return true; } } return false; }; Array.prototype.oldValues = Array.prototype.values; Array.prototype.values = function() { if (isJsArray(this) && Array.prototype.oldValues) { return this.oldValues(); } else { var i, result = []; for (i = 0; i < this.length; i++) { result[i] = this[i]; } return result; } }; //Remove only 1 item from the list Array.prototype.remove = function(indexOrValue) { var result = false,index = -1; if (typeof indexOrValue == 'number') { index = indexOrValue; result = this[index]; } else { index = this.indexOf(indexOrValue); if (index >= 0) { result = true; } } if (index >= 0) { this.splice(index, 1); } return result; }; //Maybe too much complex, not much inspired Array.prototype.removeAll = function(data) { if (data instanceof Array) { var result = []; this.forEach(function(v, i, a) { if (data.contains(v)) { result.push(i); } }); //Now in result we have index of items to delete if (result.length>0) { var decremental = 0; var thisList = this; result.forEach(function(v, i, a) { //Had tho change this for thisList, other scope on this here thisList.splice(v-decremental,1); decremental=decremental+1; }); } } else if (isFunction(data)) { var i; for (i = this.length - 1; i >= 0; i--) { if (data(this[i])) { this.remove(i); } } } return this; }; Array.prototype.collect = function(closure) { var i, result = gs.list([]); for (i = 0; i < this.length; i++) { result[i] = closure(this[i]); } return result; }; Array.prototype.collectMany = function(closure) { var i, result = gs.list([]); for (i = 0;i < this.length; i++) { result.addAll(closure(this[i])); } return result; }; Array.prototype.takeWhile = function(closure) { var i, result = gs.list([]); for (i = 0; i < this.length; i++) { if (closure(this[i])) { result[i] = this[i]; } else { break; } } return result; }; Array.prototype.dropWhile = function(closure) { var result = gs.list([]); var i, j=0, insert = false; for (i = 0; i < this.length; i++) { if (!closure(this[i])) { insert=true; } if (insert) { result[j++] = this[i]; } } return result; }; Array.prototype.drop = function(number) { var i, result = gs.list([]); for (i = number; i < this.length; i++) { result.push(this[i]); } return result; }; Array.prototype.findAll = function(closure) { var values = this.filter(closure); return gs.list(values); }; if (!Array.prototype.find) { Array.prototype.find = function (closure) { var result, i; for (i = 0; !result && i < this.length; i++) { if (closure(this[i])) { result = this[i]; } } return result; }; } Array.prototype.first = function() { return this[0]; }; Array.prototype.head = function() { return this.first(); }; Array.prototype.last = function() { return this[this.length - 1]; }; Array.prototype.sum = function() { var i, result = 0; //can pass a closure to sum if (arguments.length == 1) { for (i = 0; i < this.length; i++) { result = result + arguments[0](this[i]); } } else { if (this.length > 0 && this[0].plus) { var item = this[0]; for (i = 0; i + 1 < this.length; i++) { item = item.plus(this[i + 1]); } return item; } else { for (i = 0; i < this.length; i++) { result = result + this[i]; } } } return result; }; Array.prototype.inject = function() { var acc; //only 1 argument, just the closure if (arguments.length == 1) { acc = this[0]; var i; for (i=1;i result) { result = this[i]; } } return result; }; Array.prototype.min = function() { var i, result = null; for (i = 0; i < this.length; i++) { if (result === null || this[i] < result) { result = this[i]; } } return result; }; Array.prototype.oldToString = Array.prototype.toString; Array.prototype.toString = function() { if (isJsArray(this)) { return this.oldToString(); } else if (this.length > 0) { return '[' + this.join(', ') + ']'; } else { return '[]'; } }; Array.prototype.grep = function(param) { var i, result = gs.list([]); if (param instanceof RegExp) { for (i = 0; i < this.length; i++) { if (gs.match(this[i],param)) { result.add(this[i]); } } return result; } else if (param instanceof Array) { return this.intersect(param); } else if (isFunction(param)) { for (i = 0; i < this.length; i++) { if (param(this[i])) { result.add(this[i]); } } return result; } else { for (i = 0; i < this.length ;i++) { if (this[i]==param) { result.add(this[i]); } } return result; } }; Array.prototype.equals = function(other) { if (!(other instanceof Array) || other.length!=this.length) { return false; } else { var i, result = true; for (i = 0;i < this.length && result; i++) { if (!gs.equals(this[i],other[i])) { result = false; } } return result; } }; Array.prototype.gSjoin = function() { var separator = ''; if (arguments.length == 1) { separator = arguments[0]; } var i, result = ''; for (i = 0; i < this.length; i++) { result = result + this[i]; if ((i + 1) < this.length) { result = result + separator; } } return result; }; Array.prototype.oldSort = Array.prototype.sort; Array.prototype.sort = function() { var modify = true; if (arguments.length > 0 && arguments[0] === false) { modify = false; } var i,copy = []; //Maybe some closure as last parameter var tempFunction = null; if (arguments.length == 2 && isFunction(arguments[1])) { tempFunction = arguments[1]; } if (arguments.length == 1 && isFunction(arguments[0])) { tempFunction = arguments[0]; } //Copy all items for (i=0;i 0 && arguments[0] === false) { modify = false; } var i, copy = []; //Copy all items for (i = 0; i < this.length; i++) { if (!copy.contains(this[i])) { copy.push(this[i]); } } if (modify) { this.length = 0; for (i = 0; i < copy.length; i++) { this[i] = copy[i]; } return this; } else { return gs.list(copy); } }; Array.prototype.oldReverse = Array.prototype.reverse; Array.prototype.reverse = function() { var i, count = 0; if (isJsArray(this)) { return this.oldReverse(); } else if (arguments.length == 1 && arguments[0] === true) { for (i = this.length - 1; i > count; i--) { var temp = this[count]; this[count++] = this[i]; this[i] = temp; } return this; } else { var result = []; for (i = this.length - 1; i >= 0; i--) { result[count++] = this[i]; } return gs.list(result); } }; Array.prototype.take = function(number) { var i, result = []; for (i = 0; i < number; i++) { if (i < this.length) { result[i] = this[i]; } } return gs.list(result); }; Array.prototype.takeWhile = function(closure) { var result = [], i, exit=false; for (i = 0; !exit && i < this.length; i++) { if (closure(this[i])) { result[i] = this[i]; } else { exit = true; } } return gs.list(result); }; Array.prototype.multiply = function(number) { if (number === 0) { return gs.list([]); } else { var i, result = gs.list([]); for (i=0;i 0) { var i; for (i = 0; i < value.length; i++) { if (value[i] instanceof gs.spread) { var values = value[i].values; if (values.length > 0) { var j; for (j = 0; j < values.length; j++) { data.push(values[j]); } } } else { data.push(value[i]); } } } var object = data; object.clazz = {name: 'java.util.ArrayList', simpleName: 'ArrayList'}; applyBaseClassFunctions(object); return object; }; gs.flatten = function(result, list) { list.each(function (it) { if (it instanceof Array) { if (it.length>0) { gs.flatten(result, it); } } else { result.add(it); } }); }; ///////////////////////////////////////////////////////////////// //range - [x..y] from groovy ///////////////////////////////////////////////////////////////// gs.range = function(begin, end, inclusive) { var start = begin; var finish = end; var areChars = (typeof(begin) == 'string'); if (areChars) { start = start.charCodeAt(0); finish = finish.charCodeAt(0); } var reverse = false; if (finish < start) { var oldStart = start; start = finish; finish = oldStart; reverse = true; if (!inclusive) { start = start + 1; } } else { if (!inclusive) { finish = finish - 1; } } var result,number,count; for (result=[], number = start, count = 0 ; number <= finish ; number++, count++) { if (areChars) { result[count] = String.fromCharCode(number); } else { result[count] = number; } } if (reverse) { result = result.reverse(); } var object = gs.list(result); object.toList = function() { return gs.list(this.values()); }; return object; }; ///////////////////////////////////////////////////////////////// //date - Date() object from groovy / java ///////////////////////////////////////////////////////////////// gs.date = function() { var gSobject; if (arguments.length == 1) { gSobject = new Date(arguments[0]); } else { gSobject = new Date(); } createClassNames(gSobject, ['java.util.Date']); gSobject.withz = BaseClass.prototype.withz; gSobject.time = gSobject.getTime(); gSobject.setTime = function(milis) { gSobject.time = milis; }; gSobject.year = gSobject.getFullYear(); gSobject.month = gSobject.getMonth(); gSobject.date = gSobject.getDay(); gSobject.plus = function(other) { if (typeof other == 'number') { return gs.date(gSobject.time + (other * 1440000)); } else { return gSobject + other; } }; gSobject.minus = function(other) { if (typeof other == 'number') { return gs.date(gSobject.time - (other * 1440000)); } else { return gSobject - other; } }; gSobject.format = function(rule) { //TODO complete var exit = ''; if (rule) { exit = rule; exit = exit.replaceAll('yyyy', gSobject.getFullYear()); exit = exit.replaceAll('MM', fillZerosLeft(gSobject.getMonth() + 1, 2)); exit = exit.replaceAll('dd', fillZerosLeft(gSobject.getUTCDate(), 2)); exit = exit.replaceAll('HH', fillZerosLeft(gSobject.getHours(), 2)); exit = exit.replaceAll('mm', fillZerosLeft(gSobject.getMinutes(), 2)); exit = exit.replaceAll('ss', fillZerosLeft(gSobject.getSeconds(), 2)); exit = exit.replaceAll('yy', lastChars(gSobject.getFullYear(), 2)); } return exit; }; gSobject.parse = function(rule, text) { //TODO complete var pos = rule.indexOf('MM'); if (pos >= 0) { var newMonth = text.substr(pos, 2) - 1; while (gSobject.getMonth() != newMonth) { gSobject.setMonth(newMonth); } } pos = rule.indexOf('dd'); if (pos >= 0) { var newDay = text.substr(pos, 2); while (gSobject.getUTCDate() != newDay) { gSobject.setUTCDate(newDay); } } pos = rule.indexOf('yyyy'); if (pos >= 0) { gSobject.setFullYear(text.substr(pos, 4)); } else { pos = rule.indexOf('yy'); if (pos >= 0) { gSobject.setFullYear(text.substr(pos, 2)); } } pos = rule.indexOf('HH'); if (pos >= 0) { gSobject.setHours(text.substr(pos, 2)); } pos = rule.indexOf('mm'); if (pos >= 0) { gSobject.setMinutes(text.substr(pos, 2)); } pos = rule.indexOf('ss'); if (pos >= 0) { gSobject.setSeconds(text.substr(pos, 2)); } return gSobject; }; gSobject.clearTime = function() { gSobject.setHours(0, 0, 0, 0); return gSobject; }; gSobject.equals = function(other) { return gSobject.time == other.time; }; gSobject.before = function(other) { return gSobject.time < other.time; }; gSobject.after = function(other) { return gSobject.time > other.time; }; return gSobject; }; gs.rangeFromList = function(list, begin, end) { return list.slice(begin, end + 1); }; function fillZerosLeft(item, size) { var value = item + ''; while (value.length < size) { value = '0' + value; } return value; } function lastChars(item, number) { var value = item + ''; value = value.substring(value.length - number); return value; } ///////////////////////////////////////////////////////////////// //exactMatch - For regular expressions ///////////////////////////////////////////////////////////////// gs.exactMatch = function(text, regExp) { var mock = text; if (regExp instanceof RegExp) { mock = mock.replace(regExp, "#"); } else { mock = mock.replace(new RegExp(regExp), "#"); } return mock == "#"; }; gs.match = function(text, regExp) { var pos; if (regExp instanceof RegExp) { pos = text.search(regExp); } return (pos>=0); }; ///////////////////////////////////////////////////////////////// //regExp - For regular expressions ///////////////////////////////////////////////////////////////// gs.regExp = function(text, ppattern) { var patt; if (ppattern instanceof RegExp) { patt = new RegExp(ppattern.source, 'g'); } else { //g for search all occurences patt = new RegExp(ppattern, 'g'); } var object; var data = patt.exec(text); if (data === null || data === undefined) { return null; } else { var list = gs.list([]); var i = 0; while (data) { if (data instanceof Array && data.length < 2) { list[i] = data[0]; } else { list[i] = gs.list(data); } i = i + 1; data = patt.exec(text); } object = expandWithMetaClass(list, 'RegExp'); } createClassNames(object, ['java.util.regex.Matcher']); object.pattern = patt; object.text = text; object.replaceFirst = function(data) { return this.text.replaceFirst(this[0], data); }; object.replaceAll = function(data) { return this.text.replaceAll(this.pattern, data); }; object.reset = function() { return this; }; return object; }; ///////////////////////////////////////////////////////////////// //Pattern ///////////////////////////////////////////////////////////////// gs.pattern = function(pattern) { var object = gs.init('Pattern'); createClassNames(object, ['java.util.regex.Pattern']); object.value = pattern; return object; }; ///////////////////////////////////////////////////////////////// // Regular Expresions ///////////////////////////////////////////////////////////////// gs.matcher = function(item, regExpression) { var object = gs.init('Matcher'); createClassNames(object, ['java.util.regex.Matcher']); object.data = item; object.regExp = regExpression; object.matches = function() { return gs.exactMatch(this.data, this.regExp); }; return object; }; RegExp.prototype.matcher = function(item) { return gs.matcher(item, this); }; ///////////////////////////////////////////////////////////////// //Number functions ///////////////////////////////////////////////////////////////// Number.prototype.times = function(closure) { var i; for (i = 0; i < this; i++) { closure(i); } }; Number.prototype.upto = function(number, closure) { var i; for (i = this.value; i <= number; i++) { closure(i); } }; Number.prototype.step = function(number, jump, closure) { var i; for (i = this.value; i < number;) { closure(i); i = i + jump; } }; Number.prototype.multiply = function(number) { return this * number; }; Number.prototype.power = function(number) { return Math.pow(this,number); }; Number.prototype.byteValue = Number.prototype.doubleValue = Number.prototype.shortValue = Number.prototype.floatValue = Number.prototype.longValue = function() { return this; }; Number.prototype.intValue = function() { return Math.floor(this); }; ///////////////////////////////////////////////////////////////// //String functions ///////////////////////////////////////////////////////////////// String.prototype.contains = function(value) { return this.indexOf(value) >= 0; }; String.prototype.startsWith = function(value) { return this.indexOf(value) === 0; }; String.prototype.endsWith = function(value) { return this.indexOf(value) > -1 && this.indexOf(value) == (this.length - value.length); }; String.prototype.count = function(value) { var reg = new RegExp(value, 'g'); var result = this.match(reg); if (result) { return result.length; } else { return 0; } }; String.prototype.size = function() { return this.length; }; String.prototype.replaceAll = function(oldValue, newValue) { var reg; if (oldValue instanceof RegExp) { reg = new RegExp(oldValue.source, 'g'); } else { reg = new RegExp(oldValue, 'g'); } return this.replace(reg, newValue); }; String.prototype.replaceFirst = function(oldValue, newValue) { return this.replace(oldValue, newValue); }; String.prototype.reverse = function() { return this.split("").reverse().join(""); }; String.prototype.tokenize = function() { var str = " "; if (arguments.length == 1 && arguments[0]) { str = arguments[0]; } var list = this.split(str); return gs.list(list); }; String.prototype.multiply = function(value) { if (typeof(value) == 'number') { var result = ''; var i; for (i=0; i < (value | 0); i++) { result = result + this; } return result; } }; String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }; String.prototype.each = function(closure) { var list = gs.list(this.split('')); list.each(closure); }; String.prototype.inject = function(initial, closure) { var list = gs.list(this.split('')); return list.inject(initial, closure); }; function getItemsMultiline(text) { var items = text.split('\n'); if (items.length > 1 && items[items.length - 1] === '') { items.splice(items.length - 1, 1); } return items; } String.prototype.eachLine = function(closure) { var i, items = getItemsMultiline(this); for (i = 0; i < items.length; i++) { var item = items[i]; //Closure with 2 arguments, line and count if (closure.length == 2) { closure(item, i); } else { closure(item); } } }; String.prototype.readLines = function() { var items = getItemsMultiline(this); return gs.list(items); }; String.prototype.padRight = function(number) { var sep = ' '; if (arguments.length==2) { sep = arguments[1]; } var item = this; while (item.length < number) { item = item + sep; } return item; }; String.prototype.padLeft = function(number) { var sep = ' '; if (arguments.length == 2) { sep = arguments[1]; } var item = this; while (item.length < number) { item = sep + item; } return item; }; String.prototype.isNumber = function() { if (this.trim() === '') { return false; } else { var res = Number(this); if (isNaN(res)) { return false; } else { return true; } } }; String.prototype.plus = function(other) { var addText = 'null'; if (other !== undefined && other !== null) { if (other['toString'] !== undefined) { addText = other.toString(); } else { addText = other; } } return this + addText; }; String.prototype.toInteger = function() { return parseInt(this); }; ///////////////////////////////////////////////////////////////// // Misc Functions ///////////////////////////////////////////////////////////////// gs.classForName = function(name, obj) { var result = null; try { var pos = name.indexOf("."); while (pos >= 0) { name = name.substring(pos + 1); pos = name.indexOf("."); } result = (typeof globalThis!=="undefined"&&globalThis[name]!==undefined?globalThis[name]:undefined); } catch (err) { result = obj; } return result; }; function StaticMethods(item) { this.gSparent = item; } gs.metaClass = function(item) { var type = typeof item; if (type == "string") { item = new String(item); } else if (type == "number") { item = new Number(item); //If type is a function, it's metaClass from a Class } else if (type === "function") { if (!globalMetaClass[item.name]) { globalMetaClass[item.name] = { gSstatic: new StaticMethods(item), getStatic : function() { return this.gSstatic; } }; } item = globalMetaClass[item.name]; } return item; }; gs.passMapToObject = function(source, destination) { var prop; for (prop in source) { if (isFunction(source[prop])) continue; if (!isMapProperty(prop)) { gs.sp(destination, prop, source[prop]); } } }; gs.equals = function(value1, value2) { if (!hasFunc(value1, 'equals')) { if (hasFunc(value2, 'equals')) { return value2.equals(value1); } else { return value1==value2; } } else { return value1.equals(value2); } }; gs.is = function(value1, value2) { if (value1 !== null && hasFunc(value1, 'is')) { var count, params = gs.list([value2]); for (count = 2; count < arguments.length; count++) { params.add(arguments[count]); } return gs.mc(value1, 'is', params); } else { return value1 == value2; } }; function interceptClosureCall(func, param) { if ((param instanceof Array) && func.length > 1) { return func.apply(func, param); } else { return func(param); } } gs.random = function() { var object = gs.init('Random'); object.nextInt = function(number) { var ran = Math.ceil(Math.random()*number); return ran - 1; }; object.nextBoolean = function() { var ran = Math.random(); return ran < 0.5; }; return object; }; gs.bool = function(item) { if (item && item.isEmpty !== undefined) { return !item.isEmpty(); } else { if (item) { if (item['asBoolean']) { return item['asBoolean'](); } else if (typeof(item) == 'number' && item === 0) { return false; } else if (typeof(item) == 'string') { return item !== ''; } } return item; } }; gs.less = function(itemLeft, itemRight) { return itemLeft < itemRight; }; gs.greater = function(itemLeft, itemRight) { return itemLeft > itemRight; }; // Operator <=> gs.spaceShip = function(itemLeft, itemRight) { if (gs.equals(itemLeft, itemRight)) { return 0; } if (gs.less(itemLeft, itemRight)) { return -1; } if (gs.greater(itemLeft, itemRight)) { return 1; } }; //InstanceOf function gs.instanceOf = function(item, name) { var gotIt = false; if (name == "String") { return typeof(item) == 'string'; } else if (name == "Number") { return typeof(item) == 'number'; } else if (item.clazz) { var classInfo; classInfo = item.clazz; while (classInfo && !gotIt) { if (classInfoContainsName(classInfo, name)) { gotIt = true; } else { classInfo = classInfo.superclass; } } if (!gotIt && item.clazz.interfaces) { var i; for (i = 0; i < item.clazz.interfaces.length && !gotIt; i++) { if (classInfoContainsName(item.clazz.interfaces[i], name)) { gotIt = true; } } } } else if (isFunction(item) && name == 'Closure') { gotIt = true; } return gotIt; }; function classInfoContainsName(classInfo, name) { return classInfo.name == name || classInfo.simpleName == name; } //Elvis operator gs.elvis = function(booleanExpression, trueExpression, falseExpression) { if (gs.bool(booleanExpression)) { return trueExpression; } else { return falseExpression; } }; // * operator gs.multiply = function(a, b) { if (!hasFunc(a, 'multiply')) { return a * b; } else { return a.multiply(b); } }; // / operator gs.div = function(a, b) { if (!hasFunc(a, 'div')) { return a / b; } else { return a.div(b); } }; // ** operator gs.power = function(a, b) { if (!hasFunc(a, 'power')) { return Math.pow(a, b); } else { return a.power(b); } }; // mod operator gs.mod = function(a, b) { if (!hasFunc(a, 'mod')) { return a % b; } else { return a.mod(b); } }; // + operator gs.plus = function(a, b) { if (!hasFunc(a, 'plus')) { if ((typeof a == 'number') && (typeof b == 'number') && (a + b < 1)) { return ((a * 1000) + (b * 1000)) / 1000; } else { return a + b; } } else { return a.plus(b); } }; // - operator gs.minus = function(a, b) { if (!hasFunc(a, 'minus')) { return a - b; } else { return a.minus(b); } }; // in operator gs.gSin = function(item, group) { if (group && (isFunction(group.contains))) { return group.contains(item); } else { return false; } }; //For some special cases where access a property with this."${name}" //This can be a closure gs.thisOrObject = function(thisItem, objectItem) { return objectItem || thisItem; }; // spread operator (*) gs.spread = function(item) { if (item && item instanceof Array) { this.values = item; } }; ///////////////////////////////////////////////////////////////// // Beans functions - From groovy beans ///////////////////////////////////////////////////////////////// //If an object has a function by name function hasFunc(item, name) { if (item === null || item === undefined || item[name] === undefined || (!isFunction(item[name]))) { return false; } else { return true; } } //Set a property of a class gs.sp = function(item, nameProperty, value) { if (nameProperty == 'setProperty') { item[nameProperty] = value; } else if (nameProperty == 'getProperty') { item[nameProperty] = value; } else if (item !== null && item instanceof StaticMethods) { item[nameProperty] = value; item.gSparent[nameProperty] = value; } else { if (nameProperty === 'methodMissing' && value) { item[nameProperty] = value; } else if (!item['setProperty']) { var nameFunction = 'set' + nameProperty.charAt(0).toUpperCase() + nameProperty.slice(1); if (!item[nameFunction]) { if (item[nameProperty] === undefined && item.setPropertyMissing !== undefined && isFunction(item.setPropertyMissing)) { item.setPropertyMissing(nameProperty, value); } else { item[nameProperty] = value; } } else { item[nameFunction](value); } } else { item.setProperty(nameProperty,value); } } }; //Get a property of a class gs.gp = function(item, nameProperty, inDelegates) { //It's a get with safe operator as item?.data if (arguments.length == 3) { if (item === null || item === undefined) { return null; } } else if (item == null || item === undefined) { throw 'gs.gp Get property: ' + nameProperty + ' on null or undefined object.' } if (!item['getProperty']) { return propFromObject(item, nameProperty, inDelegates); } else { var res = item.getProperty(nameProperty); return (res !== undefined ? res : propFromObject(item, nameProperty, inDelegates)) } }; function propFromObject(item, nameProperty, inDelegates) { var nameFunction = 'get' + nameProperty.charAt(0).toUpperCase() + nameProperty.slice(1); if (!item[nameFunction]) { if (nameProperty == 'size' && isFunction(item[nameProperty])) { return item[nameProperty](); } else { if (item[nameProperty] !== undefined) { return item[nameProperty]; } else { //Lets check gp in @Delegate if (item.clazz !== undefined) { var addDelegate = mapAddDelegate[item.clazz.simpleName]; if (addDelegate !== null && addDelegate !== undefined) { var i; for (i = 0; i < addDelegate.length; i++) { var prop = addDelegate[i]; var target = item[prop][nameProperty]; if (target !== undefined) { return item[prop][nameProperty]; } } } } //Default value of a map if (item.gSdefaultValue !== undefined && (isFunction(item.gSdefaultValue))) { item[nameProperty] = item.gSdefaultValue(); } //Maybe in categories if (categories.length > 0 && item[nameProperty] === undefined) { var whereExecutes = categorySearching(nameFunction); if (whereExecutes !== null) { return whereExecutes[nameFunction].apply(item, [item]); } } if (item.propertyMissing !== undefined && isFunction(item.propertyMissing)) { return item.propertyMissing(nameProperty); } else { if (!inDelegates && delegates.length > 0) { return findPropertyInDelegates(nameProperty, item); } else { return item[nameProperty]; } } } } } else { return item[nameFunction](); } } function findPropertyInDelegates(nameProperty, item) { var i = delegates.length; var found = false; var result; while (i > 0 && !found && item ) { i = i - 1; result = gs.gp(delegates[i], nameProperty, true); if (result !== undefined) { found = true; } } return result; } //Control property changes with ++,-- gs.plusPlus = function(item, nameProperty, plus, before) { var value = gs.gp(item, nameProperty); var newValue = value; if (plus) { gs.sp(item, nameProperty, value + 1); newValue++; } else { gs.sp(item, nameProperty, value - 1); newValue--; } if (before) { return newValue; } else { return value; } }; function exFn(we, mn, it, val) { return we[mn].apply(it, joinParameters(it, val)); } //Control all method calls gs.mc = function(item, methodName, values, objectVar, isSafe) { if (gs.consoleInfo && console) { console.log('[INFO] gs.mc (' + item + ').' + methodName + ' params:' + values); } if (item === null || item === undefined) { if (isSafe) { return null; } else { throw 'gs.mc Calling method: ' + methodName + ' on null or undefined object.'; } } if (methodName == 'split' && typeof(item) == 'string') { return item.tokenize(values[0]); } if (methodName == 'length' && typeof(item) == 'string') { return item.length; } if (methodName == 'join' && (item instanceof Array)) { if (values.size() > 0) { return item.gSjoin(values[0]); } else { return item.gSjoin(); } } if (objectVar) { try { //First, try to execute function in object return gs.mc(objectVar, methodName, values); } catch(e) {} } if (!item[methodName]) { if (methodName.startsWith('get') || methodName.startsWith('set')) { var varName = getterSetterRemove(methodName); if (item[varName] !== undefined && !hasFunc(item, varName)) { if (methodName.startsWith('get')) { return gs.gp(item, varName); } else { return gs.sp(item, varName, values[0]); } } } if (methodName.startsWith('is')) { var varName = methodName.charAt(2).toLowerCase() + methodName.slice(3); if (item[varName] !== undefined && !hasFunc(item, varName)) { return gs.gp(item, varName); } } //Check newInstance if (methodName=='newInstance') { return item(); } else { var whereExecutes; //Lets check if in any category we have the static method if (categories.length > 0) { whereExecutes = categorySearching(methodName); if (whereExecutes !== null) { return exFn(whereExecutes, methodName, item, values); } } //In @Category var ob; for (ob in annotatedCategories) { if (annotatedCategories[ob] == item.clazz.simpleName) { var categoryItem = gs.myCategories[ob](); if (categoryItem[methodName] && isFunction(categoryItem[methodName])) { return exFn(categoryItem, methodName, item, values); } } } //Lets check in mixins classes if (mixins.length > 0) { whereExecutes = mixinSearching(item, methodName); if (whereExecutes !== null) { return exFn(whereExecutes, methodName, item, values); } } //Lets check in mixins objects if (mixinsObjects.length > 0) { whereExecutes = mixinObjectsSearching(item, methodName); if (whereExecutes !== null) { return exFn(whereExecutes, methodName, item, values); } } //Lets check mc in @Delegate if (item.clazz !== undefined) { var addDelegate = mapAddDelegate[item.clazz.simpleName]; if (addDelegate) { var i; for (i = 0; i < addDelegate.length; i++) { var prop = addDelegate[i]; var target = item[prop][methodName]; if (target !== undefined) { return exFn(item[prop], methodName, item[prop], values); } } } } //Lets check in delegate if (delegates.length > 0) { var delegateFunc = delegatesFunc(methodName); if (delegateFunc) { return delegateFunc[methodName].apply(item, values); } } if (item.methodMissing) { return item.methodMissing(methodName, values); } else if (delegates.length > 0 && delegatesFunc('methodMissing')) { return gs.mc(delegatesFunc('methodMissing'), methodName, values); } else { if (item.invokeMethod && item.invokeMethod !== BaseClass.prototype.invokeMethod) { return item.invokeMethod(methodName, values); } else { //Maybe there is a function in the script with the name of the method //In Node.js 'this.xxFunction()' in the main context fails if (isFunction((typeof globalThis!=="undefined"&&typeof globalThis[methodName]==="function"?globalThis[methodName]:undefined))) { return (typeof globalThis!=="undefined"&&typeof globalThis[methodName]==="function"?globalThis[methodName]:undefined).apply(this, values); } //Not exist the method, throw exception throw 'gs.mc Method ' + methodName + ' not exist in ' + item; } } } } else { var f = item[methodName]; if (f['apply']) { return f.apply(item, values); } else { return gs.execCall(f, item, values); } } }; function delegatesFunc(nameMethod) { var result = null; if (delegates.length > 0) { var i; for (i = delegates.length - 1; i >= 0 && !result; i--) { if (delegates[i][nameMethod]) { result = delegates[i]; } } } return result; } function joinParameters(item, items) { var listParameters = [item],i; for (i=0; i < items.size(); i++) { listParameters.push(items[i]); } return listParameters; } //////////////////////////////////////////////////////////// // Categories //////////////////////////////////////////////////////////// gs.categoryUse = function(item, itemClass, closure) { var ob, categoryCreated; if (existAnnotatedCategory(item)) { categoryCreated = gs.myCategories[item](); for (ob in categoryCreated) { if (!isObjectProperty(ob) && !isConstructor(ob, categoryCreated[ob]) && isFunction(categoryCreated[ob])) { addFunctionToClassIfPrototyped(ob, categoryCreated[ob], annotatedCategories[item]); } } } else { categories.push(itemClass); } closure(); if (existAnnotatedCategory(item)) { categoryCreated = gs.myCategories[item](); for (ob in categoryCreated) { if (!isObjectProperty(ob) && !isConstructor(ob, categoryCreated[ob]) && isFunction(categoryCreated[ob])) { removeFunctionToClass(ob, categoryCreated[ob], annotatedCategories[item]); } } } else { categories.splice(categories.length - 1, 1); } }; function getPrototypeOfClass(className) { if (className == 'String') { return String.prototype; } if (className == 'Number') { return Number.prototype; } if (className == 'ArrayList') { return Array.prototype; } return null; } function addFunctionToClassIfPrototyped(name, func, className) { var proto = getPrototypeOfClass(className); if (proto !== null) { if (proto[name] === undefined) { proto[name] = func; } } } function removeFunctionToClass(name, func, className) { var proto = getPrototypeOfClass(className); if (proto !== null) { if (proto[name] == func) { proto[name] = null; } } } function categorySearching(methodName) { var i, result = null; for (i = categories.length - 1; i >= 0 && result === null; i--) { var itemClass = categories[i]; if (itemClass[methodName]) { result = itemClass; } } return result; } function existAnnotatedCategory(name) { return (annotatedCategories[name] !== null && annotatedCategories[name] !== undefined); } var annotatedCategories = {}; gs.addAnnotatedCategory = function(nameCategory, nameClass) { annotatedCategories[nameCategory] = nameClass; }; //////////////////////////////////////////////////////////// // Mixins //////////////////////////////////////////////////////////// gs.mixinClass = function(item, classes) { //First check in that class has mixins var gotIt = false; if (mixins.length > 0) { var i; for (i = 0; i < mixins.length && !gotIt; i++) { if (mixins[i].name == item) { var j; for (j=0; j < classes.length; j++) { mixins[i].items.push(classes[j]); } gotIt = true; } } } if (!gotIt) { mixins.push({ name: item, items: classes}); } }; gs.mixinObject = function(item, classes) { var gotIt = false; if (mixinsObjects.length > 0) { var i; for (i = 0; i < mixinsObjects.length && !gotIt; i++) { if (mixinsObjects[i].item == item) { var j; for (j = 0; j < classes.length; j++) { mixinsObjects[i].items.push(classes[j]); } gotIt = true; } } } if (!gotIt) { mixinsObjects.push({ item: item, items: classes}); } //TODO make any kinda cleanup if mixinsObjects growing }; function mixinSearching(item, methodName) { var result = null, className = null; if (typeof(item) == 'string') { className = 'String'; } if (item.clazz && item.clazz.simpleName && typeof(item) == 'object') { className = item.clazz.simpleName; } if (className !== null) { var i, ourMixin=null; for (i = mixins.length - 1; i >= 0 && ourMixin === null; i--) { var data = mixins[i]; if (data.name == className) { ourMixin = data.items; } } if (ourMixin !== null) { for (i = 0; i < ourMixin.length && result === null; i++) { if (ourMixin[i][methodName]) { result = ourMixin[i]; } else { var classItem = ourMixin[i](); if (classItem) { var notStatic = classItem[methodName]; if (notStatic !== null && isFunction(notStatic)) { result = classItem; } } } } } } return result; } function mixinObjectsSearching(item, methodName) { var result = null, i, ourMixin = null; for (i = mixinsObjects.length - 1; i >= 0 && ourMixin === null; i--) { var data = mixinsObjects[i]; if (data.item == item) { ourMixin = data.items; } } if (ourMixin !== null) { for (i=0 ; i < ourMixin.length && result === null; i++) { if (ourMixin[i][methodName]) { result = ourMixin[i]; } } } return result; } //////////////////////////////////////////////////////////// // StringBuffer - very basic support, for add with << //////////////////////////////////////////////////////////// gs.stringBuffer = function() { var object = gs.init('StringBuffer'); object.value = ''; if (arguments.length == 1 && typeof arguments[0] === 'string') { object.value = arguments[0]; } object.toString = function() { return this.value; }; object.leftShift = function(value) { return this.append(value); }; object.plus = function(value) { return this.append(value); }; object.size = function() { return this.value.length; }; object.append = function(value) { this.value = this.value + value; return this; }; return object; }; //////////////////////////////////////////////////////////// // @Delegate //////////////////////////////////////////////////////////// gs.astDelegate = function (baseClass, nameField) { var currentDelegate = mapAddDelegate[baseClass]; if (currentDelegate === null || currentDelegate === undefined) { currentDelegate = []; } currentDelegate.push(nameField); mapAddDelegate[baseClass] = currentDelegate; }; //////////////////////////////////////////////////////////// // Delegate //////////////////////////////////////////////////////////// function applyDelegate (func, delegate, params) { delegates.push(delegate); var result = func.apply(delegate, params); delegates.pop(); return result; } gs.execCall = function (func, thisObject, params) { if (func.delegate !== undefined) { return applyDelegate(func, func.delegate, params); } else { if (func['call'] !== undefined && typeof func === 'object') { return func['call'].apply(func, params); } else { return func.apply(thisObject, params); } } }; //////////////////////////////////////////////////////////// // Functional //////////////////////////////////////////////////////////// Function.prototype.curry = function () { var slice = Array.prototype.slice, args = slice.apply(arguments), that = this; return function () { return that.apply(null, args.concat(slice.apply(arguments))); }; }; Function.prototype.rcurry = function () { var slice = Array.prototype.slice, args = slice.apply(arguments), that = this; return function () { return that.apply(null, (slice.apply(arguments)).concat(args)); }; }; Function.prototype.ncurry = function () { var slice = Array.prototype.slice, args = slice.apply(arguments, [1]), begin = arguments[0], that = this; return function () { return that.apply(null, slice.apply(arguments, [0, begin]).concat(args).concat(slice.apply(arguments, [begin]))); }; }; Function.prototype.leftShift = function () { var func = arguments[0], that = this; return function () { return that(func.apply(null, arguments)); }; }; Function.prototype.rightShift = function () { var func = arguments[0], that = this; return function () { return func(that.apply(null, arguments)); }; }; Function.prototype.run = function() { return this(); }; Function.prototype.memoize = function() { var that = this; that._input = []; that._output = []; return function() { var i, result, foundPos = -1, inputs = Array.prototype.slice.call(arguments); for (i = 0; i < that._input.length && foundPos < 0; i++) { if (gs.equals(inputs, that._input[i])) { foundPos = i; } } if (foundPos > -1) { result = that._output[foundPos]; } else { that._input.push(inputs); result = that.apply(null, inputs); that._output.push(result); } return result; }; }; //MISC Find scope of a var gs.fs = function(name, thisScope, objScope) { if (objScope && objScope[name] !== undefined) { return objScope[name]; } else if (thisScope && thisScope[name] !== undefined) { return thisScope[name]; } else { var value = gs.gp(thisScope, name); if (value === undefined) { if (aStT && aStT[name] !== undefined) { return aStT[name]; } else { var func = new Function("return " + name); return func(); } } else { return value; } } }; //Convert a groovy object to javascript, but only properties gs.toJavascript = function(obj) { if (obj && gs.isGroovyObj(obj)) { var result; if (obj && !isFunction(obj)) { if (obj instanceof Array) { result = []; var i; for (i = 0; i < obj.length; i++) { result.push(gs.toJavascript(obj[i])); } } else { if (obj instanceof Object) { result = {}; var ob; for (ob in obj) { if (!isMapProperty(ob) && !isFunction(obj[ob])) { result[ob] = gs.toJavascript(obj[ob]); } } } else { result = obj; } } } return result; } else { return obj; } }; //Convert a javascript object to 'groovy', if you define groovy type, will use it, and not a map gs.toGroovy = function(obj, objClass) { var result; if (obj !== undefined && !isFunction(obj)) { if (obj instanceof Array) { result = gs.list([]); var i; for (i = 0; i < obj.length; i++) { result.add(gs.toGroovy(obj[i], objClass)); } } else { if (obj instanceof Object) { var ob; result = (objClass ? objClass() : gs.map()); for (ob in obj) { result[ob] = gs.toGroovy(obj[ob]); } } else { result = obj; } } } return result; }; gs.toNumber = function(number) { if (number) { if (typeof(number) == 'string') { return parseFloat(number); } else { return number; } } }; gs.isGroovyObj = function(maybeGroovyObject) { return maybeGroovyObject !== null && maybeGroovyObject !== undefined && maybeGroovyObject.clazz !== undefined; }; gs.execStatic = function(obj, methodName, thisObject, params) { var old = aStT; aStT = thisObject; var res = obj[methodName].apply(thisObject, params); aStT = old; return res; }; gs.asChar = function(value) { return value.charCodeAt(0); }; //Convert a groovy map to javascript object, including functions in the map gs.toJsObj = function(obj) { if (gs.isGroovyObj(obj)) { var ob, result = {}; for (ob in obj) { if (!isMapProperty(ob)) { if (isFunction(obj[ob])) { result[ob] = obj[ob]; } else { result[ob] = gs.toJsObj(obj[ob]); } } } return result; } else { return obj; } }; }).call(this);function HtmlBuilder() { var gSobject = gs.init('HtmlBuilder'); gSobject.clazz = { name: 'org.grooscript.builder.HtmlBuilder', simpleName: 'HtmlBuilder'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.tagSolver = function(name, args) { gSobject.htmCd += "<" + (name) + ""; if ((((gs.bool(args)) && (gs.mc(args,"size",[]) > 0)) && (!gs.bool(gs.instanceOf((args[0]), "String")))) && (!gs.bool(gs.instanceOf((args[0]), "Closure")))) { gs.mc(args[0],"each",[function(key, value) { return gSobject.htmCd += " " + (key) + "='" + (value) + "'"; }]); }; gSobject.htmCd += (!gs.bool(args) ? "/>" : ">"); if (gs.bool(args)) { if ((gs.equals(gs.mc(args,"size",[]), 1)) && (gs.instanceOf((args[0]), "String"))) { gs.mc(gSobject,"yield",[args[0]]); } else { var lastArg = gs.mc(args,"last",[]); if (gs.instanceOf(lastArg, "Closure")) { gs.sp(lastArg,"delegate",this); gs.execCall(lastArg, this, []); }; if ((gs.instanceOf(lastArg, "String")) && (gs.mc(args,"size",[]) > 1)) { gs.mc(gSobject,"yield",[lastArg]); }; }; return gSobject.htmCd += ""; }; }; gSobject.htmCd = null; gSobject.build = function(x0) { return HtmlBuilder.build(x0); } gSobject['yield'] = function(text) { return gs.mc(text,"each",[function(ch) { var gSswitch0 = ch; if (gs.equals(gSswitch0, "&")) { gSobject.htmCd += "&"; ; } else if (gs.equals(gSswitch0, "<")) { gSobject.htmCd += "<"; ; } else if (gs.equals(gSswitch0, ">")) { gSobject.htmCd += ">"; ; } else if (gs.equals(gSswitch0, "\"")) { gSobject.htmCd += """; ; } else if (gs.equals(gSswitch0, "'")) { gSobject.htmCd += "'"; ; } else { gSobject.htmCd += ch; ; }; }]); } gSobject['yieldUnescaped'] = function(text) { return gSobject.htmCd += text; } gSobject['comment'] = function(text) { return gSobject.htmCd += (gs.plus((gs.plus("")); } gSobject['newLine'] = function(it) { return gSobject.htmCd += "\n"; } gSobject['methodMissing'] = function(name, args) { gs.sp(this,"" + (name) + "",function(ars) { if (arguments.length == 1 && arguments[0] instanceof Array) { ars=gs.list(arguments[0]); } else if (arguments.length == 1) { ars=gs.list([arguments[1 - 1]]); } else if (arguments.length < 1) { ars=gs.list([]); } else if (arguments.length > 1) { ars=gs.list([ars]); for (gScount=1;gScount < arguments.length; gScount++) { ars.add(arguments[gScount]); } } return gs.mc(gSobject,"tagSolver",[name, ars]); }); return gs.mc(this,"invokeMethod",[name, args], gSobject); } gSobject['HtmlBuilder0'] = function(it) { gSobject.htmCd = ""; return this; } if (arguments.length==0) {gSobject.HtmlBuilder0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; HtmlBuilder.build = function(closure) { var mc = gs.expandoMetaClass(HtmlBuilder, false, true); gs.mc(mc,"initialize",[]); var builder = HtmlBuilder(); gs.sp(builder,"metaClass",mc); gs.sp(closure,"delegate",builder); gs.execCall(closure, this, []); return gs.gp(builder,"htmCd"); } function Observable() { var gSobject = gs.init('Observable'); gSobject.clazz = { name: 'org.grooscript.rx.Observable', simpleName: 'Observable'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.subscribers = gs.list([]); gSobject.sourceList = null; gSobject.chain = gs.list([]); gSobject.listen = function() { return Observable.listen(); } gSobject.from = function(x0) { return Observable.from(x0); } gSobject['produce'] = function(event) { return gs.mc(gSobject.subscribers,"each",[function(it) { return gs.mc(gSobject,"processFunction",[event, it]); }]); } gSobject['map'] = function(cl) { gs.mc(gSobject.chain,'leftShift', gs.list([cl])); return this; } gSobject['filter'] = function(cl) { gs.mc(gSobject.chain,'leftShift', gs.list([function(it) { if (gs.execCall(cl, this, [it])) { return it; } else { throw "Exception"; }; }])); return this; } gSobject['subscribe'] = function(cl) { while (gs.bool(gSobject.chain)) { cl = (gs.mc(cl,'leftShift', gs.list([gs.mc(gSobject.chain,"pop",[])]))); }; gs.mc(gSobject.subscribers,'leftShift', gs.list([cl])); if (gs.bool(gSobject.sourceList)) { return gs.mc(gSobject.sourceList,"each",[function(it) { return gs.mc(gSobject,"processFunction",[it, cl]); }]); }; } gSobject['removeSubscribers'] = function(it) { return gSobject.subscribers = gs.list([]); } gSobject['processFunction'] = function(data, cl) { try { gs.execCall(cl, this, [data]); } catch (e) { } ; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Observable.listen = function(it) { return Observable(); } Observable.from = function(list) { return Observable(gs.map().add("sourceList",list)); } function GQueryImpl() { var gSobject = gs.init('GQueryImpl'); gSobject.clazz = { name: 'org.grooscript.jquery.GQueryImpl', simpleName: 'GQueryImpl'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.clazz.interfaces = [{ name: 'org.grooscript.jquery.GQuery', simpleName: 'GQuery'}]; gSobject['bind'] = function(selector, target, nameProperty, closure) { if (closure === undefined) closure = null; return gs.mc(gs.execStatic(GQueryList,'of', this,[selector]),"bind",[target, nameProperty, closure]); } gSobject['bindProperty'] = function(selector, target, nameProperty, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",[selector, parent]),"bind",[target, nameProperty]); } gSobject['existsSelector'] = function(selector, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",[selector, parent]),"hasResults",[]); } gSobject['existsId'] = function(id, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",["#" + (id) + "", parent]),"hasResults",[]); } gSobject['existsName'] = function(name, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",["[name='" + (name) + "']", parent]),"hasResults",[]); } gSobject['existsGroup'] = function(name, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",["input:radio[name='" + (name) + "']", parent]),"hasResults",[]); } gSobject['onEvent'] = function(selector, nameEvent, func, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",[selector, parent]),"onEvent",[nameEvent, func]); } gSobject.doRemoteCall = function(url, type, params, onSuccess, onFailure, objectResult) { if (objectResult === undefined) objectResult = null; $.ajax({ type: type, //GET or POST data: gs.toJavascript(params), url: url, dataType: 'text' }).done(function(newData) { if (onSuccess) { onSuccess(gs.toGroovy(jQuery.parseJSON(newData), objectResult)); } }) .fail(function(error) { if (onFailure) { onFailure(error); } }); } gSobject.onReady = function(func) { $(document).ready(func); } gSobject['attachMethodsToDomEvents'] = function(obj, parent) { if (parent === undefined) parent = null; return gs.mc(gs.gp((obj = gs.metaClass(obj)),"methods"),"each",[function(method) { if (gs.mc(gs.gp(method,"name"),"endsWith",["Click"])) { var shortName = gs.mc(gs.gp(method,"name"),"substring",[0, gs.minus(gs.mc(gs.gp(method,"name"),"length",[]), 5)]); if (gs.mc(gSobject,"existsId",[shortName, parent])) { gs.mc(gSobject,"onEvent",[gs.plus("#", shortName), "click", obj["" + (gs.gp(method,"name")) + ""], parent]); }; }; if (gs.mc(gs.gp(method,"name"),"endsWith",["Submit"])) { var shortName = gs.mc(gs.gp(method,"name"),"substring",[0, gs.minus(gs.mc(gs.gp(method,"name"),"length",[]), 6)]); if (gs.mc(gSobject,"existsId",[shortName, parent])) { gs.mc(gSobject,"onEvent",[gs.plus("#", shortName), "submit", gs.mc(obj["" + (gs.gp(method,"name")) + ""],'leftShift', gs.list([function(it) { return gs.mc(it,"preventDefault",[]); }])), parent]); }; }; if (gs.mc(gs.gp(method,"name"),"endsWith",["Change"])) { var shortName = gs.mc(gs.gp(method,"name"),"substring",[0, gs.minus(gs.mc(gs.gp(method,"name"),"length",[]), 6)]); if (gs.mc(gSobject,"existsId",[shortName, parent])) { return gs.mc(gSobject,"onChange",[gs.plus("#", shortName), obj["" + (gs.gp(method,"name")) + ""], parent]); }; }; }]); } gSobject['onChange'] = function(selector, closure, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",[selector, parent]),"onChange",[closure]); } gSobject['focusEnd'] = function(selector, parent) { if (parent === undefined) parent = null; return gs.mc(gs.mc(gSobject,"resolveSelector",[selector, parent]),"focusEnd",[]); } gSobject['bindAllProperties'] = function(target, parent) { if (parent === undefined) parent = null; return gs.mc(gs.gp(target,"properties"),"each",[function(name, value) { if (gs.mc(gSobject,"existsId",[name, parent])) { gs.mc(gSobject,"bindProperty",["#" + (name) + "", target, name, parent]); }; if (gs.mc(gSobject,"existsName",[name, parent])) { gs.mc(gSobject,"bindProperty",["[name='" + (name) + "']", target, name, parent]); }; if (gs.mc(gSobject,"existsGroup",[name, parent])) { return gs.mc(gSobject,"bindProperty",["input:radio[name='" + (name) + "']", target, name, parent]); }; }]); } gSobject['bindAll'] = function(target, parent) { if (parent === undefined) parent = null; gs.mc(gSobject,"bindAllProperties",[target, parent]); return gs.mc(gSobject,"attachMethodsToDomEvents",[target, parent]); } gSobject['observeEvent'] = function(selector, nameEvent, data) { if (data === undefined) data = gs.map(); var observable = gs.execStatic(Observable,'listen', this,[]); gs.mc(gs.execCall(this, this, [selector]),"on",[nameEvent, data, function(event) { return gs.mc(observable,"produce",[event]); }]); return observable; } gSobject['call'] = function(selector) { return gs.execStatic(GQueryList,'of', this,[selector]); } gSobject['resolveSelector'] = function(selector, parent) { return gs.execStatic(GQueryList,'of', this,[(parent != null ? gs.mc(parent,"find",[selector]) : selector)]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function GQueryList() { var gSobject = gs.init('GQueryList'); gSobject.clazz = { name: 'org.grooscript.jquery.GQueryList', simpleName: 'GQueryList'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.list = null; gSobject.of = function(x0) { return GQueryList.of(x0); } gSobject.methodMissing = function(name, args) { return gSobject.list[name].apply(gSobject.list, args); } gSobject.withResultList = function(cl) { if (gSobject.list.length) { cl(gSobject.list.toArray()); } return gSobject; } gSobject.hasResults = function() { return gSobject.list.length > 0; } gSobject.onEvent = function(nameEvent, cl) { gSobject.list.on(nameEvent, cl); return gSobject; } gSobject.onChange = function(cl) { var jq = gSobject.list; if (jq.is(":text")) { jq.bind('input', function() { cl($(this).val()); }); } else if (jq.is('textarea')) { jq.bind('input propertychange', function() { cl($(this).val()); }); } else if (jq.is(":checkbox")) { jq.change(function() { cl($(this).is(':checked')); }); } else if (jq.is(":radio")) { jq.change(function() { cl($(this).val()); }); } else if (jq.is("select")) { jq.bind('change', function() { cl($(this).val()); }); } else { console.log('Not supporting onChange for jquery element'); console.log(jq); } return gSobject; } gSobject.focusEnd = function() { var jq = gSobject.list; if (jq.length) { if (jq.is(":text") || jq.is('textarea')) { var originalValue = jq.val(); jq.val(''); jq.blur().focus().val(originalValue); } else { jq.focus(); } } return gSobject; } gSobject.bind = function(target, nameProperty, closure) { if (closure === undefined) closure = null; var jq = gSobject.list; //Create set method var nameSetMethod = 'set'+nameProperty.capitalize(); if (jq.is(":text")) { target[nameSetMethod] = function(newValue) { this[nameProperty] = newValue; jq.val(newValue); if (closure) { closure(newValue); }; }; jq.bind('input', function() { var currentVal = $(this).val(); target[nameProperty] = currentVal; if (closure) { closure(currentVal); }; }); } else if (jq.is('textarea')) { target[nameSetMethod] = function(newValue) { this[nameProperty] = newValue; jq.val(newValue); if (closure) { closure(newValue); }; }; jq.bind('input propertychange', function() { var currentVal = $(this).val(); target[nameProperty] = currentVal; if (closure) { closure(currentVal); }; }); } else if (jq.is(":checkbox")) { target[nameSetMethod] = function(newValue) { this[nameProperty] = newValue; jq.prop('checked', newValue); if (closure) { closure(newValue); }; }; jq.change(function() { var currentVal = $(this).is(':checked'); target[nameProperty] = currentVal; if (closure) { closure(currentVal); }; }); } else if (jq.is(":radio")) { target[nameSetMethod] = function(newValue) { this[nameProperty] = newValue; jq.each(function(idx, elem) { if (elem.value == newValue) { $(elem).prop('checked', true) } }); if (closure) { closure(newValue); }; }; jq.change(function() { var currentVal = $(this).val(); target[nameProperty] = currentVal; if (closure) { closure(currentVal); }; }); } else if (jq.is("select")) { target[nameSetMethod] = function(newValue) { this[nameProperty] = newValue; jq.val(newValue); if (closure) { closure(newValue); }; }; jq.bind('change', function() { var currentVal = $(this).val(); target[nameProperty] = currentVal; if (closure) { closure(currentVal); }; }); } else { console.log('Not supporting bind for jquery element'); console.log(jq); } return gSobject; } gSobject.jqueryList = function(selec) { return $(selec); } gSobject['GQueryList1'] = function(selecOrJq) { gSobject.list = (gs.instanceOf(selecOrJq, "String") ? gs.mc(gSobject,"jqueryList",[selecOrJq]) : selecOrJq); return this; } if (arguments.length==1) {gSobject.GQueryList1(arguments[0]); } return gSobject; }; GQueryList.of = function(selecOrJq) { return GQueryList(selecOrJq); } function GrooscriptGrails() { var gSobject = gs.init('GrooscriptGrails'); gSobject.clazz = { name: 'org.grooscript.grails.util.GrooscriptGrails', simpleName: 'GrooscriptGrails'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'remoteUrl', { get: function() { return GrooscriptGrails.remoteUrl; }, set: function(gSval) { GrooscriptGrails.remoteUrl = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'controllerRemoteDomain', { get: function() { return GrooscriptGrails.controllerRemoteDomain; }, set: function(gSval) { GrooscriptGrails.controllerRemoteDomain = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'actionRemoteDomain', { get: function() { return GrooscriptGrails.actionRemoteDomain; }, set: function(gSval) { GrooscriptGrails.actionRemoteDomain = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'count', { get: function() { return GrooscriptGrails.count; }, set: function(gSval) { GrooscriptGrails.count = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'components', { get: function() { return GrooscriptGrails.components; }, set: function(gSval) { GrooscriptGrails.components = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'GRAILS_PROPERTIES', { get: function() { return GrooscriptGrails.GRAILS_PROPERTIES; }, set: function(gSval) { GrooscriptGrails.GRAILS_PROPERTIES = gSval; }, enumerable: true }); gSobject.register = function(x0) { return GrooscriptGrails.register(x0); } gSobject.recover = function(x0) { return GrooscriptGrails.recover(x0); } gSobject.getRemoteDomainClassProperties = function(x0) { return GrooscriptGrails.getRemoteDomainClassProperties(x0); } gSobject.sendClientMessage = function(x0,x1) { return GrooscriptGrails.sendClientMessage(x0,x1); } gSobject.sendWebsocketMessage = function(x0,x1) { return GrooscriptGrails.sendWebsocketMessage(x0,x1); } gSobject.doRemoteCall = function(x0,x1,x2,x3,x4) { return GrooscriptGrails.doRemoteCall(x0,x1,x2,x3,x4); } gSobject.remoteDomainAction = function(x0,x1,x2,x3) { return GrooscriptGrails.remoteDomainAction(x0,x1,x2,x3); } gSobject.createComponent = function(x0,x1) { return GrooscriptGrails.createComponent(x0,x1); } gSobject.findComponentById = function(x0) { return GrooscriptGrails.findComponentById(x0); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; GrooscriptGrails.register = function(component) { var number = GrooscriptGrails.count++; gs.sp(component,"cId",number); (GrooscriptGrails.components["id" + (number) + ""]) = component; return component; } GrooscriptGrails.recover = function(cId) { return GrooscriptGrails.components["id" + (cId) + ""]; } GrooscriptGrails.getRemoteDomainClassProperties = function(remoteDomainClass) { var data; var result = gs.map(); for (data in remoteDomainClass) { if ((typeof remoteDomainClass[data] !== "function") && !GrooscriptGrails.GRAILS_PROPERTIES.contains(data)) { result.add(data, remoteDomainClass[data]); } } return result; } GrooscriptGrails.sendClientMessage = function(channel, message) { var sendMessage = message; if (!gs.isGroovyObj(message)) { sendMessage = gs.toGroovy(message); } gsEvents.sendMessage(channel, sendMessage); } GrooscriptGrails.sendWebsocketMessage = function(channel, message) { var sendMessage = message; if (gs.isGroovyObj(message)) { sendMessage = gs.toJavascript(message); } websocketClient.send(channel, {}, JSON.stringify(sendMessage)); } GrooscriptGrails.doRemoteCall = function(controller, action, params, onSuccess, onFailure) { var url = GrooscriptGrails.remoteUrl; url = url + '/' + controller; if (action !== null) { url = url + '/' + action; } $.ajax({ type: "POST", data: (gs.isGroovyObj(params) ? gs.toJavascript(params) : params), url: url }).done(function(newData) { if (onSuccess !== null && onSuccess !== undefined) { var successData = gs.toGroovy(newData); onSuccess(successData); } }) .fail(function(error) { if (onFailure !== null && onFailure !== undefined) { onFailure(error); } }); } GrooscriptGrails.remoteDomainAction = function(params, onSuccess, onFailure, name) { var url = GrooscriptGrails.remoteUrl + params.url; var data = (gs.isGroovyObj(params.data) ? gs.toJavascript(params.data) : params.data); var type = 'GET'; if (params.action == 'create') { type = 'POST'; } if (params.action == 'update') { type = 'PUT'; } if (params.action == 'delete') { type = 'DELETE'; } if (params.action == 'read' || params.action == 'delete') { data = null; url = url + '/' + params.data.id; } $.ajax({ type: type, data: data, url: url, accepts: 'application/json' }).done(function(newData) { var successData = gs.toGroovy(newData, (typeof globalThis!=="undefined"&&globalThis[name]!==undefined?globalThis[name]:undefined)); if (onSuccess !== null && onSuccess !== undefined) { onSuccess(successData); } }) .fail(function(error) { if (onFailure !== null && onFailure !== undefined) { onFailure(error); } }); } GrooscriptGrails.createComponent = function(componentClass, name) { var component = Object.create(HTMLElement.prototype); component.createdCallback = function() { var shadow = this.createShadowRoot(); var content = this.textContent; var attrs = this.attributes; //name and value var map = {shadowRoot: shadow, content: content}; if (attrs && attrs.length > 0) { for (var i = 0; i < attrs.length; i++) { var element = attrs[i]; map[element.name] = element.value; } } GrooscriptGrails.register(componentClass(map)).render(); }; document.registerElement(name, {prototype: component}); } GrooscriptGrails.findComponentById = function(id) { return gs.gp(gs.mc(GrooscriptGrails.components,"find",[function(key, value) { return gs.equals(gs.gp(value,"id"), id); }]),"value",true); } GrooscriptGrails.remoteUrl = null; GrooscriptGrails.controllerRemoteDomain = "remoteDomain"; GrooscriptGrails.actionRemoteDomain = "doAction"; GrooscriptGrails.count = 0; GrooscriptGrails.components = gs.map(); GrooscriptGrails.GRAILS_PROPERTIES = gs.list(["url" , "class" , "clazz" , "gsName" , "transients" , "constraints" , "mapping" , "hasMany" , "belongsTo" , "validationSkipMap" , "gormPersistentEntity" , "properties" , "gormDynamicFinders" , "all" , "domainClass" , "attached" , "validationErrorsMap" , "dirtyPropertyNames" , "errors" , "dirty" , "count"]); function RemoteDomain() { var gSobject = gs.init('RemoteDomain'); gSobject.clazz = { name: 'org.grooscript.grails.promise.RemoteDomain', simpleName: 'RemoteDomain'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.clazz.interfaces = [{ name: 'org.grooscript.grails.promise.GsPromise', simpleName: 'GsPromise'}]; gSobject.action = null; gSobject.url = null; gSobject.data = null; gSobject.onSuccess = null; gSobject.onFail = null; gSobject.name = null; gSobject.closure = function(it) { var remoteData = gs.map().add("action",gSobject.action).add("url",gSobject.url).add("data",gSobject.data); return gs.execStatic(GrooscriptGrails,'remoteDomainAction', this,[remoteData, gSobject.onSuccess, gSobject.onFail, gSobject.name]); }; gSobject['then'] = function(success, fail) { gSobject.onSuccess = success; gSobject.onFail = fail; gs.sp(gSobject.closure,"delegate",this); return gs.mc(gSobject,"closure",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ClientEventHandler() { var gSobject = gs.init('ClientEventHandler'); gSobject.clazz = { name: 'org.grooscript.grails.event.ClientEventHandler', simpleName: 'ClientEventHandler'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.clazz.interfaces = [{ name: 'org.grooscript.grails.event.EventHandler', simpleName: 'EventHandler'}]; gSobject.mapHandlers = gs.map(); gSobject['sendMessage'] = function(channel, data) { if (gSobject.mapHandlers[channel]) { return gs.mc(gSobject.mapHandlers[channel],"each",[function(action) { return gs.execCall(action, this, [data]); }]); }; } gSobject['onEvent'] = function(channel, action) { if (!gs.bool(gSobject.mapHandlers[channel])) { (gSobject.mapHandlers[channel]) = gs.list([]); }; return gs.mc((gSobject.mapHandlers[channel]),'leftShift', gs.list([action])); } gSobject['close'] = function(it) { return gSobject.mapHandlers = gs.map(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; var gsEvents = ClientEventHandler(); } // __DYMICO_V1_USER_CODE__ function BootstrapBase() { var gSobject = gs.init('BootstrapBase'); gSobject.clazz = { name: 'BootstrapBase', simpleName: 'BootstrapBase'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.completed = false; gSobject.callbacks = gs.list([]); gSobject['callback'] = function(callback) { if (gs.bool(gSobject.completed)) { return gs.execCall(callback, this, []); }; return gs.mc(gSobject.callbacks,"add",[callback]); } gSobject['runCallbacks'] = function(it) { gSobject.completed = true; return gs.mc(gSobject.callbacks,"each",[function(callback) { return gs.execCall(callback, this, []); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function Transmission() { var gSobject = gs.init('Transmission'); gSobject.clazz = { name: 'Transmission', simpleName: 'Transmission'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'onReady', { get: function() { return Transmission.onReady; }, set: function(gSval) { Transmission.onReady = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'onAuthReady', { get: function() { return Transmission.onAuthReady; }, set: function(gSval) { Transmission.onAuthReady = gSval; }, enumerable: true }); if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Transmission.onReady = BootstrapBase(); Transmission.onAuthReady = BootstrapBase(); function StartupParams() { var gSobject = gs.init('StartupParams'); gSobject.clazz = { name: 'StartupParams', simpleName: 'StartupParams'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.session = gs.execStatic(Session,'instance', this,[]); Object.defineProperty(gSobject, 'deviceReadyListers', { get: function() { return StartupParams.deviceReadyListers; }, set: function(gSval) { StartupParams.deviceReadyListers = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'bootstrapComplete', { get: function() { return StartupParams.bootstrapComplete; }, set: function(gSval) { StartupParams.bootstrapComplete = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'deviceReady', { get: function() { return StartupParams.deviceReady; }, set: function(gSval) { StartupParams.deviceReady = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'doAuthToken', { get: function() { return StartupParams.doAuthToken; }, set: function(gSval) { StartupParams.doAuthToken = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'supportOfflineStart', { get: function() { return StartupParams.supportOfflineStart; }, set: function(gSval) { StartupParams.supportOfflineStart = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'websocketClientDebug', { get: function() { return StartupParams.websocketClientDebug; }, set: function(gSval) { StartupParams.websocketClientDebug = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'offlineStartFunction', { get: function() { return StartupParams.offlineStartFunction; }, set: function(gSval) { StartupParams.offlineStartFunction = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'onlineStartNoAuthFunction', { get: function() { return StartupParams.onlineStartNoAuthFunction; }, set: function(gSval) { StartupParams.onlineStartNoAuthFunction = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'onlineStartAuthSuccessFunction', { get: function() { return StartupParams.onlineStartAuthSuccessFunction; }, set: function(gSval) { StartupParams.onlineStartAuthSuccessFunction = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'onlineStartTokenAuthFailedFunction', { get: function() { return StartupParams.onlineStartTokenAuthFailedFunction; }, set: function(gSval) { StartupParams.onlineStartTokenAuthFailedFunction = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'beforeSocketInit', { get: function() { return StartupParams.beforeSocketInit; }, set: function(gSval) { StartupParams.beforeSocketInit = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'afterSocketInit', { get: function() { return StartupParams.afterSocketInit; }, set: function(gSval) { StartupParams.afterSocketInit = gSval; }, enumerable: true }); gSobject.shouldCheckStartupAuth = function() { if (typeof checkStartupAuth !== 'undefined') { return checkStartupAuth } return true } gSobject['checkStartupAuth'] = function(it) { if (gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"AUTH_TOKEN")])) { gs.println(gs.plus("Writing session auth to local storage:", gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"AUTH_TOKEN")]))); gs.mc(gs.fs('localStorage', this, gSobject),"setItem",["authToken", gs.plus((gs.plus("\"", gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"AUTH_TOKEN")]))), "\"")]); }; if (gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"DEVICE_TOKEN")])) { gs.println(gs.plus("Writing device token to local storage:", gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"DEVICE_TOKEN")]))); gs.mc(gs.fs('localStorage', this, gSobject),"setItem",["deviceToken", gs.plus((gs.plus("\"", gs.execStatic(Utils,'getCookie', this,[gs.gp(Socket,"DEVICE_TOKEN")]))), "\"")]); }; if ((gs.mc(gSobject,"shouldCheckStartupAuth",[])) && (gs.bool(StartupParams.doAuthToken))) { gs.println("Checking tokens..."); if ((!gs.bool(gs.gp(gSobject.session,"authToken"))) || (!gs.bool(gs.gp(gSobject.session,"deviceToken")))) { gs.println("Token NOT found"); return null; }; return gs.println("Tokens good"); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; StartupParams.deviceReadyListers = gs.list([]); StartupParams.bootstrapComplete = false; StartupParams.deviceReady = true; StartupParams.doAuthToken = true; StartupParams.supportOfflineStart = false; StartupParams.websocketClientDebug = false; StartupParams.offlineStartFunction = null; StartupParams.onlineStartNoAuthFunction = function(it) { }; StartupParams.onlineStartAuthSuccessFunction = function(it) { return gs.println("NB: onlineStartAuthSuccessFunction NOT SET!"); }; StartupParams.onlineStartTokenAuthFailedFunction = function(it) { gs.println("onlineStartTokenAuthFailedFunction"); return gs.execStatic(Utils,'logout', this,[]); }; StartupParams.beforeSocketInit = function(it) { gs.println(gs.plus("beforeSocketInit:", StartupParams.supportOfflineStart)); if (gs.bool(StartupParams.supportOfflineStart)) { gs.println(gs.plus("beforeSocketInit:session.firstStartupCompleted:", gs.gp(this.session,"firstStartupCompleted"))); gs.println("startupParams.onlineStartFunction:3"); gs.mc(StartupParams,"offlineStartFunction",[]); StartupParams.bootstrapComplete = true; return gs.sp(this.session,"firstStartupCompleted",true); }; }; StartupParams.afterSocketInit = function(it) { gs.println("afterSocketInit"); if (!gs.bool(StartupParams.doAuthToken)) { gs.println("onlineStartNoAuthFunction:0"); gs.mc(StartupParams,"onlineStartNoAuthFunction",[]); StartupParams.bootstrapComplete = true; return null; }; return gs.execStatic(Utils,'tokenAuth', this,[function(it) { gs.println("onlineStartAuthSuccessFunction:1"); gs.mc(StartupParams,"onlineStartAuthSuccessFunction",[]); StartupParams.bootstrapComplete = true; return gs.mc(gs.gp(gs.fs('transmission', this),"onAuthReady"),"runCallbacks",[]); }, function(it) { gs.println("onlineStartTokenAuthFailedFunction:2"); gs.mc(StartupParams,"onlineStartTokenAuthFailedFunction",[]); StartupParams.bootstrapComplete = true; return gs.mc(gs.gp(gs.fs('transmission', this),"onAuthReady"),"runCallbacks",[]); }]); }; function Session() { var gSobject = gs.init('Session'); gSobject.clazz = { name: 'Session', simpleName: 'Session'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'sessionMap', { get: function() { return Session.sessionMap; }, set: function(gSval) { Session.sessionMap = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'self', { get: function() { return Session.self; }, set: function(gSval) { Session.self = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'zoner', { get: function() { return Session.zoner; }, set: function(gSval) { Session.zoner = gSval; }, enumerable: true }); gSobject.zonerRoleMap = gs.map(); gSobject.instance = function() { return Session.instance(); } gSobject.toJs = function() { return Session.toJs(); } gSobject.setSessionStorage = function(x0,x1) { return Session.setSessionStorage(x0,x1); } gSobject.getSessionStorage = function(x0) { return Session.getSessionStorage(x0); } gSobject.clear = function() { var remember_me = localStorage.getItem('remember_me'); localStorage.clear(); localStorage.setItem('remember_me', remember_me); } gSobject['setProperty'] = function(name, value) { (Session.sessionMap[name]) = value; Session.setSessionStorage(name, value); if (gs.equals(name, "zoner")) { Session.zoner = null; return gSobject.zonerRoleMap = gs.map(); }; } gSobject['getProperty'] = function(name) { if (!gs.bool(Session.sessionMap[name])) { var value = Session.getSessionStorage(name); (Session.sessionMap[name]) = value; }; return Session.sessionMap[name]; } gSobject['hasRole'] = function(roles) { if (!gs.bool(roles)) { return true; }; var result = gSobject.zonerRoleMap[roles]; if (result != null) { return result; }; if (!gs.bool(Session.zoner)) { Session.zoner = gs.mc(gSobject,"getProperty",["zoner"]); }; if (!gs.bool(Session.zoner)) { return false; }; if (gs.instanceOf(roles, "String")) { result = (gs.gSin(roles, gs.gp(Session.zoner,"roles"))); (gSobject.zonerRoleMap[roles]) = result; return result; }; for (_i0 = 0, role = roles[0]; _i0 < roles.length; role = roles[++_i0]) { if (gs.gSin(role, gs.gp(Session.zoner,"roles"))) { (gSobject.zonerRoleMap[roles]) = true; return true; }; }; (gSobject.zonerRoleMap[roles]) = false; return false; } gSobject['toString'] = function(it) { return gs.mc(Session.sessionMap,"toString",[]); } gSobject['Session0'] = function(it) { return this; } if (arguments.length==0) {gSobject.Session0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Session.instance = function(it) { if (!gs.bool(Session.self)) { Session.self = Session(); }; return Session.self; } Session.toJs = function(it) { return Session.sessionMap; } Session.setSessionStorage = function(name, value) { value = JSON.stringify(value) localStorage.setItem(name, value) return value } Session.getSessionStorage = function(name) { var value = localStorage.getItem(name) try{ return gs.toGroovy(jQuery.parseJSON(value)) }catch(all){} return null } Session.sessionMap = gs.map(); Session.self = null; Session.zoner = null; function Modals() { var gSobject = gs.init('Modals'); gSobject.clazz = { name: 'Modals', simpleName: 'Modals'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.showModalCustom = function(x0,x1) { return Modals.showModalCustom(x0,x1); } gSobject.showModal = function(x0) { return Modals.showModal(x0); } gSobject.hideModal = function(x0) { return Modals.hideModal(x0); } gSobject.closeModal = function(x0) { return Modals.closeModal(x0); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Modals.showModalCustom = function(id, type) { $(id).css("display", type); $(id).css("pointer-events", "initial"); } Modals.showModal = function(id) { $(id).css("display", "block"); $(id).css("pointer-events", "initial"); } Modals.hideModal = function(id) { $(id).css("display", "none"); $(id).css("pointer-events", "none"); } Modals.closeModal = function(id) { $(id).trigger( "click" ); } function Socket() { var gSobject = gs.init('Socket'); gSobject.clazz = { name: 'Socket', simpleName: 'Socket'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'SOCKET_URL', { get: function() { return Socket.SOCKET_URL; }, set: function(gSval) { Socket.SOCKET_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_USER_URL', { get: function() { return Socket.SOCKET_USER_URL; }, set: function(gSval) { Socket.SOCKET_USER_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_OBJECT_URL', { get: function() { return Socket.SOCKET_OBJECT_URL; }, set: function(gSval) { Socket.SOCKET_OBJECT_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_TOPIC_URL', { get: function() { return Socket.SOCKET_TOPIC_URL; }, set: function(gSval) { Socket.SOCKET_TOPIC_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_OVER_HTTP_SYNCHRONOUS_URL', { get: function() { return Socket.SOCKET_OVER_HTTP_SYNCHRONOUS_URL; }, set: function(gSval) { Socket.SOCKET_OVER_HTTP_SYNCHRONOUS_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_OVER_HTTP_ASYNCHRONOUS_URL', { get: function() { return Socket.SOCKET_OVER_HTTP_ASYNCHRONOUS_URL; }, set: function(gSval) { Socket.SOCKET_OVER_HTTP_ASYNCHRONOUS_URL = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SESSION_REFRESH_MINS', { get: function() { return Socket.SESSION_REFRESH_MINS; }, set: function(gSval) { Socket.SESSION_REFRESH_MINS = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_CHECK_MSG_RECEIVED_SEC', { get: function() { return Socket.SOCKET_CHECK_MSG_RECEIVED_SEC; }, set: function(gSval) { Socket.SOCKET_CHECK_MSG_RECEIVED_SEC = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_RUNNER_RETRY_MS', { get: function() { return Socket.SOCKET_RUNNER_RETRY_MS; }, set: function(gSval) { Socket.SOCKET_RUNNER_RETRY_MS = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_QUEUE_TIMEOUT_MIN', { get: function() { return Socket.SOCKET_QUEUE_TIMEOUT_MIN; }, set: function(gSval) { Socket.SOCKET_QUEUE_TIMEOUT_MIN = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'AUTH_TOKEN', { get: function() { return Socket.AUTH_TOKEN; }, set: function(gSval) { Socket.AUTH_TOKEN = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'DEVICE_TOKEN', { get: function() { return Socket.DEVICE_TOKEN; }, set: function(gSval) { Socket.DEVICE_TOKEN = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'window', { get: function() { return Socket.window; }, set: function(gSval) { Socket.window = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'navigator', { get: function() { return Socket.navigator; }, set: function(gSval) { Socket.navigator = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'sendProtocol', { get: function() { return Socket.sendProtocol; }, set: function(gSval) { Socket.sendProtocol = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'queue', { get: function() { return Socket.queue; }, set: function(gSval) { Socket.queue = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'socketHeadersMap', { get: function() { return Socket.socketHeadersMap; }, set: function(gSval) { Socket.socketHeadersMap = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'userDataPipe', { get: function() { return Socket.userDataPipe; }, set: function(gSval) { Socket.userDataPipe = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'session', { get: function() { return Socket.session; }, set: function(gSval) { Socket.session = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'connected', { get: function() { return Socket.connected; }, set: function(gSval) { Socket.connected = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'socket', { get: function() { return Socket.socket; }, set: function(gSval) { Socket.socket = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'websocketClient', { get: function() { return Socket.websocketClient; }, set: function(gSval) { Socket.websocketClient = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'subscriptions', { get: function() { return Socket.subscriptions; }, set: function(gSval) { Socket.subscriptions = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'sessionRefresherThreads', { get: function() { return Socket.sessionRefresherThreads; }, set: function(gSval) { Socket.sessionRefresherThreads = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'socketReadyQueue', { get: function() { return Socket.socketReadyQueue; }, set: function(gSval) { Socket.socketReadyQueue = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'intervalRunner', { get: function() { return Socket.intervalRunner; }, set: function(gSval) { Socket.intervalRunner = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'reconnectMutex', { get: function() { return Socket.reconnectMutex; }, set: function(gSval) { Socket.reconnectMutex = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'SOCKET_PING_TIMEOUT_MS', { get: function() { return Socket.SOCKET_PING_TIMEOUT_MS; }, set: function(gSval) { Socket.SOCKET_PING_TIMEOUT_MS = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'websocketPingCount', { get: function() { return Socket.websocketPingCount; }, set: function(gSval) { Socket.websocketPingCount = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'nextQueueClean', { get: function() { return Socket.nextQueueClean; }, set: function(gSval) { Socket.nextQueueClean = gSval; }, enumerable: true }); gSobject.init = function() { return Socket.init(); } gSobject.socketHeaders = function() { return Socket.socketHeaders(); } gSobject.initSocket = function(x0,x1) { return Socket.initSocket(x0,x1); } gSobject.socketReady = function(x0) { return Socket.socketReady(x0); } gSobject.socketReadyQueueCallAll = function() { return Socket.socketReadyQueueCallAll(); } gSobject.addUserDataPipe = function() { return Socket.addUserDataPipe(); } gSobject.startSessionRefresher = function() { return Socket.startSessionRefresher(); } gSobject.sessionRefresher = function(x0,x1) { return Socket.sessionRefresher(x0,x1); } gSobject.reconnect = function(x0) { return Socket.reconnect(x0); } gSobject.socketConnectionInterval = function(x0) { return Socket.socketConnectionInterval(x0); } gSobject.socketConnect = function(x0,x1,x2) { return Socket.socketConnect(x0,x1,x2); } gSobject.pingHttp = function(callback) { if (!this.inUse) { this.status = 'unchecked'; this.inUse = true; this.callback = callback; this.ip = ip; var _that = this; this.img = new Image(); this.img.onload = function () { _that.inUse = false; _that.callback('responded'); }; this.img.onerror = function (e) { if (_that.inUse) { _that.inUse = false; _that.callback('responded', e); } }; this.start = new Date().getTime(); this.img.src = 'http://'+ window.location.hostname + '/index/ping'; this.timer = setTimeout(function () { if (_that.inUse) { _that.inUse = false; _that.callback('timeout'); } }, 1500); } } gSobject.pingWebSocket = function(x0) { return Socket.pingWebSocket(x0); } gSobject.remote = function(x0,x1,x2,x3) { return Socket.remote(x0,x1,x2,x3); } gSobject.callChain = function(x0,x1,x2) { return Socket.callChain(x0,x1,x2); } gSobject.callObject = function(x0,x1,x2,x3,x4) { return Socket.callObject(x0,x1,x2,x3,x4); } gSobject.isDymicoSystemUpdating = function() { return Socket.isDymicoSystemUpdating(); } gSobject.send = function(x0,x1,x2,x3) { return Socket.send(x0,x1,x2,x3); } gSobject.doSend = function(x0,x1) { return Socket.doSend(x0,x1); } gSobject.doSendNativeHttp = function(x0,x1) { return Socket.doSendNativeHttp(x0,x1); } gSobject.doSendNative = function(x0,x1) { return Socket.doSendNative(x0,x1); } gSobject.checkMessageReceived = function(x0) { return Socket.checkMessageReceived(x0); } gSobject.resendMessageQueue = function() { return Socket.resendMessageQueue(); } gSobject.cleanQueue = function() { return Socket.cleanQueue(); } gSobject.receive = function(x0) { return Socket.receive(x0); } gSobject.processException = function(x0) { return Socket.processException(x0); } gSobject.subscribe = function(x0,x1,x2) { return Socket.subscribe(x0,x1,x2); } gSobject.subscribeTopic = function(x0,x1) { return Socket.subscribeTopic(x0,x1); } gSobject.unsubscribeTopic = function(x0) { return Socket.unsubscribeTopic(x0); } gSobject.addSubscription = function(x0,x1,x2) { return Socket.addSubscription(x0,x1,x2); } gSobject.subscribeJs = function(x0,x1,x2) { return Socket.subscribeJs(x0,x1,x2); } gSobject.doReceiveNative = function(x0,x1) { return Socket.doReceiveNative(x0,x1); } gSobject.resubscribeAll = function() { return Socket.resubscribeAll(); } gSobject.unsubscribe = function(x0,x1) { return Socket.unsubscribe(x0,x1); } gSobject.post = function(x0,x1,x2,x3,x4) { return Socket.post(x0,x1,x2,x3,x4); } gSobject.postJson = function(x0,x1,x2,x3) { return Socket.postJson(x0,x1,x2,x3); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Socket.init = function(it) { gs.sp(Socket.session,"domain",gs.gp(gs.gp(Socket.window,"location"),"hostname")); gs.sp(Socket.session,"incomingUrl",(gs.plus((gs.plus(gs.gp(gs.gp(Socket.window,"location"),"protocol"), "//")), gs.gp(gs.gp(Socket.window,"location"),"hostname")))); return gs.sp(GrooscriptGrails,"remoteUrl",gs.gp(Socket.session,"incomingUrl")); } Socket.socketHeaders = function(it) { gs.sp(Socket.socketHeadersMap,"domain",gs.gp(gs.gp(Socket.window,"location"),"hostname")); gs.sp(Socket.socketHeadersMap,"" + (Socket.AUTH_TOKEN) + "",gs.execStatic(Utils,'getAuthToken', this,[])); gs.sp(Socket.socketHeadersMap,"" + (Socket.DEVICE_TOKEN) + "",gs.execStatic(Utils,'getDeviceToken', this,[])); if (gs.bool(gs.gp(Socket.session,"jwt"))) { gs.sp(Socket.socketHeadersMap,"jwt",gs.gp(Socket.session,"jwt")); }; return Socket.socketHeadersMap; } Socket.initSocket = function(success, failure) { if (success === undefined) success = null; if (failure === undefined) failure = null; return gs.execStatic(Socket,'socketConnectionInterval', this,[success, failure]); } Socket.socketReady = function(callback) { if (gs.bool(Socket.connected)) { gs.execCall(callback, this, []); return null; }; return gs.mc(Socket.socketReadyQueue,"add",[callback]); } Socket.socketReadyQueueCallAll = function(it) { var socketReadyQueueLocal = Socket.socketReadyQueue; Socket.socketReadyQueue = gs.list([]); return gs.mc(socketReadyQueueLocal,"each",[function(callback) { try { gs.execCall(callback, this, []); } catch (all) { gs.println(gs.fs('all', this)); } ; }]); } Socket.addUserDataPipe = function(it) { return Socket.addSubscription(gs.execStatic(Utils,'getDeviceToken', this,[]), Socket.SOCKET_USER_URL, Socket.userDataPipe); } Socket.startSessionRefresher = function(it) { if (gs.bool(gs.gp(Socket.session,"authToken"))) { var sessionRefresherCallback = function(data) { if (data != "authed") { gs.println("NOT AUTHED"); return gs.execStatic(Utils,'logout', this,[]); }; }; Socket.sessionRefresher(gs.gp(Socket.session,"authToken"), sessionRefresherCallback); for (_i1 = 0, sessionRefresherThread = Socket.sessionRefresherThreads[0]; _i1 < Socket.sessionRefresherThreads.length; sessionRefresherThread = Socket.sessionRefresherThreads[++_i1]) { gs.execStatic(Utils,'clearInterval', this,[sessionRefresherThread]); gs.mc(Socket.sessionRefresherThreads,"remove",[sessionRefresherThread]); }; return gs.mc(Socket.sessionRefresherThreads,"add",[gs.execStatic(Utils,'setInterval', this,[function(it) { return gs.mc(Socket,"sessionRefresher",[gs.gp(Socket.session,"authToken"), sessionRefresherCallback]); }, gs.multiply((gs.multiply(1000, 60)), Socket.SESSION_REFRESH_MINS)])]); }; } Socket.sessionRefresher = function(token, sessionRefresherCallback) { console.log("refreshing:" + token +':'+new Date()); $.ajax({ url : '/login/tokenAuth?token='+token, type : 'GET', processData: false, contentType: false, success : function(data) { console.log("grails session re-auth:"+data); sessionRefresherCallback(data) } }); } Socket.reconnect = function(retryInMs) { if (retryInMs === undefined) retryInMs = 0; if (gs.bool(retryInMs)) { return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(Socket,"reconnect",[]); }, retryInMs]); }; if ((gs.bool(Socket.reconnectMutex)) || (!gs.bool(Socket.intervalRunner))) { return Socket.reconnect(500); }; Socket.reconnectMutex = true; return gs.mc(Socket,"intervalRunner",[function(it) { return Socket.reconnectMutex = false; }]); } Socket.socketConnectionInterval = function(success) { var reconnectCallback = function(it) { gs.println("Socket reconnected"); Socket.connected = true; gs.mc(Socket,"addUserDataPipe",[]); gs.mc(Socket,"resubscribeAll",[]); gs.mc(Socket,"resendMessageQueue",[]); gs.mc(Socket,"startSessionRefresher",[]); gs.execCall(success, this, []); success = function(it) { }; return gs.mc(Socket,"socketReadyQueueCallAll",[]); }; var disconnectSockets = function(it) { gs.println("Socket disconnect"); Socket.connected = false; try { gs.mc(gs.gp(Socket,"websocketClient"),"disconnect",[]); } catch (all) { } ; }; Socket.intervalRunner = function(done) { gs.println(gs.plus((gs.plus((gs.plus((gs.plus((gs.plus("navigator.onLine:", gs.gp(Socket.navigator,"onLine"))), ":")), gs.gp(gs.gp(Socket,"websocketClient"),"connected"))), ":")), Socket.connected)); if (!gs.bool(gs.gp(gs.gp(Socket,"websocketClient"),"connected"))) { gs.println("Socket.websocketClient.connected:false:reconnecting..."); gs.mc(Socket,"socketConnect",[gs.map().add("domain",gs.gp(Socket.session,"domain")), function(it) { gs.println(gs.plus("Socket.websocketClient.connected:", gs.gp(gs.gp(Socket,"websocketClient"),"connected"))); Socket.connected = true; gs.execCall(reconnectCallback, this, []); return gs.execCall(done, this, []); }, function(it) { gs.println("Socket.websocketClient.connected:connection down"); gs.execCall(disconnectSockets, this, []); gs.execCall(done, this, []); if (gs.bool(Socket.queue)) { return gs.mc(Socket,"reconnect",[Socket.SOCKET_RUNNER_RETRY_MS]); }; }]); return null; }; gs.println("Sockets believed to be online. Pinging socket connection..."); gs.mc(Socket,"pingWebSocket",[function(pingResponse) { gs.println(gs.plus("pingWebSocket:", pingResponse)); if (gs.equals(pingResponse, "timeout")) { gs.println("Connection timed out, reconnecting..."); gs.execCall(disconnectSockets, this, []); gs.mc(Socket,"reconnect",[]); return gs.execCall(done, this, []); }; gs.println("Connection good, false alarm."); return gs.execCall(done, this, []); }]); return gs.println(gs.plus("intervalRunner:Socket.websocketClient.connected:", gs.gp(gs.gp(Socket,"websocketClient"),"connected"))); }; return Socket.reconnect(); } Socket.socketConnect = function(headers, success, failed) { try{ Socket.socket = new SockJS('/stomp'); Socket.websocketClient = Stomp.over(Socket.socket); if (!StartupParams.websocketClientDebug){ //switch off debuggging Socket.websocketClient.debug = function () {} } Socket.websocketClient.connect(gs.toJavascript(headers), success, failed); }catch(error) { console.info(error); } } Socket.pingWebSocket = function(callback) { var websocketPingCountNow = Socket.websocketPingCount; var wrapper = gs.mc(gs.map().add("uuid","ping").add("call","callChain").add("data",gs.list([gs.map().add("property","transmissionService") , gs.map().add("method","ping")])),'leftShift', gs.list([Socket.socketHeaders()])); Socket.doSendNative(Socket.SOCKET_URL, wrapper); return gs.execStatic(Utils,'setTimeout', this,[function(it) { if (gs.equals(websocketPingCountNow, Socket.websocketPingCount)) { gs.execCall(callback, this, ["timeout"]); return null; }; return gs.execCall(callback, this, ["responded"]); }, Socket.SOCKET_PING_TIMEOUT_MS]); } Socket.remote = function(closure, data, success, fail) { if (success === undefined) success = null; if (fail === undefined) fail = null; return gs.execStatic(Socket,'send', this,["remoteExec", closure, data, success, fail]); } Socket.callChain = function(callChain, success, fail) { if (success === undefined) success = null; if (fail === undefined) fail = null; if (Socket.isDymicoSystemUpdating()) { return null; }; gs.println(gs.plus("callChain:", callChain)); return gs.execStatic(Socket,'send', this,["callChain", callChain, success, fail]); } Socket.callObject = function(self, method, args, success, fail) { if (fail === undefined) fail = null; if (Socket.isDymicoSystemUpdating()) { return null; }; gs.println(gs.plus("callObject:OObject:", self)); gs.println(gs.plus("callObject:method:", method)); return gs.execStatic(Socket,'send', this,["callObject", gs.map().add("self",self).add("method",method).add("args",args), success, fail]); } Socket.isDymicoSystemUpdating = function() { try{ if (typeof dymicoVersionUpdater !== 'undefined') { return dymicoVersionUpdater.dymicoSystemUpdating; } }catch(all){ } return false; } Socket.send = function(call, data, success, fail) { if (fail === undefined) fail = function(it) { return false; }; var uuid = gs.execStatic(Utils,'uuid', this,[]); var wrapper = gs.map().add("uuid",uuid).add("call",call).add("data",data); var queueItem = gs.map().add("success",success).add("fail",fail).add("dataStr",gs.mc(data,"toString",[])).add("date",gs.gp(gs.date(),"time")).add("wrapper",wrapper); (Socket.queue[uuid]) = queueItem; Socket.doSend(Socket.SOCKET_URL, queueItem); return uuid; } Socket.doSend = function(channel, queueItem) { if (gs.equals(Socket.sendProtocol, "websocket")) { Socket.doSendNative(channel, gs.mc(gs.gp(queueItem,"wrapper"),'leftShift', gs.list([Socket.socketHeaders()]))); gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(Socket,"checkMessageReceived",[queueItem]); }, gs.multiply(Socket.SOCKET_CHECK_MSG_RECEIVED_SEC, 1000)]); if (!gs.bool(Socket.connected)) { return Socket.reconnect(); }; } else { if (gs.equals(Socket.sendProtocol, "http")) { return Socket.doSendNativeHttp(gs.mc(gs.gp(queueItem,"wrapper"),'leftShift', gs.list([Socket.socketHeaders()])), function(it) { gs.println("HTTP TIMEOUT"); return gs.mc(Socket,"reconnect",[]); }); } else { throw "Exception"; }; }; } Socket.doSendNativeHttp = function(map, timeoutCallback) { var sendMessage = map; sendMessage = Utils.mapToJsonString(sendMessage); // sendMessage = LZString.compressToBase64(sendMessage); //no compression needed, cause the browser will gzip it anyway sendMessage = "message="+encodeURIComponent(sendMessage) var xhr = new XMLHttpRequest(); xhr.ontimeout = timeoutCallback xhr.open('POST', Socket.SOCKET_OVER_HTTP_SYNCHRONOUS_URL, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function(e) { if (this.status == 404) { console.log('AJAX FAILED'); } if (this.readyState == 4 && this.status == 200) { Socket.receive(Socket.doReceiveNative(this.responseText, false)) } }; xhr.send(sendMessage); } Socket.doSendNative = function(channel, map) { try{ var sendMessage = map; sendMessage = Utils.mapToJsonString(sendMessage) sendMessage = LZString.compressToBase64(sendMessage) return Socket.websocketClient.send(channel, {}, sendMessage); }catch(all){ } } Socket.checkMessageReceived = function(queueItem) { if (Socket.queue[gs.gp(gs.gp(queueItem,"wrapper"),"uuid")]) { Socket.reconnect(); return Socket.cleanQueue(); }; } Socket.resendMessageQueue = function(it) { return gs.mc(gs.mc(gs.mc(Socket.queue,"values",[]),"sort",[function(it) { return gs.gp(it,"date",true); }]),"each",[function(queueItem) { return gs.mc(Socket,"doSend",[Socket.SOCKET_URL, queueItem]); }]); } Socket.cleanQueue = function(it) { if (Socket.nextQueueClean < gs.gp(gs.date(),"time")) { var timeoutMs = gs.multiply((gs.multiply(Socket.SOCKET_QUEUE_TIMEOUT_MIN, 60)), 1000); Socket.nextQueueClean = (gs.plus(gs.gp(gs.date(),"time"), timeoutMs)); gs.println(gs.plus("nextQueueClean:", Socket.nextQueueClean)); gs.println("cleanQueue.start"); var timeout = gs.minus(gs.gp(gs.date(),"time"), timeoutMs); gs.println(gs.plus("cleanQueue.queue.size:", gs.mc(Socket.queue,"size",[]))); gs.mc(Socket.queue,"each",[function(key, queueItem) { if (gs.gp(queueItem,"date") < timeout) { gs.println("REMOVED"); gs.mc(Socket.queue,"remove",[key]); return gs.mc(queueItem,"fail",[]); }; }]); return gs.println("cleanQueue.end"); }; } Socket.receive = function(wrapper) { Socket.websocketPingCount++; if (gs.equals(gs.gp(wrapper,"uuid"), "ping")) { return null; }; var queueItem = Socket.queue[gs.gp(wrapper,"uuid")]; gs.mc(Socket.queue,"remove",[gs.gp(wrapper,"uuid")]); if (gs.bool(queueItem)) { if (gs.bool(gs.gp(wrapper,"error"))) { gs.mc(queueItem,"fail",[gs.gp(wrapper,"data")]); Socket.processException(gs.gp(wrapper,"data")); return null; }; var object = gs.execStatic(ObjectRegistry,'register', this,[gs.gp(wrapper,"data")]); return gs.mc(queueItem,"success",[object]); }; } Socket.processException = function(ex) { gs.execStatic(Utils,'logExceptionStack', this,[gs.plus((gs.plus(ex.clazz, ":")), gs.gp(ex,"message"))]); return gs.execStatic(Utils,'logExceptionStack', this,[gs.gp(ex,"stackTrace")]); } Socket.subscribe = function(objectId, success, topic) { if (topic === undefined) topic = Socket.SOCKET_OBJECT_URL; return Socket.socketReady(function(it) { gs.mc(Socket,"unsubscribe",[objectId, topic]); gs.println(gs.plus("subscribe:", objectId)); var successWrapper = function(messageObject) { return gs.execCall(success, this, [messageObject]); }; gs.mc(Socket,"addSubscription",[objectId, topic, success]); try { gs.mc(Socket,"subscribeJs",[objectId, gs.plus(topic, objectId), successWrapper]); } catch (all) { gs.println("subscribeJs failed"); gs.println(gs.fs('all', this)); } ; }); } Socket.subscribeTopic = function(topicId, success) { return Socket.subscribe(topicId, success, Socket.SOCKET_TOPIC_URL); } Socket.unsubscribeTopic = function(topicId) { return Socket.unsubscribe(topicId, Socket.SOCKET_TOPIC_URL); } Socket.addSubscription = function(objectId, topic, success) { return (Socket.subscriptions[objectId]) = gs.map().add("objectId",objectId).add("success",success).add("topic",topic); } Socket.subscribeJs = function(objectId, subId, success) { console.log('subscribeJs:'+subId) return Socket.websocketClient.subscribe(subId, function(message){ success(Socket.doReceiveNative(message.body)) }, {id:objectId}) } Socket.doReceiveNative = function(message, compressed) { if (compressed === undefined) compressed = true; if (compressed) message = LZString.decompressFromBase64(message) // console.log('message', message) return Utils.stringToJson(message) } Socket.resubscribeAll = function(it) { var oldSubscriptions = Socket.subscriptions; Socket.subscriptions = gs.map(); return gs.mc(oldSubscriptions,"each",[function(key, subscription) { return gs.mc(Socket,"subscribe",[gs.gp(subscription,"objectId"), gs.gp(subscription,"success"), gs.gp(subscription,"topic")]); }]); } Socket.unsubscribe = function(objectId, topic) { if (topic === undefined) topic = Socket.SOCKET_OBJECT_URL; gs.println(gs.plus("unsubscribe:", objectId)); try { gs.mc(gs.gp(Socket,"websocketClient"),"unsubscribe",[objectId]); gs.mc(Socket.subscriptions,"remove",[objectId]); } catch (all) { gs.println(all); } ; } Socket.post = function(file, parameter, objectName, id, callback) { var postUrl = "/post/upload"; var formData = new FormData(); formData.append('file', file); formData.append('id', id); formData.append('parameter', parameter); formData.append('objectName', objectName); $.ajax({ url : postUrl, type : 'POST', data : formData, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success : function(data) { console.log(data); callback(data); } }); } Socket.postJson = function(url, map, success, failed) { if (success === undefined) success = function(it) { }; if (failed === undefined) failed = function(it) { }; } Socket.SOCKET_URL = "/app/api4WebSocketForPublic"; Socket.SOCKET_USER_URL = "/topic/api4WebSocketForUser/"; Socket.SOCKET_OBJECT_URL = "/topic/api4WebSocketForObject/"; Socket.SOCKET_TOPIC_URL = "/topic/api4WebSocketForTopic/"; Socket.SOCKET_OVER_HTTP_SYNCHRONOUS_URL = "/api4WebSocket/synchronous"; Socket.SOCKET_OVER_HTTP_ASYNCHRONOUS_URL = "/api4WebSocket/asynchronous"; Socket.SESSION_REFRESH_MINS = 10; Socket.SOCKET_CHECK_MSG_RECEIVED_SEC = 7; Socket.SOCKET_RUNNER_RETRY_MS = 5000; Socket.SOCKET_QUEUE_TIMEOUT_MIN = 2; Socket.AUTH_TOKEN = "secToken2"; Socket.DEVICE_TOKEN = "deviceToken1"; Socket.window = null; Socket.navigator = null; Socket.sendProtocol = "http"; Socket.queue = gs.map(); Socket.socketHeadersMap = gs.map(); Socket.userDataPipe = function(data) { return gs.mc(Socket,"receive",[data]); }; Socket.session = gs.execStatic(Session,'instance', this,[]); Socket.connected = false; Socket.socket = null; Socket.websocketClient = gs.map().add("connected",false).add("disconnect",function(it) { }).add("subscriptions",function(it) { }); Socket.subscriptions = gs.map(); Socket.sessionRefresherThreads = gs.list([]); Socket.socketReadyQueue = gs.list([]); Socket.intervalRunner = null; Socket.reconnectMutex = false; Socket.SOCKET_PING_TIMEOUT_MS = 3000; Socket.websocketPingCount = 0; Socket.nextQueueClean = 0; function Utils() { var gSobject = gs.init('Utils'); gSobject.clazz = { name: 'Utils', simpleName: 'Utils'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'session', { get: function() { return Utils.session; }, set: function(gSval) { Utils.session = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'window', { get: function() { return Utils.window; }, set: function(gSval) { Utils.window = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'document', { get: function() { return Utils.document; }, set: function(gSval) { Utils.document = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'DeviceTypes', { get: function() { return Utils.DeviceTypes; }, set: function(gSval) { Utils.DeviceTypes = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'AUTH_FAILED', { get: function() { return Utils.AUTH_FAILED; }, set: function(gSval) { Utils.AUTH_FAILED = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'NO_AUTH', { get: function() { return Utils.NO_AUTH; }, set: function(gSval) { Utils.NO_AUTH = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'REMEMBER_FALLBACK_DAYS', { get: function() { return Utils.REMEMBER_FALLBACK_DAYS; }, set: function(gSval) { Utils.REMEMBER_FALLBACK_DAYS = gSval; }, enumerable: true }); gSobject.getAuthToken = function() { return Utils.getAuthToken(); } gSobject.getDeviceToken = function() { return Utils.getDeviceToken(); } gSobject.setTimeout = function(x0,x1) { return Utils.setTimeout(x0,x1); } gSobject.setInterval = function(x0,x1) { return Utils.setInterval(x0,x1); } gSobject.clearInterval = function(x0) { return Utils.clearInterval(x0); } gSobject.localDateString = function(x0) { return Utils.localDateString(x0); } gSobject.utcDateString = function(x0) { return Utils.utcDateString(x0); } gSobject.newDate = function(x0,x1,x2) { return Utils.newDate(x0,x1,x2); } gSobject.documentReady = function(x0) { return Utils.documentReady(x0); } gSobject.uniqueList = function(x0,x1) { return Utils.uniqueList(x0,x1); } gSobject.listsEqual = function(x0,x1) { return Utils.listsEqual(x0,x1); } gSobject.uuid = function() { return Utils.uuid(); } gSobject.guid = function() { return Utils.guid(); } gSobject.callChain = function(x0,x1,x2) { return Utils.callChain(x0,x1,x2); } gSobject.callObject = function(x0,x1,x2,x3,x4) { return Utils.callObject(x0,x1,x2,x3,x4); } gSobject.send = function(x0,x1,x2,x3) { return Utils.send(x0,x1,x2,x3); } gSobject.subscribe = function(x0,x1,x2) { return Utils.subscribe(x0,x1,x2); } gSobject.unsubscribe = function(x0) { return Utils.unsubscribe(x0); } gSobject.subscribeTopic = function(x0,x1) { return Utils.subscribeTopic(x0,x1); } gSobject.unsubscribeTopic = function(x0) { return Utils.unsubscribeTopic(x0); } gSobject.rememberDays = function() { return Utils.rememberDays(); } gSobject.rememberWindowExpired = function() { return Utils.rememberWindowExpired(); } gSobject.clearRememberedLogin = function() { return Utils.clearRememberedLogin(); } gSobject.parseDays = function(x0) { return Utils.parseDays(x0); } gSobject.toWholeNumber = function(x0) { return Utils.toWholeNumber(x0); } gSobject.nowMillis = function() { return Utils.nowMillis(); } gSobject.toMillis = function(x0) { return Utils.toMillis(x0); } gSobject.launchMarkerPresent = function() { return Utils.launchMarkerPresent(); } gSobject.markLaunch = function() { return Utils.markLaunch(); } gSobject.clearLaunchMarker = function() { return Utils.clearLaunchMarker(); } gSobject.tokenAuth = function(x0,x1) { return Utils.tokenAuth(x0,x1); } gSobject.userAgent = function() { return Utils.userAgent(); } gSobject.login = function(x0,x1,x2,x3) { return Utils.login(x0,x1,x2,x3); } gSobject.updateAuthTokenToSession = function(x0,x1) { return Utils.updateAuthTokenToSession(x0,x1); } gSobject.roleSignature = function(x0) { return Utils.roleSignature(x0); } gSobject.triggerLoginRerenderCheck = function(x0) { return Utils.triggerLoginRerenderCheck(x0); } gSobject.logout = function(x0,x1) { return Utils.logout(x0,x1); } gSobject.urlSafeBase64Encode = function(x0) { return Utils.urlSafeBase64Encode(x0); } gSobject.open = function(x0,x1,x2) { return Utils.open(x0,x1,x2); } gSobject.inAppBrowser = function(x0,x1,x2) { return Utils.inAppBrowser(x0,x1,x2); } gSobject.loadPage = function(x0) { return Utils.loadPage(x0); } gSobject.reloadPage = function() { return Utils.reloadPage(); } gSobject.setCookie = function(x0,x1) { return Utils.setCookie(x0,x1); } gSobject.getCookie = function(x0) { return Utils.getCookie(x0); } gSobject.deviceType = function() { return Utils.deviceType(); } gSobject.isBrowser = function() { return Utils.isBrowser(); } gSobject.isAndroid = function() { return Utils.isAndroid(); } gSobject.isIos = function() { return Utils.isIos(); } gSobject.isCordova = function() { return Utils.isCordova(); } gSobject.cordovaDevice = function() { return Utils.cordovaDevice(); } gSobject.isOnline = function() { return Utils.isOnline(); } gSobject.userAgent = function() { return Utils.userAgent(); } gSobject.toast = function(x0,x1) { return Utils.toast(x0,x1); } gSobject.post = function(x0,x1,x2,x3,x4) { return Utils.post(x0,x1,x2,x3,x4); } gSobject.validateEmail = function(x0) { return Utils.validateEmail(x0); } gSobject.validateCellphone = function(x0) { return Utils.validateCellphone(x0); } gSobject.getType = function(x0) { return Utils.getType(x0); } gSobject.dateString = function(x0) { return Utils.dateString(x0); } gSobject.clearTime = function(x0) { return Utils.clearTime(x0); } gSobject.utc = function(x0) { return Utils.utc(x0); } gSobject.appendAppVersion = function(x0) { return Utils.appendAppVersion(x0); } gSobject.logExceptionStack = function(x0) { return Utils.logExceptionStack(x0); } gSobject.getIp = function(x0) { return Utils.getIp(x0); } gSobject.preloadImage = function(x0) { return Utils.preloadImage(x0); } gSobject.loadScript = function(x0,x1,x2) { return Utils.loadScript(x0,x1,x2); } gSobject.mapToJsonString = function(x0) { return Utils.mapToJsonString(x0); } gSobject.stringToJson = function(x0,x1) { return Utils.stringToJson(x0,x1); } gSobject.stringToDate = function(x0) { return Utils.stringToDate(x0); } gSobject.isDate = function(x0) { return Utils.isDate(x0); } gSobject.deepCopyMap = function(x0) { return Utils.deepCopyMap(x0); } gSobject.findDeep = function(x0,x1) { return Utils.findDeep(x0,x1); } gSobject.removeMapKey = function(x0,x1,x2) { return Utils.removeMapKey(x0,x1,x2); } gSobject.formatNumber = function(x0,x1,x2,x3) { return Utils.formatNumber(x0,x1,x2,x3); } gSobject.iFrameById = function(x0) { return Utils.iFrameById(x0); } gSobject.decodeJWT = function(x0) { return Utils.decodeJWT(x0); } gSobject.embedTextInBlob = function(x0,x1,x2) { return Utils.embedTextInBlob(x0,x1,x2); } gSobject.embedTextInBlobNative = function(x0,x1,x2) { return Utils.embedTextInBlobNative(x0,x1,x2); } gSobject.blobToDataUrl = function(x0,x1) { return Utils.blobToDataUrl(x0,x1); } gSobject.dataUrlToBlob = function(x0,x1) { return Utils.dataUrlToBlob(x0,x1); } gSobject.take = function(x0,x1) { return Utils.take(x0,x1); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; Utils.getAuthToken = function(it) { return gs.gp(Utils.session,"authToken"); } Utils.getDeviceToken = function(it) { return gs.gp(Utils.session,"deviceToken"); } Utils.setTimeout = function(callback, timeout) { return setTimeout(callback, timeout); } Utils.setInterval = function(callback, timeout) { return setInterval(callback, timeout); } Utils.clearInterval = function(interval) { return clearInterval(interval); } Utils.localDateString = function(date) { return gs.mc(gs.mc(gs.mc(Utils,"moment",[date]),"utcOffset",[0, true]),"toISOString",[]); } Utils.utcDateString = function(date) { return gs.mc(gs.mc(gs.mc(Utils,"moment",[date]),"utc",[]),"toISOString",[]); } Utils.newDate = function(year, month, day) { return new Date(year, month, day) } Utils.documentReady = function(callback) { if ((gs.gp(Utils.document,"readyState") === "complete") || ((gs.gp(Utils.document,"readyState") !== "loading") && (!gs.bool(gs.gp(gs.gp(Utils.document,"documentElement"),"doScroll"))))) { return gs.execCall(callback, this, []); } else { return gs.mc(Utils.document,"addEventListener",["DOMContentLoaded", callback]); }; } Utils.uniqueList = function(list, closure) { var newList = gs.list([]); gs.mc(gs.mc(list,"reverse",[]),"each",[function(listItem) { if (!gs.bool(gs.mc(newList,"find",[function(it) { return gs.equals(gs.execCall(closure, this, [listItem]), gs.execCall(closure, this, [it])); }]))) { return gs.mc(newList,"add",[listItem]); }; }]); return gs.mc(newList,"reverse",[]); } Utils.listsEqual = function(a, b) { if (gs.mc(a,"size",[]) != gs.mc(b,"size",[])) { return false; }; for (var i = 0 ; i < gs.mc(a,"size",[]) ; i++) { if ((a[i]) != (b[i])) { return false; }; }; return true; } Utils.uuid = function(it) { return gs.mc(Utils.guid(),"replaceAll",["-", ""]); } Utils.guid = function() { const UNIX_TS_MS_BITS = 48; const VER_DIGIT = "7"; const SEQ_BITS = 12; const VAR = 0b10; const VAR_BITS = 2; const RAND_BITS = 62; let prevTimestamp = -1; let seq = 0; const timestamp = Math.max(Date.now(), prevTimestamp); seq = timestamp === prevTimestamp ? seq + 1 : 0; prevTimestamp = timestamp; const var_rand = new Uint32Array(2); crypto.getRandomValues(var_rand); var_rand[0] = (VAR << (32 - VAR_BITS)) | (var_rand[0] >>> VAR_BITS); const digits = timestamp.toString(16).padStart(UNIX_TS_MS_BITS / 4, "0") + VER_DIGIT + seq.toString(16).padStart(SEQ_BITS / 4, "0") + var_rand[0].toString(16).padStart((VAR_BITS + RAND_BITS) / 2 / 4, "0") + var_rand[1].toString(16).padStart((VAR_BITS + RAND_BITS) / 2 / 4, "0"); return (digits.slice(0, 8) + "-" + digits.slice(8, 12) + "-" + digits.slice(12, 16) + "-" + digits.slice(16, 20) + "-" + digits.slice(20)); } Utils.callChain = function(callChain, success, fail) { if (success === undefined) success = null; if (fail === undefined) fail = null; return gs.execStatic(Socket,'callChain', this,[callChain, success, fail]); } Utils.callObject = function(self, method, args, success, fail) { if (fail === undefined) fail = null; return gs.execStatic(Socket,'callObject', this,[self, method, args, success, fail]); } Utils.send = function(call, data, success, fail) { if (fail === undefined) fail = null; return gs.execStatic(Socket,'send', this,[call, data, success, fail]); } Utils.subscribe = function(objectId, success, topic) { if (topic === undefined) topic = gs.gp(Socket,"SOCKET_OBJECT_URL"); return gs.execStatic(Socket,'subscribe', this,[objectId, success, topic]); } Utils.unsubscribe = function(objectId) { return gs.execStatic(Socket,'unsubscribe', this,[objectId]); } Utils.subscribeTopic = function(topicId, success) { return gs.execStatic(Socket,'subscribeTopic', this,[topicId, success]); } Utils.unsubscribeTopic = function(topicId) { return gs.execStatic(Socket,'unsubscribeTopic', this,[topicId]); } Utils.rememberDays = function(it) { var days = Utils.parseDays(gs.gp(Utils.session,"rememberDays")); return (gs.equals(days, null) ? Utils.REMEMBER_FALLBACK_DAYS : days); } Utils.rememberWindowExpired = function(it) { var days = Utils.rememberDays(); if (gs.equals(days, 0)) { return !Utils.launchMarkerPresent(); }; var loginAt = gs.gp(Utils.session,"loginAt"); if (!gs.bool(loginAt)) { return true; }; return (gs.minus(Utils.nowMillis(), Utils.toMillis(loginAt))) > (gs.multiply((gs.multiply((gs.multiply((gs.multiply(days, 24)), 60)), 60)), 1000)); } Utils.clearRememberedLogin = function(it) { gs.sp(Utils.session,"zoner",null); gs.sp(Utils.session,"zonerId",null); gs.sp(Utils.session,"jwt",null); gs.sp(Utils.session,"loginAt",null); gs.sp(Utils.session,"rememberDays",null); return Utils.clearLaunchMarker(); } Utils.parseDays = function(raw) { if (gs.equals(raw, null)) { return null; }; return Utils.toWholeNumber(raw); } Utils.toWholeNumber = function(raw) { var s = ('' + raw).trim(); if (!/^[0-9]+$/.test(s)) return null; var n = parseInt(s, 10); return isNaN(n) ? null : n; } Utils.nowMillis = function() { return new Date().getTime(); } Utils.toMillis = function(value) { if (value == null) return 0; if (value instanceof Date) return value.getTime(); var n = parseInt('' + value, 10); return isNaN(n) ? 0 : n; } Utils.launchMarkerPresent = function() { try { return sessionStorage.getItem('dymicoLoginLaunch') === 'true'; } catch(e){ return false; } } Utils.markLaunch = function() { try { sessionStorage.setItem('dymicoLoginLaunch', 'true'); } catch(e){} } Utils.clearLaunchMarker = function() { try { sessionStorage.removeItem('dymicoLoginLaunch'); } catch(e){} } Utils.tokenAuth = function(success, fail) { if (fail === undefined) fail = function(it) { }; gs.println(gs.plus("Utils:tokenAuth:", gs.gp(StartupParams,"doAuthToken"))); if ((gs.bool(gs.gp(Utils.session,"zoner"))) && (!gs.bool(Utils.rememberWindowExpired()))) { gs.println("Utils:tokenAuth:zoner cached"); gs.execCall(success, this, []); success = null; return null; }; if (gs.bool(gs.gp(Utils.session,"zoner"))) { gs.println("Utils:tokenAuth:remember window expired"); Utils.clearRememberedLogin(); }; gs.println("Utils:tokenAuth:loading zoner"); var callback = function(authMap) { gs.println(gs.plus("tokenAuth:callback:authMap:", authMap)); if (gs.bool(gs.gp(authMap,"authenticated",true))) { gs.mc(Utils,"updateAuthTokenToSession",[authMap, false]); if (gs.bool(success)) { gs.execCall(success, this, []); }; return null; }; return gs.execCall(fail, this, []); }; gs.println(gs.plus("getDeviceToken():", Utils.getDeviceToken())); return gs.execStatic(Utils,'send', this,["authenticationToken", gs.map().add("deviceId",Utils.getDeviceToken()), callback]); } Utils.userAgent = function() { return navigator.userAgent.toLowerCase() } Utils.login = function(username, password, success, fail) { if (fail === undefined) fail = function(it) { }; var callback = function(authMap) { if (gs.bool(gs.gp(authMap,"authenticated",true))) { gs.mc(Utils,"updateAuthTokenToSession",[authMap]); gs.execCall(success, this, []); return null; }; gs.sp(Utils.session,"zoner",null); gs.println("Login failed"); return gs.execCall(fail, this, []); }; return gs.execStatic(Utils,'send', this,["authentication", gs.map().add("username",username).add("password",password).add("deviceId",Utils.getDeviceToken()).add("userAgent",Utils.userAgent()), callback, fail]); } Utils.updateAuthTokenToSession = function(authMap, freshLogin) { if (freshLogin === undefined) freshLogin = true; Utils.setCookie(gs.gp(Socket,"AUTH_TOKEN"), gs.gp(gs.gp(authMap,"zoner"),"token")); gs.sp(Utils.session,"zoner",gs.gp(authMap,"zoner")); gs.sp(Utils.session,"zonerId",gs.gp(gs.gp(authMap,"zoner"),"id")); if (gs.gp(authMap,"rememberDays") != null) { gs.sp(Utils.session,"rememberDays",gs.gp(authMap,"rememberDays")); }; if ((gs.bool(freshLogin)) || (!gs.bool(gs.gp(Utils.session,"loginAt")))) { gs.sp(Utils.session,"loginAt",Utils.nowMillis()); }; Utils.markLaunch(); if (gs.bool(gs.gp(authMap,"jwt"))) { gs.sp(Utils.session,"jwt",gs.gp(authMap,"jwt")); }; return Utils.triggerLoginRerenderCheck(Utils.roleSignature(gs.gp(gs.gp(authMap,"zoner"),"roles"))); } Utils.roleSignature = function(roles) { return gs.mc(gs.mc(gs.mc(gs.elvis(gs.bool(roles) , roles , gs.list([])),"collect",[function(it) { return gs.mc(it,"toString",[], null, true); }]),"sort",[]),"join",[","]); } Utils.triggerLoginRerenderCheck = function(zonerId) { try { if (window.dymicoVersionUpdater && window.dymicoVersionUpdater.checkAfterLogin){ window.dymicoVersionUpdater.checkAfterLogin(zonerId); } } catch(e){ console.log('triggerLoginRerenderCheck failed', e); } } Utils.logout = function(pathAfterLogout, dropDatabase) { if (pathAfterLogout === undefined) pathAfterLogout = "/login/logout"; if (dropDatabase === undefined) dropDatabase = true; if (!gs.bool(pathAfterLogout)) { pathAfterLogout = "/login/logout"; }; gs.println("Utils.logout"); gs.sp(Utils.session,"zoner",null); gs.sp(Utils.session,"redirectAfterLogin",null); gs.sp(Utils.session,"authToken",null); gs.sp(Utils.session,"deviceToken",null); gs.mc(Utils.session,"clear",[]); if (gs.bool(dropDatabase)) { gs.execStatic(LocalDB,'getInstance', this,[function(it) { return gs.mc(gs.execStatic(LocalDB,'getInstance', this,[]),"dropDatabase",[]); }]); }; gs.println(gs.plus("Utils.logout:redirect to ", pathAfterLogout)); return Utils.loadPage(pathAfterLogout); } Utils.urlSafeBase64Encode = function(str) { // 1. Encode to standard Base64 let base64 = btoa(str); // 2. Modify to be URL-safe (RFC 4648 Section 5) return base64 .replace(/\+/g, '-') // Replace + with - .replace(/\//g, '_') // Replace / with _ .replace(/=+$/, ''); // Remove trailing = padding } Utils.open = function(url, target, options) { if (target === undefined) target = "_system"; if (options === undefined) options = ""; if (Utils.isCordova()) { return Utils.inAppBrowser(gs.mc(Utils,"encodeURI",[url]), target, options); }; return gs.mc(Utils.window,"open",[url, target, options]); } Utils.inAppBrowser = function(url, target, options) { return cordova.InAppBrowser.open(encodeURI(url), target, options) } Utils.loadPage = function(url) { window.location = url } Utils.reloadPage = function() { var url = window.location.href; var seperator = '?' if (url.indexOf('?') > -1){ seperator = '&' } window.location.href = url+seperator+'v='+ new Date().getTime(); window.location.reload(true); } Utils.setCookie = function(name, value) { Cookies.set(name, JSON.stringify(value)); } Utils.getCookie = function(name) { try{ return JSON.parse(Cookies.get(name)); // return gs.toGroovy(jQuery.parseJSON(unescape(Cookies.get(name)))); }catch(all){ return null } } Utils.deviceType = function(it) { if (gs.mc(gs.mc(Utils.userAgent(),"toLowerCase",[]),"contains",["electron"])) { return gs.gp(gs.gp(Utils,"DeviceTypes"),"ELECTRON"); }; if ((gs.mc(gs.mc(Utils.userAgent(),"toLowerCase",[]),"contains",["iphone"])) || (gs.mc(gs.mc(Utils.userAgent(),"toLowerCase",[]),"contains",["ipad"]))) { return gs.gp(gs.gp(Utils,"DeviceTypes"),"IOS"); }; if (gs.mc(gs.mc(Utils.userAgent(),"toLowerCase",[]),"contains",["android"])) { return gs.gp(gs.gp(Utils,"DeviceTypes"),"ANDROID"); }; return gs.gp(gs.gp(Utils,"DeviceTypes"),"BROWSER"); } Utils.isBrowser = function(it) { return gs.equals(Utils.deviceType(), gs.gp(Utils.DeviceTypes,"BROWSER")); } Utils.isAndroid = function(it) { return gs.equals(Utils.deviceType(), gs.gp(gs.gp(Utils,"DeviceTypes"),"ANDROID")); } Utils.isIos = function(it) { return gs.equals(Utils.deviceType(), gs.gp(gs.gp(Utils,"DeviceTypes"),"IOS")); } Utils.isCordova = function(it) { return gs.mc(Utils.userAgent(),"contains",["cordova"]); } Utils.cordovaDevice = function(it) { return Utils.isCordova(); } Utils.isOnline = function() { return window.navigator.onLine } Utils.userAgent = function() { return navigator.userAgent.toLowerCase() } Utils.toast = function(message, showDuration) { if (showDuration === undefined) showDuration = 300; toastr.options = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": false, "positionClass": "toast-bottom-center", "preventDuplicates": false, "onclick": null, "showDuration": showDuration, "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" } toastr.info(message); } Utils.post = function(file, parameter, objectName, id, callback) { return gs.execStatic(Socket,'post', this,[file, parameter, objectName, id, callback]); } Utils.validateEmail = function(text) { return gs.exactMatch(text,/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[A-Za-z.]{2,}$/); } Utils.validateCellphone = function(text) { var cleaned = gs.mc(gs.mc(gs.mc(text,"toString",[], null, true),"trim",[], null, true),"replaceAll",["[\s\-\(\)]", ""], null, true); if (!gs.bool(cleaned)) { return false; }; if (gs.mc(cleaned,"startsWith",["+"])) { return gs.exactMatch(cleaned,/^\+[0-9]{7,15}$/); }; return gs.exactMatch(cleaned,/^0[0-9]{9}$/); } Utils.getType = function(value) { return typeof value } Utils.dateString = function(date) { return gs.plus((gs.plus((gs.plus((gs.plus(gs.mc(date,"getDate",[]), "/")), (gs.plus(gs.mc(date,"getMonth",[]), 1)))), "/")), gs.mc(date,"getFullYear",[])); } Utils.clearTime = function(date) { if (date === undefined) date = gs.date(); return gs.mc(gs.mc(Utils,"moment",[date]),"startOf",["day"]); } Utils.utc = function(date) { if (date === undefined) date = gs.date(); return gs.mc(gs.mc(Utils,"moment",[date]),"utc",[]); } Utils.appendAppVersion = function(url) { if (gs.bool(gs.gp(Utils.session,"branchRevision"))) { var appender = "?"; if (gs.mc(url,"contains",["?"])) { appender = "&"; }; url += (gs.plus((gs.plus(appender, "branchRevision=")), gs.gp(Utils.session,"branchRevision"))); }; return url; } Utils.logExceptionStack = function(msg) { console.log('%c ' + msg + ' ', 'color: #cc0000'); } Utils.getIp = function(callback) { Utils.documentReady(function () { $.getJSON("http://jsonip.com/?callback=?", function (data) { callback(data.ip) }); }); } Utils.preloadImage = function(path) { new Image().src = path } Utils.loadScript = function(scriptUrl, type, callback) { if (type === undefined) type = "text/javascript"; if (callback === undefined) callback = function(it) { }; } Utils.mapToJsonString = function(map) { return JSON.stringify(map) } Utils.stringToJson = function(message, parseDate) { if (parseDate === undefined) parseDate = true; var jsonMessage = JSON.parse(message, function(key, value) { return Utils.stringToDate(value); } ) return gs.toGroovy(jsonMessage) } Utils.stringToDate = function(value) { if (typeof value === 'string') { //var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})?\.(\d*)?Z$/.exec(value); if (a) { // console.log('stringToDate:value', value) const date = new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6], +a[7])); // console.log('stringToDate:date', date) return date } } return value; } Utils.isDate = function(date) { return date instanceof Date } Utils.deepCopyMap = function(map) { return Utils.removeMapKey(gs.toGroovy(Utils.stringToJson(Utils.mapToJsonString(map))),'clazz') } Utils.findDeep = function(m, key) { if (m[key]) { return m[key]; }; var foundValue = null; gs.mc(m,"each",[function(k, v) { if (gs.bool(foundValue)) { return null; }; if (gs.instanceOf(v, "HashMap")) { return foundValue = gs.mc(Utils,"findDeep",[v, key]); } else { if (gs.instanceOf(v, "ArrayList")) { return gs.mc(v,"each",[function(item) { if (gs.bool(foundValue)) { return null; }; if (gs.instanceOf(item, "HashMap")) { return foundValue = gs.mc(Utils,"findDeep",[item, key]); }; }]); }; }; }]); return foundValue; } Utils.removeMapKey = function(value, removeKey, list) { if (removeKey === undefined) removeKey = "clazz"; if (list === undefined) list = gs.list([]); if (!gs.bool(value)) { return value; }; if (((gs.instanceOf(value, "Map")) || (gs.instanceOf(value, "LinkedHashMap"))) || (gs.instanceOf(value, "HashMap"))) { gs.mc(value,"remove",[removeKey]); if (gs.mc(list,"includes",[value])) { return value; }; gs.mc(list,"add",[value]); gs.mc(value,"each",[function(key, mapValue) { return gs.mc(Utils,"removeMapKey",[mapValue, removeKey, list]); }]); }; if ((gs.instanceOf(value, "List")) || (gs.instanceOf(value, "ArrayList"))) { for (_i0 = 0, listValue = value[0]; _i0 < value.length; listValue = value[++_i0]) { Utils.removeMapKey(listValue, removeKey, list); }; }; return value; } Utils.formatNumber = function(number, decimals, dec, sep) { if (decimals === undefined) decimals = 0; if (dec === undefined) dec = "."; if (sep === undefined) sep = " "; var n = !isFinite(+number) ? 0 : +number, prec = Math.abs(decimals), toFixedFix = function (n, prec) { // Fix for IE parseFloat(0.55).toFixed(0) = 0; var k = Math.pow(10, prec); return Math.round(n * k) / k; }, s = (prec ? toFixedFix(n, prec) : Math.round(n)).toString().split('.'); if (s[0].length > 3) { s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep); } if ((s[1] || '').length < prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } return s.join(dec); } Utils.iFrameById = function(id) { var x = gs.mc(Utils.document,"getElementById",[id]); return gs.elvis(gs.bool(gs.gp(x,"contentWindow")) , gs.gp(x,"contentWindow") , gs.gp(x,"contentDocument")); } Utils.decodeJWT = function(token) { var base64Url = token.split('.')[1]; var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); return JSON.parse(jsonPayload); } Utils.embedTextInBlob = function(fileOrBlob, textToEmbed, callback) { gs.println("textToEmbed"); gs.println(textToEmbed); if (!gs.bool(textToEmbed)) { return gs.execCall(callback, this, [fileOrBlob]); }; return Utils.embedTextInBlobNative(fileOrBlob, textToEmbed, callback); } Utils.embedTextInBlobNative = function(fileOrBlob, text, callback) { const reader = new FileReader(); reader.onload = function (e) { const img = new Image(); img.onload = function () { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); canvas.width = img.width; canvas.height = img.height; var fontSize = canvas.width * 0.025 console.log('fontSize1', fontSize) if (fontSize < 5 ) fontSize = 5 console.log('fontSize2', fontSize) // Draw the image ctx.drawImage(img, 0, 0); // Draw text bottom-right ctx.font = fontSize+"px Sans-serif"; ctx.fillStyle = "White"; ctx.textAlign = "right"; ctx.textBaseline = "bottom"; const padding = 2; ctx.fillText(text, canvas.width - padding, canvas.height - padding); // Return result as a Blob canvas.toBlob(function (blob) { callback(blob); }, "image/png"); }; img.onerror = function (err) { callback("Image failed to load: " + err); }; img.src = e.target.result; }; reader.onerror = function (err) { callback("FileReader error: " + err); }; // Read the file/blob as Data URL reader.readAsDataURL(fileOrBlob); } Utils.blobToDataUrl = function(blob, callback) { const fileReader = new FileReader(); fileReader.onload = function() { callback(fileReader.result) } fileReader.readAsDataURL(blob); } Utils.dataUrlToBlob = function(dataUrl, callback) { return gs.mc(gs.mc(gs.mc(Utils.window,"fetch",[dataUrl]),"then",[function(res) { return gs.mc(res,"blob",[]); }]),"then",[function(blob) { return gs.execCall(callback, this, [blob]); }]); } Utils.take = function(string, len) { if (len === undefined) len = 40; if ((!gs.bool(string)) || (gs.mc(string,"size",[]) < len)) { return string; }; return gs.rangeFromList(string, 0, len); } Utils.session = gs.execStatic(Session,'instance', this,[]); Utils.window = null; Utils.document = null; Utils.DeviceTypes = gs.map().add("ANDROID","android").add("IOS","ios").add("ELECTRON","electron").add("BROWSER","browser"); Utils.AUTH_FAILED = "AUTH_FAILED"; Utils.NO_AUTH = "NO_AUTH"; Utils.REMEMBER_FALLBACK_DAYS = 30; function ObjectRegistry() { var gSobject = gs.init('ObjectRegistry'); gSobject.clazz = { name: 'ObjectRegistry', simpleName: 'ObjectRegistry'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'objectRegistry', { get: function() { return ObjectRegistry.objectRegistry; }, set: function(gSval) { ObjectRegistry.objectRegistry = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'enabled', { get: function() { return ObjectRegistry.enabled; }, set: function(gSval) { ObjectRegistry.enabled = gSval; }, enumerable: true }); gSobject.object = function(x0) { return ObjectRegistry.object(x0); } gSobject.register = function(x0) { return ObjectRegistry.register(x0); } gSobject.registerSingle = function(x0,x1) { return ObjectRegistry.registerSingle(x0,x1); } gSobject.isDatabaseObject = function(x0) { return ObjectRegistry.isDatabaseObject(x0); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; ObjectRegistry.object = function(id) { return ObjectRegistry.objectRegistry[id]; } ObjectRegistry.register = function(objects) { if (!gs.bool(ObjectRegistry.enabled)) { return objects; }; if (gs.instanceOf(objects, "ArrayList")) { var oObjectList = gs.list([]); gs.mc(objects,"eachWithIndex",[function(object, index) { return gs.mc(oObjectList,"add",[gs.mc(ObjectRegistry,"registerSingle",[object])]); }]); return oObjectList; } else { return ObjectRegistry.registerSingle(objects); }; } ObjectRegistry.registerSingle = function(object, flatCopy) { if (flatCopy === undefined) flatCopy = true; if (!gs.bool(ObjectRegistry.isDatabaseObject(object))) { return object; }; var oObject = ObjectRegistry.objectRegistry[gs.gp(object,"_id")]; if (!gs.bool(oObject)) { oObject = OObject(object); (ObjectRegistry.objectRegistry[gs.gp(object,"_id")]) = oObject; } else { gs.mc(oObject,"merge",[object, flatCopy]); }; gs.mc(object,"each",[function(key, value) { if (gs.mc(ObjectRegistry,"isDatabaseObject",[value])) { var newValue = gs.mc(ObjectRegistry,"registerSingle",[value, false]); return (gs.gp(oObject,"internalMap")[key]) = gs.mc(newValue,"toJs",[]); } else { if ((value != null) && (gs.instanceOf(value, "ArrayList"))) { var oObjectList = gs.list([]); gs.mc(value,"eachWithIndex",[function(objectVal, index) { if (gs.mc(ObjectRegistry,"isDatabaseObject",[objectVal])) { return gs.mc(oObjectList,"add",[gs.mc(gs.mc(ObjectRegistry,"registerSingle",[objectVal]),"toJs",[])]); } else { return gs.mc(oObjectList,"add",[objectVal]); }; }]); return (gs.gp(oObject,"internalMap")[key]) = oObjectList; }; }; }]); gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gs.execStatic(LocalDB,'getInstance', this,[]),"updateIfExists",[oObject]); }, 100]); return oObject; } ObjectRegistry.isDatabaseObject = function(object) { return ((object != null) && (gs.instanceOf(object, "HashMap"))) && (gs.bool(gs.gp(object,"_id"))); } ObjectRegistry.objectRegistry = gs.map(); ObjectRegistry.enabled = false; function OObject() { var gSobject = gs.init('OObject'); gSobject.clazz = { name: 'OObject', simpleName: 'OObject'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.internalMap = gs.map(); gSobject.methodMissingName = null; gSobject.methodMissingArgs = null; gs.astDelegate('OObject', 'internalMap'); gSobject.refresher = null; gSobject.updateCallback = function(it) { }; gSobject['subscribe'] = function(it) { return gs.execStatic(Utils,'subscribe', this,[gs.gp(gSobject.internalMap,"_id"), gSobject.updateCallback]); } gSobject['unsubscribe'] = function(it) { return gs.execStatic(Utils,'unsubscribe', this,[gs.gp(gSobject.internalMap,"_id")]); } gSobject['setRefresher'] = function(closure, update) { if (update === undefined) update = true; gs.mc(gSobject,"subscribe",[]); if ((!gs.bool(gSobject.refresher)) || ((gs.bool(gSobject.refresher)) && (gs.bool(update)))) { return gSobject.refresher = closure; }; } gSobject['merge'] = function(object, flatCopy) { if (flatCopy === undefined) flatCopy = true; if ((gs.bool(object)) && (gs.instanceOf(object, "OObject"))) { object = gs.gp(object,"internalMap"); }; gs.mc(object,"each",[function(key, value) { if (gs.bool(flatCopy)) { (gSobject.internalMap[key]) = value; return null; }; if (!gs.bool(((value != null) && (gs.instanceOf(value, "String"))) && (gs.execStatic(ObjectRegistry,'isDatabaseObject', this,[gSobject.internalMap[key]])))) { return (gSobject.internalMap[key]) = value; } else { gs.println("WARNING: skip overwrite of DatabaseObject with String"); gs.println(gs.plus("Key:", key)); gs.println(gs.plus("String:", value)); gs.println("internalMap[key]:"); gs.println(gSobject.internalMap[key]); gs.println("Object:"); return gs.println(gSobject.internalMap); }; }]); if (gs.bool(gSobject.refresher)) { return gs.mc(gSobject,"refresher",[this]); }; } gSobject['toJs'] = function(it) { return gSobject.internalMap; } gSobject['toString'] = function(it) { return gs.mc(gSobject.internalMap,"toString",[]); } gSobject['setProperty'] = function(name, value) { return (gSobject.internalMap[name]) = value; } gSobject['getProperty'] = function(name) { return gSobject.internalMap[name]; } gSobject['methodMissing'] = function(name, args) { gSobject.methodMissingName = name; gSobject.methodMissingArgs = args; if (gs.bool(args)) { var successClosure = gs.mc(args,"last",[]); if (gs.instanceOf(successClosure, "Closure")) { if (gs.equals(gs.mc(args,"size",[]), 1)) { args = null; } else { args = (gs.rangeFromList(args, 0, -2)); }; gSobject.methodMissingArgs = args; return gs.mc(gSobject,"then",[successClosure]); }; }; } gSobject['then'] = function(successClosure, fail) { if (successClosure === undefined) successClosure = function(it) { }; if (fail === undefined) fail = function(it) { }; return gs.execStatic(Utils,'callObject', this,[gSobject.internalMap, gSobject.methodMissingName, gSobject.methodMissingArgs, successClosure, fail]); } gSobject['do'] = function(success) { if (success === undefined) success = function(it) { }; return gs.mc(gSobject,"then",[success, null]); } gSobject.await = function() { } gSobject.promise = function() { var self = this; return new Promise(function(resolve, reject) { self.then(resolve, function(err) { reject(err); }); }); } gSobject['OObject1'] = function(self) { gs.mc(gSobject,"merge",[self]); return this; } if (arguments.length==1) {gSobject.OObject1(arguments[0]); } return gSobject; }; function ObjectFinder() { var gSobject = gs.init('ObjectFinder'); gSobject.clazz = { name: 'ObjectFinder', simpleName: 'ObjectFinder'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'singleO', { get: function() { return ObjectFinder.singleO; }, set: function(gSval) { ObjectFinder.singleO = gSval; }, enumerable: true }); gSobject.log = RemoteLog("Transmission"); gSobject.getInstance = function() { return ObjectFinder.getInstance(); } gSobject['propertyMissing'] = function(name) { var argList = gs.list([gs.map().add("property",name)]); return NestedO(argList, CacheCallTracker(0, false, false)); } gSobject['local'] = function(ttl, remoteOnce) { if (remoteOnce === undefined) remoteOnce = false; var argList = gs.list([]); return NestedO(argList, CacheCallTracker(ttl, remoteOnce)); } gSobject['localAndRemote'] = function(ttl) { if (ttl === undefined) ttl = -1; gs.println("localAndRemote"); return gs.mc(gSobject,"local",[ttl]); } gSobject['localAndRemoteOnce'] = function(ttl) { if (ttl === undefined) ttl = -1; return gs.mc(gSobject,"local",[ttl, true]); } gSobject['post'] = function(file, parameter, objectName, id, callback) { if (objectName === undefined) objectName = null; if (id === undefined) id = null; if (callback === undefined) callback = function(it) { }; if (!gs.bool(file)) { gs.println("No file selected"); return null; }; gs.println(gs.plus("file: ", file)); gs.println(gs.plus("parameter: ", parameter)); gs.println(gs.plus("objectName: ", objectName)); gs.println(gs.plus("id: ", id)); return gs.execStatic(Utils,'post', this,[file, parameter, objectName, id, callback]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; ObjectFinder.getInstance = function(it) { if (gs.bool(ObjectFinder.singleO)) { return ObjectFinder.singleO; }; ObjectFinder.singleO = ObjectFinder(); return ObjectFinder.singleO; } ObjectFinder.singleO = null; function RemoteLog() { var gSobject = gs.init('RemoteLog'); gSobject.clazz = { name: 'RemoteLog', simpleName: 'RemoteLog'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.className = null; gSobject['info'] = function(message) { return gs.mc(gSobject,"generic",["info", message]); } gSobject['debug'] = function(message) { return gs.mc(gSobject,"generic",["debug", message]); } gSobject['warn'] = function(message) { return gs.mc(gSobject,"generic",["warn", message]); } gSobject['error'] = function(message) { return gs.mc(gSobject,"generic",["error", message]); } gSobject['off'] = function(message) { return gs.mc(gSobject,"generic",["off", message]); } gSobject['trace'] = function(message) { return gs.mc(gSobject,"generic",["trace", message]); } gSobject['generic'] = function(callName, message) { try { gs.println(gs.plus((gs.plus(gSobject.className, ":")), message)); } catch (all) { } ; return gs.mc(gs.mc(gs.mc(gs.execStatic(ObjectFinder,'getInstance', this,[]),"propertyMissing",["log"]),"" + (callName) + "",[message, gSobject.className]),"do",[]); } gSobject['RemoteLog1'] = function(className) { gs.sp(this,"className",className); return this; } if (arguments.length==1) {gSobject.RemoteLog1(arguments[0]); } return gSobject; }; function NestedO() { var gSobject = gs.init('NestedO'); gSobject.clazz = { name: 'NestedO', simpleName: 'NestedO'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.cacheCallTracker = null; gSobject.successClosure = null; gSobject.failClosure = function(it) { }; gSobject.argList = gs.list([]); gSobject['methodMissing'] = function(name, args) { if (gs.mc(gSobject.argList,"size",[]) > 16) { throw {message: "Maximum call stack size 16 exceeded"}; }; if (gs.bool(args)) { var successClosure = gs.mc(args,"last",[]); var failClosure = function(it) { }; if ((gs.bool(successClosure)) && (gs.instanceOf(successClosure, "Closure"))) { if (gs.equals(gs.mc(args,"size",[]), 1)) { args = null; } else { args = (gs.rangeFromList(args, 0, -2)); if ((gs.mc(args,"last",[])) && (gs.instanceOf(gs.mc(args,"last",[]), "Closure"))) { failClosure = successClosure; successClosure = gs.mc(args,"last",[]); if (gs.equals(gs.mc(args,"size",[]), 1)) { args = null; } else { args = (gs.rangeFromList(args, 0, -2)); }; }; }; gs.mc(gSobject.argList,"add",[gs.map().add("method",name).add("args",args)]); gs.sp(this,"successClosure",successClosure); gs.sp(this,"failClosure",failClosure); gs.mc(gSobject,"then",[successClosure, failClosure]); return null; }; }; gs.mc(gSobject.argList,"add",[gs.map().add("method",name).add("args",args)]); return NestedO(gSobject.argList, gSobject.cacheCallTracker); } gSobject.isUndefined = function(val) { return val === undefined } gSobject['propertyMissing'] = function(name) { if (gs.mc(gSobject.argList,"size",[]) > 16) { throw {message: "Maximum call stack size 16 exceeded"}; }; gs.mc(gSobject.argList,"add",[gs.map().add("property",name)]); return NestedO(gSobject.argList, gSobject.cacheCallTracker); } gSobject['then'] = function(success, fail) { if (fail === undefined) fail = function(it) { }; return gs.mc(gSobject.cacheCallTracker,"callAndCache",[gSobject.argList, success, fail]); } gSobject['do'] = function(it) { return gs.mc(gSobject,"then",[function(it) { }]); } gSobject.await = function() { } gSobject.promise = function() { var self = this; return new Promise(function(resolve, reject) { self.then(resolve, function(err) { reject(err); }); }); } gSobject['NestedO2'] = function(argList, cacheCallTracker) { gs.sp(this,"cacheCallTracker",cacheCallTracker); gs.sp(this,"argList",argList); return this; } if (arguments.length==2) {gSobject.NestedO2(arguments[0], arguments[1]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function LocalDB() { var gSobject = gs.init('LocalDB'); gSobject.clazz = { name: 'LocalDB', simpleName: 'LocalDB'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'DB_VERSION_NO', { get: function() { return LocalDB.DB_VERSION_NO; }, set: function(gSval) { LocalDB.DB_VERSION_NO = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'DB_NAME', { get: function() { return LocalDB.DB_NAME; }, set: function(gSval) { LocalDB.DB_NAME = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'MAX_ROWS_PER_BATCH', { get: function() { return LocalDB.MAX_ROWS_PER_BATCH; }, set: function(gSval) { LocalDB.MAX_ROWS_PER_BATCH = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'ASYNC_DB', { get: function() { return LocalDB.ASYNC_DB; }, set: function(gSval) { LocalDB.ASYNC_DB = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'DB_COMPRESS', { get: function() { return LocalDB.DB_COMPRESS; }, set: function(gSval) { LocalDB.DB_COMPRESS = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'DB_ENCRYPT', { get: function() { return LocalDB.DB_ENCRYPT; }, set: function(gSval) { LocalDB.DB_ENCRYPT = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'startupCompleted', { get: function() { return LocalDB.startupCompleted; }, set: function(gSval) { LocalDB.startupCompleted = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'instance', { get: function() { return LocalDB.instance; }, set: function(gSval) { LocalDB.instance = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'jsDbInstance', { get: function() { return LocalDB.jsDbInstance; }, set: function(gSval) { LocalDB.jsDbInstance = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'db', { get: function() { return LocalDB.db; }, set: function(gSval) { LocalDB.db = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'objectMaps', { get: function() { return LocalDB.objectMaps; }, set: function(gSval) { LocalDB.objectMaps = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'callbacks', { get: function() { return LocalDB.callbacks; }, set: function(gSval) { LocalDB.callbacks = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'checkVersion', { get: function() { return LocalDB.checkVersion; }, set: function(gSval) { LocalDB.checkVersion = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'cleanupStaleData', { get: function() { return LocalDB.cleanupStaleData; }, set: function(gSval) { LocalDB.cleanupStaleData = gSval; }, enumerable: true }); gSobject.localO = LocalDB$LocalO(this); gSobject.getInstance = function(x0) { return LocalDB.getInstance(x0); } gSobject.initDb = function(x0,x1) { return LocalDB.initDb(x0,x1); } gSobject.dropDatabase = function(x0) { return LocalDB.dropDatabase(x0); } gSobject['cacheObjects'] = function(key, objectsIn, ttl, callback) { var ttlInMs = (gs.equals(ttl, -1) ? null : gs.plus(gs.gp(gs.date(),"time"), (gs.multiply(ttl, 1000)))); key = (gs.plus("c:", key)); return gs.mc(LocalDB.db,"upsert",[gs.map().add("_id",key).add("_ttl",ttlInMs).add("stringValue",gs.execStatic(Utils,'mapToJsonString', this,[objectsIn])), function(it) { var callbackTmp = callback; callback = null; if (gs.bool(callbackTmp)) { return gs.execCall(callbackTmp, this, []); }; }]); } gSobject['readCache'] = function(key) { key = (gs.plus("c:", key)); var keyObject = gs.mc(LocalDB.db,"find",[gs.map().add("_id",key)]); gs.println(keyObject); if (gs.equals(gs.gp(keyObject,"length"), 0)) { return null; }; keyObject = (keyObject[0]); if ((gs.bool(gs.gp(keyObject,"_ttl"))) && (gs.gp(keyObject,"_ttl") <= gs.gp(gs.date(),"time"))) { gs.mc(LocalDB.db,"remove",[gs.map().add("_id",key)]); gs.mc(LocalDB.db,"save",[]); return null; }; return gs.execStatic(Utils,'stringToJson', this,[gs.gp(keyObject,"stringValue")]); } gSobject['registerPath'] = function(objectName, objectMap) { return (LocalDB.objectMaps[objectName]) = objectMap; } gSobject['insert'] = function(object, callback) { if (callback === undefined) callback = null; object = (gs.mc(gs.map(),'leftShift', gs.list([object]))); gs.mc(gSobject,"fixDatesToDb",[object]); if (gs.bool(callback)) { return gs.mc(LocalDB.db,"upsert",[object, function(it) { var callbackTmp = callback; callback = null; if (gs.bool(callbackTmp)) { return gs.execCall(callbackTmp, this, [object]); }; }]); }; gs.mc(LocalDB.db,"upsert",[object]); gs.mc(LocalDB.db,"save",[]); return object; } gSobject['save'] = function(object, callback) { if (callback === undefined) callback = null; gs.sp(object,"_dateCreated",gs.elvis(gs.bool(gs.gp(object,"_dateCreated")) , gs.gp(object,"_dateCreated") , gs.date())); gs.sp(object,"_lastUpdated",gs.date()); gs.sp(object,"_remoteChange",true); return gs.mc(gSobject,"insert",[object, callback]); } gSobject['insertAll'] = function(objects, callback) { if (callback === undefined) callback = function(it) { }; for (_i3 = 0, object = objects[0]; _i3 < objects.length; object = objects[++_i3]) { gs.mc(this,"fixDatesToDb",[object], gSobject); }; return gs.mc(LocalDB.db,"upsert",[objects, callback]); } gSobject['saveAll'] = function(objects, callback) { if (callback === undefined) callback = function(it) { }; for (_i4 = 0, object = objects[0]; _i4 < objects.length; object = objects[++_i4]) { gs.sp(object,"_dateCreated",gs.elvis(gs.bool(gs.gp(object,"_dateCreated")) , gs.gp(object,"_dateCreated") , gs.date())); gs.sp(object,"_lastUpdated",gs.date()); gs.sp(object,"_remoteChange",true); }; return gs.mc(gSobject,"insertAll",[objects, callback]); } gSobject['commit'] = function(errorCallback) { if (errorCallback === undefined) errorCallback = function(it) { }; return gs.mc(LocalDB.db,"save",[errorCallback]); } gSobject['updateIfExists'] = function(object) { var keyObject = gs.mc(LocalDB.db,"find",[gs.toJavascript(gs.map().add("_id",gs.gp(object,"_id")))]); if (gs.bool(keyObject)) { return gs.mc(gSobject,"insert",[object]); }; } gSobject['getO'] = function(it) { return gSobject.localO; } gSobject['objectCallWrapper'] = function(objectName) { var staticFilter = LocalDB.objectMaps[objectName]; return gs.map().add("getOne",function(id, callback) { if (callback === undefined) callback = null; return gs.mc(LocalDB.instance,"getOne",[id, callback]); }).add("findOne",function(filter, callback) { if (callback === undefined) callback = null; return gs.mc(LocalDB.instance,"findOne",[gs.mc(filter,'leftShift', gs.list([staticFilter])), callback]); }).add("findOrCreate",function(filter, mapToSave, callback) { if (mapToSave === undefined) mapToSave = gs.map(); if (callback === undefined) callback = null; return gs.mc(LocalDB.instance,"findOrCreate",[gs.mc(filter,'leftShift', gs.list([staticFilter])), mapToSave, callback]); }).add("find",function(filter, params) { if (params === undefined) params = gs.map(); return gs.mc(LocalDB.instance,"find",[gs.mc(filter,'leftShift', gs.list([staticFilter])), params]); }).add("findAll",function(params) { if (params === undefined) params = gs.map(); return gs.mc(LocalDB.instance,"find",[staticFilter, params]); }).add("new",function(initParams) { if (initParams === undefined) initParams = gs.map(); var item = gs.mc(initParams,'leftShift', gs.list([staticFilter])); gs.sp(item,"_id",gs.execStatic(Utils,'uuid', this,[])); return gs.mc(gSobject,"decorate",[item]); }); } gSobject['findOrCreate'] = function(filter, mapToSave, callback) { if (mapToSave === undefined) mapToSave = gs.map(); if (callback === undefined) callback = null; var item = gs.mc(gSobject,"findOne",[filter]); if (gs.bool(item)) { if (gs.bool(callback)) { return gs.execCall(callback, this, [item]); }; return item; }; mapToSave = (gs.mc(gs.mc(mapToSave,"clone",[]),'leftShift', gs.list([filter]))); gs.sp(mapToSave,"_id",gs.execStatic(Utils,'uuid', this,[])); if (gs.bool(callback)) { return gs.mc(LocalDB.instance,"save",[mapToSave, function(savedItem) { return gs.mc(gSobject,"getOne",[gs.gp(savedItem,"_id"), callback]); }]); }; item = gs.mc(LocalDB.instance,"save",[mapToSave]); return gs.mc(gSobject,"getOne",[gs.gp(item,"_id")]); } gSobject['getOne'] = function(id, expandableFields, level) { if (expandableFields === undefined) expandableFields = null; if (level === undefined) level = 1; return gs.mc(gSobject,"getOne",[id, null, expandableFields, level]); } gSobject['getOne'] = function(id, callback, expandableFields, level) { if (expandableFields === undefined) expandableFields = null; if (level === undefined) level = 1; if (gs.bool(expandableFields)) { return gs.mc(gSobject,"findOne",[gs.map().add("_id",id), callback, expandableFields, level]); } else { return gs.mc(gSobject,"findOne",[gs.map().add("_id",id), callback]); }; } gSobject['findOne'] = function(filter, callback, expandableFields, level) { if (callback === undefined) callback = null; if (expandableFields === undefined) expandableFields = null; if (level === undefined) level = 1; return gs.mc(gSobject,"findOne",[filter, null, expandableFields, level]); } gSobject['findOne'] = function(filter, callback, expandableFields, level) { if (callback === undefined) callback = null; if (expandableFields === undefined) expandableFields = null; if (level === undefined) level = 1; var item = null; if (gs.bool(expandableFields)) { item = gs.mc(gSobject,"find",[filter, gs.map().add("limit",1), expandableFields, level]); } else { item = gs.mc(gSobject,"find",[filter, gs.map().add("limit",1)]); }; if (!gs.bool(item)) { if (gs.bool(callback)) { gs.execCall(callback, this, [gs.map()]); }; return gs.map(); }; item = (item[0]); gs.mc(gSobject,"decorate",[item]); if (gs.bool(callback)) { gs.execCall(callback, this, [item]); }; return item; } gSobject['delete'] = function(id, callback) { if (callback === undefined) callback = function(it) { }; gs.mc(LocalDB.db,"remove",[gs.map().add("_id",id)]); return gs.mc(LocalDB.db,"save",[callback]); } gSobject['find'] = function(filter, params, expandableFields, level) { if (params === undefined) params = gs.map(); if (expandableFields === undefined) expandableFields = null; if (level === undefined) level = 1; var dbList = gs.mc(LocalDB.db,"find",[gs.toJavascript(filter), gs.toJavascript(gs.mc((gs.mc(gs.mc(gSobject,"getLimit",[params]),'leftShift', gs.list([gs.mc(gSobject,"getSkip",[params])]))),'leftShift', gs.list([gs.mc(gSobject,"getSort",[params])])))]); var objectList = gs.list([]); gs.mc(dbList,"each",[function(dbItem) { var item = gs.mc(gs.map(),'leftShift', gs.list([dbItem])); gs.mc(gSobject,"fixDatesFromDb",[item]); gs.mc(gSobject,"decorate",[item]); if (gs.bool(expandableFields)) { item = gs.mc(gSobject,"expandItem",[item, expandableFields, level]); }; return gs.mc(objectList,"add",[item]); }]); return objectList; } gSobject['remove'] = function(filter, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(LocalDB.db,"remove",[gs.toJavascript(filter)]); } gSobject['count'] = function(filter) { return gs.mc(LocalDB.db,"count",[gs.toJavascript(filter)]); } gSobject['expandItem'] = function(item, expandableFields, level) { if (level === undefined) level = 1; var fields = gs.mc(expandableFields,"collect",[function(it) { return gs.gp(it,"field"); }]); gs.mc(item,"each",[function(k, v) { if (gs.mc(fields,"contains",[k])) { if (((gs.equals(v, null)) || (gs.equals(v, gs.fs('undefined', this, gSobject)))) || (gs.equals(v, ""))) { return null; }; var currentField = gs.mc(expandableFields,"find",[function(it) { return gs.equals(gs.gp(it,"field"), k); }]); if (gs.instanceOf(v, "List")) { var expandResult = gs.mc(LocalDB.db,"find",[gs.toJavascript(gs.map().add("_id",gs.map().add("$in",v)).add("_path",gs.gp(currentField,"_path")))]); var expandResultObjects = gs.list([]); gs.mc(expandResult,"each",[function(expandResultItem) { var expandedItem = gs.mc(gs.map(),'leftShift', gs.list([expandResultItem])); gs.mc(gSobject,"fixDatesFromDb",[expandedItem]); if (level > 1) { expandedItem = gs.mc(gSobject,"expandItem",[expandedItem, expandableFields, gs.minus(level, 1)]); }; return gs.mc(expandResultObjects,"add",[expandedItem]); }]); return (item[k]) = gs.elvis(gs.bool(expandResultObjects) , expandResultObjects , gs.list([])); } else { var expandResult = gs.mc(LocalDB.db,"find",[gs.toJavascript(gs.map().add("_id",v).add("_path",gs.gp(currentField,"_path"))), gs.toJavascript(gs.mc(gSobject,"getLimit",[gs.map().add("limit",1)]))])[0]; var expandedItem = gs.mc(gs.map(),'leftShift', gs.list([expandResult])); gs.mc(gSobject,"fixDatesFromDb",[expandedItem]); if (level > 1) { expandedItem = gs.mc(gSobject,"expandItem",[expandedItem, expandableFields, gs.minus(level, 1)]); }; return (item[k]) = gs.elvis(gs.bool(expandedItem) , expandedItem , null); }; }; }]); return item; } gSobject['getLimit'] = function(params) { return gs.map().add("$limit",gs.elvis(gs.bool(params["limit"]) , params["limit"] , gs.elvis(gs.bool(gs.gp(params,"max")) , gs.gp(params,"max") , LocalDB.MAX_ROWS_PER_BATCH))); } gSobject['getSkip'] = function(params) { return gs.map().add("$skip",gs.elvis(gs.bool(gs.gp(params,"offset")) , gs.gp(params,"offset") , gs.elvis(gs.bool(params["skip"]) , params["skip"] , 0))); } gSobject['getSort'] = function(params) { var order = 1; if (gs.equals(gs.gp(params,"order"), "desc")) { order = -1; }; if (gs.bool(params["sort"])) { return gs.map().add("$orderBy",gs.map().add(params["sort"],order)); }; return gs.map(); } gSobject['fixDatesToDb'] = function(object) { gs.mc(object,"each",[function(key, value) { if ((gs.bool(value)) && (gs.instanceOf(value, "HashMap"))) { gs.mc(gSobject,"fixDatesToDb",[value]); }; if (gs.execStatic(Utils,'isDate', this,[value])) { return (object[key]) = gs.mc(LocalDB.db,"make",[value]); }; }]); return object; } gSobject['fixDatesFromDb'] = function(object) { gs.mc(object,"each",[function(key, value) { if ((gs.bool(value)) && (gs.instanceOf(value, "HashMap"))) { gs.mc(gSobject,"fixDatesFromDb",[value]); }; if (gs.execStatic(Utils,'isDate', this,[value])) { return (object[key]) = gs.date(value); }; }]); return object; } gSobject['decorate'] = function(item) { gs.sp(item,"merge",function(map) { gs.mc(item,"putAll",[map]); return item; }); gs.sp(item,"save",function(callback) { if (callback === undefined) callback = null; return gs.mc(LocalDB.instance,"save",[item, callback]); }); gs.sp(item,"delete",function(callback) { if (callback === undefined) callback = null; return gs.mc(LocalDB.instance,"delete",[gs.gp(item,"_id"), callback]); }); return item; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; LocalDB.getInstance = function(callback) { if (callback === undefined) callback = function(it) { }; if (!gs.bool(LocalDB.instance)) { LocalDB.instance = LocalDB(); if (!gs.bool(LocalDB.db)) { LocalDB.initDb(LocalDB.DB_NAME, function(it) { return gs.mc(LocalDB,"checkVersion",[function(it) { return gs.mc(LocalDB,"cleanupStaleData",[function(it) { LocalDB.startupCompleted = true; gs.execCall(callback, this, [LocalDB.instance]); gs.mc(LocalDB.callbacks,"each",[function(it) { return gs.execCall(it, this, [LocalDB.instance]); }]); return LocalDB.callbacks = gs.list([]); }]); }]); }); }; } else { if (!gs.bool(LocalDB.startupCompleted)) { gs.mc(LocalDB.callbacks,"add",[callback]); return LocalDB.instance; }; gs.execCall(callback, this, [LocalDB.instance]); }; return LocalDB.instance; } LocalDB.initDb = function(dbName, callback) { var fdb = new ForerunnerDB(); var forerunnerdb = fdb.db(dbName); // if (LocalDB.DB_COMPRESS) forerunnerdb.persist.addStep(new forerunnerdb.shared.plugins.FdbCompress()); // if (LocalDB.DB_ENCRYPT) forerunnerdb.persist.addStep(new forerunnerdb.shared.plugins.FdbCrypto({ // pass: "dbStoreCode" // })); forerunnerdb.persist.addStep(new forerunnerdb.shared.plugins.FdbCompress()); forerunnerdb.persist.addStep(new forerunnerdb.shared.plugins.FdbCrypto({ pass: "dbStoreCode" })); var collection = forerunnerdb.collection("appCollection") // collection.deferredCalls(LocalDB.ASYNC_DB) collection.deferredCalls(false) collection.load(function (err, tableStats, metaStats) { if (err) { console.error('forerunnerdb error') }else{ console.log('forerunnerdb started') } LocalDB.jsDbInstance = forerunnerdb LocalDB.db = collection callback() }); } LocalDB.dropDatabase = function(callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(LocalDB.jsDbInstance,"drop",[true, function(it) { return gs.mc(LocalDB,"initDb",[LocalDB.DB_NAME, function(it) { return gs.mc(LocalDB.db,"upsert",[gs.map().add("_id","dbVersionNumber").add("version",LocalDB.DB_VERSION_NO), callback]); }]); }]); } LocalDB.DB_VERSION_NO = "1.2"; LocalDB.DB_NAME = "1"; LocalDB.MAX_ROWS_PER_BATCH = 1000; LocalDB.ASYNC_DB = false; LocalDB.DB_COMPRESS = true; LocalDB.DB_ENCRYPT = true; LocalDB.startupCompleted = false; LocalDB.instance = null; LocalDB.jsDbInstance = null; LocalDB.db = null; LocalDB.objectMaps = gs.map(); LocalDB.callbacks = gs.list([]); LocalDB.checkVersion = function(callback) { if (callback === undefined) callback = function(it) { }; gs.println("LocalDB.checkVersion"); var version = gs.mc(LocalDB.db,"find",[gs.map().add("_id","dbVersionNumber")]); if ((gs.equals(gs.gp(version,"length"), 0)) || (gs.gp(version[0],"version") != LocalDB.DB_VERSION_NO)) { gs.println("FOUND OLD DB:DROP DB"); gs.mc(LocalDB,"dropDatabase",[callback]); return null; }; return gs.execCall(callback, this, []); }; LocalDB.cleanupStaleData = function(callback) { if (callback === undefined) callback = function(it) { }; gs.println("LocalDB.cleanupStaleData"); var nowMs = gs.gp(gs.date(),"time"); return gs.execCall(callback, this, []); }; function LocalDB$LocalO() { var gSobject = gs.init('LocalDB$LocalO'); gSobject.clazz = { name: 'LocalDB$LocalO', simpleName: 'LocalDB$LocalO'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.this$0 = null; gSobject['propertyMissing'] = function(objectName) { return gs.mc(gs.gp(LocalDB,"instance"),"objectCallWrapper",[objectName]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CacheCallTracker() { var gSobject = gs.init('CacheCallTracker'); gSobject.clazz = { name: 'CacheCallTracker', simpleName: 'CacheCallTracker'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'remoteOnceMap', { get: function() { return CacheCallTracker.remoteOnceMap; }, set: function(gSval) { CacheCallTracker.remoteOnceMap = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'resultCache', { get: function() { return CacheCallTracker.resultCache; }, set: function(gSval) { CacheCallTracker.resultCache = gSval; }, enumerable: true }); gSobject.ttl = 0; gSobject.remoteOnce = false; gSobject['callAndCache'] = function(argList, successClosure, fail) { if (successClosure === undefined) successClosure = function(it) { }; if (fail === undefined) fail = null; var argListString = gs.mc(argList,"toString",[]); if (!gs.bool(gSobject.ttl)) { return gs.execStatic(Socket,'callChain', this,[argList, function(result) { return gs.execCall(successClosure, this, [result]); }, fail]); }; var objects = CacheCallTracker.resultCache[argListString]; return gs.execStatic(LocalDB,'getInstance', this,[function(localDB) { if (!gs.bool(objects)) { objects = gs.mc(gs.execStatic(LocalDB,'getInstance', this,[]),"readCache",[argListString]); }; if (gs.bool(objects)) { gs.execStatic(ObjectRegistry,'register', this,[objects]); gs.execCall(successClosure, this, [objects]); }; return gs.execStatic(Utils,'setTimeout', this,[function(it) { if (gs.bool(objects)) { (CacheCallTracker.remoteOnceMap[argListString]) = (CacheCallTracker.remoteOnceMap[argListString] ? gs.plus((CacheCallTracker.remoteOnceMap[argListString]), 1) : 1); if ((gs.bool(gSobject.remoteOnce)) && ((CacheCallTracker.remoteOnceMap[argListString]) > 1)) { return null; }; }; return gs.execStatic(Socket,'callChain', this,[argList, function(result) { (CacheCallTracker.resultCache[argListString]) = result; gs.execCall(successClosure, this, [result]); return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gSobject,"syncCache",[argListString, result, function(it) { return gs.println("syncCache:done"); }]); }, 0]); }, fail]); }, 0]); }]); } gSobject['syncCache'] = function(argListString, objects, callback) { if (gs.bool(gSobject.ttl)) { return gs.execStatic(LocalDB,'getInstance', this,[function(it) { return gs.mc(gs.execStatic(LocalDB,'getInstance', this,[]),"cacheObjects",[argListString, objects, gSobject.ttl, callback]); }]); }; } gSobject['CacheCallTracker2'] = function(ttl, remoteOnce) { gs.sp(this,"ttl",ttl); gs.sp(this,"remoteOnce",remoteOnce); return this; } if (arguments.length==2) {gSobject.CacheCallTracker2(arguments[0], arguments[1]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CacheCallTracker.remoteOnceMap = gs.map(); CacheCallTracker.resultCache = gs.map(); function GpsLocationTracker() { var gSobject = gs.init('GpsLocationTracker'); gSobject.clazz = { name: 'GpsLocationTracker', simpleName: 'GpsLocationTracker'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'HIGH_ACCURACY', { get: function() { return GpsLocationTracker.HIGH_ACCURACY; }, set: function(gSval) { GpsLocationTracker.HIGH_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'MEDIUM_ACCURACY', { get: function() { return GpsLocationTracker.MEDIUM_ACCURACY; }, set: function(gSval) { GpsLocationTracker.MEDIUM_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'LOW_ACCURACY', { get: function() { return GpsLocationTracker.LOW_ACCURACY; }, set: function(gSval) { GpsLocationTracker.LOW_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'PASSIVE_ACCURACY', { get: function() { return GpsLocationTracker.PASSIVE_ACCURACY; }, set: function(gSval) { GpsLocationTracker.PASSIVE_ACCURACY = gSval; }, enumerable: true }); gSobject.gpsService = null; gSobject.lastLocation = null; Object.defineProperty(gSobject, 'singletonInstance', { get: function() { return GpsLocationTracker.singletonInstance; }, set: function(gSval) { GpsLocationTracker.singletonInstance = gSval; }, enumerable: true }); gSobject.desiredAccuracy = GpsLocationTracker.HIGH_ACCURACY; gSobject.instance = function() { return GpsLocationTracker.instance(); } gSobject['config'] = function(config) { gs.mc(gSobject.gpsService,"setConfig",[config]); return this; } gSobject['getCurrentLocation'] = function(successCallback, failedCallback, config) { if (failedCallback === undefined) failedCallback = function(it) { }; if (config === undefined) config = gs.map(); var callbackWrapper = function(location) { gSobject.lastLocation = location; gs.execCall(successCallback, this, [location]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userLocation",[location]),"do",[]); }; gs.mc(gSobject.gpsService,"getCurrentLocation",[callbackWrapper, failedCallback]); return this; } gSobject['onLocation'] = function(successCallback, failedCallback) { if (failedCallback === undefined) failedCallback = function(it) { }; var callbackWrapper = function(location) { gSobject.lastLocation = location; gs.execCall(successCallback, this, [location]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userLocation",[location]),"do",[]); }; gs.mc(gSobject.gpsService,"onLocation",[callbackWrapper, failedCallback]); return this; } gSobject['onStationary'] = function(stationaryCallback, failedCallback) { if (failedCallback === undefined) failedCallback = function(it) { }; gs.mc(gSobject.gpsService,"onStationary",[stationaryCallback, failedCallback]); return this; } gSobject['start'] = function(it) { gs.mc(gSobject.gpsService,"start",[]); return this; } gSobject['stop'] = function(it) { gs.mc(gSobject.gpsService,"stop",[]); return this; } gSobject['sync'] = function(it) { gs.mc(gSobject.gpsService,"sync",[]); return this; } gSobject['getName'] = function(it) { gs.mc(gSobject.gpsService,"getName",[]); return this; } gSobject.backgroundGeoLocationDefined = function() { return typeof BackgroundGeolocation !== 'undefined'; } gSobject['GpsLocationTracker0'] = function(it) { if (gs.mc(gSobject,"backgroundGeoLocationDefined",[])) { gSobject.gpsService = GpsLocationTracker$CordovaBackgroundGeolocation(this); } else { if (gs.bool(gs.gp(navigator,"geolocation"))) { gSobject.gpsService = GpsLocationTracker$Html5Gps(this); } else { throw {message: "GPS not supported"}; }; }; return this; } if (arguments.length==0) {gSobject.GpsLocationTracker0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; GpsLocationTracker.instance = function(it) { if (!gs.bool(GpsLocationTracker.singletonInstance)) { GpsLocationTracker.singletonInstance = GpsLocationTracker(); }; return GpsLocationTracker.singletonInstance; } GpsLocationTracker.HIGH_ACCURACY = 0; GpsLocationTracker.MEDIUM_ACCURACY = 10; GpsLocationTracker.LOW_ACCURACY = 1000; GpsLocationTracker.PASSIVE_ACCURACY = 10000; GpsLocationTracker.singletonInstance = null; function GpsLocationTracker$Html5Gps() { var gSobject = gs.init('GpsLocationTracker$Html5Gps'); gSobject.clazz = { name: 'GpsLocationTracker$Html5Gps', simpleName: 'GpsLocationTracker$Html5Gps'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.watchPositionId = null; gSobject.onLocationSuccessCallback = function(it) { }; gSobject.onLocationFailedCallback = function(it) { }; gSobject.config = gs.map().add("desiredAccuracy",gs.gp(GpsLocationTracker,"HIGH_ACCURACY")).add("backgroundDesiredAccuracy",gs.gp(GpsLocationTracker,"LOW_ACCURACY")).add("enableHighAccuracy",true).add("maximumAge",30000).add("timeout",30000); gSobject.this$0 = null; gSobject['getName'] = function(it) { return "Html5Gps"; } gSobject['setConfig'] = function(config) { return gs.mc(gs.gp(gs.thisOrObject(this,gSobject),"config"),'leftShift', gs.list([config])); } gSobject['getCurrentLocation'] = function(successCallback, failedCallback, config) { if (config === undefined) config = gs.map(); return gs.mc(gs.gp(gs.fs('navigator', this, gSobject),"geolocation"),"getCurrentPosition",[function(location) { return gs.execCall(successCallback, this, [gs.gp(location,"coords")]); }, failedCallback, gs.map().add("enableHighAccuracy",gs.gp(config,"desiredAccuracy") <= gs.gp(GpsLocationTracker,"MEDIUM_ACCURACY")).add("maximumAge",gs.gp(config,"maximumAge")).add("timeout",gs.gp(config,"timeout"))]); } gSobject['onLocation'] = function(successCallback, failedCallback) { gSobject.onLocationSuccessCallback = successCallback; return gSobject.onLocationFailedCallback = failedCallback; } gSobject['setDesiredAccuracy'] = function(desiredAccuracy) { return gs.sp(gSobject.config,"desiredAccuracy",desiredAccuracy); } gSobject['onStationary'] = function(stationaryCallback) { } gSobject['sync'] = function(it) { } gSobject['start'] = function(it) { return gSobject.watchPositionId = gs.mc(gs.gp(gs.fs('navigator', this, gSobject),"geolocation"),"watchPosition",[function(location) { var gpsMap = gs.mc(gs.map().add("fixId",gs.execStatic(Utils,'uuid', this,[])).add("provider",gs.mc(gSobject,"getName",[])).add("unixTimeMs",gs.gp(location,"timestamp")).add("accuracy",null).add("speed",null).add("altitude",null).add("latitude",null).add("longitude",null).add("bearing",gs.gp(gs.gp(location,"coords"),"heading")).add("service","Html5Gps").add("user",gs.gp(gs.fs('session', this, gSobject),"userId")).add("uuid",gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"uuid")),'leftShift', gs.list([gs.gp(location,"coords")])); return gs.mc(gSobject,"onLocationSuccessCallback",[gs.mc(gs.fs('gs', this, gSobject),"toJavascript",[gpsMap])]); }, gSobject.onLocationFailedCallback, gs.map().add("enableHighAccuracy",gs.gp(gSobject.config,"backgroundDesiredAccuracy") <= gs.gp(GpsLocationTracker,"MEDIUM_ACCURACY")).add("maximumAge",gs.gp(gSobject.config,"maximumAge")).add("timeout",gs.gp(gSobject.config,"timeout"))]); } gSobject['stop'] = function(it) { if (gs.bool(gSobject.watchPositionId)) { return gs.mc(gs.gp(gs.fs('navigator', this, gSobject),"geolocation"),"clearWatch",[gSobject.watchPositionId]); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function GpsLocationTracker$CordovaBackgroundGeolocation() { var gSobject = gs.init('GpsLocationTracker$CordovaBackgroundGeolocation'); gSobject.clazz = { name: 'GpsLocationTracker$CordovaBackgroundGeolocation', simpleName: 'GpsLocationTracker$CordovaBackgroundGeolocation'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.config = gs.map().add("debug",false).add("locationProvider",gs.gp(BackgroundGeolocation,"DISTANCE_FILTER_PROVIDER")).add("backgroundLocationProvider",gs.gp(BackgroundGeolocation,"DISTANCE_FILTER_PROVIDER")).add("desiredAccuracy",gs.gp(GpsLocationTracker,"HIGH_ACCURACY")).add("backgroundDesiredAccuracy",gs.gp(GpsLocationTracker,"HIGH_ACCURACY")).add("activityType","OtherNavigation").add("stationaryRadius",10).add("distanceFilter",10).add("notificationTitle","GPS tracking").add("notificationText","enabled").add("enableHighAccuracy",true).add("startForeground",true).add("stopOnTerminate",false).add("interval",5000).add("fastestInterval",5000).add("activitiesInterval",5000).add("autoSync",true).add("syncThreshold",100).add("maxLocations",gs.multiply(10, 1000)).add("url","" + (gs.gp(session,"incomingUrl")) + "/cordovaWrapper/gps").add("syncUrl","" + (gs.gp(session,"incomingUrl")) + "/cordovaWrapper/gps").add("httpHeaders",gs.map()).add("postTemplate",gs.map().add("fixId","@id").add("provider","@provider").add("unixTimeMs","@time").add("accuracy","@accuracy").add("speed","@speed").add("altitude","@altitude").add("latitude","@latitude").add("longitude","@longitude").add("bearing","@bearing").add("service","BackgroundGeolocation").add("user",gs.gp(session,"userId")).add("uuid",gs.gp(gs.gp(cordovaDevice,"device"),"uuid"))); gSobject.this$0 = null; gSobject['getName'] = function(it) { return "CordovaBackgroundGeolocation"; } gSobject['setConfig'] = function(config) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("BackgroundGeolocation:setConfig:", config)]); gs.mc(gs.gp(gs.thisOrObject(this,gSobject),"config"),'leftShift', gs.list([config])); gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"configure",[gs.gp(gs.thisOrObject(this,gSobject),"config")]); return this; } gSobject['getCurrentLocation'] = function(successCallback, failedCallback, config) { if (config === undefined) config = gs.map(); return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"getCurrentLocation",[successCallback, failedCallback, gs.mc(gs.map().add("enableHighAccuracy",true).add("maximumAge",gs.multiply((gs.multiply(4, 60)), 1000)).add("timeout",gs.multiply(60, 1000)),'leftShift', gs.list([config]))]); } gSobject['onLocation'] = function(successCallback, failedCallback) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["location", function(location) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"startTask",[function(taskKey) { gs.execCall(successCallback, this, [location]); return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"endTask",[taskKey]); }]); }]); } gSobject['onStationary'] = function(stationaryCallback) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["stationary", stationaryCallback]); } gSobject['sync'] = function(it) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"forceSync",[]); } gSobject['start'] = function(it) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"start",[]); gs.mc(gSobject,"sync",[]); return this; } gSobject['stop'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("BackgroundGeolocation:stop:", gs.gp(gs.fs('session', this, gSobject),"userId"))]); } gSobject['GpsLocationTracker$CordovaBackgroundGeolocation0'] = function(it) { gs.mc(BackgroundGeolocation,"on",["background", function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["BackgroundGeolocation:background"]); appStatus = "background"; return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"configure",[function(it) { return gs.gp(gSobject.config,"backgroundDesiredAccuracy"); }]); }]); gs.mc(BackgroundGeolocation,"on",["foreground", function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["BackgroundGeolocation:foreground"]); appStatus = "foreground"; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"configure",[function(it) { return gs.gp(gSobject.config,"desiredAccuracy"); }]); return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"forceSync",[]); }]); gs.mc(BackgroundGeolocation,"on",["authorization", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("BackgroundGeolocation:authorization:status: ", status)]); if (status !== gs.gp(gs.fs('BackgroundGeolocation', this, gSobject),"AUTHORIZED")) { return gs.execStatic(Utils,'setTimeout', this,[function(it) { var showSettings = gs.mc(this,"confirm",["App requires location tracking permission. Would you like to open app settings?"], gSobject); if (gs.bool(showSettings)) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"showAppSettings",[]); }; }, 500]); }; }]); return this; } if (arguments.length==0) {gSobject.GpsLocationTracker$CordovaBackgroundGeolocation0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaAppleSignIn() { var gSobject = gs.init('CordovaAppleSignIn'); gSobject.clazz = { name: 'CordovaAppleSignIn', simpleName: 'CordovaAppleSignIn'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.AppleSignIn = function(onSuccess, onError) { window.cordova.plugins.SignInWithApple.signin({ requestedScopes: [FullName, Email] }, function(succ){ console.log(succ) alert(JSON.stringify(succ)) }, function(err){ console.error(err) console.log(JSON.stringify(err)) onError(err) } ) } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function QRScanner() { var gSobject = gs.init('QRScanner'); gSobject.clazz = { name: 'QRScanner', simpleName: 'QRScanner'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['scan'] = function(success, failure) { var options = gs.map().add("preferFrontCamera",false).add("showFlipCameraButton",true).add("prompt","Place a barcode inside the scan area"); return gs.mc(gs.gp(gs.gp(gs.fs('cordova', this, gSobject),"plugins"),"barcodeScanner"),"scan",[success, failure, options]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaCamera() { var gSobject = gs.init('CordovaCamera'); gSobject.clazz = { name: 'CordovaCamera', simpleName: 'CordovaCamera'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['takePhotoAndUpload'] = function(objectName, property, objectId, onSuccess, onError) { if (onError === undefined) onError = function(it) { }; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["takePhotoAndUpload"]); var success = function(tempImageUrl) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["takePhotoAndUpload:success1"]); gs.println(tempImageUrl); return gs.mc(gs.fs('cordovaFile', this, gSobject),"addFile",[tempImageUrl, objectName, property, objectId, onSuccess, onError]); }; return gs.mc(gSobject,"takePhoto",[success, onError]); } gSobject['takePhotoBlob'] = function(onSuccess, onError) { if (onError === undefined) onError = function(it) { }; var success = function(imageUri) { return gs.mc(gs.fs('cordovaFile', this, gSobject),"blobFromFileUrl",[imageUri, function(blob) { gs.execCall(onSuccess, this, [blob]); return gs.mc(gSobject,"clearCache",[]); }, onError]); }; return gs.mc(gSobject,"takePhoto",[success, onError]); } gSobject['takePhoto'] = function(onSuccess, onFail, config) { if (config === undefined) config = gs.map(); CordovaCamera.hasCameraPermission("android.permission.CAMERA", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.CAMERA:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); CordovaCamera.hasCameraPermission("android.permission.ACTION_CREATE_DOCUMENT", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.ACTION_CREATE_DOCUMENT:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); CordovaCamera.hasCameraPermission("android.permission.ACTION_OPEN_DOCUMENT", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.ACTION_OPEN_DOCUMENT:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); CordovaCamera.hasCameraPermission("android.permission.READ_EXTERNAL_STORAGE", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.READ_EXTERNAL_STORAGE:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); CordovaCamera.hasCameraPermission("android.permission.READ_MEDIA_IMAGES", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.READ_MEDIA_IMAGES:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); CordovaCamera.hasCameraPermission("android.permission.READ_MEDIA_VIDEO", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("android.permission.READ_MEDIA_IMAGES:", gs.gp(status,"hasPermission"))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }); gs.mc(gs.fs('camera', this, gSobject),"getPicture",[onSuccess, onFail, gs.mc(gs.map().add("destinationType",gs.gp(gs.gp(gs.fs('camera', this, gSobject),"DestinationType"),"FILE_URI")).add("sourceType",gs.gp(gs.gp(gs.fs('camera', this, gSobject),"PictureSourceType"),"CAMERA")).add("encodingType",gs.gp(gs.gp(gs.fs('cameraConst', this, gSobject),"EncodingType"),"JPEG")).add("correctOrientation",true).add("saveToPhotoAlbum",false).add("targetHeight",1024).add("targetWidth",1024),'leftShift', gs.list([config]))]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["takePhoto2"]); } gSobject.hasCameraPermission = function(x0,x1) { return CordovaCamera.hasCameraPermission(x0,x1); } gSobject.verifyCameraPlugin = function() { return CordovaCamera.verifyCameraPlugin(); } gSobject['clearCache'] = function(it) { return gs.mc(gs.fs('camera', this, gSobject),"cleanup",[]); } gSobject.getCamera = function() { return CordovaCamera.getCamera(); } gSobject.getCameraConst = function() { return CordovaCamera.getCameraConst(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaCamera.hasCameraPermission = function(permission, callback) { if (!Utils.isCordova()) return false; var permissions = cordova.plugins.permissions; if (!permissions) return false console.log('permission', permission) permissions.checkPermission(permission, function( status ){ if ( status.hasPermission ) { return callback(status); } else { permissions.requestPermission(permissions.CAMERA, function( result ){ return callback(result) }); } }); } CordovaCamera.verifyCameraPlugin = function() { return ( typeof navigator !== 'undefined' && typeof navigator.camera !== 'undefined' ) } CordovaCamera.getCamera = function() { return navigator.camera } CordovaCamera.getCameraConst = function() { return Camera } function VueApp() { var gSobject = gs.init('VueApp'); gSobject.clazz = { name: 'VueApp', simpleName: 'VueApp'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.componentList = gs.list([]); gSobject.authComponentPath = null; gSobject.vue = null; gSobject.router = null; gSobject.scope = gs.map().add("topHeading","").add("backStack",gs.list([])); gSobject.data = function(it) { return gSobject.scope = gs.mc(gs.fs('Vue', this, gSobject),"reactive",[gSobject.scope]); }; gSobject.methods = gs.map(); gSobject.watch = gs.map(); gSobject.compute = gs.map(); gSobject.events = gs.map(); gSobject.filters = gs.map(); gSobject.mixins = gs.list([]); gSobject.toggleDarkMode = function(it) { gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Dark"),"toggle",[]); return gs.sp(gs.fs('session', this, gSobject),"darkMode",gs.gp(gs.gp(gs.fs('Quasar', this, gSobject),"Dark"),"isActive")); }; gSobject.initialised = false; gSobject['init'] = function(mountElement) { if (mountElement === undefined) mountElement = "#vue-app"; gs.println("VueApp.init"); if (gs.bool(gSobject.initialised)) { return null; }; gSobject.initialised = true; gs.mc(gSobject.componentList,"each",[function(component) { return gs.mc(gSobject,"registerVueComponent",[gs.gp(component,"vueComponentName"), component]); }]); var routes = gs.list([]); var childComponents = gs.set(); gs.mc(gSobject.componentList,"each",[function(component) { return gs.mc(gs.gp(component,"children"),"each",[function(child) { return gs.mc(childComponents,"add",[gs.gp(child,"vueComponentName")]); }], null, true); }]); var buildRoute = null; buildRoute = function(component) { var route = gs.map().add("path",gs.gp(component,"path")).add("component",gs.mc(gSobject.componentList,"find",[function(it) { return gs.equals(gs.gp(it,"vueComponentName"), gs.gp(component,"vueComponentName")); }])); if (gs.bool(gs.gp(component,"children"))) { gs.sp(route,"children",gs.mc(gs.gp(component,"children"),"collect",[function(child) { return gs.execCall(buildRoute, this, [child]); }])); }; return route; }; gs.mc(gSobject.componentList,"each",[function(component) { if (!gs.bool(gs.mc(childComponents,"contains",[gs.gp(component,"vueComponentName")]))) { if (gs.instanceOf(gs.gp(component,"path"), "ArrayList")) { return gs.mc(gs.gp(component,"path"),"each",[function(it) { if (gs.bool(it)) { var cloned = gs.execStatic(Utils,'deepCopyMap', this,[component]); gs.sp(cloned,"path",it); return gs.mc(routes,"add",[gs.execCall(buildRoute, this, [cloned])]); }; }]); } else { if (gs.bool(gs.gp(component,"path"))) { return gs.mc(routes,"add",[gs.execCall(buildRoute, this, [component])]); }; }; }; }]); gs.println("routes"); gs.println(routes); gs.mc(gSobject.filters,"each",[function(key, filterFunction) { return gs.mc(gSobject,"addVueFilter",[key, filterFunction]); }]); gSobject.router = gs.mc(gSobject,"newVueRouter",[routes]); gs.mc(gSobject.vue,"use",[gs.fs('Quasar', this, gSobject)]); gs.mc(gSobject.vue,"use",[gSobject.router]); gs.mc(gSobject,"setQuasarTheme",[]); gs.mc(gSobject.vue,"mount",[mountElement]); return this; } gSobject['registerComponent'] = function(component) { return gs.mc(gSobject.componentList,"add",[component]); } gSobject['registerAuthComponent'] = function(component) { var path = gs.gp(component,"path"); if (gs.instanceOf(gs.gp(component,"path"), "ArrayList")) { path = (path[0]); }; return gSobject.authComponentPath = path; } gSobject['setQuasarTheme'] = function(it) { gs.sp(gs.fs('session', this, gSobject),"darkMode",gs.elvis(gs.bool(gs.gp(gs.fs('session', this, gSobject),"darkMode")) , gs.gp(gs.fs('session', this, gSobject),"darkMode") , gs.gp(gs.gp(gs.fs('Quasar', this, gSobject),"Dark"),"isActive"))); return gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Dark"),"set",[gs.gp(gs.fs('session', this, gSobject),"darkMode")]); } gSobject['registerVueComponent'] = function(name, component) { return gs.mc(gSobject,"registerVueComponentNative",[gSobject.vue, name, component]); } gSobject.addVueFilter = function(name, filter) { Vue.filter(name, filter) } gSobject.registerVueComponentNative = function(vue, name, component) { return vue.component(name, component) } gSobject.newVue = function(router, data, methods, watch, compute, events, mixins) { return Vue.createApp({ router : router, data : data, methods : methods, watch : watch, computed : compute, events : events, mixins : mixins }); } gSobject.newVueRouter = function(routes) { return VueRouter.createRouter({routes:routes, history: VueRouter.createWebHashHistory()}) } gSobject['VueApp0'] = function(it) { gSobject.vue = gs.mc(gSobject,"newVue",[gSobject.router, gs.toJsObj(gSobject.data), gs.toJsObj(gSobject.methods), gs.toJsObj(gSobject.watch), gs.toJsObj(gSobject.compute), gs.toJsObj(gSobject.events), gSobject.mixins]); return this; } if (arguments.length==0) {gSobject.VueApp0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function VueComponent() { var gSobject = gs.init('VueComponent'); gSobject.clazz = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.vueComponentName = null; gSobject.path = ""; gSobject.template = ""; gSobject.props = gs.list([]); gSobject.vueMeta = gs.map(); gSobject.route = null; gSobject.q = null; gSobject.refs = null; gSobject.options = gs.map(); gSobject.emit = null; gSobject.scope = gs.map(); gSobject.methods = null; gSobject.watch = null; gSobject.compute = null; gSobject.events = null; gSobject.roles = gs.list([]); gSobject.self = null; gSobject.beforeCreate = function(it) { gSobject.self = this; gSobject.route = gs.gp(gSobject.self,"$route"); gSobject.q = gs.gp(gSobject.self,"$q"); gSobject.options = gs.gp(gSobject.self,"$options"); gSobject.nextTick = gs.gp(gSobject.self,"$nextTick"); gSobject.emit = gs.gp(gSobject.self,"$emit"); return gs.mc(gs.gp(gs.fs('document', this, gSobject),"body"),"scrollTo",[0, 0]); }; gSobject.nextTick = function(callback) { return gs.execCall(callback, this, []); }; Object.defineProperty(gSobject, 'notifyParams', { get: function() { return VueComponent.notifyParams; }, set: function(gSval) { VueComponent.notifyParams = gSval; }, enumerable: true }); gSobject.notify = function(message, type, map) { if (type === undefined) type = "positive"; if (map === undefined) map = gs.map(); gs.sp(map,"message",message); gs.sp(map,"type",type); return gs.mc(gSobject.q,"notify",[gs.mc(gs.mc(VueComponent.notifyParams,"clone",[]),'leftShift', gs.list([map]))]); }; Object.defineProperty(gSobject, 'dialogParams', { get: function() { return VueComponent.dialogParams; }, set: function(gSval) { VueComponent.dialogParams = gSval; }, enumerable: true }); gSobject.dialog = function(title, message, map) { if (map === undefined) map = gs.map(); gs.sp(map,"title",title); gs.sp(map,"message",message); return gs.mc(gSobject.q,"dialog",[gs.mc(gs.mc(VueComponent.dialogParams,"clone",[]),'leftShift', gs.list([map]))]); }; gSobject.data = function(it) { gSobject.scope = gs.map(); return gSobject.scope = gs.mc(gs.fs('Vue', this, gSobject),"reactive",[gSobject.scope]); }; gSobject.meta = function(it) { return gSobject.vueMeta; }; Object.defineProperty(gSobject, 'METHOD_EXCLUDE_LIST', { get: function() { return VueComponent.METHOD_EXCLUDE_LIST; }, set: function(gSval) { VueComponent.METHOD_EXCLUDE_LIST = gSval; }, enumerable: true }); gSobject['register'] = function(templateName, componentName) { if (templateName === undefined) templateName = ""; if (componentName === undefined) componentName = ""; gSobject.vueComponentName = gs.elvis(gs.bool(componentName) , componentName , gs.mc(gs.mc(this,"getClass",[], gSobject),"getSimpleName",[])); if (!gs.bool(gSobject.template)) { gSobject.template = (gs.bool(templateName) ? gs.plus("#", templateName) : gs.plus((gs.plus("#", gs.mc(gs.mc(this,"getClass",[], gSobject),"getSimpleName",[]))), "View")); }; gs.println("VueComponent.register:" + (gSobject.vueComponentName) + ":" + (gSobject.template) + ":" + (gSobject.path) + ""); var methodsMap = gs.map(); gs.mc(gs.mc(gs.gp(this,"methods"),"findAll",[function(method) { var name = gs.gp(method,"name"); return (((!gs.bool(gs.mc(name,"startsWith",["set"]))) && (!gs.bool(gs.mc(name,"startsWith",["get"])))) && (!gs.bool(gs.mc(name,"contains",["$"])))) && (!gs.bool(gs.gSin(name, VueComponent.METHOD_EXCLUDE_LIST))); }]),"each",[function(it) { return (methodsMap[gs.gp(it,"name")]) = gs.gp(gs.thisOrObject(this,gSobject),"" + (gs.gp(it,"name")) + ""); }]); gSobject.methods = gs.toJsObj(methodsMap); var watchMap = gs.map(); gs.mc(gs.mc(gs.gp(this,"methods"),"findAll",[function(method) { return gs.mc(gs.gp(method,"name"),"startsWith",["watch"]); }]),"each",[function(method) { var watchVar = gs.mc(gs.gp(method,"name"),"substring",[5]); watchVar = (gs.plus(gs.mc(watchVar[0],"toLowerCase",[]), gs.mc(watchVar,"substring",[1]))); return (watchMap[watchVar]) = gs.gp(gs.thisOrObject(this,gSobject),"" + (gs.gp(method,"name")) + ""); }]); gSobject.watch = gs.toJsObj(watchMap); var computeMap = gs.map(); gs.mc(gs.mc(gs.gp(this,"methods"),"findAll",[function(method) { return gs.mc(gs.gp(method,"name"),"startsWith",["computed"]); }]),"each",[function(it) { return (computeMap[gs.gp(it,"name")]) = gs.gp(gs.thisOrObject(this,gSobject),"" + (gs.gp(it,"name")) + ""); }]); gSobject.compute = gs.toJsObj(computeMap); var eventsMap = gs.map(); gs.mc(gs.mc(gs.gp(this,"methods"),"findAll",[function(method) { return gs.mc(gs.gp(method,"name"),"startsWith",["event"]); }]),"each",[function(it) { return (eventsMap[gs.gp(it,"name")]) = gs.gp(gs.thisOrObject(this,gSobject),"" + (gs.gp(it,"name")) + ""); }]); gSobject.events = gs.toJsObj(eventsMap); gs.mc(gs.fs('vue', this, gSobject),"registerComponent",[this]); return this; } gSobject['registerAsAuthComponent'] = function(it) { gs.mc(gs.fs('vue', this, gSobject),"registerAuthComponent",[this]); return this; } gSobject['getRefs'] = function(it) { gs.sp(this,"refs",gs.gp(gSobject.self,"$refs")); return gs.gp(gSobject.self,"$refs"); } gSobject['beforeMount'] = function(it) { return gs.mc(gSobject,"enforceComponentRoles",[]); } gSobject['created'] = function(it) { } gSobject['mounted'] = function(it) { return gs.mc(gSobject,"nextTick",[function(it) { gs.mc(gSobject,"getRefs",[]); return gs.mc(gSobject,"afterMounted",[]); }]); } gSobject['afterMounted'] = function(it) { } gSobject['unmounted'] = function(it) { return gs.mc(gSobject,"destroyed",[]); } gSobject['destroyed'] = function(it) { return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"topHeading",""); } gSobject['toggleDarkMode'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"scope"),"toggleDarkMode",[]); } gSobject['showLoading'] = function(text, spinnerColor) { if (text === undefined) text = "Loading..."; if (spinnerColor === undefined) spinnerColor = "primary"; return gs.mc(gs.gp(gSobject.q,"loading"),"show",[gs.map().add("group",text).add("message",text).add("delay",250).add("spinnerColor",spinnerColor).add("backgroundColor","transparent")]); } gSobject['hideLoading'] = function(text) { if (text === undefined) text = ""; if (!gs.bool(text)) { return gs.mc(gs.gp(gSobject.q,"loading"),"hide",[]); }; return gs.mc(gs.gp(gSobject.q,"loading"),"hide",[gs.map().add("group",text)]); } gSobject.moment = function(date) { return moment(date) } gSobject['placeholder'] = function(value, placeholder) { return gs.elvis(gs.bool(value) , value , placeholder); } gSobject['onPaste'] = function(evt, reference) { var text = ""; var elem = (gs.mc(gSobject,"getRefs",[])[reference])[0]; if (!gs.bool(elem)) { elem = (gs.mc(gSobject,"getRefs",[])[reference]); }; if ((gs.bool(gs.gp(elem,"originalEvent"))) && (gs.bool(gs.gp(gs.gp(gs.gp(evt,"originalEvent"),"clipboardData"),"getData")))) { text = gs.mc(gs.gp(gs.gp(evt,"originalEvent"),"clipboardData"),"getData",["text/plain"]); }; if ((gs.bool(gs.gp(evt,"clipboardData"))) && (gs.bool(gs.gp(gs.gp(evt,"clipboardData"),"getData")))) { text = gs.mc(gs.gp(evt,"clipboardData"),"getData",["text/plain"]); }; return gs.mc(elem,"runCmd",["insertText", text]); } gSobject['filterOptions'] = function(val, update, options, filteredOptions, object, excludeSelected) { if (object === undefined) object = gs.map(); if (excludeSelected === undefined) excludeSelected = false; return gs.execCall(update, this, [function(it) { return (gSobject.scope[filteredOptions]) = gs.mc(gs.mc(gSobject.scope[options],"findAll",[function(option) { if ((gs.bool(excludeSelected)) && (gs.equals(gs.gp(option,"_id"), gs.gp(object,"_id")))) { return false; }; if (!gs.bool(val)) { return true; }; return gs.mc(gs.mc(gs.gp(option,"name"),"toLowerCase",[], null, true),"contains",[gs.mc(val,"toLowerCase",[], null, true)], null, true); }]),"sort",[]); }]); } gSobject['enforceComponentRoles'] = function(it) { if (gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"embedded"))) { gs.println("enforceComponentRoles skipped for embedded mode"); return true; }; if ((!gs.bool(gSobject.roles)) || (gs.mc(gs.fs('session', this, gSobject),"hasRole",[gSobject.roles]))) { return true; }; if (gs.bool(gs.gp(gs.fs('vue', this, gSobject),"authComponentPath"))) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"replace",[gs.gp(gs.fs('vue', this, gSobject),"authComponentPath")]); }; throw {message: "" + (gSobject.vueComponentName) + " roles required: " + (gSobject.roles) + ""}; } gSobject['formatCurrency'] = function(value) { try { gs.mc(value,"split",["."]); gs.mc(this,"parseFloat",[value], gSobject); } catch (all) { value = "0.00"; } ; if (!gs.bool(gs.mc(value,"contains",["."]))) { value = (gs.plus("0.0", value)); }; var newValue = null; var decPartSize = gs.mc(gs.mc(value,"split",["."])[1],"size",[]); if (decPartSize > 2) { newValue = gs.mc(gs.multiply(gs.mc(this,"parseFloat",[value], gSobject), 10),"toFixed",[2]); } else { if (gs.equals(decPartSize, 1)) { newValue = gs.mc(gs.div(gs.mc(this,"parseFloat",[value], gSobject), 10),"toFixed",[2]); } else { newValue = gs.mc(gs.mc(this,"parseFloat",[value], gSobject),"toFixed",[2]); }; }; return newValue; } gSobject['formatNumberInput'] = function(scopeName, size, decimals, parent) { if (size === undefined) size = 0; if (decimals === undefined) decimals = 0; if (parent === undefined) parent = gSobject.scope; var oldVal = gs.mc(gs.gp(parent,"" + (scopeName) + ""),"toString",[]); var newVal = ""; if ((gs.equals((oldVal[0]), ".")) || (gs.equals((oldVal[0]), ","))) { newVal = "0"; }; var index = 0; var dotCount = 0; var afterDotCount = 0; gs.mc(oldVal,"each",[function(character) { index++; if (gs.equals(decimals, 0)) { if ((gs.mc(character,"isNumber",[])) && ((gs.equals(size, 0)) || (index <= size))) { newVal += character; }; return null; }; if (gs.equals(character, ",")) { character = "."; }; if (gs.equals(character, ".")) { dotCount++; }; if (dotCount > 1) { return null; }; if (gs.equals(dotCount, 1)) { afterDotCount++; if (afterDotCount > (gs.plus(decimals, 1))) { return null; }; }; if (((gs.mc(character,"isNumber",[])) || (gs.equals(character, "."))) && ((gs.equals(size, 0)) || (index <= size))) { return newVal += character; }; }]); return gs.mc(gSobject,"nextTick",[function(it) { return gs.sp(parent,"" + (scopeName) + "",newVal); }]); } gSobject['formatNumberInputOnBlur'] = function(scopeName, size, decimals, parent) { if (size === undefined) size = 0; if (decimals === undefined) decimals = 0; if (parent === undefined) parent = gSobject.scope; gs.mc(gSobject,"formatNumberInput",[scopeName, size, decimals, parent]); return gs.mc(gSobject,"nextTick",[function(it) { return gs.sp(parent,"" + (scopeName) + "",gs.mc(this,"Number",[gs.mc(gs.gp(parent,"" + (scopeName) + ""),"toString",[])], gSobject)); }]); } gSobject['formatCurrencyInput'] = function(scopeName, parent) { if (parent === undefined) parent = gSobject.scope; return gs.mc(gSobject,"formatNumberInput",[scopeName, 15, 2, parent]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; VueComponent.notifyParams = gs.map().add("type","positive").add("position","bottom").add("avatar","").add("timeout",3000).add("actions",null).add("spinner",false).add("multiLine",false).add("progress",false); VueComponent.dialogParams = gs.map().add("ok",gs.map().add("push",true).add("color","primary")).add("cancel",gs.map().add("push",true).add("color","negative")).add("persistent",true); VueComponent.METHOD_EXCLUDE_LIST = gs.list(["equals" , "hashCode" , "notify" , "notifyAll" , "toString" , "wait" , "register" , "invokeMethod" , "data" , "beforeCreate" , "created" , "mounted" , "destroyed"]); function LegionLoginComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'LegionLoginComponent', simpleName: 'LegionLoginComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/login"; gSobject.appleAuth = gs.map(); gSobject['created'] = function(it) { gs.println("LegionLoginComponent.created()"); gs.sp(gSobject.scope,"showFooter",false); gs.sp(gSobject.scope,"showApple",gs.execStatic(Utils,'isIos', this,[])); gs.sp(gSobject.scope,"showAndroid",gs.execStatic(Utils,'isAndroid', this,[])); gs.sp(gSobject.scope,"email",""); return gs.sp(gSobject.scope,"phoneNumber",""); } gSobject['login'] = function(it) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username",gs.elvis(gs.bool(gs.gp(gSobject.scope,"email")) , gs.gp(gSobject.scope,"email") , gs.gp(gSobject.scope,"phoneNumber"))); if (!gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username"))) { gs.mc(gSobject,"notify",["Please enter details", "negative"]); return null; }; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"generatePinForExistingUser",[gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username"), (gs.bool(gs.gp(gSobject.scope,"phoneNumber")) ? true : false)]),"then",[function(it) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/legionPin"]); return gs.mc(gSobject,"notify",["Pin Sent"]); }, function(error) { return gs.mc(gSobject,"notify",[gs.gp(error,"message"), "negative"]); }]); } gSobject['googleSignIn'] = function(it) { if (!gs.bool(gs.execStatic(Utils,'isCordova', this,[]))) { return gs.mc(gSobject,"notify",["Could not complete sign in", "negative"]); }; return gs.mc(gs.fs('cordovaGoogleSignIn', this, gSobject),"googleSignIn",[function(success) { gs.println("cordovaGoogleSignIn"); gs.println(success); var object = gs.mc(gSobject,"toObject",[success]); gs.println(object); return gs.mc(gSobject,"signInWith",[gs.gp(gs.gp(object,"message"),"email"), gs.gp(gs.gp(object,"message"),"id"), function(it) { return gs.mc(gs.fs('legionUserService', this, gSobject),"loadLegionUser",[function(user) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }]); }, function(error) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/login"]); return gs.mc(gSobject,"errorNotification",[error]); }]); }, function(error) { gs.println(error); return gs.mc(gSobject,"notify",["Error Signing in with Google", "negative"]); }]); } gSobject['signInWithApple'] = function(it) { if (!gs.bool(gs.execStatic(Utils,'isCordova', this,[]))) { return gs.mc(gSobject,"notify",["Could not complete sign in", "negative"]); }; return LegionLoginComponent.signInWithAppleAuth(function(result) { gs.println("signInWithAppleAuth result:"); gs.println(result); var jwt = gs.execStatic(Utils,'decodeJWT', this,[gs.gp(result,"identityToken")]); var email = gs.gp(jwt,"email"); var password = gs.gp(jwt,"sub"); gSobject.appleAuth = result; return gs.mc(gSobject,"signInWith",[email, password, function(it) { return gs.mc(gs.fs('legionUserService', this, gSobject),"loadLegionUser",[function(user) { gs.mc(gSobject,"saveAppleCustomer",[gs.gp(user,"_id")]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }]); }, function(error) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/login"]); return gs.mc(gSobject,"errorNotification",[error]); }]); }); } gSobject.signInWithAppleAuth = function(x0) { return LegionLoginComponent.signInWithAppleAuth(x0); } gSobject['saveAppleCustomer'] = function(userId) { var user = gs.map(); if (gs.bool(gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"familyName"))) { gs.sp(user,"surname",gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"familyName")); }; if (gs.bool(gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"givenName"))) { gs.sp(user,"name",gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"givenName")); }; return gs.mc(gs.fs('legionUserService', this, gSobject),"updateUserDetails",[userId, gs.gp(user,"name"), gs.gp(user,"surname")]); } gSobject['signInWith'] = function(email, password, successCallback, failCallback) { return gs.mc(gs.fs('legionUserService', this, gSobject),"auth",[email, password, function(authenticated) { if (gs.bool(authenticated)) { return gs.execCall(successCallback, this, [authenticated]); }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"repairUser",[email, password, function(result) { if (!gs.bool(gs.gp(result,"success"))) { gs.execCall(failCallback, this, ["Registration Failed"]); }; return gs.mc(gs.fs('legionUserService', this, gSobject),"auth",[email, password, function(isAuthenticated) { if (gs.bool(isAuthenticated)) { return gs.execCall(successCallback, this, [isAuthenticated]); }; return gs.execCall(failCallback, this, ["Login Failed"]); }]); }]); }]); } gSobject['errorNotification'] = function(notification) { return gs.mc(this,"alert",[notification], gSobject); } gSobject['differentLogin'] = function(it) { return gs.mc(gSobject,"notify",["WIP"]); } gSobject.toObject = function(data) { return JSON.parse(data) } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; LegionLoginComponent.signInWithAppleAuth = function(callback) { var value window.cordova.plugins.SignInWithApple.signin( { requestedScopes: [0,1] }, function(succ){ value = succ console.log("signInWithAppleAuth----------------------------------") console.log(JSON.stringify(value)) callback(value) }, function(err){ if(err.code == "1001" || err.code == "1003"){ alert('Authentication failed: User cancelled sign in.'); }else if(err.code == "1002"){ alert('Error: Sign in response received an invalid response'); }else{ alert('Error: Authentication failed'); } } ) } function LegionUserService() { var gSobject = gs.init('LegionUserService'); gSobject.clazz = { name: 'LegionUserService', simpleName: 'LegionUserService'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.legionUser = null; gSobject.country = null; gSobject['lookupCountry'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionLocaleService"),"fetchCountry",[function(countryIn) { return gSobject.country = countryIn; }]); } gSobject['auth'] = function(username, password, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"authenticate",[username, password, function(authData) { gs.println("LegionUserService.auth1"); gs.println(authData); if (!gs.bool(authData)) { return gs.execCall(callback, this, [false]); }; if (gs.bool(gs.gp(authData,"authenticated"))) { gs.execStatic(Utils,'updateAuthTokenToSession', this,[authData]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("User authdata:", authData)]); gs.mc(gSobject,"updateSession",[authData]); gs.mc(gSobject,"loadLegionUser",[function(it) { return gs.execCall(callback, this, [gs.gp(authData,"authenticated")]); }]); return null; }; return gs.execCall(callback, this, [gs.gp(authData,"authenticated")]); }]); } gSobject['updateSession'] = function(authData) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("User authdata:", authData)]); gs.sp(gs.fs('session', this, gSobject),"legionUser",gs.gp(authData,"legionUser")); gs.sp(gs.fs('session', this, gSobject),"user",gs.gp(authData,"legionUser")); gs.sp(gs.fs('session', this, gSobject),"legionUserId",gs.gp(gs.gp(authData,"legionUser"),"_id",true)); gs.sp(gs.fs('session', this, gSobject),"userId",gs.gp(gs.gp(authData,"legionUser"),"_id",true)); if (gs.bool(gs.gp(authData,"zoner"))) { gs.sp(gs.fs('session', this, gSobject),"zoner",gs.gp(authData,"zoner")); gs.sp(gs.fs('session', this, gSobject),"zonerId",gs.gp(gs.gp(authData,"zoner"),"id")); return gs.sp(gs.fs('session', this, gSobject),"authToken",gs.gp(gs.gp(authData,"zoner"),"token")); }; } gSobject['authWithPin'] = function(username, pin, callback, failCallback) { if (callback === undefined) callback = function(it) { }; if (failCallback === undefined) failCallback = function(it) { }; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"authenticateWithPin",[username, pin]),"then",[function(authData) { if (!gs.bool(authData)) { return gs.execCall(callback, this, [false]); }; if (gs.bool(gs.gp(authData,"authenticated"))) { gs.execStatic(Utils,'updateAuthTokenToSession', this,[authData]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[gs.plus("User authdata:", authData)]); gs.mc(gSobject,"updateSession",[authData]); gs.mc(gSobject,"loadLegionUser",[function(it) { return gs.execCall(callback, this, [gs.gp(authData,"authenticated")]); }]); return null; }; return gs.mc(this,"success",[gs.gp(authData,"authenticated")], gSobject); }, function(error) { return gs.execCall(failCallback, this, [error]); }]); } gSobject['loadLegionUserFromServer'] = function(callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gs.gp(gs.fs('transmission', this, gSobject),"onAuthReady"),"callback",[function(it) { if (gs.bool(gs.gp(gs.fs('session', this, gSobject),"legionUserId"))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"loadLegionUser",[gs.gp(gs.fs('session', this, gSobject),"legionUserId"), function(legionUser) { gs.mc(gSobject,"updateSession",[gs.map().add("legionUser",legionUser)]); return gs.execCall(callback, this, [gs.gp(gs.fs('session', this, gSobject),"legionUser")]); }]); return null; }; if (gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"zoner"),"id",true))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"loadLegionUserFromZonerId",[gs.gp(gs.gp(gs.fs('session', this, gSobject),"zoner"),"id"), function(legionUser) { gs.println("legionUser2"); gs.println(legionUser); gs.mc(gSobject,"updateSession",[gs.map().add("legionUser",legionUser)]); return gs.execCall(callback, this, [gs.gp(gs.fs('session', this, gSobject),"legionUser")]); }]); }; return gs.execCall(callback, this, []); }]); } gSobject['loadLegionUser'] = function(callback, failCallback, resetCache) { if (callback === undefined) callback = function(it) { }; if (failCallback === undefined) failCallback = function(it) { }; if (resetCache === undefined) resetCache = false; if ((gs.bool(gSobject.legionUser)) && (!gs.bool(resetCache))) { return gs.execCall(callback, this, [gSobject.legionUser]); }; if (gs.bool(gs.gp(gs.fs('session', this, gSobject),"authToken"))) { gs.mc(gs.gp(gs.fs('transmission', this, gSobject),"onAuthReady"),"callback",[function(it) { if (!gs.bool(gs.gp(gs.fs('session', this, gSobject),"legionUser"))) { throw {message: "Auth is authenticated, but legionUser not found"}; }; gSobject.legionUser = gs.gp(gs.fs('session', this, gSobject),"legionUser"); gs.execStatic(Utils,'subscribe', this,[gs.gp(gSobject.legionUser,"_id"), function(updatedlegionUser) { return gSobject.legionUser = updatedlegionUser; }]); return gs.execCall(callback, this, [gSobject.legionUser]); }]); return null; }; return gs.execCall(failCallback, this, []); } gSobject['registerPushDevice'] = function(data) { return gs.mc(gSobject,"loadLegionUser",[function(user) { gs.println(">>>>>>>>>>> Register Push Device"); gs.println(gs.plus((gs.plus((gs.plus((gs.plus((gs.plus("Data: ", gs.gp(user,"_id"))), " ")), gs.gp(data,"registrationId"))), " ")), gs.execStatic(Utils,'deviceType', this,[]))); gs.println(data); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionPushService"),"registerDevice",[gs.gp(user,"_id"), gs.gp(data,"registrationId"), gs.execStatic(Utils,'deviceType', this,[]), function(it) { return gs.println(">>>>>>>>>>> Register Push Device - SUCCESS"); }]); }]); } gSobject['getSetting'] = function(key, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gSobject,"loadLegionUser",[function(user) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionService"),"getUserSetting",[gs.gp(user,"_id"), key, function(result) { return gs.execCall(callback, this, [result]); }]); }]); } gSobject['setSetting'] = function(key, value, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gSobject,"loadLegionUser",[function(user) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionService"),"getUserSetting",[gs.gp(user,"_id"), key, value, function(result) { return gs.execCall(callback, this, [result]); }]); }]); } gSobject['updateUserDetails'] = function(userId, name, surname) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"loadLegionUser",[userId, function(user) { gs.sp(user,"name",name); gs.sp(user,"surname",surname); return gs.mc(user,"save",[]); }]); } gSobject['LegionUserService0'] = function(it) { gs.mc(gSobject,"loadLegionUserFromServer",[]); gs.mc(gSobject,"lookupCountry",[]); return this; } if (arguments.length==0) {gSobject.LegionUserService0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaDevice() { var gSobject = gs.init('CordovaDevice'); gSobject.clazz = { name: 'CordovaDevice', simpleName: 'CordovaDevice'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.network = gs.map().add("type","NONE").add("status","online"); gSobject.battery = gs.map().add("level",50).add("isPlugged",false).add("state","normal").add("date",gs.date()); gSobject.device = gs.map().add("network",gSobject.network).add("battery",gSobject.battery).add("orientation","portrait").add("keyboard","hide"); gSobject.onKeyboardListeners = gs.list([]); gSobject.appEventListeners = gs.list([]); gSobject.onBackKeyDown = function(it) { }; gSobject.userId = null; gSobject['splashScreenHide'] = function(it) { if (gs.execStatic(Utils,'isCordova', this,[])) { try { gs.mc(gs.gp(gs.fs('navigator', this, gSobject),"splashscreen"),"hide",[], null, true); if (CordovaDevice.cordovaPluginStatusBarInstalled()) { gs.mc(gs.fs('StatusBar', this, gSobject),"overlaysWebView",[false]); gs.mc(gs.fs('StatusBar', this, gSobject),"backgroundColorByName",["black"]); }; try { var p = gs.mc(gs.gp(gs.fs('screen', this, gSobject),"orientation"),"lock",["portrait"]); if ((gs.bool(p)) && (gs.bool(gs.gp(p,"catch")))) { gs.mc(p,"catch",[gs.mc(this,"function",[function(it) { }], gSobject)]); }; } catch (e) { } ; } catch (all) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["splashScreenHide:" + (gs.fs('all', this, gSobject)) + ""]); } ; }; } gSobject['disableBackButton'] = function(it) { return gs.mc(gs.fs('document', this, gSobject),"addEventListener",["backbutton", gSobject.onBackKeyDown, false]); } gSobject['setupCordovaAppEvents'] = function(it) { gs.mc(gs.fs('document', this, gSobject),"addEventListener",["pause", function(it) { return gs.mc(gSobject,"emitEvent",["app.pause"]); }, false]); gs.mc(gs.fs('document', this, gSobject),"addEventListener",["resume", function(it) { return gs.mc(gSobject,"emitEvent",["app.resume"]); }, false]); return gs.mc(gs.fs('document', this, gSobject),"addEventListener",["menubutton", function(it) { return gs.mc(gSobject,"emitEvent",["app.menubutton"]); }, false]); } gSobject['preventScreenshots'] = function(it) { gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gs.fs('OurCodeWorldpreventscreenshots', this, gSobject),"enable",[]); }, 1]); return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"preventscreenshot"),"enable",[function(it) { }, function(it) { }]); }, 1]); } gSobject['allowScreenshots'] = function(it) { gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gs.fs('OurCodeWorldpreventscreenshots', this, gSobject),"disable",[]); }, 1]); return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"plugins"),"preventscreenshot"),"disable",[function(it) { }, function(it) { }]); }, 1]); } gSobject['setupCordovaPluginKeyboard'] = function(it) { var initialViewportHeight = gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"height"); var initialViewportWidth = gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"width"); return gs.mc(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"addEventListener",["resize", function(it) { if (initialViewportWidth != gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"width")) { gs.execStatic(Utils,'setTimeout', this,[function(it) { initialViewportHeight = gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"height"); initialViewportWidth = gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"width"); gs.mc(gSobject,"emitEvent",["orientation." + (gs.mc(gSobject,"getOrientation",[])) + ""]); gs.sp(gSobject.device,"orientation",gs.mc(gSobject,"getOrientation",[])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["setupCordovaPluginKeyboard:orientation." + (gs.mc(gSobject,"getOrientation",[])) + ""]); }, 100]); return null; }; if (gs.equals(gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"height"), initialViewportHeight)) { gs.sp(gSobject.device,"keyboard","hide"); gs.mc(gSobject,"emitEvent",["keyboard.hide"]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["setupCordovaPluginKeyboard:keyboard.hide"]); } else { gs.sp(gSobject.device,"keyboard","show"); gs.mc(gSobject,"emitEvent",["keyboard.show"]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["setupCordovaPluginKeyboard:keyboard.show"]); }; }]); } gSobject['getOrientation'] = function(it) { return gs.gp(gs.fs('screen', this, gSobject)["orientation"],"type"); } gSobject['setupCordovaPluginDevice'] = function(it) { gs.mc(gSobject.device,"putAll",[gs.gp(gs.fs('window', this, gSobject),"device")]); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userDevice",[gSobject.userId, gSobject.device]),"do",[]); } gSobject['setupCordovaPluginBatteryStatus'] = function(it) { var batteryUpdate = function(status, state) { if (gs.bool(gs.gp(state,"level"))) { gSobject.battery = gs.map().add("level",gs.gp(state,"level")).add("isPlugged",gs.gp(state,"isPlugged")).add("isTrusted",gs.gp(state,"isTrusted")).add("status",status).add("date",gs.date()); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userDeviceBattery",[gSobject.userId, gs.gp(gSobject.device,"uuid"), gSobject.battery]),"do",[]); }; gs.sp(gSobject.network,"bettery",status); return gs.mc(gSobject,"emitEvent",["bettery." + (status) + ""]); }; gs.mc(gs.fs('window', this, gSobject),"addEventListener",["batterystatus", function(state) { return gs.execCall(batteryUpdate, this, ["normal", state]); }, false]); gs.mc(gs.fs('window', this, gSobject),"addEventListener",["batterylow", function(state) { return gs.execCall(batteryUpdate, this, ["low", state]); }, false]); return gs.mc(gs.fs('window', this, gSobject),"addEventListener",["batterycritical", function(state) { return gs.execCall(batteryUpdate, this, ["critical", state]); }, false]); } gSobject['setupCordovaPluginNetworkInformation'] = function(it) { var networkUpdate = function(status) { gs.sp(gSobject.network,"status",status); gs.sp(gSobject.network,"type",gs.gp(gs.gp(gs.fs('navigator', this, gSobject),"connection"),"type")); gs.sp(gSobject.network,"date",gs.date()); gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userNetwork",[gSobject.userId, gs.gp(gSobject.device,"uuid"), gSobject.network]),"do",[]); return gs.mc(gSobject,"emitEvent",["network." + (status) + ""]); }; gs.mc(gs.fs('document', this, gSobject),"addEventListener",["offline", function(it) { return gs.execCall(networkUpdate, this, ["offline"]); }, false]); gs.mc(gs.fs('document', this, gSobject),"addEventListener",["online", function(it) { return gs.execCall(networkUpdate, this, ["online"]); }, false]); return gs.execCall(networkUpdate, this, ["online"]); } gSobject['addAppEventListeners'] = function(callback) { return gs.mc(gSobject.appEventListeners,"add",[callback]); } gSobject['emitEvent'] = function(event) { return gs.mc(gSobject.appEventListeners,"each",[function(listner) { return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.execCall(listner, this, [event]); }, 0]); }]); } gSobject['vibrate'] = function(timeMs) { return gs.mc(gs.fs('navigator', this, gSobject),"vibrate",[timeMs]); } gSobject.spinnerInstalled = function() { return CordovaDevice.spinnerInstalled(); } gSobject['statusBarShow'] = function(it) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"show",[]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarShow error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['statusBarHide'] = function(it) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"hide",[]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarHide error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['statusBarColor'] = function(hex) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"backgroundColorByHexString",[hex]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarColor error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['statusBarStyleLight'] = function(it) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"styleLightContent",[]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarStyleLight error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['statusBarStyleDark'] = function(it) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"styleDefault",[]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarStyleDark error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['statusBarOverlay'] = function(overlay) { if (!gs.bool(CordovaDevice.cordovaPluginStatusBarInstalled())) { return null; }; try { gs.mc(gs.fs('StatusBar', this, gSobject),"overlaysWebView",[overlay]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["statusBarOverlay error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['lockPortrait'] = function(it) { return gs.mc(gSobject,"doLockOrientation",["portrait"]); } gSobject['lockLandscape'] = function(it) { return gs.mc(gSobject,"doLockOrientation",["landscape"]); } gSobject['unlockOrientation'] = function(it) { try { gs.mc(gs.gp(gs.fs('screen', this, gSobject),"orientation"),"unlock",[], null, true); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["unlockOrientation: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject.doLockOrientation = function(orientation) { try { var result = screen.orientation.lock(orientation); // iOS 16+ returns a Promise — handle rejection silently if (result && result.then) { result.catch(function(e) { console.log('orientation lock rejected:', e); }); } return 'ok'; } catch (e) { console.log('orientation lock error:', e); return 'Not supported: ' + (e.message || e); } } gSobject['hasPermission'] = function(name, callback) { if (!gs.bool(CordovaDevice.permissionsInstalled())) { gs.execCall(callback, this, [gs.map().add("hasPermission",true)]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('cordova', this, gSobject),"plugins"),"permissions"),"checkPermission",[name, callback, function(e) { return gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",e)]); }]); } catch (e) { gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",gs.fs('e', this, gSobject))]); } ; } gSobject['requestPermission'] = function(name, callback) { if (!gs.bool(CordovaDevice.permissionsInstalled())) { gs.execCall(callback, this, [gs.map().add("hasPermission",true)]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('cordova', this, gSobject),"plugins"),"permissions"),"requestPermission",[name, callback, function(e) { return gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",e)]); }]); } catch (e) { gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",gs.fs('e', this, gSobject))]); } ; } gSobject['hasPermissions'] = function(names, callback) { if (!gs.bool(CordovaDevice.permissionsInstalled())) { gs.execCall(callback, this, [gs.map().add("hasPermission",true)]); return null; }; try { gs.mc(gs.gp(gs.gp(gs.fs('cordova', this, gSobject),"plugins"),"permissions"),"checkPermission",[names, callback, function(e) { return gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",e)]); }]); } catch (e) { gs.execCall(callback, this, [gs.map().add("hasPermission",false).add("error",gs.fs('e', this, gSobject))]); } ; } gSobject.permissionsInstalled = function() { return CordovaDevice.permissionsInstalled(); } gSobject.cordovaPluginStatusBarInstalled = function() { return CordovaDevice.cordovaPluginStatusBarInstalled(); } gSobject.cordovaPluginDeviceInstalled = function() { return CordovaDevice.cordovaPluginDeviceInstalled(); } gSobject.crdovaPluginNetworkInformationInstalled = function() { return CordovaDevice.crdovaPluginNetworkInformationInstalled(); } gSobject['showSpinner'] = function(message, cancelable) { if (message === undefined) message = ""; if (cancelable === undefined) cancelable = false; return gs.mc(gSobject,"nativeSpinnerShow",[gs.map().add("message",message).add("cancelable",cancelable), function(it) { }, function(it) { }]); } gSobject['hideSpinner'] = function(it) { return gs.mc(gSobject,"nativeSpinnerHide",[function(it) { }, function(it) { }]); } gSobject.nativeSpinnerShow = function(options, success, error) { if (typeof window.dymicoSpinner !== 'undefined') { window.dymicoSpinner.show(options, success, error); } else if (typeof SpinnerDialog !== 'undefined') { SpinnerDialog.show(null, options.message || '', options.cancelable || false); if (success) success(); } else { if (error) error('Spinner not available'); } } gSobject.nativeSpinnerHide = function(success, error) { if (typeof window.dymicoSpinner !== 'undefined') { window.dymicoSpinner.hide(success, error); } else if (typeof SpinnerDialog !== 'undefined') { SpinnerDialog.hide(); if (success) success(); } else { if (error) error('Spinner not available'); } } gSobject['preventCapture'] = function(enabled, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativePreventCapture",[enabled, success, error]); } gSobject['onScreenshot'] = function(callback) { return gs.mc(gSobject,"nativeOnScreenshot",[callback]); } gSobject['onScreenRecording'] = function(callback) { return gs.mc(gSobject,"nativeOnScreenRecording",[callback]); } gSobject.nativePreventCapture = function(enabled, success, error) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.dymicoScreenshot) { cordova.plugins.dymicoScreenshot.preventCapture(enabled, success, error); } else { if (error) error('dymicoScreenshot not available'); } } gSobject.nativeOnScreenshot = function(callback) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.dymicoScreenshot) { cordova.plugins.dymicoScreenshot.onScreenshot(callback); } } gSobject.nativeOnScreenRecording = function(callback) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.dymicoScreenshot) { cordova.plugins.dymicoScreenshot.onScreenRecording(callback); } } gSobject['getAppInfo'] = function(callback, error) { if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeGetAppInfo",[callback, error]); } gSobject['setBadge'] = function(count, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeSetBadge",[count, success, error]); } gSobject['clearBadge'] = function(success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeSetBadge",[0, success, error]); } gSobject.nativeGetAppInfo = function(success, error) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.dymicoApp) { cordova.plugins.dymicoApp.getInfo(success, error); } else { if (error) error('dymicoApp not available'); } } gSobject.nativeSetBadge = function(count, success, error) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.dymicoApp) { cordova.plugins.dymicoApp.setBadge(count, success, error); } else { if (error) error('dymicoApp not available'); } } gSobject['print'] = function(content, options, callback) { if (options === undefined) options = gs.map(); if (callback === undefined) callback = function(it) { }; return gs.mc(gSobject,"nativePrint",[content, options, callback]); } gSobject.nativePrint = function(content, options, callback) { if (typeof cordova !== 'undefined' && cordova.plugins && cordova.plugins.printer) { cordova.plugins.printer.print(content, options, callback); } else { if (callback) callback(false); } } gSobject['installErrorCapture'] = function(it) { gs.mc(gSobject,"nativeInstallErrorCapture",[]); gs.mc(gSobject,"nativeInstallConsoleTail",[]); return gs.mc(gSobject,"nativeInstallRouteHistory",[]); } gSobject['enableErrorFlush'] = function(it) { gs.mc(gSobject,"nativePrimeErrorContext",[gs.map().add("userId",gs.elvis(gs.bool(gSobject.userId) , gSobject.userId , "")).add("uuid",gs.elvis(gs.bool(gs.gp(gSobject.device,"uuid")) , gs.gp(gSobject.device,"uuid") , "")).add("platform",gs.elvis(gs.bool(gs.gp(gSobject.device,"platform")) , gs.gp(gSobject.device,"platform") , "browser")).add("appVersion",gs.elvis(gs.bool(gs.gp(gSobject.device,"version")) , gs.gp(gSobject.device,"version") , "")).add("appBuild",gs.elvis(gs.bool(gs.gp(gSobject.device,"cordova")) , gs.gp(gSobject.device,"cordova") , ""))]); return gs.mc(gSobject,"nativeFlushErrors",[]); } gSobject.nativeInstallErrorCapture = function() { if (window._cwErr) return; // idempotent var BUF_KEY = 'cw.errBuf'; var BUF_CAP = 50; var DEDUP_MS = 60000; var dedup = {}; var ctx = { userId: '', uuid: '', platform: 'browser', appVersion: '', appBuild: '' }; var flushing = false; var buf; function readBuf() { try { var s = window.localStorage.getItem(BUF_KEY); return s ? JSON.parse(s) : []; } catch(e) { return []; } } function writeBuf(arr) { try { if (arr.length > BUF_CAP) arr = arr.slice(arr.length - BUF_CAP); window.localStorage.setItem(BUF_KEY, JSON.stringify(arr)); } catch(e) {} } buf = readBuf(); function fingerprint(type, msg, stack) { var first = (stack || '').split('\n')[0] || ''; var s = (type || '') + ':' + (msg || '').substring(0, 80) + ':' + first.substring(0, 120); var h = 0; for (var i = 0; i < s.length; i++) { h = ((h << 5) - h) + s.charCodeAt(i); h |= 0; } return ('00000000' + (h >>> 0).toString(16)).slice(-8); } function capture(rec) { try { if (!rec.fingerprint) rec.fingerprint = fingerprint(rec.type, rec.message, rec.stack); if (!rec.clientReportedAt) rec.clientReportedAt = Date.now(); if (!rec.userAgent && typeof navigator !== 'undefined') rec.userAgent = navigator.userAgent || ''; rec.count = rec.count || 1; var now = Date.now(); var d = dedup[rec.fingerprint]; if (d && (now - d.lastTs) < DEDUP_MS && buf[d.idx] && buf[d.idx].fingerprint === rec.fingerprint) { buf[d.idx].count = (buf[d.idx].count || 1) + 1; d.lastTs = now; writeBuf(buf); return; } buf.push(rec); if (buf.length > BUF_CAP) { buf = buf.slice(buf.length - BUF_CAP); dedup = {}; } dedup[rec.fingerprint] = { idx: buf.length - 1, lastTs: now }; writeBuf(buf); if (typeof navigator !== 'undefined' && navigator.onLine !== false) flush(); } catch(e) { try { console.log('[cwErr] capture failed:', e); } catch(_) {} } } function buildUrl() { try { var p = window.location.pathname.split('/').filter(function(s){ return s; }); if (p.length >= 2) return '/' + p[0] + '/' + p[1] + '/cordova/errors'; } catch(e) {} return '/cordova/errors'; } function flush() { if (flushing || buf.length === 0) return; if (typeof navigator !== 'undefined' && navigator.onLine === false) return; flushing = true; var sent = buf.length; var batch = buf.slice(); for (var i = 0; i < batch.length; i++) { if (!batch[i].user && ctx.userId) batch[i].user = ctx.userId; if (!batch[i].uuid && ctx.uuid) batch[i].uuid = ctx.uuid; if (!batch[i].platform && ctx.platform) batch[i].platform = ctx.platform; if (!batch[i].appVersion && ctx.appVersion) batch[i].appVersion = ctx.appVersion; if (!batch[i].appBuild && ctx.appBuild) batch[i].appBuild = ctx.appBuild; } var done = function(ok) { flushing = false; if (ok) { buf = buf.slice(sent); dedup = {}; writeBuf(buf); } }; try { var xhr = new XMLHttpRequest(); xhr.open('POST', buildUrl(), true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.timeout = 5000; xhr.onload = function() { done(xhr.status >= 200 && xhr.status < 300); }; xhr.onerror = function() { done(false); }; xhr.ontimeout = function() { done(false); }; xhr.send('json=' + encodeURIComponent(JSON.stringify(batch))); } catch(e) { done(false); } } window.onerror = function(message, source, line, col, error) { capture({ type: 'js_error', message: message ? String(message) : '', stack: error && error.stack ? String(error.stack) : '', source: source || '', line: line || 0, col: col || 0 }); }; window.addEventListener('unhandledrejection', function(event) { var reason = event.reason || {}; var msg; if (reason && reason.message) { msg = String(reason.message); } else { try { msg = String(reason); } catch(e) { msg = ''; } } capture({ type: 'unhandled_rejection', message: msg, stack: reason && reason.stack ? String(reason.stack) : '', source: '', line: 0, col: 0 }); }); function installExecInterceptor() { if (!(window.cordova && window.cordova.exec) || window.cordova.exec.__cwWrapped) return false; var orig = window.cordova.exec; var wrapped = function(success, fail, service, action, args) { var wrappedFail = function(err) { try { var emsg; if (typeof err === 'string') emsg = err; else if (err && err.message) emsg = String(err.message); else { try { emsg = JSON.stringify(err); } catch(e) { emsg = String(err); } } capture({ type: 'plugin_error', message: emsg, stack: '', source: service + '.' + action, line: 0, col: 0 }); } catch(_) {} if (fail) fail(err); }; return orig(success, wrappedFail, service, action, args); }; wrapped.__cwWrapped = true; window.cordova.exec = wrapped; return true; } if (!installExecInterceptor()) { var tries = 0; var iv = setInterval(function() { tries++; if (installExecInterceptor() || tries > 50) clearInterval(iv); }, 100); } window.addEventListener('online', flush); document.addEventListener('resume', flush, false); document.addEventListener('deviceready', flush, false); window._cwErr = { capture: capture, flush: flush, setContext: function(c) { for (var k in c) ctx[k] = c[k]; }, _ctx: ctx, _buf: function() { return buf.slice(); } }; try { console.log('[CordovaDevice] error capture installed (offline-aware)'); } catch(_) {} } gSobject.nativePrimeErrorContext = function(ctx) { if (window._cwErr) window._cwErr.setContext(ctx); } gSobject.nativeFlushErrors = function() { if (window._cwErr) window._cwErr.flush(); } gSobject['reportProblem'] = function(userMessage, opts, success, error) { if (opts === undefined) opts = gs.map(); if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; if (!gs.bool(gs.mc(userMessage,"trim",[], null, true))) { return gs.execCall(error, this, ["userMessage is required"]); }; return gs.mc(gs.fs('cordovaScreenCapture', this, gSobject),"reportProblem",[userMessage, opts, success, error]); } gSobject.nativeInstallConsoleTail = function() { if (window._cwConsoleTailInstalled) return; window._cwConsoleTailInstalled = true; window._cwConsoleTail = window._cwConsoleTail || []; var CAP = 50; var levels = ['log', 'info', 'warn', 'error']; for (var i = 0; i < levels.length; i++) { (function(level) { var orig = console[level]; console[level] = function() { try { var parts = []; for (var j = 0; j < arguments.length; j++) { var a = arguments[j]; if (a == null) { parts.push(String(a)); continue; } if (typeof a === 'string') { parts.push(a); continue; } try { parts.push(JSON.stringify(a)); } catch(e) { parts.push(String(a)); } } var line = '[' + new Date().toISOString().substr(11,12) + '] ' + level.toUpperCase() + ' ' + parts.join(' '); if (line.length > 500) line = line.substring(0, 500) + '...'; window._cwConsoleTail.push(line); if (window._cwConsoleTail.length > CAP) { window._cwConsoleTail = window._cwConsoleTail.slice(-CAP); } } catch(_) {} if (orig && orig.apply) orig.apply(console, arguments); }; })(levels[i]); } } gSobject.nativeInstallRouteHistory = function() { if (window._cwRouteHistoryInstalled) return; var CAP = 10; window._cwRouteHistory = window._cwRouteHistory || []; var tries = 0; var iv = setInterval(function() { tries++; try { if (window.vue && window.vue.router && window.vue.router.afterEach) { window.vue.router.afterEach(function(to) { try { var path = to && (to.fullPath || to.path) ? (to.fullPath || to.path) : ''; if (path) { window._cwRouteHistory.push(path); if (window._cwRouteHistory.length > CAP) { window._cwRouteHistory = window._cwRouteHistory.slice(-CAP); } } } catch(_) {} }); window._cwRouteHistoryInstalled = true; clearInterval(iv); } } catch(_) {} if (tries > 100) clearInterval(iv); }, 200); } gSobject['CordovaDevice0'] = function(it) { gs.mc(gSobject,"installErrorCapture",[]); gs.mc(document,"addEventListener",["deviceready", function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaDevice:deviceready"]); gs.mc(gSobject,"splashScreenHide",[]); gs.mc(gSobject,"setupCordovaPluginKeyboard",[]); if (!gs.bool(gs.mc(this,"cordovaPluginDeviceInstalled",[], gSobject))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaDevice:NOT INSTALLED"]); gs.mc(gSobject,"enableErrorFlush",[]); return null; }; if (!gs.bool(gs.gp(gs.fs('session', this, gSobject),"userId"))) { gs.mc(gSobject,"enableErrorFlush",[]); return null; }; gSobject.userId = gs.gp(gs.fs('session', this, gSobject),"userId"); try { gs.mc(gSobject,"setupCordovaPluginDevice",[]); gs.mc(gSobject,"setupCordovaPluginBatteryStatus",[]); gs.mc(gSobject,"setupCordovaPluginNetworkInformation",[]); gs.mc(gSobject,"disableBackButton",[]); } catch (all) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",[gs.plus("CordovaDevice:init:ERROR:", gs.fs('all', this, gSobject))]); } ; return gs.mc(gSobject,"enableErrorFlush",[]); }]); gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gSobject,"splashScreenHide",[]); }, 1000]); return this; } if (arguments.length==0) {gSobject.CordovaDevice0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaDevice.spinnerInstalled = function() { return typeof window.dymicoSpinner !== 'undefined'; } CordovaDevice.permissionsInstalled = function() { return typeof cordova !== 'undefined' && cordova.plugins && typeof cordova.plugins.permissions !== 'undefined'; } CordovaDevice.cordovaPluginStatusBarInstalled = function() { return ( typeof StatusBar !== 'undefined' ) } CordovaDevice.cordovaPluginDeviceInstalled = function() { return ( typeof device !== 'undefined' || typeof window.device !== 'undefined') } CordovaDevice.crdovaPluginNetworkInformationInstalled = function() { return ( typeof navigator.connection !== 'undefined') } function CordovaDeepLink() { var gSobject = gs.init('CordovaDeepLink'); gSobject.clazz = { name: 'CordovaDeepLink', simpleName: 'CordovaDeepLink'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.callbackList = gs.list([]); gSobject['registerCallback'] = function(callback) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["================CordovaDeepLink registerCallback"]); return gs.mc(gSobject.callbackList,"add",[callback]); } gSobject['openDeepLink'] = function(eventData) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["=====================CordovaDeepLink openDeepLink"]); return gs.mc(gSobject.callbackList,"each",[function(callback) { return gs.execCall(callback, this, [eventData]); }]); } gSobject['CordovaDeepLink0'] = function(it) { gs.mc(document,"addEventListener",["deviceready", function(it) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["======================CordovaDeepLink eventlistener"]); return gs.mc(gs.fs('universalLinks', this, gSobject),"subscribe",["openDeepLink", gs.gp(gs.thisOrObject(this,gSobject),"openDeepLink")]); }, false]); return this; } if (arguments.length==0) {gSobject.CordovaDeepLink0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function VueDateComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'VueDateComponent', simpleName: 'VueDateComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.toJavascript(gs.list(["modelValue" , "label" , "onSelect" , "outlined" , "filled" , "standout" , "borderless" , "square" , "dark" , "clearable" , "required" , "autoClose" , "format" , "time"])); gSobject.data = function(it) { return gs.map().add("dateString","").add("selectedDate","").add("selectedTime","").add("hasTime",false).add("showDate",false).add("showTime",false).add("rules",gs.list(["val => false"])).add("autoCloseData",true).add("formatData","DD MMM YYYY"); }; gSobject['mounted'] = function(it) { var self = this; gs.sp(self,"hasTime",(gs.equals(gs.gp(self,"time"), ""))); if (gs.bool(gs.gp(self,"hasTime"))) { gs.sp(self,"formatData","DD MMM YYYY HH:mm"); }; if (gs.bool(gs.gp(self,"required"))) { gs.sp(self,"rules",gs.list(["date"])); }; if (gs.equals(gs.gp(self,"autoClose"), "false")) { gs.sp(self,"autoCloseData",false); }; if (gs.bool(gs.gp(self,"format"))) { gs.sp(self,"formatData",gs.gp(self,"format")); }; return gs.mc(gSobject,"updateDate",[self, gs.gp(self,"modelValue")]); } gSobject['updateDate'] = function(self, date) { gs.sp(this,"modelValue",date); gs.sp(self,"dateString",(gs.bool(date) ? gs.mc(gs.mc(gSobject,"moment",[date]),"format",[gs.gp(self,"formatData")]) : null)); return gs.mc(self,"$emit",["update:modelValue", date]); } gSobject['clearDate'] = function(it) { gs.sp(this,"modelValue",null); gs.sp(this,"dateString",null); return gs.mc(gSobject.self,"$emit",["update:modelValue", gs.fs('date', this, gSobject)]); } gSobject['openDate'] = function(it) { return gs.sp(this,"showDate",true); } gSobject['closeAll'] = function(it) { gs.sp(this,"showDate",false); return gs.sp(this,"showTime",false); } gSobject['selectedDateString'] = function(dateStringValue) { if (!gs.bool(dateStringValue)) { return null; }; gs.mc(gSobject,"updateDate",[this, gs.date(dateStringValue)]); var self = this; gs.sp(this,"showDate",false); if (gs.bool(gs.gp(self,"hasTime"))) { return gs.sp(this,"showTime",true); }; } gSobject['selectedTimeString'] = function(timeStringValue) { if (!gs.bool(timeStringValue)) { return null; }; gs.sp(this,"showTime",false); var timeParts = gs.mc(timeStringValue,"split",[":"]); gs.mc(gs.gp(gs.thisOrObject(this,gSobject),"modelValue"),"setHours",[timeParts[0]]); gs.mc(gs.gp(gs.thisOrObject(this,gSobject),"modelValue"),"setMinutes",[timeParts[1]]); return gs.mc(gSobject,"updateDate",[this, gs.gp(gs.thisOrObject(this,gSobject),"modelValue")]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3MenuButton() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3MenuButton', simpleName: 'I3MenuButton'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list([]); gSobject.defaults = gs.map().add("type","button").add("label","Button").add("color","primary").add("textColor","").add("size","xs").add("noCaps",true).add("outline",false).add("flat",false).add("unelevated",true).add("rounded",false).add("push",false).add("square",false).add("glossy",false).add("dense",false); gSobject['created'] = function(it) { var self = this; var appConfig = gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig") , gs.map()); var config = (gs.gp(appConfig,"menubutton") != null ? gs.gp(appConfig,"menubutton") : gs.map()); var attrs = (gs.gp(self,"$attrs") != null ? gs.gp(self,"$attrs") : gs.map()); gs.sp(self,"btnProps",gs.toJavascript(gs.plus((gs.plus(gSobject.defaults, config)), attrs))); return gs.sp(gs.gp(self,"btnProps"),"size",gs.elvis(attrs["size"] , attrs["size"] , gs.elvis(config["size"] , config["size"] , gSobject.defaults["size"]))); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function UnitDetailsTab() { var gSobject = VueComponent(); gSobject.clazz = { name: 'UnitDetailsTab', simpleName: 'UnitDetailsTab'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("id",String); gSobject['created'] = function(it) { gs.sp(gSobject.scope,"unit",gs.map()); gs.sp(gSobject.scope,"latestFix",gs.map()); gs.sp(gSobject.scope,"digitalIOColumns",gs.list([gs.map().add("name","sensorProfile").add("label","Sensor Profile").add("field","sensorProfile").add("align","left") , gs.map().add("name","label").add("label","Label").add("field","label").add("align","left") , gs.map().add("name","reading").add("label","Reading").add("field","reading").add("align","left") , gs.map().add("name","message").add("label","Message").add("field","message").add("align","left")])); gs.sp(gSobject.scope,"digitalIOReadings",gs.list([])); gs.sp(gSobject.scope,"activeEvents",gs.list([])); gs.sp(gSobject.scope,"highestTemp",null); gs.sp(gSobject.scope,"lowestTemp",null); gs.sp(gSobject.scope,"lastUpdated",null); gs.sp(gSobject.scope,"status",null); gs.sp(gSobject.scope,"fromDate",null); gs.sp(gSobject.scope,"toDate",null); gs.sp(gSobject.scope,"fromTime","00:00"); gs.sp(gSobject.scope,"toTime","23:59"); gs.sp(gSobject.scope,"sensorProfileOptions",gs.list([])); gs.sp(gSobject.scope,"selectedProfileIds",gs.list([])); gs.sp(gSobject.scope,"reportTemplates",gs.list([gs.map().add("value","operational").add("label","Operational Summary").add("description","Charts and a current alert summary for day to day monitoring. No full reading history.") , gs.map().add("value","compliance").add("label","Compliance / Audit").add("description","Full record of every reading and alert (active and resolved) for audits.") , gs.map().add("value","incident").add("label","Incident Report").add("description","Focused on alerts: charts plus active and resolved alerts with logs.")])); gs.sp(gSobject.scope,"selectedTemplate","operational"); gs.sp(gSobject.scope,"generatingPdf",false); return gs.mc(gSobject,"loadOverview",[]); } gSobject['configureUnit'] = function(it) { var orgId = gs.elvis(gs.bool(gs.gp(gs.gp(gs.gp(gSobject.scope,"unit"),"org",true),"_id",true)) , gs.gp(gs.gp(gs.gp(gSobject.scope,"unit"),"org",true),"_id",true) , gs.gp(gs.gp(gSobject.scope,"unit"),"org",true)); var unitId = gs.elvis(gs.bool(gs.gp(gs.gp(gSobject.scope,"unit"),"_id",true)) , gs.gp(gs.gp(gSobject.scope,"unit"),"_id",true) , gs.gp(gs.gp(gSobject.route,"params"),"id")); if ((!gs.bool(orgId)) || (!gs.bool(unitId))) { return null; }; return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/organisation/" + (orgId) + "/unit/" + (unitId) + ""]); } gSobject['loadOverview'] = function(it) { var unitId = gs.gp(gs.gp(gSobject.route,"params"),"id"); if (!gs.bool(unitId)) { gs.mc(gSobject,"notify",["No unit ID provided", "negative"]); return null; }; return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwUnitService"),"fetchUnitOverview",[unitId]),"then",[function(payload) { gs.sp(gSobject.scope,"unit",gs.elvis(gs.bool(gs.gp(payload,"unit",true)) , gs.gp(payload,"unit",true) , gs.map())); gs.sp(gSobject.scope,"latestFix",gs.elvis(gs.bool(gs.gp(payload,"latestFix",true)) , gs.gp(payload,"latestFix",true) , gs.map())); gs.sp(gSobject.scope,"lastUpdated",gs.gp(payload,"lastUpdated",true)); gs.sp(gSobject.scope,"status",gs.gp(payload,"status",true)); gs.sp(gSobject.scope,"highestTemp",gs.gp(payload,"highestTemp",true)); gs.sp(gSobject.scope,"lowestTemp",gs.gp(payload,"lowestTemp",true)); gs.sp(gSobject.scope,"activeEvents",gs.list([])); gs.sp(gSobject.scope,"digitalIOReadings",gs.list([])); return gs.mc(gSobject,"loadSensorProfiles",[unitId]); }, function(error) { gs.println("Failed to load unit overview: " + (error) + ""); gs.mc(gSobject,"notify",["Failed to load unit overview", "negative"]); gs.sp(gSobject.scope,"unit",gs.map()); return gs.sp(gSobject.scope,"latestFix",gs.map()); }]); } gSobject['loadSensorProfiles'] = function(unitId) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwSensorProfileService"),"fetchMany",[gs.map().add("unit",unitId), function(profiles) { var list = gs.elvis(gs.bool(profiles) , profiles , gs.list([])); gs.sp(gSobject.scope,"sensorProfileOptions",gs.mc(list,"collect",[function(it) { return gs.map().add("label",gs.elvis(gs.bool(gs.gp(it,"name",true)) , gs.gp(it,"name",true) , gs.elvis(gs.bool(gs.gp(gs.gp(it,"sensor",true),"name",true)) , gs.gp(gs.gp(it,"sensor",true),"name",true) , "Unknown"))).add("value",gs.gp(it,"_id",true)); }])); return gs.sp(gSobject.scope,"selectedProfileIds",gs.mc(gs.gp(gSobject.scope,"sensorProfileOptions"),"collect",[function(it) { return gs.gp(it,"value"); }])); }]); } gSobject['selectAllProfiles'] = function(it) { return gs.sp(gSobject.scope,"selectedProfileIds",gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.scope,"sensorProfileOptions")) , gs.gp(gSobject.scope,"sensorProfileOptions") , gs.list([])),"collect",[function(it) { return gs.gp(it,"value"); }])); } gSobject['deselectAllProfiles'] = function(it) { return gs.sp(gSobject.scope,"selectedProfileIds",gs.list([])); } gSobject['loadUnitData'] = function(unitId) { gs.sp(gSobject.scope,"lastUpdated",null); gs.sp(gSobject.scope,"status",null); gs.sp(gSobject.scope,"highestTemp",null); gs.sp(gSobject.scope,"lowestTemp",null); gs.sp(gSobject.scope,"activeEvents",gs.list([])); return gs.sp(gSobject.scope,"digitalIOReadings",gs.list([])); } gSobject['validateDateFilter'] = function(it) { if ((!gs.bool(gs.gp(gSobject.scope,"fromDate"))) || (!gs.bool(gs.gp(gSobject.scope,"toDate")))) { gs.mc(gSobject,"notify",["Please select both From and To dates", "warning"]); return false; }; var from = gs.date(gs.gp(gSobject.scope,"fromDate")); var to = gs.date(gs.gp(gSobject.scope,"toDate")); var diffMs = gs.minus(gs.mc(to,"getTime",[]), gs.mc(from,"getTime",[])); var diffDays = Math.floor(gs.div(diffMs, (gs.multiply((gs.multiply((gs.multiply(1000, 60)), 60)), 24)))); if (diffDays > 31) { gs.mc(gSobject,"notify",["Date range cannot exceed 31 days", "warning"]); return false; }; if (diffDays < 0) { gs.mc(gSobject,"notify",["To date must be after From date", "warning"]); return false; }; return true; } gSobject['exportTempHumidityPdf'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"generatingPdf"))) { return null; }; if (!gs.bool(gs.mc(gSobject,"validateDateFilter",[]))) { return null; }; if ((!gs.bool(gs.gp(gSobject.scope,"selectedProfileIds"))) || (gs.equals(gs.mc(gs.gp(gSobject.scope,"selectedProfileIds"),"size",[]), 0))) { gs.mc(gSobject,"notify",["Please select at least one sensor profile", "warning"]); return null; }; var profileIds = gs.mc(gs.gp(gSobject.scope,"selectedProfileIds"),"join",[","]); var url = gs.plus((gs.plus((gs.plus((gs.plus((gs.plus((gs.plus("/cwExportPdfReport/generatePdfReport/" + (gs.gp(gs.gp(gSobject.scope,"unit"),"_id")) + "", "?fromDate=" + (gs.gp(gSobject.scope,"fromDate")) + "")), "&toDate=" + (gs.gp(gSobject.scope,"toDate")) + "")), "&fromTime=" + (gs.gp(gSobject.scope,"fromTime")) + "")), "&toTime=" + (gs.gp(gSobject.scope,"toTime")) + "")), "&profileIds=" + (profileIds) + "")), "&template=" + (gs.elvis(gs.bool(gs.gp(gSobject.scope,"selectedTemplate")) , gs.gp(gSobject.scope,"selectedTemplate") , "operational")) + ""); var fileName = "report_" + (gs.gp(gs.gp(gSobject.scope,"unit"),"name")) + ".pdf"; gs.sp(gSobject.scope,"generatingPdf",true); return gs.mc(gSobject,"downloadPdfBlob",[url, fileName]); } gSobject['onPdfDone'] = function(it) { return gs.sp(gSobject.scope,"generatingPdf",false); } gSobject['onPdfError'] = function(message) { gs.sp(gSobject.scope,"generatingPdf",false); return gs.mc(gSobject,"notify",[gs.elvis(gs.bool(message) , message , "Failed to generate PDF report"), "negative"]); } gSobject.downloadPdfBlob = function(url, fileName) { var component = this; fetch(url, { credentials: 'same-origin' }) .then(function(response) { if (!response.ok) { throw new Error('HTTP ' + response.status); } return response.blob(); }) .then(function(blob) { var blobUrl = window.URL.createObjectURL(blob); var a = document.createElement('a'); a.href = blobUrl; a.download = fileName; a.style.display = 'none'; document.body.appendChild(a); a.click(); document.body.removeChild(a); window.URL.revokeObjectURL(blobUrl); component.onPdfDone(); }) .catch(function(err) { console.error('PDF generation failed:', err); component.onPdfError('Failed to generate PDF report'); }); } gSobject['exportTempHumidityCsv'] = function(it) { if (!gs.bool(gs.mc(gSobject,"validateDateFilter",[]))) { return null; }; if (!gs.bool(gs.gp(gs.gp(gSobject.scope,"unit"),"_id",true))) { gs.mc(gSobject,"notify",["No unit loaded", "warning"]); return null; }; gs.sp(gSobject.scope,"loading",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwExportService"),"exportUnitHistoryCsv",[gs.gp(gs.gp(gSobject.scope,"unit"),"_id"), gs.gp(gSobject.scope,"fromDate"), gs.gp(gSobject.scope,"toDate"), gs.gp(gSobject.scope,"fromTime"), gs.gp(gSobject.scope,"toTime"), function(payload) { gs.sp(gSobject.scope,"loading",false); if (!gs.bool(gs.gp(payload,"content",true))) { gs.mc(gSobject,"notify",["No export data was returned", "warning"]); return null; }; gs.mc(gSobject,"downloadCsv",[gs.elvis(gs.bool(gs.gp(payload,"fileName")) , gs.gp(payload,"fileName") , "UnitHistory.csv"), gs.gp(payload,"content")]); return gs.mc(gSobject,"notify",["CSV exported" + ((gs.gp(payload,"rowCount") != null ? " (" + (gs.gp(payload,"rowCount")) + " rows)" : "")) + "", "positive"]); }]); } gSobject['downloadCsv'] = function(fileName, content) { var link = gs.mc(gs.fs('document', this, gSobject),"createElement",["a"]); var url = gs.plus("data:text/csv;charset=utf-8,", gs.mc(this,"encodeURIComponent",[gs.elvis(gs.bool(content) , content , "")], gSobject)); gs.sp(link,"href",url); gs.sp(link,"download",fileName); gs.mc(gs.gp(gs.fs('document', this, gSobject),"body"),"appendChild",[link]); gs.mc(link,"click",[]); return gs.mc(gs.gp(gs.fs('document', this, gSobject),"body"),"removeChild",[link]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaSimBridge() { var gSobject = gs.init('CordovaSimBridge'); gSobject.clazz = { name: 'CordovaSimBridge', simpleName: 'CordovaSimBridge'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.active = false; gSobject.pendingCallbacks = gs.map(); gSobject.eventListeners = gs.map(); gSobject.shouldActivate = function() { return CordovaSimBridge.shouldActivate(); } gSobject['activate'] = function(it) { gSobject.active = true; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaSimBridge: ACTIVE — running in simulator mode"]); gs.mc(gSobject,"setupFakeCordova",[]); gs.mc(gSobject,"setupMessageListener",[]); return gs.mc(gSobject,"fireDeviceReady",[]); } gSobject['setupFakeCordova'] = function(it) { gs.mc(gSobject,"createFakePlugins",[]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaSimBridge: fake plugin globals created"]); } gSobject.createFakePlugins = function() { var bridge = this; // Core cordova object window.cordova = window.cordova || {}; window.cordova.plugins = window.cordova.plugins || {}; // --- Scanner --- window.cordova.plugins.barcodeScanner = { scan: function(success, error, config) { bridge._storePending('scanner', 'scan', success, error); console.log('[SimBridge] Scanner: waiting for simulated scan...'); // Notify parent we're waiting window.parent.postMessage({type:'cordova-sim-ready', plugin:'scanner', action:'scan'}, '*'); } }; // --- BackgroundGeolocation (cordova-plugin-i3-bggeo) --- window.BackgroundGeolocation = { events: ['location','stationary','activity','start','stop','error','authorization','foreground','background','abort_requested','http_authorization','geofence'], AUTHORIZED: 1, NOT_AUTHORIZED: 0, AUTHORIZED_FOREGROUND: 2, HIGH_ACCURACY: 0, MEDIUM_ACCURACY: 100, LOW_ACCURACY: 1000, PASSIVE_ACCURACY: 10000, BACKGROUND_MODE: 0, FOREGROUND_MODE: 1, GEOFENCE_TRANSITION_ENTER: 1, GEOFENCE_TRANSITION_EXIT: 2, GEOFENCE_TRANSITION_DWELL: 4, PERMISSION_DENIED: 1, LOCATION_UNAVAILABLE: 2, TIMEOUT: 3, DISTANCE_FILTER_PROVIDER: 0, ACTIVITY_PROVIDER: 1, RAW_PROVIDER: 2, LOG_ERROR: 'ERROR', LOG_WARN: 'WARN', LOG_INFO: 'INFO', LOG_DEBUG: 'DEBUG', LOG_TRACE: 'TRACE', _listeners: {}, _config: {}, _geofences: [], _geofenceQueue: [], _status: { isRunning: false, locationServicesEnabled: true, authorization: 1 }, configure: function(config, success, failure) { var bg = window.BackgroundGeolocation; for (var k in (config || {})) bg._config[k] = config[k]; console.log('[SimBridge] BgGeo configured', config); if(success) success(); }, getConfig: function(success, failure) { if(success) success(window.BackgroundGeolocation._config || {}); }, start: function(s,f) { window.BackgroundGeolocation._status.isRunning = true; console.log('[SimBridge] BgGeo started'); if(s) s(); }, stop: function(s,f) { window.BackgroundGeolocation._status.isRunning = false; console.log('[SimBridge] BgGeo stopped'); if(s) s(); }, switchMode: function(m,s,f) { console.log('[SimBridge] BgGeo switchMode', m); if(s) s(); }, getCurrentLocation: function(success, failure, options) { bridge._storePending('gps', 'currentLocation', success, failure); console.log('[SimBridge] GPS: waiting for simulated location...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'gps', action:'currentLocation'}, '*'); }, on: function(event, fn) { var bg = window.BackgroundGeolocation; if (!bg._listeners[event]) bg._listeners[event] = []; bg._listeners[event].push(fn); return { remove: function() { var arr = bg._listeners[event] || []; for (var i = arr.length - 1; i >= 0; i--) if (arr[i] === fn) arr.splice(i, 1); }}; }, removeAllListeners: function(event) { var bg = window.BackgroundGeolocation; if(event) bg._listeners[event] = []; else bg._listeners = {}; }, checkStatus: function(cb) { var s = window.BackgroundGeolocation._status; if(cb) cb({isRunning: s.isRunning, locationServicesEnabled: s.locationServicesEnabled, authorization: s.authorization}); }, showAppSettings: function() { console.log('[SimBridge] BgGeo showAppSettings'); }, showLocationSettings: function() { console.log('[SimBridge] BgGeo showLocationSettings'); }, addGeofence: function(fence, s, e) { var fences = window.BackgroundGeolocation._geofences; for (var i = fences.length - 1; i >= 0; i--) if (fence && fences[i].id === fence.id) fences.splice(i, 1); if (fence) fences.push(fence); console.log('[SimBridge] BgGeo addGeofence', fence); if(s) s(); }, addGeofences: function(arr, s, e) { var fences = window.BackgroundGeolocation._geofences; arr = arr || []; for (var j = 0; j < arr.length; j++) { var fence = arr[j]; for (var i = fences.length - 1; i >= 0; i--) if (fences[i].id === fence.id) fences.splice(i, 1); fences.push(fence); } console.log('[SimBridge] BgGeo addGeofences count=' + arr.length); if(s) s(); }, removeGeofence: function(id, s, e) { var fences = window.BackgroundGeolocation._geofences; for (var i = fences.length - 1; i >= 0; i--) if (fences[i].id === id) fences.splice(i, 1); console.log('[SimBridge] BgGeo removeGeofence', id); if(s) s(); }, removeGeofences: function(ids, s, e) { var fences = window.BackgroundGeolocation._geofences; ids = ids || []; var idSet = {}; for (var k = 0; k < ids.length; k++) idSet[ids[k]] = true; for (var i = fences.length - 1; i >= 0; i--) if (idSet[fences[i].id]) fences.splice(i, 1); console.log('[SimBridge] BgGeo removeGeofences count=' + ids.length); if(s) s(); }, removeAllGeofences: function(s, e) { window.BackgroundGeolocation._geofences = []; console.log('[SimBridge] BgGeo removeAllGeofences'); if(s) s(); }, getGeofences: function(cb) { if(cb) cb((window.BackgroundGeolocation._geofences || []).slice()); }, getGeofenceEvents: function(cb) { var bg = window.BackgroundGeolocation; var q = (bg._geofenceQueue || []).slice(); bg._geofenceQueue = []; if(cb) cb(q); }, getStationaryLocation: function(s, f) { if(s) s(null); }, // Backward-compat no-ops (matched to plugin's own stubs) getLocations: function(s, f) { if(s) s([]); }, getValidLocations: function(s, f) { if(s) s([]); }, deleteLocation: function(id, s, f) { if(s) s(); }, deleteAllLocations: function(s, f) { if(s) s(); }, getLogEntries: function() { var args = arguments; for (var i = 0; i < args.length; i++) if (typeof args[i] === 'function') { args[i]([]); return; } }, startTask: function(s, f) { if(s) s(0); }, endTask: function(k, s, f) { if(s) s(); }, headlessTask: function(fn, s, f) { if(s) s(); }, forceSync: function(s, f) { if(s) s(); }, isLocationEnabled: function(s, f) { if(s) s(window.BackgroundGeolocation._status.locationServicesEnabled ? 1 : 0); }, }; // --- Bluetooth LE --- window.bluetoothle = { _scanCallback: null, initialize: function(success, params) { if(success) success({status: 'enabled'}); }, isInitialized: function(cb) { if(cb) cb({isInitialized: true}); }, isEnabled: function(cb) { if(cb) cb({isEnabled: true}); }, enable: function(s,e) { if(s) s(); }, startScan: function(success, error, params) { window.bluetoothle._scanCallback = success; if(success) success({status: 'scanStarted'}); console.log('[SimBridge] BLE: scanning, waiting for simulated devices...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'ble', action:'scan'}, '*'); }, stopScan: function(success, error) { window.bluetoothle._scanCallback = null; if(success) success({status: 'scanStopped'}); }, isScanning: function(cb) { if(cb) cb({isScanning: !!window.bluetoothle._scanCallback}); }, getAdapterInfo: function(cb) { if(cb) cb({name:'Simulated Adapter', address:'00:00:00:00:00:00', isInitialized:true, isEnabled:true, isScanning:false, isDiscoverable:false}); }, connect: function(s,e,p) { if(s) s({status:'connected', address:p.address}); }, disconnect: function(s,e,p) { if(s) s({status:'disconnected', address:p.address}); }, close: function(s,e,p) { if(s) s({status:'closed'}); }, discover: function(s,e,p) { if(s) s({status:'discovered', services:[]}); }, read: function(s,e,p) { if(s) s({status:'read', value:'AAAA'}); }, write: function(s,e,p) { if(s) s({status:'written'}); }, subscribe: function(s,e,p) { if(s) s({status:'subscribed'}); }, unsubscribe: function(s,e,p) { if(s) s({status:'unsubscribed'}); }, }; // --- Social Sharing --- window.plugins = window.plugins || {}; window.plugins.socialsharing = { share: function(msg, subj, files, url, success, failure) { console.log('[SimBridge] Share:', msg, subj, url); if(success) success(); }, shareViaEmail: function(msg, subj, to, cc, bcc, files, success, failure) { console.log('[SimBridge] Email:', msg, subj, to); if(success) success(); }, shareViaSMS: function(opts, phone, success, failure) { console.log('[SimBridge] SMS:', opts, phone); if(success) success(); }, shareViaWhatsApp: function(msg, files, url, success, failure) { console.log('[SimBridge] WhatsApp:', msg); if(success) success(); }, canShareVia: function(via, msg, subj, files, url, success, failure) { if(success) success(); }, available: function(cb) { if(cb) cb(true); }, saveToPhotoAlbum: function(files, s, e) { if(s) s(); }, }; // --- InAppBrowser --- window.cordova.InAppBrowser = { open: function(url, target, options) { console.log('[SimBridge] Browser:', url, target); if (target === '_system' || target === '_blank') { window.parent.postMessage({type:'cordova-sim-event', plugin:'browser', action:'open', data:{url:url, target:target}}, '*'); } return { addEventListener: function(e,cb) {}, removeEventListener: function(e,cb) {}, close: function() {}, show: function() {}, hide: function() {}, executeScript: function(d,cb) { if(cb) cb([]); }, }; } }; // --- Contacts --- window.navigator.contacts = window.navigator.contacts || { find: function(fields, success, error, options) { bridge._storePending('contacts', 'find', success, error); console.log('[SimBridge] Contacts: waiting for simulated contacts...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'contacts', action:'find', data:{filter: options ? options.filter : ''}}, '*'); }, pickContact: function(success, error) { bridge._storePending('contacts', 'pick', success, error); window.parent.postMessage({type:'cordova-sim-ready', plugin:'contacts', action:'pick'}, '*'); }, create: function(props) { return props || {}; }, fieldType: { displayName:'displayName', phoneNumbers:'phoneNumbers', emails:'emails', name:'name' }, }; // --- Deep Links --- window.universalLinks = { _callbacks: {}, subscribe: function(event, cb) { this._callbacks[event] = cb; }, unsubscribe: function(event) { delete this._callbacks[event]; }, checkDeepLink: function(ms) { return { then: function(cb) { return { catch: function(e) {} }; } }; }, }; // --- Camera --- window.navigator.camera = { getPicture: function(success, failure, opts) { bridge._storePending('camera', 'photo', success, failure); console.log('[SimBridge] Camera: waiting for simulated photo...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'camera', action:'photo'}, '*'); }, cleanup: function() {}, DestinationType: { FILE_URI: 1, DATA_URL: 0 }, PictureSourceType: { CAMERA: 1, PHOTOLIBRARY: 0 }, }; window.Camera = { EncodingType: { JPEG: 0, PNG: 1 } }; // --- i3 Spinner --- window.i3Spinner = { show: function(opts, success, error) { console.log('[SimBridge] Spinner show:', opts); window.parent.postMessage({type:'cordova-sim-event', plugin:'spinner', action:'show', data:opts}, '*'); if(success) success(); }, hide: function(success, error) { console.log('[SimBridge] Spinner hide'); window.parent.postMessage({type:'cordova-sim-event', plugin:'spinner', action:'hide'}, '*'); if(success) success(); }, }; // --- Fingerprint / Biometrics --- window.Fingerprint = { isAvailable: function(success, error) { bridge._storePending('biometrics', 'available', success, error); window.parent.postMessage({type:'cordova-sim-ready', plugin:'biometrics', action:'available'}, '*'); }, show: function(params, success, error) { bridge._storePending('biometrics', 'auth', success, error); console.log('[SimBridge] Biometrics: waiting for simulated auth...'); window.parent.postMessage({type:'cordova-sim-ready', plugin:'biometrics', action:'auth'}, '*'); }, registerBiometricSecret: function(params, success, error) { if(success) success('registered'); }, loadBiometricSecret: function(params, success, error) { if(success) success('sim-secret-123'); }, }; // --- Device --- window.device = { platform: 'Simulator', model: 'Desktop Browser', version: '1.0', manufacturer: 'Dymico', uuid: 'sim-' + Date.now(), serial: 'SIM000', cordova: '12.0.0', isVirtual: true, }; // --- StatusBar --- window.StatusBar = { show: function() { console.log('[SimBridge] StatusBar show'); }, hide: function() { console.log('[SimBridge] StatusBar hide'); }, overlaysWebView: function(v) { console.log('[SimBridge] StatusBar overlay', v); }, styleDefault: function() {}, styleLightContent: function() {}, backgroundColorByName: function(n) {}, backgroundColorByHexString: function(h) {}, }; // --- Battery (navigator.battery is set by cordova-plugin-battery-status) --- window.navigator.battery = { level: 75, isPlugged: false }; // --- Permissions --- window.cordova.plugins.permissions = { checkPermission: function(perm, success, error) { if(success) success({hasPermission: true}); }, requestPermission: function(perm, success, error) { if(success) success({hasPermission: true}); }, }; // --- Push --- window.PushNotification = { init: function(opts) { var _handlers = {}; var pushObj = { on: function(event, cb) { _handlers[event] = cb; }, _handlers: _handlers, }; // Fire registration after a tick setTimeout(function() { if(_handlers.registration) _handlers.registration({registrationId: 'sim-push-token-' + Date.now()}); }, 500); bridge._simPush = pushObj; return pushObj; } }; // --- Screen Orientation --- // screen.orientation is already available in browsers // --- SpinnerDialog (legacy fallback) --- window.SpinnerDialog = { show: function(t,m,c) { window.i3Spinner.show({message: m || t || '', cancelable: !!c}); }, hide: function() { window.i3Spinner.hide(); }, }; // --- Media --- window.Media = function(src, onSuccess, onError, onStatus) { return { startRecord: function() { console.log('[SimBridge] Media record:', src); }, stopRecord: function() { console.log('[SimBridge] Media stop record'); if(onSuccess) onSuccess(); }, play: function() { console.log('[SimBridge] Media play:', src); }, stop: function() { console.log('[SimBridge] Media stop'); }, release: function() {}, getDuration: function() { return 0; }, getCurrentPosition: function(cb) { if(cb) cb(0); }, }; }; console.log('[SimBridge] All fake Cordova plugins registered'); } gSobject['setupMessageListener'] = function(it) { return gs.mc(gSobject,"listenForMessages",[]); } gSobject.listenForMessages = function() { var bridge = this; window.addEventListener('message', function(event) { var msg = event.data; if (!msg || msg.type !== 'cordova-sim') return; console.log('[SimBridge] Received:', msg.plugin, msg.action, msg.data); switch(msg.plugin) { case 'scanner': if (msg.action === 'result') bridge._firePending('scanner', 'scan', msg.data); if (msg.action === 'cancel') bridge._firePending('scanner', 'scan', {text:'', format:'', cancelled:true}); break; case 'gps': if (msg.action === 'location') { bridge._firePending('gps', 'currentLocation', msg.data); var listeners = window.BackgroundGeolocation._listeners['location'] || []; for (var i = 0; i < listeners.length; i++) { listeners[i](msg.data); } } if (msg.action === 'stationary') { var sListeners = window.BackgroundGeolocation._listeners['stationary'] || []; for (var i = 0; i < sListeners.length; i++) { sListeners[i](msg.data); } } if (msg.action === 'activity') { var aListeners = window.BackgroundGeolocation._listeners['activity'] || []; for (var i = 0; i < aListeners.length; i++) { aListeners[i](msg.data); } } if (msg.action === 'geofence') { var fenceEvent = { fenceId: msg.data.fenceId || msg.data.id, transition: msg.data.transition, location: msg.data.location || null, data: msg.data.data || null, timestamp: msg.data.timestamp || Date.now() }; var bgGf = window.BackgroundGeolocation; bgGf._geofenceQueue = bgGf._geofenceQueue || []; bgGf._geofenceQueue.push(fenceEvent); var gListeners = bgGf._listeners['geofence'] || []; for (var i = 0; i < gListeners.length; i++) { gListeners[i](fenceEvent); } } if (msg.action === 'start' || msg.action === 'stop' || msg.action === 'foreground' || msg.action === 'background' || msg.action === 'abort_requested') { if (msg.action === 'start') window.BackgroundGeolocation._status.isRunning = true; if (msg.action === 'stop') window.BackgroundGeolocation._status.isRunning = false; var lListeners = window.BackgroundGeolocation._listeners[msg.action] || []; for (var i = 0; i < lListeners.length; i++) { lListeners[i](msg.data || {}); } } if (msg.action === 'error') { var eListeners = window.BackgroundGeolocation._listeners['error'] || []; for (var i = 0; i < eListeners.length; i++) { eListeners[i](msg.data); } } if (msg.action === 'authorization') { if (msg.data && typeof msg.data.code !== 'undefined') { window.BackgroundGeolocation._status.authorization = msg.data.code; } var auListeners = window.BackgroundGeolocation._listeners['authorization'] || []; for (var i = 0; i < auListeners.length; i++) { auListeners[i](msg.data); } } if (msg.action === 'http_authorization') { var hListeners = window.BackgroundGeolocation._listeners['http_authorization'] || []; for (var i = 0; i < hListeners.length; i++) { hListeners[i](msg.data || {}); } } if (msg.action === 'status') { if (msg.data && typeof msg.data === 'object') { var st = window.BackgroundGeolocation._status; for (var k in msg.data) st[k] = msg.data[k]; } } break; case 'ble': if (msg.action === 'device' && window.bluetoothle._scanCallback) { window.bluetoothle._scanCallback({status:'scanResult', name:msg.data.name, address:msg.data.address, rssi:msg.data.rssi}); } break; case 'camera': if (msg.action === 'photo') bridge._firePending('camera', 'photo', msg.data.uri || msg.data); break; case 'contacts': if (msg.action === 'results') bridge._firePending('contacts', 'find', msg.data); if (msg.action === 'picked') bridge._firePending('contacts', 'pick', msg.data); break; case 'deeplink': if (msg.action === 'trigger') { var dl = window.universalLinks._callbacks; for (var key in dl) { if (dl[key]) dl[key](msg.data); } } break; case 'battery': if (msg.action === 'status') { window.navigator.battery = msg.data; var evt = new CustomEvent('batterystatus', {detail: msg.data}); window.dispatchEvent(evt); } break; case 'network': if (msg.action === 'status') { var evtName = msg.data.online ? 'online' : 'offline'; document.dispatchEvent(new Event(evtName)); } break; case 'biometrics': if (msg.action === 'available') bridge._firePending('biometrics', 'available', msg.data.result || {biometryType:'face'}); if (msg.action === 'pass') bridge._firePending('biometrics', 'auth', msg.data || 'success'); if (msg.action === 'fail') bridge._firePendingError('biometrics', 'auth', msg.data || 'cancelled'); break; case 'push': if (msg.action === 'notification' && bridge._simPush && bridge._simPush._handlers.notification) { bridge._simPush._handlers.notification(msg.data); } break; } }); console.log('[SimBridge] postMessage listener registered'); } gSobject['fireDeviceReady'] = function(it) { return gs.mc(gSobject,"fireDeviceReadyEvent",[]); } gSobject.fireDeviceReadyEvent = function() { // Fire deviceready after a short delay so all plugins are set up setTimeout(function() { document.dispatchEvent(new Event('deviceready')); console.log('[SimBridge] deviceready fired'); }, 500); } gSobject._storePending = function(plugin, action, success, error) { var key = plugin + ':' + action; this.pendingCallbacks[key] = { success: success, error: error }; } gSobject._firePending = function(plugin, action, data) { var key = plugin + ':' + action; var pending = this.pendingCallbacks[key]; if (pending && pending.success) { pending.success(data); delete this.pendingCallbacks[key]; } } gSobject._firePendingError = function(plugin, action, data) { var key = plugin + ':' + action; var pending = this.pendingCallbacks[key]; if (pending && pending.error) { pending.error(data); delete this.pendingCallbacks[key]; } } gSobject['CordovaSimBridge0'] = function(it) { if (CordovaSimBridge.shouldActivate()) { gs.mc(gSobject,"activate",[]); }; return this; } if (arguments.length==0) {gSobject.CordovaSimBridge0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaSimBridge.shouldActivate = function() { // Activate in iframe without real Cordova, or when simulator flag is set by /cordova/header return (window.parent !== window) && ((typeof window.cordova === 'undefined') || window.__dymicoSimulator === true); } function I3QrCode() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3QrCode', simpleName: 'I3QrCode'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("text",gs.map().add("default","")).add("width",gs.map().add("default",300)).add("height",gs.map().add("default",300)); gSobject.qRCodeObject = null; gSobject['created'] = function(it) { return gSobject.self = this; } gSobject['afterMounted'] = function(it) { if (gs.bool(gs.gp(gSobject.self,"text"))) { return gs.mc(gSobject,"generateQrCode",[]); }; } gSobject['watchText'] = function(it) { if ((gs.bool(gs.gp(gSobject.self,"text"))) && (gs.bool(gs.gp(gSobject.refs,"qrCodeRef")))) { return gs.mc(gSobject,"generateQrCode",[]); }; } gSobject['generateQrCode'] = function(it) { if (!gs.bool(gs.gp(gSobject.refs,"qrCodeRef"))) { return null; }; if (gs.bool(gSobject.qRCodeObject)) { gs.mc(gSobject.qRCodeObject,"clear",[]); }; gSobject.qRCodeObject = gs.mc(gSobject,"newQrCode",[gs.gp(gSobject.refs,"qrCodeRef"), gs.gp(gSobject.self,"text"), gs.gp(gSobject.self,"width"), gs.gp(gSobject.self,"height")]); return gs.mc(gSobject.qRCodeObject,"makeCode",[gs.gp(gSobject.self,"text")]); } gSobject.newQrCode = function(element, text, width, height) { return new QRCode(element, { text: text, width: width, height: height, colorDark: '#000000', colorLight: '#ffffff', correctLevel: QRCode.CorrectLevel.H }) } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function UnitTemperatureSensorsTab() { var gSobject = VueComponent(); gSobject.clazz = { name: 'UnitTemperatureSensorsTab', simpleName: 'UnitTemperatureSensorsTab'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaErrorViewer() { var gSobject = VueComponent(); gSobject.clazz = { name: 'CordovaErrorViewer', simpleName: 'CordovaErrorViewer'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/cordovaErrors"; gSobject.roles = gs.list(["ROLE_DEV_I3"]); gSobject['created'] = function(it) { gs.sp(gSobject.scope,"errors",gs.list([])); gs.sp(gSobject.scope,"filter",gs.map().add("uuid","").add("user","").add("type","")); gs.sp(gSobject.scope,"loading",false); gs.sp(gSobject.scope,"total",0); gs.sp(gSobject.scope,"selectedError",null); return gs.mc(gSobject,"loadErrors",[]); } gSobject['loadErrors'] = function(it) { gs.sp(gSobject.scope,"loading",true); var query = gs.map(); if (gs.bool(gs.gp(gs.gp(gSobject.scope,"filter"),"uuid"))) { gs.sp(query,"uuid",gs.gp(gs.gp(gSobject.scope,"filter"),"uuid")); }; if (gs.bool(gs.gp(gs.gp(gSobject.scope,"filter"),"user"))) { gs.sp(query,"user",gs.gp(gs.gp(gSobject.scope,"filter"),"user")); }; if (gs.bool(gs.gp(gs.gp(gSobject.scope,"filter"),"type"))) { gs.sp(query,"type",gs.gp(gs.gp(gSobject.scope,"filter"),"type")); }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"userError"),"find",[query, gs.map().add("sort","_dateCreated").add("order","desc").add("limit",100), function(results) { gs.sp(gSobject.scope,"errors",gs.elvis(gs.bool(results) , results , gs.list([]))); gs.sp(gSobject.scope,"total",gs.mc(gs.gp(gSobject.scope,"errors"),"size",[])); return gs.sp(gSobject.scope,"loading",false); }]); } gSobject['clearFilter'] = function(it) { gs.sp(gSobject.scope,"filter",gs.map().add("uuid","").add("user","").add("type","")); return gs.mc(gSobject,"loadErrors",[]); } gSobject['selectError'] = function(error) { return gs.sp(gSobject.scope,"selectedError",error); } gSobject['closeDetail'] = function(it) { return gs.sp(gSobject.scope,"selectedError",null); } gSobject['deleteError'] = function(error) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"userError"),"delete",[gs.gp(error,"_id"), function(it) { gs.sp(gSobject.scope,"selectedError",null); return gs.mc(gSobject,"loadErrors",[]); }]); } gSobject['deleteAll'] = function(it) { gs.mc(gs.gp(gSobject.scope,"errors"),"each",[function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"userError"),"delete",[gs.gp(it,"_id")]); }]); gs.sp(gSobject.scope,"selectedError",null); return gs.execStatic(Utils,'setTimeout', this,[function(it) { return gs.mc(gSobject,"loadErrors",[]); }, 500]); } gSobject['screenshotUrl'] = function(error) { if (!gs.bool(gs.gp(error,"_id",true))) { return ""; }; return "/media/userError/screenshot/" + (gs.gp(error,"_id")) + ""; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaPhoto() { var gSobject = gs.init('CordovaPhoto'); gSobject.clazz = { name: 'CordovaPhoto', simpleName: 'CordovaPhoto'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['takePhoto'] = function(onSuccess, onFail, config) { if (config === undefined) config = gs.map(); return gs.mc(gSobject,"capture",["camera", onSuccess, onFail, config]); } gSobject['pickFromLibrary'] = function(onSuccess, onFail, config) { if (config === undefined) config = gs.map(); return gs.mc(gSobject,"capture",["library", onSuccess, onFail, config]); } gSobject['takePhotoBlob'] = function(onSuccess, onError) { if (onError === undefined) onError = function(it) { }; var success = function(imageUri) { return gs.mc(gs.fs('cordovaFile', this, gSobject),"blobFromFileUrl",[imageUri, function(blob) { gs.execCall(onSuccess, this, [blob]); return gs.mc(gSobject,"clearCache",[]); }, onError]); }; return gs.mc(gSobject,"takePhoto",[success, onError]); } gSobject['takePhotoAndUpload'] = function(objectName, property, objectId, onSuccess, onError) { if (onError === undefined) onError = function(it) { }; var success = function(tempImageUrl) { return gs.mc(gs.fs('cordovaFile', this, gSobject),"addFile",[tempImageUrl, objectName, property, objectId, onSuccess, onError]); }; return gs.mc(gSobject,"takePhoto",[success, onError]); } gSobject['clearCache'] = function(it) { } gSobject['capture'] = function(source, onSuccess, onFail, config) { var opts = gs.mc(gs.map().add("source",source).add("output","fileUri").add("maxWidth",1024).add("maxHeight",1024),'leftShift', gs.list([config])); return CordovaPhoto.pick(opts, function(result) { return gs.execCall(onSuccess, this, [gs.gp(result,"data")]); }, onFail); } gSobject.pick = function(x0,x1,x2) { return CordovaPhoto.pick(x0,x1,x2); } gSobject.isAvailable = function() { return CordovaPhoto.isAvailable(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaPhoto.pick = function(options, onSuccess, onFail) { if (typeof cordova === 'undefined' || !cordova.plugins || !cordova.plugins.dymicoPhoto) { return onFail('dymico-photo plugin not available'); } cordova.plugins.dymicoPhoto.pick(options, onSuccess, onFail); } CordovaPhoto.isAvailable = function() { return ( typeof cordova !== 'undefined' && cordova.plugins && typeof cordova.plugins.dymicoPhoto !== 'undefined' ); } function UnitFixHistoryTab() { var gSobject = VueComponent(); gSobject.clazz = { name: 'UnitFixHistoryTab', simpleName: 'UnitFixHistoryTab'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("unitId",String); gSobject.self = null; gSobject.data = function(it) { return gs.map().add("fromDate",null).add("toDate",null).add("fixHistoryRows",gs.list([])).add("loading",false).add("unit",gs.map()).add("totalDistanceText","0").add("showRawJson",false).add("rawJsonContent","").add("rawJsonLoading",false).add("exporting",false).add("pagination",gs.map().add("page",1).add("rowsPerPage",10).add("rowsNumber",0).add("sortBy","recordedAtText").add("descending",true)).add("columns",gs.list([])); }; gSobject['created'] = function(it) { gSobject.self = this; gs.sp(gSobject.self,"columns",gs.list([gs.map().add("name","actions").add("label","").add("field","actions").add("align","center").add("sortable",false) , gs.map().add("name","recordedAtText").add("label","Date / Time").add("field","recordedAtText").add("align","left").add("sortable",false) , gs.map().add("name","latLngText").add("label","Lat / Lng").add("field","latLngText").add("align","left").add("sortable",false) , gs.map().add("name","distanceText").add("label","Distance (m)").add("field","distanceText").add("align","left").add("sortable",false) , gs.map().add("name","cumulativeDistanceText").add("label","Cumulative dist. (m)").add("field","cumulativeDistanceText").add("align","left").add("sortable",false) , gs.map().add("name","voltageText").add("label","Voltage").add("field","voltageText").add("align","left").add("sortable",false) , gs.map().add("name","tempText").add("label","Temp").add("field","tempText").add("align","left").add("sortable",false) , gs.map().add("name","humidText").add("label","Humid").add("field","humidText").add("align","left").add("sortable",false) , gs.map().add("name","co2Text").add("label","CO2").add("field","co2Text").add("align","left").add("sortable",false) , gs.map().add("name","speedText").add("label","Speed (km/h)").add("field","speedText").add("align","left").add("sortable",false) , gs.map().add("name","geofenceText").add("label","Geofence").add("field","geofenceText").add("align","left").add("sortable",false)])); gs.mc(gSobject,"initializeDefaultDateRange",[]); gs.mc(gSobject,"loadUnit",[]); return gs.mc(gSobject,"loadFixHistory",[]); } gSobject['resetFilters'] = function(it) { gs.mc(gSobject,"initializeDefaultDateRange",[]); gs.sp(gs.gp(gSobject.self,"pagination"),"page",1); return gs.mc(gSobject,"loadFixHistory",[]); } gSobject['applyFilters'] = function(it) { if (!gs.bool(gs.mc(gSobject,"validateDateRange",[]))) { return null; }; gs.sp(gs.gp(gSobject.self,"pagination"),"page",1); return gs.mc(gSobject,"loadFixHistory",[]); } gSobject['formatFixDate'] = function(value) { if (!gs.bool(value)) { return "-"; }; var date = (gs.instanceOf(value, "Date") ? value : gs.date(gs.mc(value,"toString",[]))); return gs.mc(date,"format",["dd/MM/yyyy HH:mm"]); } gSobject['loadFixHistory'] = function(it) { if (!gs.bool(gs.gp(gSobject.self,"unitId"))) { gs.sp(gSobject.self,"fixHistoryRows",gs.list([])); gs.sp(gSobject.self,"totalDistanceText","0"); return null; }; gs.sp(gSobject.self,"loading",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwUnitService"),"paginatedUnitFixHistory",[gs.gp(gSobject.self,"unitId"), gs.gp(gSobject.self,"fromDate"), gs.gp(gSobject.self,"toDate"), gs.gp(gSobject.self,"pagination"), function(data) { var rows = gs.elvis(gs.bool(gs.gp(data,"rows",true)) , gs.gp(data,"rows",true) , gs.list([])); gs.sp(gSobject.self,"fixHistoryRows",gs.mc(rows,"collect",[function(row) { return gs.mc(gSobject,"mapTableRow",[row]); }])); gs.sp(gs.gp(gSobject.self,"pagination"),"rowsNumber",gs.elvis(gs.bool(gs.gp(data,"totalRows",true)) , gs.gp(data,"totalRows",true) , 0)); gs.sp(gSobject.self,"totalDistanceText",gs.mc(gSobject,"formatDistance",[gs.gp(data,"totalDistance",true)])); return gs.sp(gSobject.self,"loading",false); }]); } gSobject['onRequest'] = function(props) { return gs.mc(gSobject.self,"updatePagination",[gs.gp(props,"pagination")]); } gSobject['updatePagination'] = function(pagination) { gs.sp(gSobject.self,"pagination",pagination); return gs.mc(gSobject,"loadFixHistory",[]); } gSobject['loadUnit'] = function(it) { if (!gs.bool(gs.gp(gSobject.self,"unitId"))) { gs.sp(gSobject.self,"unit",gs.map()); return null; }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwUnitService"),"fetchOneById",[gs.gp(gSobject.self,"unitId"), function(data) { return gs.sp(gSobject.self,"unit",gs.elvis(gs.bool(data) , data , gs.map())); }]); } gSobject['validateDateRange'] = function(it) { if ((!gs.bool(gs.gp(gSobject.self,"fromDate"))) || (!gs.bool(gs.gp(gSobject.self,"toDate")))) { gs.mc(gSobject,"notify",["Please select both From and To dates", "warning"]); return false; }; var from = gs.date(gs.gp(gSobject.self,"fromDate")); var to = gs.date(gs.gp(gSobject.self,"toDate")); if (gs.mc(to,"before",[from])) { gs.mc(gSobject,"notify",["To date must be after From date", "warning"]); return false; }; return true; } gSobject['initializeDefaultDateRange'] = function(it) { var today = gs.date(); var sevenDaysAgo = gs.date(gs.minus(gs.gp(today,"time"), (gs.multiply((gs.multiply((gs.multiply((gs.multiply(6, 24)), 60)), 60)), 1000)))); gs.sp(gSobject.self,"fromDate",gs.mc(sevenDaysAgo,"format",["yyyy-MM-dd"])); return gs.sp(gSobject.self,"toDate",gs.mc(today,"format",["yyyy-MM-dd"])); } gSobject['formatCoordinate'] = function(value) { if (gs.equals(value, null)) { return "-"; }; var numericValue = value; return gs.mc(numericValue,"toFixed",[4]); } gSobject['formatDistance'] = function(value) { if (gs.equals(value, null)) { return "-"; }; return gs.mc(Math.round(value),"toString",[]); } gSobject['formatSensorValues'] = function(values) { if ((!gs.bool(values)) || (gs.equals(gs.mc(values,"size",[]), 0))) { return "-"; }; return gs.mc(gs.mc(gs.mc(values,"collect",[function(it) { return gs.mc(it,"toString",[], null, true); }]),"findAll",[function(it) { return (gs.bool(it)) && (gs.mc(it,"trim",[])); }]),"join",[", "]); } gSobject['mapTableRow'] = function(row) { return gs.map().add("_id",gs.gp(row,"_id")).add("recordedAtText",gs.mc(gSobject,"formatFixDate",[gs.gp(row,"recordedAt")])).add("latLngText",((gs.gp(row,"lat") != null) && (gs.gp(row,"lng") != null) ? gs.plus((gs.plus(gs.mc(gSobject,"formatCoordinate",[gs.gp(row,"lat")]), " / ")), gs.mc(gSobject,"formatCoordinate",[gs.gp(row,"lng")])) : "-")).add("distanceText",gs.mc(gSobject,"formatDistance",[gs.gp(row,"distance")])).add("cumulativeDistanceText",gs.mc(gSobject,"formatDistance",[gs.gp(row,"cumulativeDistance")])).add("voltageText",((gs.gp(row,"vBat") != null) || (gs.gp(row,"vIn") != null) ? gs.plus((gs.plus((gs.gp(row,"vBat") != null ? gs.gp(row,"vBat") : "-"), " / ")), (gs.gp(row,"vIn") != null ? gs.gp(row,"vIn") : "-")) : "-")).add("tempText",gs.mc(gSobject,"formatSensorValues",[gs.gp(row,"temps")])).add("humidText",gs.mc(gSobject,"formatSensorValues",[gs.gp(row,"humids")])).add("co2Text",gs.mc(gSobject,"formatSensorValues",[gs.gp(row,"co2s")])).add("speedText",(gs.gp(row,"speed") != null ? gs.mc(gs.gp(row,"speed"),"toString",[]) : "-")).add("geofenceText",(gs.bool(gs.gp(row,"geofence"))) || ("n/a")); } gSobject['exportCsv'] = function(it) { if (!gs.bool(gs.mc(gSobject,"validateDateRange",[]))) { return null; }; if (!gs.bool(gs.gp(gSobject.self,"unitId"))) { gs.mc(gSobject,"notify",["No unit selected", "warning"]); return null; }; gs.sp(gSobject.self,"exporting",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwExportService"),"exportUnitHistoryCsv",[gs.gp(gSobject.self,"unitId"), gs.gp(gSobject.self,"fromDate"), gs.gp(gSobject.self,"toDate"), function(payload) { gs.sp(gSobject.self,"exporting",false); if (!gs.bool(gs.gp(payload,"content",true))) { gs.mc(gSobject,"notify",["No export data was returned", "warning"]); return null; }; gs.mc(gSobject,"downloadCsv",[gs.elvis(gs.bool(gs.gp(payload,"fileName")) , gs.gp(payload,"fileName") , "UnitHistory.csv"), gs.gp(payload,"content")]); return gs.mc(gSobject,"notify",["CSV exported" + ((gs.gp(payload,"rowCount") != null ? " (" + (gs.gp(payload,"rowCount")) + " rows)" : "")) + "", "positive"]); }]); } gSobject['downloadCsv'] = function(fileName, content) { var link = gs.mc(gs.fs('document', this, gSobject),"createElement",["a"]); var url = gs.plus("data:text/csv;charset=utf-8,", gs.mc(this,"encodeURIComponent",[gs.elvis(gs.bool(content) , content , "")], gSobject)); gs.sp(link,"href",url); gs.sp(link,"download",fileName); gs.mc(gs.gp(gs.fs('document', this, gSobject),"body"),"appendChild",[link]); gs.mc(link,"click",[]); return gs.mc(gs.gp(gs.fs('document', this, gSobject),"body"),"removeChild",[link]); } gSobject['viewRawJson'] = function(row) { gs.sp(gSobject.self,"rawJsonLoading",true); gs.sp(gSobject.self,"showRawJson",true); gs.sp(gSobject.self,"rawJsonContent",""); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwUnitService"),"fetchFixRawData",[gs.gp(row,"_id"), function(data) { gs.sp(gSobject.self,"rawJsonLoading",false); if (gs.bool(data)) { return gs.sp(gSobject.self,"rawJsonContent",gs.mc(gs.fs('JSON', this, gSobject),"stringify",[data, null, 2])); } else { return gs.sp(gSobject.self,"rawJsonContent","No raw data found for this fix."); }; }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function PinchToZoomHandler() { var gSobject = gs.init('PinchToZoomHandler'); gSobject.clazz = { name: 'PinchToZoomHandler', simpleName: 'PinchToZoomHandler'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.addPinchToZoomById = function(x0) { return PinchToZoomHandler.addPinchToZoomById(x0); } gSobject.addPinchToZoomByElement = function(x0) { return PinchToZoomHandler.addPinchToZoomByElement(x0); } gSobject.addPinchToZoomToPdf = function(x0) { return PinchToZoomHandler.addPinchToZoomToPdf(x0); } gSobject['PinchToZoomHandler2'] = function(id, type) { if (gs.equals(type, "pdf")) { return PinchToZoomHandler.addPinchToZoomToPdf(id); }; PinchToZoomHandler.addPinchToZoomById(id); return this; } if (arguments.length==2) {gSobject.PinchToZoomHandler2(arguments[0], arguments[1]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; PinchToZoomHandler.addPinchToZoomById = function(id) { new PinchZoom(document.getElementById(id)); } PinchToZoomHandler.addPinchToZoomByElement = function(element) { new PinchZoom(element); } PinchToZoomHandler.addPinchToZoomToPdf = function(id) { let canvasList = document.getElementById(id).children for (let canvas of canvasList) { PinchToZoomHandler.addPinchToZoomByElement(canvas); } } function CordovaBle() { var gSobject = gs.init('CordovaBle'); gSobject.clazz = { name: 'CordovaBle', simpleName: 'CordovaBle'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'singletonInstance', { get: function() { return CordovaBle.singletonInstance; }, set: function(gSval) { CordovaBle.singletonInstance = gSval; }, enumerable: true }); gSobject.initialized = false; gSobject.scanning = false; gSobject.discoveredDevices = gs.map(); gSobject.connectedDevices = gs.map(); gSobject.instance = function() { return CordovaBle.instance(); } gSobject['initialize'] = function(callback, params) { if (callback === undefined) callback = function(it) { }; if (params === undefined) params = gs.map().add("request",true).add("statusReceiver",false); if (!gs.bool(CordovaBle.bleInstalled())) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBle: bluetoothle not installed"]); gs.execCall(callback, this, [gs.map().add("status","unavailable")]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"initialize",[function(result) { gSobject.initialized = (gs.equals(gs.gp(result,"status"), "enabled")); return gs.execCall(callback, this, [result]); }, params]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBle.initialize error: " + (gs.fs('e', this, gSobject)) + ""]); gs.execCall(callback, this, [gs.map().add("status","error").add("message","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['isEnabled'] = function(callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map().add("isEnabled",false)]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"isEnabled",[callback]); } catch (e) { gs.execCall(callback, this, [gs.map().add("isEnabled",false)]); } ; return this; } gSobject['enable'] = function(success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(error, this, [gs.map().add("message","BLE not installed")]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"enable",[success, error]); } catch (e) { gs.execCall(error, this, [gs.map().add("message","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['startScan'] = function(onDevice, onError, params) { if (onDevice === undefined) onDevice = function(it) { }; if (onError === undefined) onError = function(it) { }; if (params === undefined) params = gs.map().add("services",gs.list([])).add("allowDuplicates",false); if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(onError, this, [gs.map().add("message","BLE not installed")]); return this; }; gSobject.discoveredDevices = gs.map(); gSobject.scanning = true; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"startScan",[function(result) { if (gs.equals(gs.gp(result,"status"), "scanStarted")) { return null; }; if (gs.equals(gs.gp(result,"status"), "scanResult")) { if (!gs.bool(gs.mc(gSobject.discoveredDevices,"containsKey",[gs.gp(result,"address")]))) { var dev = gs.map().add("name",gs.elvis(gs.bool(gs.gp(result,"name")) , gs.gp(result,"name") , "Unknown")).add("address",gs.gp(result,"address")).add("rssi",gs.gp(result,"rssi")); (gSobject.discoveredDevices[gs.gp(result,"address")]) = dev; return gs.execCall(onDevice, this, [dev]); }; }; }, function(e) { gSobject.scanning = false; return gs.execCall(onError, this, [e]); }, params]); } catch (e) { gSobject.scanning = false; gs.execCall(onError, this, [gs.map().add("message","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['stopScan'] = function(callback) { if (callback === undefined) callback = function(it) { }; if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"stopScan",[function(r) { gSobject.scanning = false; return gs.execCall(callback, this, [r]); }, function(e) { gSobject.scanning = false; return gs.execCall(callback, this, [gs.map().add("error",e)]); }]); } catch (e) { gSobject.scanning = false; gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['isScanning'] = function(callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map().add("isScanning",false)]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"isScanning",[callback]); } catch (e) { gs.execCall(callback, this, [gs.map().add("isScanning",gSobject.scanning)]); } ; return this; } gSobject['getAdapterInfo'] = function(callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"getAdapterInfo",[callback]); } catch (e) { gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['connect'] = function(address, onStatus, onError) { if (onStatus === undefined) onStatus = function(it) { }; if (onError === undefined) onError = function(it) { }; if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(onError, this, [gs.map().add("message","BLE not installed")]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"connect",[function(result) { if (gs.equals(gs.gp(result,"status"), "connected")) { (gSobject.connectedDevices[address]) = result; }; if (gs.equals(gs.gp(result,"status"), "disconnected")) { gs.mc(gSobject.connectedDevices,"remove",[address]); }; return gs.execCall(onStatus, this, [result]); }, onError, gs.map().add("address",address)]); } catch (e) { gs.execCall(onError, this, [gs.map().add("message","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['disconnect'] = function(address, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(error, this, [gs.map().add("message","BLE not installed")]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"disconnect",[function(r) { gs.mc(gSobject.connectedDevices,"remove",[address]); gs.mc(gs.fs('bluetoothle', this, gSobject),"close",[function(it) { }, function(it) { }, gs.map().add("address",address)]); return gs.execCall(success, this, [r]); }, error, gs.map().add("address",address)]); } catch (e) { gs.execCall(error, this, [gs.map().add("message","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['discoverServices'] = function(address, callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"discover",[callback, function(e) { return gs.execCall(callback, this, [gs.map().add("error",e)]); }, gs.map().add("address",address)]); } catch (e) { gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['read'] = function(address, service, characteristic, callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"read",[callback, function(e) { return gs.execCall(callback, this, [gs.map().add("error",e)]); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic)]); } catch (e) { gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['write'] = function(address, service, characteristic, value, callback) { if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"write",[callback, function(e) { return gs.execCall(callback, this, [gs.map().add("error",e)]); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic).add("value",value)]); } catch (e) { gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject['subscribe'] = function(address, service, characteristic, onNotify) { if (!gs.bool(CordovaBle.bleInstalled())) { return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"subscribe",[onNotify, function(e) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["subscribe error: " + (e) + ""]); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic)]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["subscribe: " + (gs.fs('e', this, gSobject)) + ""]); } ; return this; } gSobject['unsubscribe'] = function(address, service, characteristic, callback) { if (callback === undefined) callback = function(it) { }; if (!gs.bool(CordovaBle.bleInstalled())) { gs.execCall(callback, this, [gs.map()]); return this; }; try { gs.mc(gs.fs('bluetoothle', this, gSobject),"unsubscribe",[callback, function(e) { return gs.execCall(callback, this, [gs.map().add("error",e)]); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic)]); } catch (e) { gs.execCall(callback, this, [gs.map().add("error","" + (gs.fs('e', this, gSobject)) + "")]); } ; return this; } gSobject.bleInstalled = function() { return CordovaBle.bleInstalled(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaBle.instance = function(it) { if (!gs.bool(CordovaBle.singletonInstance)) { CordovaBle.singletonInstance = CordovaBle(); }; return CordovaBle.singletonInstance; } CordovaBle.bleInstalled = function() { return typeof window.bluetoothle !== 'undefined'; } CordovaBle.singletonInstance = null; function CordovaBiometrics() { var gSobject = gs.init('CordovaBiometrics'); gSobject.clazz = { name: 'CordovaBiometrics', simpleName: 'CordovaBiometrics'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.disableBackup = false; gSobject.requireStrongBiometrics = false; gSobject.storeKeyName = "com.i3"; gSobject['deviceHasBiometrics'] = function(onSuccess, onError, opts) { if (onError === undefined) onError = function(it) { }; if (opts === undefined) opts = gs.map().add("requireStrongBiometrics",gSobject.requireStrongBiometrics); return gs.mc(gs.fs('Fingerprint', this, gSobject),"isAvailable",[onSuccess, onError, opts]); } gSobject['showBiometricDialog'] = function(onSuccess, onError, params) { if (onError === undefined) onError = function(it) { }; if (params === undefined) params = gs.map().add("title","Biometric Sign On").add("description","Authenticate").add("subtitle","").add("disableBackup",gSobject.disableBackup).add("requireStrongBiometrics",gSobject.requireStrongBiometrics).add("keyName",gSobject.storeKeyName); return gs.mc(gs.fs('Fingerprint', this, gSobject),"show",[params, onSuccess, onError]); } gSobject['registerSecret'] = function(secret, onSuccess, onError, params) { if (onError === undefined) onError = function(it) { }; if (params === undefined) params = gs.map().add("description","Register new biometric").add("invalidateOnEnrollment",true).add("disableBackup",gSobject.disableBackup).add("keyName",gSobject.storeKeyName); gs.sp(params,"secret",secret); return gs.mc(gs.fs('Fingerprint', this, gSobject),"registerBiometricSecret",[params, onSuccess, onError]); } gSobject['loadSecret'] = function(onSuccess, onError, params) { if (onError === undefined) onError = function(it) { }; if (params === undefined) params = gs.map().add("description","Load biometrics").add("disableBackup",gSobject.disableBackup).add("keyName",gSobject.storeKeyName); return gs.mc(gs.fs('Fingerprint', this, gSobject),"loadBiometricSecret",[params, onSuccess, onError]); } gSobject['deleteSecret'] = function(onSuccess, onError, params) { if (onSuccess === undefined) onSuccess = function(it) { }; if (onError === undefined) onError = function(it) { }; if (params === undefined) params = gs.map().add("keyName",gSobject.storeKeyName); return gs.mc(gs.fs('Fingerprint', this, gSobject),"deleteBiometricSecret",[params, onSuccess, onError]); } gSobject.verifyBiometricsPlugin = function() { return CordovaBiometrics.verifyBiometricsPlugin(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaBiometrics.verifyBiometricsPlugin = function() { return ( window?.Fingerprint !== undefined) } function I3Input() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3Input', simpleName: 'I3Input'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("modelValue",gs.map().add("type",String).add("default","")).add("rules",gs.map().add("type",Array).add("default",gs.list([]))).add("mask",gs.map().add("type",String).add("default","")).add("beforeIcon",gs.map().add("type",String).add("default","")).add("prependIcon",gs.map().add("type",String).add("default","")).add("appendIcon",gs.map().add("type",String).add("default","")).add("afterIcon",gs.map().add("type",String).add("default","")).add("prependBtn",gs.map().add("type",String).add("default","")).add("appendBtn",gs.map().add("type",String).add("default","")); gSobject.defaults = gs.map().add("filled",true).add("dense",false).add("outlined",false).add("rounded",false).add("borderless",false).add("square",false).add("dense",true).add("debounce","500"); gSobject.validationRules = gs.map().add("ruleRequired",function(val) { return gs.mc(gSobject,"ruleRequired",[val]); }).add("ruleEmail",function(val) { return gs.mc(gSobject,"ruleEmail",[val]); }).add("rulePassword",function(val) { return gs.mc(gSobject,"rulePassword",[val]); }).add("rulePhone",function(val) { return gs.mc(gSobject,"rulePhone",[val]); }); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; var appConfig = gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig")) , gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig") , gs.map()); var config = (gs.gp(appConfig,"input") != null ? gs.gp(appConfig,"input") : gs.map()); var attrs = (gs.gp(self,"$attrs") != null ? gs.gp(self,"$attrs") : gs.map()); return gs.sp(self,"inputProps",gs.toJavascript(gs.plus((gs.plus(gSobject.defaults, config)), attrs))); } gSobject['update'] = function(val) { var self = this; gs.mc(self,"$emit",["update:modelValue", val]); return gs.mc(self,"$emit",["change"]); } gSobject['onAppendBtnClick'] = function(it) { var self = this; return gs.mc(self,"$emit",["append:click"]); } gSobject['onPrependBtnClick'] = function(it) { var self = this; return gs.mc(self,"$emit",["prepend:click"]); } gSobject['ruleRequired'] = function(val) { return (gs.mc(gs.mc(val,"toString",[], null, true),"trim",[], null, true) ? true : "Field Required"); } gSobject['ruleEmail'] = function(val) { var emailPattern = "^(?=[a-zA-Z0-9@._%+-]{6,254}$)[a-zA-Z0-9._%+-]{1,64}@(?:[a-zA-Z0-9-]{1,63}\.){1,8}[a-zA-Z]{2,63}$"; return (gs.exactMatch(val,emailPattern) ? true : "Invalid Email"); } gSobject['rulePassword'] = function(val) { return (gs.mc(gs.mc(gs.mc(val,"toString",[]),"trim",[]),"size",[]) >= 6 ? true : "Password Error Message"); } gSobject['rulePhone'] = function(val) { if (!gs.bool(gs.mc(gs.mc(val,"toString",[], null, true),"trim",[], null, true))) { return true; }; var cleaned = gs.mc(gs.mc(gs.mc(gs.mc(gs.mc(gs.mc(val,"toString",[]),"trim",[]),"replace",[" ", ""]),"replace",["-", ""]),"replace",["(", ""]),"replace",[")", ""]); if (gs.mc(cleaned,"startsWith",["+"])) { var digits = gs.mc(cleaned,"substring",[1]); return (gs.exactMatch(digits,/^[0-9]{7,15}$/) ? true : "Invalid Phone Number"); }; if (gs.mc(cleaned,"startsWith",["0"])) { return (gs.exactMatch(cleaned,/^[0-9]{10}$/) ? true : "Invalid Phone Number"); }; return "Invalid Phone Number"; } gSobject['calcRules'] = function(rules) { return (gs.bool(rules) ? gs.mc(rules,"collect",[function(ruleName) { return gSobject.validationRules[ruleName]; }]) : gs.list([])); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function UnitCarbonDioxideReadingsTab() { var gSobject = VueComponent(); gSobject.clazz = { name: 'UnitCarbonDioxideReadingsTab', simpleName: 'UnitCarbonDioxideReadingsTab'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("unitId",String); gSobject.self = null; gSobject.data = function(it) { return gs.map().add("sensorReadings",gs.list([])).add("highestCo2",null).add("lowestCo2",null).add("selectedTimeframe","5min").add("historyLabels",gs.list([])).add("historyDatasets",gs.list([])); }; gSobject['created'] = function(it) { gSobject.self = this; gs.mc(gSobject,"loadMeasurements",[]); return gs.mc(gSobject,"loadSampleHistoryData",[]); } gSobject['loadHistoryTimeframe'] = function(timeframe) { gs.sp(gSobject.self,"selectedTimeframe",timeframe); return gs.mc(gSobject,"loadSampleHistoryData",[]); } gSobject['loadSampleHistoryData'] = function(it) { var sampleByTimeframe = gs.map().add("5min",gs.map().add("labels",gs.list(["-5m" , "-4m" , "-3m" , "-2m" , "-1m" , "Now"])).add("datasets",gs.list([gs.list([620.0 , 622.0 , 619.0 , 621.0 , 623.0 , 621.0]) , gs.list([855.0 , 857.0 , 860.0 , 858.0 , 856.0 , 859.0]) , gs.list([510.0 , 512.0 , 511.0 , 513.0 , 510.0 , 512.0])]))).add("1hour",gs.map().add("labels",gs.list(["-60m" , "-50m" , "-40m" , "-30m" , "-20m" , "-10m" , "Now"])).add("datasets",gs.list([gs.list([610.0 , 613.0 , 616.0 , 618.0 , 620.0 , 621.0 , 621.0]) , gs.list([840.0 , 845.0 , 849.0 , 852.0 , 855.0 , 857.0 , 859.0]) , gs.list([500.0 , 503.0 , 506.0 , 508.0 , 510.0 , 511.0 , 512.0])]))).add("8hours",gs.map().add("labels",gs.list(["-8h" , "-7h" , "-6h" , "-5h" , "-4h" , "-3h" , "-2h" , "-1h" , "Now"])).add("datasets",gs.list([gs.list([580.0 , 588.0 , 595.0 , 601.0 , 607.0 , 612.0 , 616.0 , 619.0 , 621.0]) , gs.list([800.0 , 812.0 , 820.0 , 829.0 , 836.0 , 843.0 , 849.0 , 854.0 , 859.0]) , gs.list([476.0 , 483.0 , 489.0 , 494.0 , 499.0 , 504.0 , 507.0 , 510.0 , 512.0])]))).add("24hours",gs.map().add("labels",gs.list(["-24h" , "-21h" , "-18h" , "-15h" , "-12h" , "-9h" , "-6h" , "-3h" , "Now"])).add("datasets",gs.list([gs.list([540.0 , 552.0 , 562.0 , 571.0 , 579.0 , 588.0 , 597.0 , 610.0 , 621.0]) , gs.list([750.0 , 765.0 , 778.0 , 790.0 , 803.0 , 817.0 , 830.0 , 845.0 , 859.0]) , gs.list([445.0 , 455.0 , 463.0 , 471.0 , 479.0 , 487.0 , 495.0 , 503.0 , 512.0])]))); var selected = gs.elvis(sampleByTimeframe[gs.gp(gSobject.self,"selectedTimeframe")] , sampleByTimeframe[gs.gp(gSobject.self,"selectedTimeframe")] , sampleByTimeframe["5min"]); gs.sp(gSobject.self,"historyLabels",gs.gp(selected,"labels")); return gs.sp(gSobject.self,"historyDatasets",gs.gp(selected,"datasets")); } gSobject['loadMeasurements'] = function(it) { gs.println("CO2 unitId=" + (gs.gp(gSobject.self,"unitId")) + ""); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwMeasurementService"),"fetchLatestMeasurementsByType",[gs.gp(gSobject.self,"unitId"), "co2", function(result) { gs.println("CO2 result"); gs.println(result); var list = gs.elvis(gs.bool(result) , result , gs.list([])); var co2Values = gs.mc(gs.mc(list,"collect",[function(it) { return gs.gp(gs.gp(it,"data",true),"currentCo2",true); }]),"findAll",[function(value) { return value != null; }]); gs.sp(gSobject.self,"highestCo2",(gs.bool(co2Values) ? gs.mc(co2Values,"max",[]) : null)); gs.sp(gSobject.self,"lowestCo2",(gs.bool(co2Values) ? gs.mc(co2Values,"min",[]) : null)); gs.sp(gSobject.self,"sensorReadings",gs.mc(list,"collect",[function(it) { return gs.map().add("id",gs.gp(it,"_id",true)).add("sensorId",gs.gp(gs.gp(it,"sensor",true),"_id",true)).add("snoozed",gs.elvis(gs.bool(gs.gp(it,"snoozed",true)) , gs.gp(it,"snoozed",true) , false)).add("sensorName",gs.elvis(gs.bool(gs.gp(gs.gp(it,"sensor",true),"name",true)) , gs.gp(gs.gp(it,"sensor",true),"name",true) , "-")).add("currentCo2",gs.gp(gs.gp(it,"data",true),"currentCo2",true)).add("low",gs.gp(gs.gp(gs.gp(it,"sensorProfile",true),"profile",true),"low",true)).add("high",gs.gp(gs.gp(gs.gp(it,"sensorProfile",true),"profile",true),"high",true)).add("lowWarn",gs.gp(gs.gp(gs.gp(it,"sensorProfile",true),"profile",true),"lowWarn",true)).add("highWarn",gs.gp(gs.gp(gs.gp(it,"sensorProfile",true),"profile",true),"highWarn",true)); }])); gs.println("CO2 sensorReadings"); return gs.println(gs.gp(gSobject.self,"sensorReadings")); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CwBrowser() { var gSobject = gs.init('CwBrowser'); gSobject.clazz = { name: 'CwBrowser', simpleName: 'CwBrowser'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.reloadToRoot = function() { return CwBrowser.reloadToRoot(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CwBrowser.reloadToRoot = function() { console.log('[CwBrowser] reloadToRoot running, pathname=' + window.location.pathname); if (window.location.pathname === '/') { window.location.reload(); } else { window.location.href = '/'; } } function VueListSearchComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'VueListSearchComponent', simpleName: 'VueListSearchComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.toJavascript(gs.list(["value" , "onFilter" , "onSelect" , "label" , "options" , "outlined" , "filled" , "standout" , "borderless" , "square" , "dark" , "clearable" , "required" , "style" , "onLabel" , "optionLabel"])); gSobject.data = function(it) { var self = this; return gs.map().add("objectValue",gs.gp(self,"value")).add("optionsList",gs.list([])).add("initOptions",gs.gp(self,"options")).add("optionLabelValue",gs.elvis(gs.bool(gs.gp(self,"optionLabel")) , gs.gp(self,"optionLabel") , "name")); }; gSobject['mounted'] = function(it) { var self = this; } gSobject['watchValue'] = function(newValue, oldValue) { var self = this; return gs.sp(self,"objectValue",newValue); } gSobject['lookupObjects'] = function(val, update, abort) { if (val === undefined) val = null; if (update === undefined) update = function(it) { return gs.execCall(it, this, []); }; if (abort === undefined) abort = null; var self = this; if (gs.bool(gs.gp(self,"options"))) { gs.execCall(update, this, [function(it) { gs.sp(self,"optionsList",gs.gp(self,"options")); return gs.mc(gSobject,"configLabel",[self]); }]); return null; }; return gs.mc(self,"onFilter",[val, function(dbOptionsList) { return gs.execCall(update, this, [function(it) { gs.sp(self,"optionsList",dbOptionsList); return gs.mc(gSobject,"configLabel",[self]); }]); }]); } gSobject['configLabel'] = function(self) { if (gs.bool(gs.gp(self,"onLabel"))) { return gs.sp(self,"optionLabel",gs.gp(self,"onLabel")); }; } gSobject['objectSelected'] = function(it) { var self = this; gs.mc(self,"$emit",["input", gs.gp(self,"objectValue")]); if (gs.bool(gs.gp(self,"onSelect"))) { return gs.mc(self,"onSelect",[gs.gp(self,"objectValue")]); }; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3SidePanel() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3SidePanel', simpleName: 'I3SidePanel'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("modelValue",gs.map().add("type",String)).add("position",gs.map().add("type",String).add("default","right")); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function UnitEventsTab() { var gSobject = VueComponent(); gSobject.clazz = { name: 'UnitEventsTab', simpleName: 'UnitEventsTab'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list(["unitId"]); gSobject.self = null; gSobject.pollingTimer = null; gSobject.data = function(it) { return gs.map().add("activeEvents",gs.list([])).add("activeEventsExpanded",true).add("eventExpandedMap",gs.map()).add("eventSearch","").add("selectedSeverity","all").add("selectedStatus","active").add("selectedSensorProfile","all").add("severityFilterOptions",gs.list([gs.map().add("label","All Severities").add("value","all") , gs.map().add("label","Alarms Only").add("value","alarm") , gs.map().add("label","Warnings Only").add("value","warning")])).add("statusFilterOptions",gs.list([gs.map().add("label","All Statuses").add("value","all") , gs.map().add("label","Active").add("value","active") , gs.map().add("label","Acknowledged").add("value","acknowledged") , gs.map().add("label","Snoozed").add("value","snoozed") , gs.map().add("label","Resolved").add("value","resolved") , gs.map().add("label","Auto-Resolved").add("value","system-auto-resolved")])).add("statusOptions",gs.list([gs.map().add("label","Acknowledged").add("value","acknowledged") , gs.map().add("label","Snoozed").add("value","snoozed") , gs.map().add("label","Resolved").add("value","resolved")])).add("resolvedEvents",gs.list([])).add("resolvedEventsExpanded",true).add("resolvedEventExpandedMap",gs.map()).add("resolvedEventLimit",25).add("resolvedEventLimitOptions",gs.list([gs.map().add("label","25 Events").add("value",25) , gs.map().add("label","50 Events").add("value",50) , gs.map().add("label","100 Events").add("value",100)])).add("skeletonRows",gs.list([1 , 2 , 3])).add("isLoading",false).add("canEdit",false); }; gSobject['created'] = function(it) { gSobject.self = this; if (gs.mc(gs.fs('session', this, gSobject),"hasRole",["ROLE_ADMIN"])) { gs.sp(gSobject.self,"canEdit",true); } else { gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwUserService"),"isUnitOrgAdmin",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gSobject.self,"unitId"), function(admin) { return gs.sp(gSobject.self,"canEdit",admin); }]); }; gs.mc(gSobject,"loadEvents",[]); return gSobject.pollingTimer = gs.execStatic(Utils,'setInterval', this,[function(it) { return gs.mc(gSobject,"loadEvents",[]); }, 60000]); } gSobject['destroyed'] = function(it) { return gs.execStatic(Utils,'clearInterval', this,[gSobject.pollingTimer]); } gSobject['loadEvents'] = function(it) { if (!gs.bool(gs.gp(gSobject.self,"unitId"))) { gs.mc(gSobject,"clearEvents",[]); gs.sp(gSobject.self,"isLoading",false); return null; }; gs.sp(gSobject.self,"isLoading",true); gs.mc(gSobject,"clearEvents",[]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwAlertService"),"fetchUnitEvents",[gs.gp(gSobject.self,"unitId"), gs.gp(gSobject.self,"resolvedEventLimit"), function(payload) { gs.sp(gSobject.self,"activeEvents",gs.elvis(gs.bool(gs.gp(payload,"activeEvents",true)) , gs.gp(payload,"activeEvents",true) , gs.list([]))); gs.sp(gSobject.self,"resolvedEvents",gs.elvis(gs.bool(gs.gp(payload,"resolvedEvents",true)) , gs.gp(payload,"resolvedEvents",true) , gs.list([]))); gs.mc(gSobject,"rebuildExpandedMaps",[]); return gs.sp(gSobject.self,"isLoading",false); }]); } gSobject['rebuildExpandedMaps'] = function(it) { var activeMap = gs.map(); gs.mc(gs.gp(gSobject.self,"activeEvents"),"each",[function(event) { return (activeMap[gs.gp(event,"_id")]) = gs.elvis(gs.gp(gSobject.self,"eventExpandedMap")[gs.gp(event,"_id")] , gs.gp(gSobject.self,"eventExpandedMap")[gs.gp(event,"_id")] , false); }]); gs.sp(gSobject.self,"eventExpandedMap",activeMap); var resolvedMap = gs.map(); gs.mc(gs.gp(gSobject.self,"resolvedEvents"),"each",[function(event) { return (resolvedMap[gs.gp(event,"_id")]) = (gs.mc(gs.gp(gSobject.self,"resolvedEventExpandedMap"),"containsKey",[gs.gp(event,"_id")]) ? gs.gp(gSobject.self,"resolvedEventExpandedMap")[gs.gp(event,"_id")] : false); }]); return gs.sp(gSobject.self,"resolvedEventExpandedMap",resolvedMap); } gSobject['clearEvents'] = function(it) { gs.sp(gSobject.self,"activeEvents",gs.list([])); gs.sp(gSobject.self,"eventExpandedMap",gs.map()); gs.sp(gSobject.self,"resolvedEvents",gs.list([])); return gs.sp(gSobject.self,"resolvedEventExpandedMap",gs.map()); } gSobject['formatEventDate'] = function(dateValue) { if (!gs.bool(dateValue)) { return ""; }; var date = (gs.instanceOf(dateValue, "Date") ? dateValue : gs.date(gs.mc(dateValue,"toString",[]))); return gs.mc(date,"format",["dd/MM/yyyy HH:mm"]); } gSobject['refreshEvents'] = function(it) { return gs.mc(gSobject,"loadEvents",[]); } gSobject['joinedEventSummary'] = function(it) { if (!gs.bool(gs.mc(gSobject,"filteredActiveEvents",[]))) { return ""; }; return gs.mc(gs.mc(gs.mc(gSobject,"filteredActiveEvents",[]),"collect",[function(it) { return gs.gp(it,"summary"); }]),"join",["; "]); } gSobject['activeSeverityCount'] = function(severity) { return gs.mc(gs.mc(gSobject,"filteredActiveEvents",[]),"count",[function(it) { return gs.equals(gs.mc(gSobject,"normalizedSeverity",[gs.gp(it,"severity",true)]), gs.mc(gSobject,"normalizedSeverity",[severity])); }]); } gSobject['activeLatestTimestamp'] = function(it) { var events = gs.mc(gs.mc(gSobject,"filteredActiveEvents",[]),"findAll",[function(it) { return gs.gp(it,"startedAt",true); }]); if (!gs.bool(events)) { return ""; }; var latestEvent = gs.mc(events,"max",[function(it) { return gs.gp(it,"startedAt"); }]); return (gs.bool(gs.gp(latestEvent,"startedAt",true)) ? gs.mc(gSobject,"formatEventDate",[gs.gp(latestEvent,"startedAt")]) : ""); } gSobject['filteredActiveEvents'] = function(it) { return gs.mc(gSobject,"applyEventFilters",[gs.elvis(gs.bool(gs.gp(gSobject.self,"activeEvents")) , gs.gp(gSobject.self,"activeEvents") , gs.list([])), false]); } gSobject['filteredAllEvents'] = function(it) { var actives = gs.mc(gs.mc(gSobject,"applyEventFilters",[gs.elvis(gs.bool(gs.gp(gSobject.self,"activeEvents")) , gs.gp(gSobject.self,"activeEvents") , gs.list([])), false]),"sort",[function(a, b) { var aDate = gs.elvis(gs.bool(gs.gp(a,"lastTriggeredAt",true)) , gs.gp(a,"lastTriggeredAt",true) , gs.elvis(gs.bool(gs.gp(a,"startedAt",true)) , gs.gp(a,"startedAt",true) , gs.date(0))); var bDate = gs.elvis(gs.bool(gs.gp(b,"lastTriggeredAt",true)) , gs.gp(b,"lastTriggeredAt",true) , gs.elvis(gs.bool(gs.gp(b,"startedAt",true)) , gs.gp(b,"startedAt",true) , gs.date(0))); return gs.mc(bDate,"compareTo",[aDate]); }]); var resolveds = gs.mc(gs.mc(gSobject,"applyEventFilters",[gs.elvis(gs.bool(gs.gp(gSobject.self,"resolvedEvents")) , gs.gp(gSobject.self,"resolvedEvents") , gs.list([])), false]),"sort",[function(a, b) { var aDate = gs.elvis(gs.bool(gs.gp(a,"resolvedAt",true)) , gs.gp(a,"resolvedAt",true) , gs.elvis(gs.bool(gs.gp(a,"startedAt",true)) , gs.gp(a,"startedAt",true) , gs.date(0))); var bDate = gs.elvis(gs.bool(gs.gp(b,"resolvedAt",true)) , gs.gp(b,"resolvedAt",true) , gs.elvis(gs.bool(gs.gp(b,"startedAt",true)) , gs.gp(b,"startedAt",true) , gs.date(0))); return gs.mc(bDate,"compareTo",[aDate]); }]); return gs.plus(actives, resolveds); } gSobject['filteredActiveCount'] = function(it) { return gs.mc(gs.mc(gSobject,"filteredActiveEvents",[]),"size",[]); } gSobject['sensorProfileFilterOptions'] = function(it) { var options = gs.list([gs.map().add("label","All Sensor Profiles").add("value","all")]); var seen = gs.set(gs.list([])); gs.mc(gs.plus(gs.elvis(gs.bool(gs.gp(gSobject.self,"activeEvents")) , gs.gp(gSobject.self,"activeEvents") , gs.list([])), gs.elvis(gs.bool(gs.gp(gSobject.self,"resolvedEvents")) , gs.gp(gSobject.self,"resolvedEvents") , gs.list([]))),"each",[function(event) { var name = gs.mc(gs.mc(gs.gp(gs.gp(event,"sensorProfile",true),"name",true),"toString",[], null, true),"trim",[], null, true); if ((!gs.bool(name)) || (gs.mc(seen,"contains",[name]))) { return null; }; gs.mc(seen,'leftShift', gs.list([name])); return gs.mc(options,'leftShift', gs.list([gs.map().add("label",name).add("value",name)])); }]); return gs.mc(options,"sort",[function(a, b) { if (gs.equals(gs.gp(a,"value"), "all")) { return -1; }; if (gs.equals(gs.gp(b,"value"), "all")) { return 1; }; return gs.spaceShip(gs.gp(a,"label"), gs.gp(b,"label")); }]); } gSobject['filteredResolvedCount'] = function(it) { return gs.mc(gs.mc(gSobject,"applyEventFilters",[gs.elvis(gs.bool(gs.gp(gSobject.self,"resolvedEvents")) , gs.gp(gSobject.self,"resolvedEvents") , gs.list([])), false]),"size",[]); } gSobject['isSensorProfileFilterActive'] = function(it) { return (gs.bool(gs.gp(gSobject.self,"selectedSensorProfile"))) && (gs.gp(gSobject.self,"selectedSensorProfile") != "all"); } gSobject['everyLastUpdatedBySystem'] = function(it) { var events = gs.mc(gSobject,"filteredAllEvents",[]); if (!gs.bool(events)) { return true; }; return gs.mc(events,"every",[function(event) { var actor = gs.mc(gs.mc(gs.mc(gs.elvis(gs.mc(gSobject,"latestLogSummary",[event]) , gs.mc(gSobject,"latestLogSummary",[event]) , ""),"toString",[]),"trim",[]),"toLowerCase",[]); return (!gs.bool(actor)) || (gs.equals(actor, "system")); }]); } gSobject['formatOpenFor'] = function(fromDate) { if (!gs.bool(fromDate)) { return ""; }; var from = (gs.instanceOf(fromDate, "Date") ? fromDate : gs.date(gs.mc(fromDate,"toString",[]))); var diffMs = gs.minus(gs.gp(gs.date(),"time"), gs.gp(from,"time")); if (diffMs < 0) { diffMs = 0; }; var mins = Math.floor(gs.div(diffMs, 60000)); var days = Math.floor(gs.div(mins, 1440)); var hours = Math.floor(gs.div((gs.mod(mins, 1440)), 60)); var remMins = Math.floor(gs.mod(mins, 60)); if (days > 0) { return gs.mc("Open " + (days) + "d " + (hours) + "h","toString",[]); }; if (hours > 0) { return gs.mc("Open " + (hours) + "h " + (remMins) + "m","toString",[]); }; return gs.mc("Open " + (remMins) + "m","toString",[]); } gSobject['oldestActiveOpenFor'] = function(it) { var actives = gs.mc(gSobject,"filteredActiveEvents",[]); if (!gs.bool(actives)) { return ""; }; var oldest = gs.mc(gs.mc(actives,"findAll",[function(it) { return gs.gp(it,"startedAt",true); }]),"sort",[function(a, b) { return gs.spaceShip(gs.gp(a,"startedAt"), gs.gp(b,"startedAt")); }])[0]; return (gs.bool(oldest) ? gs.mc(gSobject,"formatOpenFor",[gs.gp(oldest,"startedAt")]) : ""); } gSobject['openForLabel'] = function(event) { if ((!gs.bool(event)) || (gs.bool(gs.gp(event,"isResolved")))) { return ""; }; return gs.mc(gSobject,"formatOpenFor",[gs.elvis(gs.bool(gs.gp(event,"startedAt")) , gs.gp(event,"startedAt") , gs.gp(event,"lastTriggeredAt"))]); } gSobject['isRecovering'] = function(event) { return ((gs.bool(event)) && (!gs.bool(gs.gp(event,"isResolved")))) && (gs.bool(gs.gp(event,"recoveringSince"))); } gSobject['recoveringLabel'] = function(event) { if (!gs.bool(gs.mc(gSobject,"isRecovering",[event]))) { return ""; }; var from = (gs.instanceOf(gs.gp(event,"recoveringSince"), "Date") ? gs.gp(event,"recoveringSince") : gs.date(gs.mc(gs.gp(event,"recoveringSince"),"toString",[]))); var diffMs = gs.minus(gs.gp(gs.date(),"time"), gs.gp(from,"time")); if (diffMs < 0) { diffMs = 0; }; var mins = Math.floor(gs.div(diffMs, 60000)); if (mins < 60) { return gs.mc("Recovering " + (mins) + "m","toString",[]); }; var hours = Math.floor(gs.div(mins, 60)); var remMins = Math.floor(gs.mod(mins, 60)); return gs.mc("Recovering " + (hours) + "h " + (remMins) + "m","toString",[]); } gSobject['filteredEventCount'] = function(it) { return gs.mc(gs.mc(gSobject,"filteredAllEvents",[]),"size",[]); } gSobject['visibleEvents'] = function(it) { return gs.mc(gSobject,"filteredAllEvents",[]); } gSobject['hasAnyEvents'] = function(it) { return (gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.self,"activeEvents")) , gs.gp(gSobject.self,"activeEvents") , gs.list([])),"size",[]) > 0) || (gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.self,"resolvedEvents")) , gs.gp(gSobject.self,"resolvedEvents") , gs.list([])),"size",[]) > 0); } gSobject['isEventExpanded'] = function(event) { if (!gs.bool(gs.gp(event,"_id",true))) { return false; }; return (gs.bool(gs.gp(event,"isResolved")) ? gs.elvis(gs.gp(gSobject.self,"resolvedEventExpandedMap")[gs.gp(event,"_id")] , gs.gp(gSobject.self,"resolvedEventExpandedMap")[gs.gp(event,"_id")] , false) : gs.elvis(gs.gp(gSobject.self,"eventExpandedMap")[gs.gp(event,"_id")] , gs.gp(gSobject.self,"eventExpandedMap")[gs.gp(event,"_id")] , false)); } gSobject['setEventExpanded'] = function(event, expanded) { if (!gs.bool(gs.gp(event,"_id",true))) { return null; }; if (gs.bool(gs.gp(event,"isResolved"))) { return gs.sp(gSobject.self,"resolvedEventExpandedMap",(gs.plus(gs.gp(gSobject.self,"resolvedEventExpandedMap"), gs.map().add(gs.gp(event,"_id"),expanded)))); } else { return gs.sp(gSobject.self,"eventExpandedMap",(gs.plus(gs.gp(gSobject.self,"eventExpandedMap"), gs.map().add(gs.gp(event,"_id"),expanded)))); }; } gSobject['hasActiveFilters'] = function(it) { return (((gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.self,"eventSearch")) , gs.gp(gSobject.self,"eventSearch") , ""),"trim",[])) || (gs.gp(gSobject.self,"selectedSeverity") != "all")) || (gs.gp(gSobject.self,"selectedStatus") != "all")) || (gs.gp(gSobject.self,"selectedSensorProfile") != "all"); } gSobject['resetFilters'] = function(it) { gs.sp(gSobject.self,"eventSearch",""); gs.sp(gSobject.self,"selectedSeverity","all"); gs.sp(gSobject.self,"selectedStatus","all"); return gs.sp(gSobject.self,"selectedSensorProfile","all"); } gSobject['applyEventFilters'] = function(events, resolvedView) { var searchText = gs.mc(gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(gSobject.self,"eventSearch")) , gs.gp(gSobject.self,"eventSearch") , ""),"toString",[]),"trim",[]),"toLowerCase",[]); return gs.mc(gs.elvis(gs.bool(events) , events , gs.list([])),"findAll",[function(event) { var severity = gs.mc(gSobject,"normalizedSeverity",[gs.gp(event,"severity",true)]); var status = gs.mc(gSobject,"normalizedStatus",[event, resolvedView]); var sensorProfileName = gs.elvis(gs.mc(gs.mc(gs.gp(gs.gp(event,"sensorProfile",true),"name",true),"toString",[], null, true),"trim",[], null, true) , gs.mc(gs.mc(gs.gp(gs.gp(event,"sensorProfile",true),"name",true),"toString",[], null, true),"trim",[], null, true) , ""); var haystack = gs.mc(gs.mc(gs.mc(gs.list([gs.gp(event,"summary",true) , gs.gp(gs.gp(event,"sensorProfile",true),"name",true) , gs.gp(event,"status",true) , gs.gp(event,"severity",true) , gs.gp(gs.mc(gs.gp(event,"eventLogs",true),"find",[function(it) { return gs.gp(it,"comment",true); }], null, true),"comment",true)]),"findAll",[function(it) { return it != null; }]),"collect",[function(it) { return gs.mc(gs.mc(it,"toString",[]),"toLowerCase",[]); }]),"join",[" "]); var matchesSearch = (!gs.bool(searchText)) || (gs.mc(haystack,"contains",[searchText])); var matchesSeverity = (gs.equals(gs.gp(gSobject.self,"selectedSeverity"), "all")) || (gs.equals(severity, gs.gp(gSobject.self,"selectedSeverity"))); var matchesStatus = (gs.equals(gs.gp(gSobject.self,"selectedStatus"), "all")) || (gs.equals(status, gs.gp(gSobject.self,"selectedStatus"))); var matchesSensorProfile = (gs.equals(gs.gp(gSobject.self,"selectedSensorProfile"), "all")) || (gs.equals(sensorProfileName, gs.gp(gSobject.self,"selectedSensorProfile"))); return (((gs.bool(matchesSearch)) && (gs.bool(matchesSeverity))) && (gs.bool(matchesStatus))) && (gs.bool(matchesSensorProfile)); }]); } gSobject['normalizedSeverity'] = function(severity) { return gs.mc(gs.mc(gs.elvis(gs.bool(severity) , severity , "warning"),"toString",[]),"toLowerCase",[]); } gSobject['normalizedStatus'] = function(event, resolvedView) { if (resolvedView === undefined) resolvedView = false; var raw = gs.mc(gs.mc(gs.elvis(gs.bool(gs.gp(event,"status",true)) , gs.gp(event,"status",true) , ""),"toString",[]),"toLowerCase",[]); if (gs.equals(raw, "system-auto-resolved")) { return "system-auto-resolved"; }; if ((gs.bool(resolvedView)) || (gs.bool(gs.gp(event,"isResolved",true)))) { return "resolved"; }; return gs.elvis(gs.bool(raw) , raw , "active"); } gSobject['severityChipColor'] = function(severity) { var gSswitch0 = gs.mc(gs.mc(gs.elvis(gs.bool(severity) , severity , ""),"toString",[]),"toLowerCase",[]); if (gs.equals(gSswitch0, "alarm")) { return "negative"; } else if (gs.equals(gSswitch0, "warning")) { return "warning"; } else { return "grey-7"; }; } gSobject['severityChipTextColor'] = function(severity, resolved) { if (resolved === undefined) resolved = false; if (gs.bool(resolved)) { return "white"; }; var gSswitch0 = gs.mc(gs.mc(gs.elvis(gs.bool(severity) , severity , ""),"toString",[]),"toLowerCase",[]); if (gs.equals(gSswitch0, "warning")) { return "grey-10"; } else { return "white"; }; } gSobject['severityIcon'] = function(severity) { var gSswitch0 = gs.mc(gs.mc(gs.elvis(gs.bool(severity) , severity , ""),"toString",[]),"toLowerCase",[]); if (gs.equals(gSswitch0, "alarm")) { return "o_error"; } else if (gs.equals(gSswitch0, "warning")) { return "o_warning_amber"; } else { return "o_notifications"; }; } gSobject['statusChipColor'] = function(status) { var gSswitch0 = gs.mc(gs.mc(gs.elvis(gs.bool(status) , status , ""),"toString",[]),"toLowerCase",[]); if (gs.equals(gSswitch0, "resolved")) { return "positive"; } else if (gs.equals(gSswitch0, "system-auto-resolved")) { return "blue-grey"; } else if (gs.equals(gSswitch0, "acknowledged")) { return "primary"; } else if (gs.equals(gSswitch0, "snoozed")) { return "deep-orange"; } else if (gs.equals(gSswitch0, "active")) { return "negative"; } else { return "grey-7"; }; } gSobject['expandLabel'] = function(expanded) { return (gs.bool(expanded) ? "Hide Details" : "View Details"); } gSobject['latestLogSummary'] = function(event) { var latestLog = ((gs.bool(gs.gp(event,"eventLogs",true))) && (gs.mc(gs.gp(event,"eventLogs"),"size",[]) > 0) ? gs.gp(event,"eventLogs")[0] : null); if (!gs.bool(latestLog)) { return ""; }; var actor = gs.elvis(gs.bool(gs.gp(latestLog,"userName")) , gs.gp(latestLog,"userName") , "System"); var status = gs.elvis(gs.bool(gs.gp(latestLog,"status")) , gs.gp(latestLog,"status") , "active"); return actor; } gSobject['currentEditorName'] = function(it) { return gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"name",true)) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"name",true) , gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"fullName",true)) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"fullName",true) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"email",true))); } gSobject['currentEditorOrgId'] = function(it) { return gs.gp(gs.fs('session', this, gSobject),"orgName",true); } gSobject['addEventLog'] = function(event) { var status = gs.mc(gs.mc(gs.gp(event,"logStatus"),"toString",[], null, true),"trim",[], null, true); var comment = gs.mc(gs.mc(gs.gp(event,"logComment"),"toString",[], null, true),"trim",[], null, true); if (!gs.bool(status)) { gs.mc(gSobject,"notify",["Select a status before adding an entry", "warning"]); return null; }; if (!gs.bool(comment)) { gs.mc(gSobject,"notify",["Comment required", "warning"]); return null; }; var logEntry = gs.map().add("timestamp",gs.date()).add("userName",gs.mc(gSobject,"currentEditorName",[])).add("status",status).add("comment",comment).add("orgId",gs.mc(gSobject,"currentEditorOrgId",[])); gs.sp(event,"eventLogs",(gs.plus(gs.list([logEntry]), gs.elvis(gs.bool(gs.gp(event,"eventLogs")) , gs.gp(event,"eventLogs") , gs.list([]))))); gs.sp(event,"logComment",""); var savePayload = gs.map().add("_id",gs.gp(event,"_id")).add("eventLogs",gs.gp(event,"eventLogs")).add("status",gs.mc(gSobject,"mapAlertStatus",[status])).add("acknowledged",gs.equals(status, "acknowledged")).add("isSnoozed",gs.equals(status, "snoozed")).add("isResolved",gs.equals(status, "resolved")).add("resolvedAt",(gs.equals(status, "resolved") ? gs.date() : null)).add("resolvedBy",(gs.equals(status, "resolved") ? gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"email",true)) , gs.gp(gs.gp(gs.fs('session', this, gSobject),"user"),"email",true) , gs.elvis(gs.mc(gSobject,"currentEditorName",[]) , gs.mc(gSobject,"currentEditorName",[]) , "user")) : null)); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwAlertService"),"updateAlertStatus",[savePayload, function(data) { gs.mc(gSobject,"notify",["Entry added"]); return gs.mc(gSobject,"refreshEvents",[]); }]); } gSobject['mapAlertStatus'] = function(logStatus) { var gSswitch0 = logStatus; if (gs.equals(gSswitch0, "resolved")) { return "resolved"; } else if (gs.equals(gSswitch0, "snoozed")) { return "snoozed"; } else if (gs.equals(gSswitch0, "acknowledged")) { return "acknowledged"; } else { return "active"; }; } gSobject['onResolvedLimitChanged'] = function(it) { return gs.mc(gSobject,"refreshEvents",[]); } gSobject['logIcon'] = function(logStatus) { var status = gs.mc(gs.mc(gs.elvis(gs.bool(logStatus) , logStatus , ""),"toString",[]),"toLowerCase",[]); return ((gs.equals(status, "new")) || (gs.equals(status, "triggered")) ? "o_warning" : "o_chat"); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function UnitSensorReadingsTab() { var gSobject = VueComponent(); gSobject.clazz = { name: 'UnitSensorReadingsTab', simpleName: 'UnitSensorReadingsTab'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("unitId",String); gSobject['created'] = function(it) { var self = this; gs.sp(gSobject.scope,"selectedSensorType","Temperature"); return gs.sp(gSobject.scope,"sensorTypeOptions",gs.list(["Temperature" , "Humidity" , "CO2" , "Digital I/O"])); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaContacts() { var gSobject = gs.init('CordovaContacts'); gSobject.clazz = { name: 'CordovaContacts', simpleName: 'CordovaContacts'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.findContacts = function(filterText, callback) { navigator.contacts.find( [ navigator.contacts.fieldType.phoneNumbers, navigator.contacts.fieldType.displayName, navigator.contacts.fieldType.name ], function(data) { callback(data); }, function(error) { console.log('Error finding contacts: ', error); }, { hasPhoneNumber: true, filter: filterText || '', } ); } gSobject.newContact = function(callback) { let contact = navigator.contacts.create(); callback(contact); } gSobject.saveContact = function(contact, callback) { contact.save( function(success) { console.log('CordovaContacts: Contact Saved: ', success); callback({status: true, message: 'Contact saved successfully', contact: success}); }, function(error) { console.log('CordovaContacts: Error Saving contacts: ', error); callback({status: false, message: 'Failed to save contact'}); } ); } gSobject.deleteContact = function(contact, callback) { contact.remove( function(success) { console.log('CordovaContacts: Contact Deleted: ', success); callback({status: true, message: 'Contact deleted successfully'}); }, function(error) { console.log('CordovaContacts: Failed to delete contact: ', error); callback({status: false, message: 'Failed to delete contact'}); } ); } gSobject.isAvailable = function() { return CordovaContacts.isAvailable(); } gSobject.getContactsInstance = function() { return CordovaContacts.getContactsInstance(); } gSobject['CordovaContacts0'] = function(it) { gs.mc(document,"addEventListener",["deviceReady", function(it) { if (!gs.bool(gs.mc(this,"isAvailable",[], gSobject))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova-plugin-contacts: Not Available"]); return null; } else { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova-plugin-contacts: Available"]); }; }]); return this; } if (arguments.length==0) {gSobject.CordovaContacts0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaContacts.isAvailable = function() { // Contacts plugin is not available if (!navigator.contacts) return false; else return true; } CordovaContacts.getContactsInstance = function() { return navigator.contacts; } function CordovaCalendar() { var gSobject = gs.init('CordovaCalendar'); gSobject.clazz = { name: 'CordovaCalendar', simpleName: 'CordovaCalendar'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['createEvent'] = function(title, location, notes, startDate, endDate, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeCreateEvent",[title, location, notes, startDate, endDate, success, error]); } gSobject['createEventInteractively'] = function(title, location, notes, startDate, endDate, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeCreateEventInteractively",[title, location, notes, startDate, endDate, success, error]); } gSobject['findEvent'] = function(title, location, notes, startDate, endDate, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeFindEvent",[title, location, notes, startDate, endDate, success, error]); } gSobject['deleteEvent'] = function(title, location, notes, startDate, endDate, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeDeleteEvent",[title, location, notes, startDate, endDate, success, error]); } gSobject['listCalendars'] = function(success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; return gs.mc(gSobject,"nativeListCalendars",[success, error]); } gSobject['openCalendar'] = function(date) { if (date === undefined) date = null; return gs.mc(gSobject,"nativeOpenCalendar",[date]); } gSobject.nativeCreateEvent = function(title, location, notes, startDate, endDate, success, error) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.createEvent(title, location, notes, startDate, endDate, success, error); } else { if (error) error('Calendar not available'); } } gSobject.nativeCreateEventInteractively = function(title, location, notes, startDate, endDate, success, error) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.createEventInteractively(title, location, notes, startDate, endDate, success, error); } else { if (error) error('Calendar not available'); } } gSobject.nativeFindEvent = function(title, location, notes, startDate, endDate, success, error) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.findEvent(title, location, notes, startDate, endDate, success, error); } else { if (success) success([]); } } gSobject.nativeDeleteEvent = function(title, location, notes, startDate, endDate, success, error) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.deleteEvent(title, location, notes, startDate, endDate, success, error); } else { if (error) error('Calendar not available'); } } gSobject.nativeListCalendars = function(success, error) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.listCalendars(success, error); } else { if (success) success([]); } } gSobject.nativeOpenCalendar = function(date) { if (window.plugins && window.plugins.calendar) { window.plugins.calendar.openCalendar(date); } } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AuditTrailComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'AuditTrailComponent', simpleName: 'AuditTrailComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject['created'] = function(it) { gs.sp(gSobject.scope,"events",gs.list([])); gs.sp(gSobject.scope,"loading",false); gs.sp(gSobject.scope,"selectedId",null); gs.sp(gSobject.scope,"selectedLabel",""); gs.sp(gSobject.scope,"trail",gs.list([])); gs.sp(gSobject.scope,"trailLoading",false); gs.sp(gSobject.scope,"eventColumns",gs.list([gs.map().add("name","when").add("label","Date").add("field","when").add("align","left").add("sortable",true) , gs.map().add("name","objectType").add("label","Type").add("field","objectType").add("align","left").add("sortable",true) , gs.map().add("name","objectLabel").add("label","Record").add("field","objectLabel").add("align","left").add("sortable",true) , gs.map().add("name","updatedBy").add("label","Updated By").add("field","updatedBy").add("align","left").add("sortable",true)])); gs.sp(gSobject.scope,"trailColumns",gs.list([gs.map().add("name","lastUpdated").add("label","Date").add("field","lastUpdated").add("align","left") , gs.map().add("name","updatedBy").add("label","Updated By").add("field","updatedBy").add("align","left") , gs.map().add("name","propertyName").add("label","Property").add("field","propertyName").add("align","left") , gs.map().add("name","oldValue").add("label","Before").add("field","oldValue").add("align","left") , gs.map().add("name","newValue").add("label","After").add("field","newValue").add("align","left")])); gs.sp(gSobject.scope,"pagination",gs.map().add("rowsPerPage",15).add("sortBy","when").add("descending",true)); return gs.mc(gSobject,"loadRecent",[]); } gSobject['activated'] = function(it) { gs.mc(gSobject,"clearTrail",[]); return gs.mc(gSobject,"loadRecent",[]); } gSobject['loadRecent'] = function(it) { gs.sp(gSobject.scope,"loading",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwAuditService"),"recentUnitAudit",[gs.map().add("limit",200), function(events) { gs.sp(gSobject.scope,"loading",false); return gs.sp(gSobject.scope,"events",gs.elvis(gs.bool(events) , events , gs.list([]))); }]); } gSobject['openTrail'] = function(row) { if ((!gs.bool(row)) || (!gs.bool(gs.gp(row,"objectId")))) { return null; }; gs.sp(gSobject.scope,"selectedId",gs.gp(row,"objectId")); gs.sp(gSobject.scope,"selectedLabel",gs.elvis(gs.bool(gs.gp(row,"objectLabel")) , gs.gp(row,"objectLabel") , gs.gp(row,"objectId"))); gs.sp(gSobject.scope,"trail",gs.list([])); gs.sp(gSobject.scope,"trailLoading",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwAuditService"),"unitAuditTrail",[gs.gp(row,"objectId"), function(trail) { gs.sp(gSobject.scope,"trailLoading",false); return gs.sp(gSobject.scope,"trail",gs.elvis(gs.bool(trail) , trail , gs.list([]))); }]); } gSobject['clearTrail'] = function(it) { gs.sp(gSobject.scope,"selectedId",null); gs.sp(gSobject.scope,"selectedLabel",""); return gs.sp(gSobject.scope,"trail",gs.list([])); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaGoogleSignIn() { var gSobject = gs.init('CordovaGoogleSignIn'); gSobject.clazz = { name: 'CordovaGoogleSignIn', simpleName: 'CordovaGoogleSignIn'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.googleSignIn = function(success, error) { // Try new i3 plugin first, fall back to old plugin if (cordova.plugins.i3GoogleSignIn) { cordova.plugins.i3GoogleSignIn.login(function(authData) { success(authData); }, function(err) { if (error) error(err); }); } else if (cordova.plugins.GoogleSignInPlugin) { cordova.plugins.GoogleSignInPlugin.signIn(function(authData) { success(authData); }, function(err) { if (error) error(err); }); } else { if (error) error('No Google Sign-In plugin available'); } } gSobject.isSignedIn = function(success, error) { if (cordova.plugins.GoogleSignInPlugin && cordova.plugins.GoogleSignInPlugin.isSignedIn) { cordova.plugins.GoogleSignInPlugin.isSignedIn(function(result) { success(result); }, function(err) { if (error) error(err); }); } else { success({isSignedIn: false}); } } gSobject.signOut = function(success, error) { if (cordova.plugins.i3GoogleSignIn) { cordova.plugins.i3GoogleSignIn.logout(function(result) { if (success) success(result); }, function(err) { if (error) error(err); }); } else if (cordova.plugins.GoogleSignInPlugin) { cordova.plugins.GoogleSignInPlugin.signOut(function(result) { if (success) success(result); }, function(err) { if (error) error(err); }); } else { if (success) success(); } } gSobject.trySilentLogin = function(success, error) { if (cordova.plugins.i3GoogleSignIn) { cordova.plugins.i3GoogleSignIn.trySilentLogin(function(result) { success(result); }, function(err) { if (error) error(err); }); } else { if (error) error('Silent login not available'); } } gSobject.isAvailable = function() { return CordovaGoogleSignIn.isAvailable(); } gSobject['CordovaGoogleSignIn0'] = function(it) { gs.mc(document,"addEventListener",["deviceready", function(it) { if (!gs.bool(gs.mc(this,"isAvailable",[], gSobject))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["GoogleSignIn: Not Available"]); return null; } else { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["GoogleSignIn: Available"]); }; }]); return this; } if (arguments.length==0) {gSobject.CordovaGoogleSignIn0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaGoogleSignIn.isAvailable = function() { return !!(cordova.plugins.i3GoogleSignIn || cordova.plugins.GoogleSignInPlugin); } function I3PageHeader() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3PageHeader', simpleName: 'I3PageHeader'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("backBtn",Boolean); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; } gSobject['back'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function UnitIOReadingsTab() { var gSobject = VueComponent(); gSobject.clazz = { name: 'UnitIOReadingsTab', simpleName: 'UnitIOReadingsTab'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("unitId",String); gSobject.self = this; gSobject.data = function(it) { return gs.map().add("isLoading",false).add("isSeeding",false).add("digitalIOReadings",gs.list([])); }; gSobject['created'] = function(it) { gs.println("[UnitIOReadingsTab] created unitId=" + (gs.gp(gSobject.self,"unitId")) + ""); return gs.mc(gSobject,"refreshReadings",[]); } gSobject['activated'] = function(it) { gs.println("[UnitIOReadingsTab] activated unitId=" + (gs.gp(gSobject.self,"unitId")) + ""); return gs.mc(gSobject,"refreshReadings",[]); } gSobject['refreshReadings'] = function(it) { gs.println("[UnitIOReadingsTab] refreshReadings unitId=" + (gs.gp(gSobject.self,"unitId")) + ""); if (!gs.bool(gs.gp(gSobject.self,"unitId"))) { gs.println("[UnitIOReadingsTab] no unitId; clearing rows"); gs.sp(gSobject.self,"digitalIOReadings",gs.list([])); gs.sp(gSobject.self,"isLoading",false); return null; }; gs.sp(gSobject.self,"isLoading",true); if (!gs.bool(gs.gp(gs.gp(gs.fs('o', this, gSobject),"cwIoReadingsService"),"fetchUnitDigitalIOView",true))) { gs.sp(gSobject.self,"digitalIOReadings",gs.list([])); gs.sp(gSobject.self,"isLoading",false); gs.println("[UnitIOReadingsTab] cwIoReadingsService.fetchUnitDigitalIOView not available"); gs.mc(gSobject,"notify",["Digital I/O service is not available in this runtime", "warning"]); return null; }; try { gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwIoReadingsService"),"fetchUnitDigitalIOView",[gs.gp(gSobject.self,"unitId"), function(payload) { gs.sp(gSobject.self,"digitalIOReadings",gs.elvis(gs.bool(gs.gp(payload,"rows",true)) , gs.gp(payload,"rows",true) , gs.list([]))); gs.sp(gSobject.self,"isLoading",false); return gs.println("[UnitIOReadingsTab] fetch payload rows=" + (gs.mc(gs.gp(gSobject.self,"digitalIOReadings"),"size",[])) + " latestFixId=" + (gs.gp(gs.gp(payload,"latestFix",true),"fixId",true)) + ""); }]); } catch (all) { gs.sp(gSobject.self,"isLoading",false); gs.println("[UnitIOReadingsTab] refreshReadings error: " + (gs.fs('all', this, gSobject)) + ""); gs.mc(gSobject,"notify",["Failed to load digital I/O readings", "negative"]); } ; } gSobject['seedDemoReadings'] = function(it) { gs.println("[UnitIOReadingsTab] seedDemoReadings unitId=" + (gs.gp(gSobject.self,"unitId")) + ""); if (!gs.bool(gs.gp(gSobject.self,"unitId"))) { gs.println("[UnitIOReadingsTab] seed blocked: no unitId"); gs.mc(gSobject,"notify",["No unit selected for seeding", "warning"]); return null; }; if (!gs.bool(gs.gp(gs.gp(gs.fs('o', this, gSobject),"cwIoReadingsService"),"seedDemoFixesForUnit",true))) { gs.println("[UnitIOReadingsTab] cwIoReadingsService.seedDemoFixesForUnit not available"); gs.mc(gSobject,"notify",["Demo seed service is not available in this runtime", "warning"]); return null; }; try { gs.sp(gSobject.self,"isSeeding",true); gs.mc(gs.gp(gs.fs('o', this, gSobject),"cwIoReadingsService"),"seedDemoFixesForUnit",[gs.gp(gSobject.self,"unitId"), true, function(data) { gs.sp(gSobject.self,"isSeeding",false); var seeded = gs.elvis(gs.bool(gs.gp(data,"seeded",true)) , gs.gp(data,"seeded",true) , 0); gs.println("[UnitIOReadingsTab] seed callback seeded=" + (seeded) + " totalRows=" + (gs.gp(data,"totalRows",true)) + ""); gs.mc(gSobject,"notify",["Demo digital I/O readings seeded (" + (seeded) + ")"]); return gs.mc(gSobject,"refreshReadings",[]); }]); } catch (all) { gs.sp(gSobject.self,"isSeeding",false); gs.println("[UnitIOReadingsTab] seedDemoReadings error: " + (gs.fs('all', this, gSobject)) + ""); gs.mc(gSobject,"notify",["Failed to seed demo digital I/O readings", "negative"]); } ; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function MetricGraphComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'MetricGraphComponent', simpleName: 'MetricGraphComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.map().add("objectId",String).add("metricName",String).add("type",String); gSobject.data = function(it) { return gs.map().add("selectedPeriod","Day").add("timePeriod",gs.list([])); }; gSobject['created'] = function(it) { var self = this; gs.sp(self,"timePeriod",gs.list([gs.map().add("label","Hour").add("value","Hour") , gs.map().add("label","Day").add("value","Day") , gs.map().add("label","Month").add("value","Month")])); return gs.mc(gSobject,"loadGraph",[true, self]); } gSobject['watchObjectId'] = function(it) { return gs.mc(gSobject,"loadGraph",[true, this]); } gSobject['loadGraph'] = function(newGraph, self) { if (newGraph === undefined) newGraph = false; if (self === undefined) self = this; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"metricService"),"loadSelectedPeriodSeries",[gs.gp(self,"metricName"), gs.date(), gs.gp(self,"selectedPeriod"), gs.gp(self,"objectId"), function(data) { var rangeValues = gs.gp(data,"values"); if (gs.equals(gs.gp(self,"type"), "aggregated")) { rangeValues = gs.gp(data,"aggValues"); } else { if (gs.equals(gs.gp(self,"type"), "average")) { rangeValues = gs.gp(data,"avgValues"); }; }; if (gs.bool(newGraph)) { return gs.execStatic(MetricGraphComponent,'paintGraph', this,["graph", gs.gp(data,"labels"), rangeValues]); } else { return gs.execStatic(MetricGraphComponent,'updateData', this,["graph", gs.gp(data,"labels"), rangeValues]); }; }]); } gSobject.updateData = function(x0,x1,x2) { return MetricGraphComponent.updateData(x0,x1,x2); } gSobject.paintGraph = function(x0,x1,x2,x3) { return MetricGraphComponent.paintGraph(x0,x1,x2,x3); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; MetricGraphComponent.updateData = function(graphId, graphLabels, dataSet) { let chart = Chart.getChart(graphId); chart.data.datasets[0].data = gs.toJavascript(dataSet) chart.data.labels = gs.toJavascript(graphLabels) chart.update() } MetricGraphComponent.paintGraph = function(graphId, graphLabels, dataSet, type) { if (type === undefined) type = "line"; const oldChart = Chart.getChart(graphId) if (oldChart != undefined) oldChart.destroy() const data = { labels: gs.toJavascript(graphLabels), datasets: [{ data: gs.toJavascript(dataSet), borderColor: Quasar.getCssVar('primary'), tension: 0.1, }] } const options = { scales: { y: { beginAtZero:true, min:0 } }, plugins: { legend: { display: false } } } const config = { type: type, data: data, options: options, }; console.log('data', data) const myChart = new Chart( document.getElementById(graphId),config); } function DymicoAuthService() { var gSobject = gs.init('DymicoAuthService'); gSobject.clazz = { name: 'DymicoAuthService', simpleName: 'DymicoAuthService'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['auth'] = function(username, password, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"dymicoAuthService"),"authenticate",[username, password, function(authData) { gs.println("DymicoAuthService"); gs.println(authData); if (gs.bool(gs.gp(authData,"authenticated"))) { gs.execStatic(Utils,'updateAuthTokenToSession', this,[authData]); gs.sp(gs.fs('session', this, gSobject),"authToken",gs.gp(gs.gp(authData,"zoner"),"token")); return null; }; return gs.execCall(callback, this, [gs.gp(authData,"authenticated")]); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function I3Table() { var gSobject = VueComponent(); gSobject.clazz = { name: 'I3Table', simpleName: 'I3Table'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list([]); gSobject.data = function(it) { return gs.list([]); }; gSobject['created'] = function(it) { var self = this; } gSobject['onRequest'] = function(props) { if (props === undefined) props = gs.map(); var self = this; gs.mc(self,"$emit",["paginate", gs.gp(props,"pagination")]); return gs.mc(self,"$emit",["update:pagination", gs.gp(props,"pagination")]); } gSobject['selectRow'] = function(evt, row, index) { var self = this; return gs.mc(self,"$emit",["select-row", gs.gp(row,"_id")]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaBgGps() { var gSobject = gs.init('CordovaBgGps'); gSobject.clazz = { name: 'CordovaBgGps', simpleName: 'CordovaBgGps'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'HIGH_ACCURACY', { get: function() { return CordovaBgGps.HIGH_ACCURACY; }, set: function(gSval) { CordovaBgGps.HIGH_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'BALANCED_ACCURACY', { get: function() { return CordovaBgGps.BALANCED_ACCURACY; }, set: function(gSval) { CordovaBgGps.BALANCED_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'LOW_ACCURACY', { get: function() { return CordovaBgGps.LOW_ACCURACY; }, set: function(gSval) { CordovaBgGps.LOW_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'PASSIVE_ACCURACY', { get: function() { return CordovaBgGps.PASSIVE_ACCURACY; }, set: function(gSval) { CordovaBgGps.PASSIVE_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'MEDIUM_ACCURACY', { get: function() { return CordovaBgGps.MEDIUM_ACCURACY; }, set: function(gSval) { CordovaBgGps.MEDIUM_ACCURACY = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'GEOFENCE_ENTER', { get: function() { return CordovaBgGps.GEOFENCE_ENTER; }, set: function(gSval) { CordovaBgGps.GEOFENCE_ENTER = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'GEOFENCE_EXIT', { get: function() { return CordovaBgGps.GEOFENCE_EXIT; }, set: function(gSval) { CordovaBgGps.GEOFENCE_EXIT = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'GEOFENCE_DWELL', { get: function() { return CordovaBgGps.GEOFENCE_DWELL; }, set: function(gSval) { CordovaBgGps.GEOFENCE_DWELL = gSval; }, enumerable: true }); gSobject.lastLocation = null; gSobject.started = false; gSobject.compassHeading = 0; gSobject.acceleration = gs.map().add("x",0).add("y",0).add("z",0); gSobject.linearAccel = gs.map().add("x",0).add("y",0).add("z",0); gSobject.motionMagnitude = 0; gSobject.isMoving = false; gSobject.motionState = "unknown"; Object.defineProperty(gSobject, 'STILL_SPEED', { get: function() { return CordovaBgGps.STILL_SPEED; }, set: function(gSval) { CordovaBgGps.STILL_SPEED = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'FAST_SPEED', { get: function() { return CordovaBgGps.FAST_SPEED; }, set: function(gSval) { CordovaBgGps.FAST_SPEED = gSval; }, enumerable: true }); gSobject.lastSpeedMps = null; Object.defineProperty(gSobject, 'STILL_THRESHOLD', { get: function() { return CordovaBgGps.STILL_THRESHOLD; }, set: function(gSval) { CordovaBgGps.STILL_THRESHOLD = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'MOVING_THRESHOLD', { get: function() { return CordovaBgGps.MOVING_THRESHOLD; }, set: function(gSval) { CordovaBgGps.MOVING_THRESHOLD = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'FAST_THRESHOLD', { get: function() { return CordovaBgGps.FAST_THRESHOLD; }, set: function(gSval) { CordovaBgGps.FAST_THRESHOLD = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'singletonInstance', { get: function() { return CordovaBgGps.singletonInstance; }, set: function(gSval) { CordovaBgGps.singletonInstance = gSval; }, enumerable: true }); gSobject.compassListening = false; gSobject.accelListening = false; gSobject.onMotionStateCallback = function(it) { }; gSobject.onLocationCallback = function(it) { }; gSobject.onStationaryCallback = function(it) { }; gSobject.onActivityCallback = function(it) { }; gSobject.onGeofenceCallback = function(it) { }; gSobject.onErrorCallback = function(it) { }; gSobject.defaultConfig = gs.map().add("debug",false).add("desiredAccuracy",CordovaBgGps.BALANCED_ACCURACY).add("notificationTitle","GPS tracking").add("notificationText","Location tracking active").add("startOnBoot",false).add("stopOnTerminate",false); gSobject.currentConfig = gs.map(); gSobject.instance = function() { return CordovaBgGps.instance(); } gSobject['config'] = function(cfg) { gs.mc(gSobject.currentConfig,'leftShift', gs.list([cfg])); if (gs.mc(gSobject,"bgGeoDefined",[])) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"configure",[gSobject.currentConfig]); }; gs.mc(gSobject,"configureTelemetry",[]); return this; } gSobject['getConfig'] = function(it) { return gSobject.currentConfig; } gSobject['start'] = function(it) { if (!gs.bool(gs.mc(gSobject,"bgGeoDefined",[]))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: BackgroundGeolocation not available"]); return this; }; if (gs.bool(gSobject.started)) { return this; }; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"configure",[gSobject.currentConfig]); gs.mc(gSobject,"configureTelemetry",[]); gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"start",[]); gSobject.started = true; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: started"]); return this; } gSobject['stop'] = function(it) { if (!gs.bool(gs.mc(gSobject,"bgGeoDefined",[]))) { return this; }; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"stop",[]); gSobject.started = false; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: stopped"]); return this; } gSobject['switchToHighAccuracy'] = function(it) { if (gs.mc(gSobject,"bgGeoDefined",[])) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"switchMode",[1]); }; return this; } gSobject['switchToBalanced'] = function(it) { if (gs.mc(gSobject,"bgGeoDefined",[])) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"switchMode",[0]); }; return this; } gSobject['getCurrentLocation'] = function(successCallback, failedCallback, config) { if (failedCallback === undefined) failedCallback = function(it) { }; if (config === undefined) config = gs.map(); var callbackWrapper = function(location) { var normalized = gs.mc(gSobject,"normalizeLocation",[location]); gSobject.lastLocation = normalized; return gs.execCall(successCallback, this, [normalized]); }; if (gs.mc(gSobject,"bgGeoDefined",[])) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"getCurrentLocation",[callbackWrapper, failedCallback, gs.mc(gs.map().add("enableHighAccuracy",true).add("maximumAge",gs.multiply((gs.multiply(4, 60)), 1000)).add("timeout",gs.multiply(60, 1000)),'leftShift', gs.list([config]))]); } else { if (gs.mc(gSobject,"navigatorGeoDefined",[])) { gs.mc(gs.gp(gs.fs('navigator', this, gSobject),"geolocation"),"getCurrentPosition",[function(position) { return gs.execCall(callbackWrapper, this, [gs.gp(position,"coords")]); }, failedCallback, gs.map().add("enableHighAccuracy",true).add("maximumAge",30000).add("timeout",30000)]); } else { gs.execCall(failedCallback, this, [gs.map().add("code",2).add("message","GPS not available")]); }; }; return this; } gSobject['onLocation'] = function(successCallback, failedCallback) { if (failedCallback === undefined) failedCallback = function(it) { }; gSobject.onLocationCallback = successCallback; gSobject.onErrorCallback = failedCallback; if (gs.mc(gSobject,"bgGeoDefined",[])) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["location", function(location) { var normalized = gs.mc(gSobject,"normalizeLocation",[location]); gSobject.lastLocation = normalized; return gs.mc(gSobject,"onLocationCallback",[normalized]); }]); }; return this; } gSobject['onStationary'] = function(stationaryCallback, failedCallback) { if (failedCallback === undefined) failedCallback = function(it) { }; gSobject.onStationaryCallback = stationaryCallback; if (gs.mc(gSobject,"bgGeoDefined",[])) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["stationary", function(location) { var normalized = gs.mc(gSobject,"normalizeLocation",[location]); gSobject.lastLocation = normalized; return gs.mc(gSobject,"onStationaryCallback",[normalized]); }]); }; return this; } gSobject['onActivity'] = function(activityCallback) { gSobject.onActivityCallback = activityCallback; if (gs.mc(gSobject,"bgGeoDefined",[])) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["activity", function(activity) { return gs.mc(gSobject,"onActivityCallback",[activity]); }]); }; return this; } gSobject['onMotionState'] = function(callback) { gSobject.onMotionStateCallback = callback; return this; } gSobject['isDeviceMoving'] = function(it) { return gSobject.isMoving; } gSobject['onError'] = function(errorCallback) { gSobject.onErrorCallback = errorCallback; if (gs.mc(gSobject,"bgGeoDefined",[])) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["error", function(error) { return gs.mc(gSobject,"onErrorCallback",[error]); }]); }; return this; } gSobject['addGeofence'] = function(fence) { if (!gs.bool(gs.mc(gSobject,"bgGeoDefined",[]))) { return this; }; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"addGeofence",[fence, function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: geofence added: " + (gs.gp(fence,"id")) + ""]); }, function(error) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: geofence error: " + (error) + ""]); }]); return this; } gSobject['addGeofences'] = function(fences) { if (!gs.bool(gs.mc(gSobject,"bgGeoDefined",[]))) { return this; }; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"addGeofences",[fences, function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: " + (gs.mc(fences,"size",[])) + " geofences added"]); }, function(error) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: geofences error: " + (error) + ""]); }]); return this; } gSobject['removeGeofence'] = function(id) { if (!gs.bool(gs.mc(gSobject,"bgGeoDefined",[]))) { return this; }; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"removeGeofence",[id]); return this; } gSobject['removeAllGeofences'] = function(it) { if (!gs.bool(gs.mc(gSobject,"bgGeoDefined",[]))) { return this; }; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"removeAllGeofences",[]); return this; } gSobject['getGeofences'] = function(callback) { if (!gs.bool(gs.mc(gSobject,"bgGeoDefined",[]))) { gs.execCall(callback, this, [gs.list([])]); return this; }; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"getGeofences",[callback]); return this; } gSobject['onGeofence'] = function(geofenceCallback) { gSobject.onGeofenceCallback = geofenceCallback; if (gs.mc(gSobject,"bgGeoDefined",[])) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["geofence", function(event) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: geofence event: " + (gs.gp(event,"fenceId")) + " " + (gs.gp(event,"transition")) + ""]); return gs.mc(gSobject,"onGeofenceCallback",[event]); }]); }; return this; } gSobject['getGeofenceEvents'] = function(callback) { if (!gs.bool(gs.mc(gSobject,"bgGeoDefined",[]))) { gs.execCall(callback, this, [gs.list([])]); return this; }; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"getGeofenceEvents",[callback]); return this; } gSobject['checkStatus'] = function(callback) { if (!gs.bool(gs.mc(gSobject,"bgGeoDefined",[]))) { gs.execCall(callback, this, [gs.map().add("isRunning",false)]); return this; }; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"checkStatus",[callback]); return this; } gSobject['getName'] = function(it) { return "CordovaBgGps"; } gSobject['sync'] = function(it) { return this; } gSobject['normalizeLocation'] = function(location) { if (gs.gp(location,"speed") != null) { gSobject.lastSpeedMps = gs.gp(location,"speed"); }; var speed = gs.gp(location,"speed"); if ((speed != null) && (speed < CordovaBgGps.STILL_SPEED)) { speed = 0; }; gSobject.motionState = gs.mc(gSobject,"classifyMotion",[]); gSobject.isMoving = (gSobject.motionState != "still"); return gs.map().add("fixId",gs.execStatic(Utils,'uuid', this,[])).add("provider",gs.elvis(gs.bool(gs.gp(location,"provider")) , gs.gp(location,"provider") , "gps")).add("unixTimeMs",gs.elvis(gs.bool(gs.gp(location,"time")) , gs.gp(location,"time") , gs.mc(gs.date(),"getTime",[]))).add("accuracy",gs.gp(location,"accuracy")).add("speed",speed).add("altitude",gs.gp(location,"altitude")).add("latitude",gs.gp(location,"latitude")).add("longitude",gs.gp(location,"longitude")).add("bearing",gs.elvis(gs.bool(gs.gp(location,"bearing")) , gs.gp(location,"bearing") , 0)).add("heading",gSobject.compassHeading).add("motionState",gSobject.motionState).add("motionMagnitude",gSobject.motionMagnitude).add("service","CordovaBgGps").add("user",gs.gp(gs.fs('session', this, gSobject),"userId")).add("uuid",gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device",true),"uuid",true)); } gSobject['persistLocation'] = function(location) { return location; } gSobject['configureTelemetry'] = function(it) { if (!gs.bool(gs.mc(gSobject,"telemetryDefined",[]))) { return null; }; try { gs.mc(gs.fs('DymicoTelemetry', this, gSobject),"configure",[gs.map().add("syncUrl",gs.plus(gs.mc(gSobject,"originUrl",[]), "/cordovaTelemetryApi/telemetry")).add("user",gs.gp(gs.fs('session', this, gSobject),"userId")).add("uuid",gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device",true),"uuid",true)).add("syncIntervalMs",30000)]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: configureTelemetry error: " + (gs.fs('e', this, gSobject)) + ""]); } ; } gSobject['getBufferStats'] = function(callback) { if ((gs.mc(gSobject,"telemetryDefined",[])) && (gs.mc(gSobject,"bgGeoDefined",[]))) { gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"getBufferStats",[callback]); } else { gs.execCall(callback, this, [gs.map().add("bound",false).add("unsynced",0)]); }; return this; } gSobject['flushSync'] = function(callback) { if (callback === undefined) callback = function(it) { }; if (gs.mc(gSobject,"telemetryDefined",[])) { gs.mc(gs.fs('DymicoTelemetry', this, gSobject),"flushNow",[callback]); }; return this; } gSobject['recentTelemetry'] = function(opts, callback) { if (gs.mc(gSobject,"telemetryDefined",[])) { gs.mc(gs.fs('DymicoTelemetry', this, gSobject),"query",[opts, callback]); } else { gs.execCall(callback, this, [gs.list([])]); }; return this; } gSobject['setupAuthorizationHandler'] = function(it) { if (!gs.bool(gs.mc(gSobject,"bgGeoDefined",[]))) { return null; }; gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["authorization", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: authorization status: " + (status) + ""]); if (status !== gs.gp(gs.fs('BackgroundGeolocation', this, gSobject),"AUTHORIZED")) { return gs.execStatic(Utils,'setTimeout', this,[function(it) { var showSettings = gs.mc(this,"confirm",["App requires location tracking permission. Would you like to open app settings?"], gSobject); if (gs.bool(showSettings)) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"showAppSettings",[]); }; }, 500]); }; }]); gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["foreground", function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: app foreground"]); }]); return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"on",["background", function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: app background"]); }]); } gSobject.bgGeoDefined = function() { return typeof BackgroundGeolocation !== 'undefined'; } gSobject.navigatorGeoDefined = function() { return typeof navigator !== 'undefined' && navigator.geolocation; } gSobject.telemetryDefined = function() { return typeof DymicoTelemetry !== 'undefined'; } gSobject.originUrl = function() { return (typeof window !== 'undefined' && window.location && window.location.origin) ? window.location.origin : ''; } gSobject['setupCompass'] = function(it) { if (gs.bool(gSobject.compassListening)) { return null; }; if (CordovaBgGps.deviceOrientationAvailable()) { var handler = function(event) { if (gs.gp(event,"webkitCompassHeading") != null) { return gSobject.compassHeading = Math.round(gs.gp(event,"webkitCompassHeading")); } else { if (gs.gp(event,"alpha") != null) { return gSobject.compassHeading = Math.round(gs.gp(event,"alpha")); }; }; }; gs.mc(gSobject,"addOrientationListener",[handler]); gSobject.compassListening = true; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: compass listener started"]); } else { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: DeviceOrientation API not available"]); }; } gSobject.addOrientationListener = function(handler) { // iOS 13+ requires explicit permission via user gesture if (typeof DeviceOrientationEvent.requestPermission === 'function') { // Defer: register a one-time touch handler to request permission var requestOnce = function() { document.removeEventListener('touchend', requestOnce); document.removeEventListener('click', requestOnce); DeviceOrientationEvent.requestPermission().then(function(state) { if (state === 'granted') { window.addEventListener('deviceorientation', handler, true); } }).catch(function() {}); }; document.addEventListener('touchend', requestOnce, { once: true }); document.addEventListener('click', requestOnce, { once: true }); } else { // Android and older iOS: just add the listener window.addEventListener('deviceorientationabsolute', handler, true); window.addEventListener('deviceorientation', handler, true); } } gSobject.deviceOrientationAvailable = function() { return CordovaBgGps.deviceOrientationAvailable(); } gSobject['classifyMotion'] = function(it) { if (gSobject.lastSpeedMps != null) { if (gSobject.lastSpeedMps < CordovaBgGps.STILL_SPEED) { return "still"; }; if (gSobject.lastSpeedMps < CordovaBgGps.FAST_SPEED) { return "moving"; }; return "fast"; }; if (gSobject.motionMagnitude < CordovaBgGps.STILL_THRESHOLD) { return "still"; }; if (gSobject.motionMagnitude < CordovaBgGps.MOVING_THRESHOLD) { return "moving"; }; return "fast"; } gSobject['setupAccelerometer'] = function(it) { if (gs.bool(gSobject.accelListening)) { return null; }; if (CordovaBgGps.deviceMotionAvailable()) { gs.mc(gSobject,"addMotionListener",[function(event) { if (gs.bool(gs.gp(event,"accelerationIncludingGravity"))) { gSobject.acceleration = gs.map().add("x",gs.elvis(gs.bool(gs.gp(gs.gp(event,"accelerationIncludingGravity"),"x")) , gs.gp(gs.gp(event,"accelerationIncludingGravity"),"x") , 0)).add("y",gs.elvis(gs.bool(gs.gp(gs.gp(event,"accelerationIncludingGravity"),"y")) , gs.gp(gs.gp(event,"accelerationIncludingGravity"),"y") , 0)).add("z",gs.elvis(gs.bool(gs.gp(gs.gp(event,"accelerationIncludingGravity"),"z")) , gs.gp(gs.gp(event,"accelerationIncludingGravity"),"z") , 0)); }; if (gs.bool(gs.gp(event,"acceleration"))) { gSobject.linearAccel = gs.map().add("x",gs.elvis(gs.bool(gs.gp(gs.gp(event,"acceleration"),"x")) , gs.gp(gs.gp(event,"acceleration"),"x") , 0)).add("y",gs.elvis(gs.bool(gs.gp(gs.gp(event,"acceleration"),"y")) , gs.gp(gs.gp(event,"acceleration"),"y") , 0)).add("z",gs.elvis(gs.bool(gs.gp(gs.gp(event,"acceleration"),"z")) , gs.gp(gs.gp(event,"acceleration"),"z") , 0)); }; var ax = gs.elvis(gs.bool(gs.gp(gSobject.linearAccel,"x")) , gs.gp(gSobject.linearAccel,"x") , 0); var ay = gs.elvis(gs.bool(gs.gp(gSobject.linearAccel,"y")) , gs.gp(gSobject.linearAccel,"y") , 0); var az = gs.elvis(gs.bool(gs.gp(gSobject.linearAccel,"z")) , gs.gp(gSobject.linearAccel,"z") , 0); gSobject.motionMagnitude = Math.sqrt(gs.plus((gs.plus((gs.multiply(ax, ax)), (gs.multiply(ay, ay)))), (gs.multiply(az, az)))); var prevState = gSobject.motionState; gSobject.motionState = gs.mc(gSobject,"classifyMotion",[]); gSobject.isMoving = (gSobject.motionState != "still"); if ((prevState != gSobject.motionState) && (gs.bool(gSobject.onMotionStateCallback))) { return gs.mc(gSobject,"onMotionStateCallback",[gs.map().add("state",gSobject.motionState).add("magnitude",gSobject.motionMagnitude)]); }; }]); gSobject.accelListening = true; return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: accelerometer listener started"]); } else { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBgGps: DeviceMotion API not available"]); }; } gSobject.addMotionListener = function(handler) { window.addEventListener('devicemotion', handler, true); } gSobject.deviceMotionAvailable = function() { return CordovaBgGps.deviceMotionAvailable(); } gSobject['CordovaBgGps0'] = function(it) { gs.mc(gSobject.currentConfig,'leftShift', gs.list([gSobject.defaultConfig])); gs.mc(gSobject,"setupAuthorizationHandler",[]); gs.mc(gSobject,"setupCompass",[]); gs.mc(gSobject,"setupAccelerometer",[]); return this; } if (arguments.length==0) {gSobject.CordovaBgGps0(); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaBgGps.instance = function(it) { if (!gs.bool(CordovaBgGps.singletonInstance)) { CordovaBgGps.singletonInstance = CordovaBgGps(); }; return CordovaBgGps.singletonInstance; } CordovaBgGps.deviceOrientationAvailable = function() { return typeof DeviceOrientationEvent !== 'undefined'; } CordovaBgGps.deviceMotionAvailable = function() { return typeof DeviceMotionEvent !== 'undefined'; } CordovaBgGps.HIGH_ACCURACY = 0; CordovaBgGps.BALANCED_ACCURACY = 100; CordovaBgGps.LOW_ACCURACY = 1000; CordovaBgGps.PASSIVE_ACCURACY = 10000; CordovaBgGps.MEDIUM_ACCURACY = 100; CordovaBgGps.GEOFENCE_ENTER = 1; CordovaBgGps.GEOFENCE_EXIT = 2; CordovaBgGps.GEOFENCE_DWELL = 4; CordovaBgGps.STILL_SPEED = 0.7; CordovaBgGps.FAST_SPEED = 6.0; CordovaBgGps.STILL_THRESHOLD = 0.3; CordovaBgGps.MOVING_THRESHOLD = 1.5; CordovaBgGps.FAST_THRESHOLD = 5.0; CordovaBgGps.singletonInstance = null; function CordovaProblemReporter() { var gSobject = VueComponent(); gSobject.clazz = { name: 'CordovaProblemReporter', simpleName: 'CordovaProblemReporter'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/reportProblem"; gSobject.roles = gs.list([]); gSobject['created'] = function(it) { gs.sp(gSobject.scope,"userMessage",""); gs.sp(gSobject.scope,"severity","normal"); gs.sp(gSobject.scope,"severities",gs.list(["low" , "normal" , "high" , "critical"])); gs.sp(gSobject.scope,"thumbnailUrl",""); gs.sp(gSobject.scope,"submitting",false); gs.sp(gSobject.scope,"captureCountdown",0); gs.sp(gSobject.scope,"hasCapture",false); gs.sp(gSobject.scope,"userId",gs.elvis(gs.bool(gs.gp(gs.fs('session', this, gSobject),"userId")) , gs.gp(gs.fs('session', this, gSobject),"userId") , "(anonymous)")); gs.sp(gSobject.scope,"deviceUuid",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"uuid",true)) , gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"uuid",true) , "")); gs.sp(gSobject.scope,"platform",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"platform",true)) , gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"platform",true) , "browser")); return gs.mc(gSobject,"loadPendingCapture",[]); } gSobject['loadPendingCapture'] = function(it) { var pending = gs.mc(gSobject,"nativeReadPendingBlob",[]); if ((gs.bool(pending)) && (gs.bool(gs.gp(pending,"blob")))) { gs.sp(gSobject.scope,"hasCapture",true); return gs.sp(gSobject.scope,"thumbnailUrl",gs.mc(gSobject,"nativeBlobToObjectUrl",[gs.gp(pending,"blob")])); }; } gSobject['captureWithCountdown'] = function(it) { gs.sp(gSobject.scope,"captureCountdown",3); return gs.mc(gSobject,"tick",[]); } gSobject['tick'] = function(it) { if (gs.gp(gSobject.scope,"captureCountdown") <= 0) { gs.mc(gSobject,"doCapture",[]); return null; }; return gs.execStatic(Utils,'setTimeout', this,[function(it) { gs.sp(gSobject.scope,"captureCountdown",(gs.minus(gs.gp(gSobject.scope,"captureCountdown"), 1))); return gs.mc(gSobject,"tick",[]); }, 1000]); } gSobject['doCapture'] = function(it) { return gs.mc(gs.fs('cordovaScreenCapture', this, gSobject),"capture",[function(blob, meta) { gs.mc(gSobject,"nativeStashBlob",[blob]); gs.sp(gSobject.scope,"hasCapture",true); return gs.sp(gSobject.scope,"thumbnailUrl",gs.mc(gSobject,"nativeBlobToObjectUrl",[blob])); }, function(err) { return gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Notify"),"create",[gs.map().add("type","negative").add("message","Capture failed: " + (err) + "")]); }]); } gSobject['submit'] = function(it) { if (gs.bool(gs.gp(gSobject.scope,"submitting"))) { return null; }; if (!gs.bool(gs.mc(gs.gp(gSobject.scope,"userMessage"),"trim",[], null, true))) { gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Notify"),"create",[gs.map().add("type","warning").add("message","Please describe the problem")]); return null; }; gs.sp(gSobject.scope,"submitting",true); var opts = gs.map().add("severity",gs.gp(gSobject.scope,"severity")); return gs.mc(gs.fs('cordovaScreenCapture', this, gSobject),"reportProblem",[gs.gp(gSobject.scope,"userMessage"), opts, function(reportId) { gs.sp(gSobject.scope,"submitting",false); gs.mc(gSobject,"nativeClearPendingBlob",[]); gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Notify"),"create",[gs.map().add("type","positive").add("message","Problem reported. Thanks!").add("actions",gs.list([gs.map().add("label","View").add("color","white").add("handler",function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/cordovaErrors"]); })]))]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); }, function(err) { gs.sp(gSobject.scope,"submitting",false); return gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Notify"),"create",[gs.map().add("type","negative").add("message","Failed to send: " + (err) + "")]); }]); } gSobject['cancel'] = function(it) { gs.mc(gSobject,"nativeClearPendingBlob",[]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); } gSobject.nativeReadPendingBlob = function() { return window._cwPendingReport || null; } gSobject.nativeStashBlob = function(blob) { window._cwPendingReport = { blob: blob, ts: Date.now() }; } gSobject.nativeClearPendingBlob = function() { if (window._cwPendingReport && window._cwPendingReport.thumbnailUrl) { try { URL.revokeObjectURL(window._cwPendingReport.thumbnailUrl); } catch(_) {} } window._cwPendingReport = null; } gSobject.nativeBlobToObjectUrl = function(blob) { try { return URL.createObjectURL(blob); } catch(e) { return ''; } } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaScreenCapture() { var gSobject = gs.init('CordovaScreenCapture'); gSobject.clazz = { name: 'CordovaScreenCapture', simpleName: 'CordovaScreenCapture'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['capture'] = function(success, error, opts) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; if (opts === undefined) opts = gs.map(); return gs.mc(gSobject,"nativeCaptureSvgToPng",[gs.elvis(gs.bool(gs.gp(opts,"maxWidth")) , gs.gp(opts,"maxWidth") , 1280), success, error]); } gSobject['openProblemReport'] = function(it) { return gs.mc(gSobject,"capture",[function(blob, meta) { gs.mc(gSobject,"nativeStashBlob",[blob]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/reportProblem"]); }, function(err) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",["openProblemReport: capture failed: " + (err) + ""]); gs.mc(gSobject,"nativeStashBlob",[null]); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/reportProblem"]); }]); } gSobject['reportProblem'] = function(userMessage, opts, success, error) { if (opts === undefined) opts = gs.map(); if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; var stashed = gs.mc(gSobject,"nativeReadStashedBlob",[]); if (gs.bool(stashed)) { gs.mc(gSobject,"uploadAndCreateReport",[userMessage, opts, stashed, gs.map().add("type","image/png").add("width",0).add("height",0).add("fallback",false), success, error]); return null; }; return gs.mc(gSobject,"capture",[function(blob, meta) { return gs.mc(gSobject,"uploadAndCreateReport",[userMessage, opts, blob, meta, success, error]); }, function(captureErr) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",["CordovaScreenCapture:reportProblem:capture failed: " + (captureErr) + ""]); return gs.mc(gSobject,"uploadAndCreateReport",[userMessage, opts, null, gs.map(), success, error]); }]); } gSobject['uploadAndCreateReport'] = function(userMessage, opts, blob, meta, success, error) { var report = gs.mc(gSobject,"buildReportContext",[userMessage, opts, meta]); gs.sp(report,"hasScreenshot",(blob != null)); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaService"),"userProblem",[gs.gp(gs.fs('session', this, gSobject),"userId"), gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"uuid"), report, function(result) { if (!gs.bool(gs.gp(result,"id",true))) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",["CordovaScreenCapture:reportProblem:userProblem returned no id"]); return gs.execCall(error, this, ["Failed to create problem report"]); }; if (!gs.bool(blob)) { return gs.execCall(success, this, [gs.gp(result,"id")]); }; return gs.execStatic(Utils,'post', this,[blob, "screenshot", "userError", gs.gp(result,"id"), function(uploadResult) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaScreenCapture:reportProblem:uploaded screenshot for " + (gs.gp(result,"id")) + ""]); return gs.execCall(success, this, [gs.gp(result,"id")]); }, function(uploadErr) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",["CordovaScreenCapture:reportProblem:screenshot upload failed: " + (uploadErr) + ""]); return gs.execCall(success, this, [gs.gp(result,"id")]); }]); }]); } gSobject['buildReportContext'] = function(userMessage, opts, meta) { var ctx = gs.mc(gSobject,"nativeGatherContext",[]); return gs.map().add("userMessage",gs.elvis(gs.bool(userMessage) , userMessage , "")).add("severity",gs.elvis(gs.bool(gs.gp(opts,"severity")) , gs.gp(opts,"severity") , "normal")).add("message",gs.elvis(gs.bool(userMessage) , userMessage , "(no description)")).add("route",gs.gp(ctx,"route")).add("pageTitle",gs.gp(ctx,"pageTitle")).add("appPath",gs.gp(ctx,"appPath")).add("viewport",gs.gp(ctx,"viewport")).add("orientation",gs.gp(ctx,"orientation")).add("locale",gs.gp(ctx,"locale")).add("tz",gs.gp(ctx,"tz")).add("consoleTail",gs.gp(ctx,"consoleTail")).add("routeHistory",gs.gp(ctx,"routeHistory")).add("userAgent",gs.gp(ctx,"userAgent")).add("platform",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"platform")) , gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"platform") , "browser")).add("appVersion",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"version")) , gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"version") , "")).add("appBuild",gs.elvis(gs.bool(gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"cordova")) , gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"cordova") , "")).add("clientReportedAt",gs.mc(gs.date(),"getTime",[])); } gSobject.nativeGatherContext = function() { var route = ''; var routeHistory = ''; try { if (window.vue && window.vue.router && window.vue.router.currentRoute) { route = window.vue.router.currentRoute.value ? window.vue.router.currentRoute.value.fullPath : window.vue.router.currentRoute.fullPath || ''; } } catch(e) {} try { if (window._cwRouteHistory) routeHistory = window._cwRouteHistory.slice(-5).join(' -> '); } catch(e) {} var tail = ''; try { if (window._cwConsoleTail) tail = window._cwConsoleTail.join('\n'); } catch(e) {} return { route : route, pageTitle : (typeof document !== 'undefined') ? (document.title || '') : '', appPath : (typeof window !== 'undefined' && window.location) ? window.location.pathname : '', viewport : (window.innerWidth + 'x' + window.innerHeight + ' @ ' + (window.devicePixelRatio || 1) + 'x'), orientation : (screen && screen.orientation) ? (screen.orientation.type || '') : '', locale : (navigator && navigator.language) ? navigator.language : '', tz : (Intl && Intl.DateTimeFormat) ? Intl.DateTimeFormat().resolvedOptions().timeZone : '', consoleTail : tail, routeHistory: routeHistory, userAgent : (navigator && navigator.userAgent) ? navigator.userAgent : '' }; } gSobject.nativeStashBlob = function(blob) { if (blob) window._cwPendingReport = { blob: blob, ts: Date.now() }; else window._cwPendingReport = null; } gSobject.nativeReadStashedBlob = function() { return window._cwPendingReport ? window._cwPendingReport.blob : null; } gSobject.nativeCaptureSvgToPng = function(maxWidth, success, error) { try { var node = document.documentElement; var w = Math.max(node.scrollWidth, document.body ? document.body.scrollWidth : 0, window.innerWidth); var h = Math.max(node.scrollHeight, document.body ? document.body.scrollHeight : 0, window.innerHeight); // Clone so we can inline computed styles without mutating the live DOM. var clone = node.cloneNode(true); // Strip