// DYMICO_TRANSPILER_V=v2-cleanroom1 source=convertGs-fallback runtime=dymicoAsset cacheTier=cold console.log("[DYMICO_TRANSPILER_V=v2-cleanroom1 source=convertGs-fallback runtime=dymicoAsset cacheTier=cold]"); 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 (gSobject.completed) { return callback(); } return gs.mc(gSobject.callbacks,"add",[callback]); } gSobject['runCallbacks'] = function(it) { gSobject.completed = true; return gs.mc(gSobject.callbacks,"each",[function(callback) { return callback(); }]); } 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 Session() { var gSobject = gs.init('Session'); gSobject.clazz = { name: 'Session', simpleName: 'Session'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.zonerRoleMap = gs.map(); 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['setProperty'] = function(name, value) { Session.sessionMap[name] = value; gs.execStatic(Session,"setSessionStorage", this,[name, value]); if (gs.equals(name, "zoner")) { Session.zoner = null; gSobject.zonerRoleMap = gs.map(); } } gSobject['getProperty'] = function(name) { if (!Session.sessionMap[name]) { var value = gs.execStatic(Session,"getSessionStorage", this,[name]); Session.sessionMap[name] = value; } return Session.sessionMap[name]; } gSobject['hasRole'] = function(roles) { if (!roles) { return true; } var result = gSobject.zonerRoleMap[roles]; if (!gs.equals(result, null)) { return result; } if (!Session.zoner) { Session.zoner = gs.mc(gSobject,"getProperty",["zoner"]); } if (!Session.zoner) { return false; } if (roles instanceof String) { result = gs.mc(gs.gp(Session.zoner,"roles"),"contains",[roles]); gSobject.zonerRoleMap[roles] = result; return result; } for (var role in roles) { if (gs.mc(gs.gp(Session.zoner,"roles"),"contains",[role])) { gSobject.zonerRoleMap[roles] = true; return true; } } gSobject.zonerRoleMap[roles] = false; return false; } gSobject['toString'] = function(it) { return gs.mc(Session.sessionMap,"toString",[]); } gSobject['clear'] = function() { localStorage.clear(); sessionStorage.removeItem('dymicoLoginLaunch'); }; if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; 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.instance = function() { if (!Session.self) { Session.self = Session(); } return Session.self; } Session.toJs = function() { return Session.sessionMap; } Session.sessionMap = gs.map(); Session.self = null; Session.zoner = null; 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.mc(Session,"instance",[]); 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['checkStartupAuth'] = function(it) { if (gs.mc(Utils,"getCookie",[gs.gp(Socket,"AUTH_TOKEN")])) { gs.println("Writing session auth to local storage:" + gs.mc(Utils,"getCookie",[gs.gp(Socket,"AUTH_TOKEN")])); gs.mc(gs.fs('localStorage', this, gSobject),"setItem",["authToken", "\"" + gs.mc(Utils,"getCookie",[gs.gp(Socket,"AUTH_TOKEN")]) + "\""]); } if (gs.mc(Utils,"getCookie",[gs.gp(Socket,"DEVICE_TOKEN")])) { gs.println("Writing device token to local storage:" + gs.mc(Utils,"getCookie",[gs.gp(Socket,"DEVICE_TOKEN")])); gs.mc(gs.fs('localStorage', this, gSobject),"setItem",["deviceToken", "\"" + gs.mc(Utils,"getCookie",[gs.gp(Socket,"DEVICE_TOKEN")]) + "\""]); } if (gs.mc(gSobject,"shouldCheckStartupAuth",[]) && StartupParams.doAuthToken) { gs.println("Checking tokens..."); if (!gs.gp(gSobject.session,"authToken") || !gs.gp(gSobject.session,"deviceToken")) { gs.println("Token NOT found"); return null; } gs.println("Tokens good"); } } gSobject['shouldCheckStartupAuth'] = function() { if (typeof checkStartupAuth !== 'undefined') { return checkStartupAuth } return true }; 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.mc(Utils,"logout",[]); }; StartupParams.beforeSocketInit = function(it) { gs.println("beforeSocketInit:" + StartupParams.supportOfflineStart); if (StartupParams.supportOfflineStart) { gs.println("beforeSocketInit:session.firstStartupCompleted:" + gs.gp(session,"firstStartupCompleted")); gs.println("startupParams.onlineStartFunction:3"); gs.mc(StartupParams,"offlineStartFunction",[]); StartupParams.bootstrapComplete = true; gs.sp(session,"firstStartupCompleted",true); } }; StartupParams.afterSocketInit = function(it) { gs.println("afterSocketInit"); if (!StartupParams.doAuthToken) { gs.println("onlineStartNoAuthFunction:0"); gs.mc(StartupParams,"onlineStartNoAuthFunction",[]); StartupParams.bootstrapComplete = true; return null; } return gs.mc(Utils,"tokenAuth",[function(it) { gs.println("onlineStartAuthSuccessFunction:1"); gs.mc(StartupParams,"onlineStartAuthSuccessFunction",[]); StartupParams.bootstrapComplete = true; return gs.mc(gs.gp(transmission,"onAuthReady"),"runCallbacks",[]); }, function(it) { gs.println("onlineStartTokenAuthFailedFunction:2"); gs.mc(StartupParams,"onlineStartTokenAuthFailedFunction",[]); StartupParams.bootstrapComplete = true; return gs.mc(gs.gp(transmission,"onAuthReady"),"runCallbacks",[]); }]); }; function Modals() { var gSobject = gs.init('Modals'); gSobject.clazz = { name: 'Modals', simpleName: 'Modals'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; 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, 'reconnectCallbacks', { get: function() { return Socket.reconnectCallbacks; }, set: function(gSval) { Socket.reconnectCallbacks = 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['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); } }; if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; 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.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.isDymicoSystemUpdating = function() { try{ if (typeof dymicoVersionUpdater !== 'undefined') { return dymicoVersionUpdater.dymicoSystemUpdating; } }catch(all){ } return false; }; 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.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) message = LZString.decompressFromBase64(message) // console.log('message', message) return Utils.stringToJson(message) }; 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) { var sendMessage = Utils.mapToJsonString(map); var xhr = new XMLHttpRequest(); xhr.ontimeout = failed xhr.open('POST', url, true); xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.onreadystatechange = function(e) { if (this.status == 404) { console.log('postJson FAILED'); failed(this.responseText); } if (this.readyState == 4 && this.status == 200) { success(this.responseText); } }; xhr.onload = function(e) { if (this.status === 200) { var blob = this.response; var disposition = xhr.getResponseHeader('Content-Disposition'); var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; var matches = filenameRegex.exec(disposition); var fileName = matches[1].replace(/['"]/g, ''); if(window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveBlob(blob, fileName); } else{ var downloadLink = window.document.createElement('a'); var contentTypeHeader = xhr.getResponseHeader("Content-Type"); downloadLink.href = window.URL.createObjectURL(new Blob([blob], { type: contentTypeHeader })); downloadLink.download = fileName; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } } }; xhr.send(sendMessage); }; Socket.init = function() { gs.sp(Socket.session,"domain",gs.gp(gs.gp(Socket.window,"location"),"hostname")); gs.sp(Socket.session,"incomingUrl",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() { gs.sp(Socket.socketHeadersMap,"domain",gs.gp(gs.gp(Socket.window,"location"),"hostname")); gs.sp(Socket.socketHeadersMap,"$AUTH_TOKEN",gs.mc(Utils,"getAuthToken",[])); gs.sp(Socket.socketHeadersMap,"$DEVICE_TOKEN",gs.mc(Utils,"getDeviceToken",[])); if (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.mc(Socket,"socketConnectionInterval",[success, failure]); } Socket.socketReady = function(callback) { if (Socket.connected) { callback(); return null; } return gs.mc(Socket.socketReadyQueue,"add",[callback]); } Socket.socketReadyQueueCallAll = function() { var socketReadyQueueLocal = Socket.socketReadyQueue; Socket.socketReadyQueue = gs.list([]); return gs.mc(socketReadyQueueLocal,"each",[function(callback) { try { callback(); } catch (all) { gs.println(all); } }]); } Socket.addUserDataPipe = function() { return gs.execStatic(Socket,"addSubscription", this,[gs.mc(Utils,"getDeviceToken",[]), Socket.SOCKET_USER_URL, Socket.userDataPipe]); } Socket.onReconnect = function(cb) { if (cb) { gs.mc(Socket.reconnectCallbacks,"add",[cb]); } } Socket.fireReconnectCallbacks = function() { return gs.mc(Socket.reconnectCallbacks,"each",[function(cb) { try { cb(); } catch (all) { gs.println(all); } }]); } Socket.startSessionRefresher = function() { if (gs.gp(Socket.session,"authToken")) { var sessionRefresherCallback = function(data) { if (!gs.equals(data, "authed")) { gs.println("NOT AUTHED"); gs.mc(Utils,"logout",[]); } }; gs.execStatic(Socket,"sessionRefresher", this,[gs.gp(Socket.session,"authToken"), sessionRefresherCallback]); for (var sessionRefresherThread in Socket.sessionRefresherThreads) { gs.mc(Utils,"clearInterval",[sessionRefresherThread]); gs.mc(Socket.sessionRefresherThreads,"remove",[sessionRefresherThread]); } gs.mc(Socket.sessionRefresherThreads,"add",[gs.mc(Utils,"setInterval",[function(it) { return gs.mc(Socket,"sessionRefresher",[gs.gp(Socket.session,"authToken"), sessionRefresherCallback]); }, 1000 * 60 * Socket.SESSION_REFRESH_MINS])]); } } Socket.reconnect = function(retryInMs) { if (retryInMs === undefined) retryInMs = 0; if (retryInMs) { return gs.mc(Utils,"setTimeout",[function(it) { return gs.mc(Socket,"reconnect",[]); }, retryInMs]); } if (Socket.reconnectMutex || !Socket.intervalRunner) { return gs.execStatic(Socket,"reconnect", this,[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",[]); success(); success = function(it) { }; gs.mc(Socket,"socketReadyQueueCallAll",[]); return gs.mc(Socket,"fireReconnectCallbacks",[]); }; var disconnectSockets = function(it) { gs.println("Socket disconnect"); Socket.connected = false; try { gs.mc(gs.gp(Socket,"websocketClient"),"disconnect",[]); } catch (all) { return null; } }; Socket.intervalRunner = function(done) { gs.println("navigator.onLine:" + gs.gp(Socket.navigator,"onLine") + ":" + gs.gp(gs.gp(Socket,"websocketClient"),"connected") + ":" + Socket.connected); if (!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("Socket.websocketClient.connected:" + gs.gp(gs.gp(Socket,"websocketClient"),"connected")); Socket.connected = true; reconnectCallback(); return done(); }, function(it) { gs.println("Socket.websocketClient.connected:connection down"); disconnectSockets(); done(); if (Socket.queue) { 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("pingWebSocket:" + pingResponse); if (gs.equals(pingResponse, "timeout")) { gs.println("Connection timed out, reconnecting..."); disconnectSockets(); gs.mc(Socket,"reconnect",[]); return done(); } gs.println("Connection good, false alarm."); return done(); }]); return gs.println("intervalRunner:Socket.websocketClient.connected:" + gs.gp(gs.gp(Socket,"websocketClient"),"connected")); }; return gs.execStatic(Socket,"reconnect", this,[]); } 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.execStatic(Socket,"socketHeaders", this,[])]); gs.execStatic(Socket,"doSendNative", this,[Socket.SOCKET_URL, wrapper]); return gs.mc(Utils,"setTimeout",[function(it) { if (gs.equals(websocketPingCountNow, Socket.websocketPingCount)) { callback("timeout"); return null; } return callback("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.mc(Socket,"send",["remoteExec", closure, data, success, fail]); } Socket.callChain = function(callChain, success, fail) { if (success === undefined) success = null; if (fail === undefined) fail = null; if (gs.execStatic(Socket,"isDymicoSystemUpdating", this,[])) { return null; } gs.println("callChain:" + callChain); return gs.mc(Socket,"send",["callChain", callChain, success, fail]); } Socket.callObject = function(self, method, args, success, fail) { if (fail === undefined) fail = null; if (gs.execStatic(Socket,"isDymicoSystemUpdating", this,[])) { return null; } gs.println("callObject:OObject:" + self); gs.println("callObject:method:" + method); return gs.mc(Socket,"send",["callObject", gs.map().add("self",self).add("method",method).add("args",args), success, fail]); } Socket.send = function(call, data, success, fail) { if (fail === undefined) fail = function(it) { return false; }; var uuid = gs.mc(Utils,"uuid",[]); 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(Date(),"time")).add("wrapper",wrapper); Socket.queue[uuid] = queueItem; gs.execStatic(Socket,"doSend", this,[Socket.SOCKET_URL, queueItem]); return uuid; } Socket.doSend = function(channel, queueItem) { if (gs.equals(Socket.sendProtocol, "websocket")) { gs.execStatic(Socket,"doSendNative", this,[channel, gs.mc(gs.gp(queueItem,"wrapper"),"leftShift",[gs.execStatic(Socket,"socketHeaders", this,[])])]); gs.mc(Utils,"setTimeout",[function(it) { return gs.mc(Socket,"checkMessageReceived",[queueItem]); }, Socket.SOCKET_CHECK_MSG_RECEIVED_SEC * 1000]); if (!Socket.connected) { gs.execStatic(Socket,"reconnect", this,[]); } } else if (gs.equals(Socket.sendProtocol, "http")) { gs.execStatic(Socket,"doSendNativeHttp", this,[gs.mc(gs.gp(queueItem,"wrapper"),"leftShift",[gs.execStatic(Socket,"socketHeaders", this,[])]), function(it) { gs.println("HTTP TIMEOUT"); return gs.mc(Socket,"reconnect",[]); }]); } else { throw gs.mc(Socket,"Exception",["Unsuported protocol : " + Socket.sendProtocol]); } } Socket.checkMessageReceived = function(queueItem) { if (Socket.queue[gs.gp(gs.gp(queueItem,"wrapper"),"uuid")]) { gs.execStatic(Socket,"reconnect", this,[]); gs.execStatic(Socket,"cleanQueue", this,[]); } } Socket.resendMessageQueue = function() { return gs.mc(gs.mc(gs.mc(Socket.queue,"values",[]),"sort",[function(it) { return gs.gp(it,"date"); }]),"each",[function(queueItem) { return gs.mc(Socket,"doSend",[Socket.SOCKET_URL, queueItem]); }]); } Socket.cleanQueue = function() { if (Socket.nextQueueClean < gs.gp(Date(),"time")) { var timeoutMs = Socket.SOCKET_QUEUE_TIMEOUT_MIN * 60 * 1000; Socket.nextQueueClean = gs.gp(Date(),"time") + timeoutMs; gs.println("nextQueueClean:" + Socket.nextQueueClean); gs.println("cleanQueue.start"); var timeout = gs.gp(Date(),"time") - timeoutMs; gs.println("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]); gs.mc(queueItem,"fail",[]); } }]); 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 (queueItem) { if (gs.gp(wrapper,"error")) { gs.mc(queueItem,"fail",[gs.gp(wrapper,"data")]); gs.execStatic(Socket,"processException", this,[gs.gp(wrapper,"data")]); return null; } var object = gs.mc(ObjectRegistry,"register",[gs.gp(wrapper,"data")]); gs.mc(queueItem,"success",[object]); } } Socket.processException = function(ex) { gs.mc(Utils,"logExceptionStack",[gs.gp(ex,"class") + ":" + gs.gp(ex,"message")]); return gs.mc(Utils,"logExceptionStack",[gs.gp(ex,"stackTrace")]); } Socket.subscribe = function(objectId, success, topic) { if (topic === undefined) topic = Socket.SOCKET_OBJECT_URL; return gs.execStatic(Socket,"socketReady", this,[function(it) { gs.mc(Socket,"unsubscribe",[objectId, topic]); gs.println("subscribe:" + objectId); var successWrapper = function(messageObject) { return success(messageObject); }; gs.mc(Socket,"addSubscription",[objectId, topic, success]); try { gs.mc(Socket,"subscribeJs",[objectId, topic + objectId, successWrapper]); } catch (all) { gs.println("subscribeJs failed"); gs.println(all); } }]); } Socket.subscribeTopic = function(topicId, success) { return gs.execStatic(Socket,"subscribe", this,[topicId, success, Socket.SOCKET_TOPIC_URL]); } Socket.unsubscribeTopic = function(topicId) { return gs.execStatic(Socket,"unsubscribe", this,[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.resubscribeAll = function() { 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("unsubscribe:" + objectId); try { gs.mc(gs.gp(Socket,"websocketClient"),"unsubscribe",[objectId]); gs.mc(Socket.subscriptions,"remove",[objectId]); } catch (all) { gs.println(all); } } 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.mc(Session,"instance",[]); 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.reconnectCallbacks = 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 }); if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; 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.newDate = function(year, month, day) { return new Date(year, month, day) }; 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.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.userAgent = function() { return navigator.userAgent }; Utils.triggerLoginRerenderCheck = function(zonerId) { try { if (window.dymicoVersionUpdater && window.dymicoVersionUpdater.checkAfterLogin){ window.dymicoVersionUpdater.checkAfterLogin(zonerId); } } catch(e){ console.log('triggerLoginRerenderCheck failed', e); } }; 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.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.isOnline = function() { return window.navigator.onLine }; Utils.userAgent = function() { return navigator.userAgent }; Utils.toast = function(message, showDuration) { 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.getType = function(value) { return typeof value }; 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) { var script = document.createElement("script") script.type = type; if (script.readyState){ //IE script.onreadystatechange = function(){ if (script.readyState == "loaded" || script.readyState == "complete"){ script.onreadystatechange = null; callback(); } }; } else { //Others script.onload = function(){ callback(); }; } script.src = scriptUrl; document.getElementsByTagName("head")[0].appendChild(script); }; Utils.mapToJsonString = function(map) { return JSON.stringify(map) }; Utils.stringToJson = function(message, parseDate) { 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.formatNumber = function(number, decimals, dec, 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.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.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.getAuthToken = function() { return gs.gp(Utils.session,"authToken"); } Utils.getDeviceToken = function() { return gs.gp(Utils.session,"deviceToken"); } 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.documentReady = function(callback) { if (gs.equals(gs.gp(Utils.document,"readyState"), "complete") || !gs.equals(gs.gp(Utils.document,"readyState"), "loading") && !gs.gp(gs.gp(Utils.document,"documentElement"),"doScroll")) { callback(); } else { 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.mc(newList,"find",[function(it) { return gs.equals(closure(listItem), closure(it)); }])) { gs.mc(newList,"add",[listItem]); } }]); return gs.mc(newList,"reverse",[]); } Utils.listsEqual = function(a, b) { if (!gs.equals(gs.mc(a,"size",[]), gs.mc(b,"size",[]))) { return false; } for (var i = 0; i < gs.mc(a,"size",[]); i++) { if (!gs.equals(a[i], b[i])) { return false; } } return true; } Utils.uuid = function() { return gs.mc(gs.execStatic(Utils,"guid", this,[]),"replaceAll",["-", ""]); } Utils.callChain = function(callChain, success, fail) { if (success === undefined) success = null; if (fail === undefined) fail = null; return gs.mc(Socket,"callChain",[callChain, success, fail]); } Utils.callObject = function(self, method, args, success, fail) { if (fail === undefined) fail = null; return gs.mc(Socket,"callObject",[self, method, args, success, fail]); } Utils.send = function(call, data, success, fail) { if (fail === undefined) fail = null; return gs.mc(Socket,"send",[call, data, success, fail]); } Utils.subscribe = function(objectId, success, topic) { if (topic === undefined) topic = gs.gp(Socket,"SOCKET_OBJECT_URL"); return gs.mc(Socket,"subscribe",[objectId, success, topic]); } Utils.unsubscribe = function(objectId) { return gs.mc(Socket,"unsubscribe",[objectId]); } Utils.subscribeTopic = function(topicId, success) { return gs.mc(Socket,"subscribeTopic",[topicId, success]); } Utils.unsubscribeTopic = function(topicId) { return gs.mc(Socket,"unsubscribeTopic",[topicId]); } Utils.rememberDays = function() { var days = gs.execStatic(Utils,"parseDays", this,[gs.gp(Utils.session,"rememberDays")]); return (gs.equals(days, null) ? Utils.REMEMBER_FALLBACK_DAYS : days); } Utils.rememberWindowExpired = function() { var days = gs.execStatic(Utils,"rememberDays", this,[]); if (gs.equals(days, 0)) { return !gs.execStatic(Utils,"launchMarkerPresent", this,[]); } var loginAt = gs.gp(Utils.session,"loginAt"); if (!loginAt) { return true; } return gs.execStatic(Utils,"nowMillis", this,[]) - gs.execStatic(Utils,"toMillis", this,[loginAt]) > days * 24 * 60 * 60 * 1000; } Utils.clearRememberedLogin = function() { 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 gs.execStatic(Utils,"clearLaunchMarker", this,[]); } Utils.parseDays = function(raw) { if (gs.equals(raw, null)) { return null; } return gs.execStatic(Utils,"toWholeNumber", this,[raw]); } Utils.tokenAuth = function(success, fail) { if (fail === undefined) fail = function(it) { }; gs.println("Utils:tokenAuth:" + gs.gp(StartupParams,"doAuthToken")); if (gs.gp(Utils.session,"zoner") && !gs.execStatic(Utils,"rememberWindowExpired", this,[])) { gs.println("Utils:tokenAuth:zoner cached"); success(); success = null; return null; } if (gs.gp(Utils.session,"zoner")) { gs.println("Utils:tokenAuth:remember window expired"); gs.execStatic(Utils,"clearRememberedLogin", this,[]); } gs.println("Utils:tokenAuth:loading zoner"); var callback = function(authMap) { gs.println("tokenAuth:callback:authMap:" + authMap); if (gs.gp(authMap,"authenticated")) { gs.mc(Utils,"updateAuthTokenToSession",[authMap, false]); if (success) { success(); } return null; } return fail(); }; gs.println("getDeviceToken():" + gs.execStatic(Utils,"getDeviceToken", this,[])); return gs.mc(Utils,"send",["authenticationToken", gs.map().add("deviceId",gs.execStatic(Utils,"getDeviceToken", this,[])), callback]); } Utils.login = function(username, password, success, fail) { if (fail === undefined) fail = function(it) { }; var callback = function(authMap) { if (gs.gp(authMap,"authenticated")) { gs.mc(Utils,"updateAuthTokenToSession",[authMap]); success(); return null; } gs.sp(Utils.session,"zoner",null); gs.println("Login failed"); return fail(); }; return gs.mc(Utils,"send",["authentication", gs.map().add("username",username).add("password",password).add("deviceId",gs.execStatic(Utils,"getDeviceToken", this,[])).add("userAgent",gs.execStatic(Utils,"userAgent", this,[])), callback, fail]); } Utils.updateAuthTokenToSession = function(authMap, freshLogin) { if (freshLogin === undefined) freshLogin = true; gs.execStatic(Utils,"setCookie", this,[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.equals(gs.gp(authMap,"rememberDays"), null)) { gs.sp(Utils.session,"rememberDays",gs.gp(authMap,"rememberDays")); } if (freshLogin || !gs.gp(Utils.session,"loginAt")) { gs.sp(Utils.session,"loginAt",gs.execStatic(Utils,"nowMillis", this,[])); } gs.execStatic(Utils,"markLaunch", this,[]); if (gs.gp(authMap,"jwt")) { gs.sp(Utils.session,"jwt",gs.gp(authMap,"jwt")); } return gs.execStatic(Utils,"triggerLoginRerenderCheck", this,[gs.execStatic(Utils,"roleSignature", this,[gs.gp(gs.gp(authMap,"zoner"),"roles")])]); } Utils.roleSignature = function(roles) { return gs.mc(gs.mc(gs.mc((roles ? roles : gs.list([])),"collect",[function(it) { return (function(){var _o=it;return _o!=null?gs.mc(_o,"toString",[]):null;})(); }]),"sort",[]),"join",[","]); } Utils.logout = function(pathAfterLogout, dropDatabase) { if (pathAfterLogout === undefined) pathAfterLogout = "/login/logout"; if (dropDatabase === undefined) dropDatabase = true; if (!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 (dropDatabase) { gs.mc(LocalDB,"getInstance",[function(it) { return gs.mc(gs.mc(LocalDB,"getInstance",[]),"dropDatabase",[]); }]); } gs.println("Utils.logout:redirect to " + pathAfterLogout); return gs.execStatic(Utils,"loadPage", this,[pathAfterLogout]); } Utils.open = function(url, target, options) { if (target === undefined) target = "_system"; if (options === undefined) options = ""; if (gs.execStatic(Utils,"isCordova", this,[])) { return gs.execStatic(Utils,"inAppBrowser", this,[gs.mc(Utils,"encodeURI",[url]), target, options]); } return gs.mc(Utils.window,"open",[url, target, options]); } Utils.deviceType = function() { if (gs.mc(gs.mc(gs.execStatic(Utils,"userAgent", this,[]),"toLowerCase",[]),"contains",["electron"])) { return gs.gp(gs.gp(Utils,"DeviceTypes"),"ELECTRON"); } if (gs.mc(gs.mc(gs.execStatic(Utils,"userAgent", this,[]),"toLowerCase",[]),"contains",["iphone"]) || gs.mc(gs.mc(gs.execStatic(Utils,"userAgent", this,[]),"toLowerCase",[]),"contains",["ipad"])) { return gs.gp(gs.gp(Utils,"DeviceTypes"),"IOS"); } if (gs.mc(gs.mc(gs.execStatic(Utils,"userAgent", this,[]),"toLowerCase",[]),"contains",["android"])) { return gs.gp(gs.gp(Utils,"DeviceTypes"),"ANDROID"); } return gs.gp(gs.gp(Utils,"DeviceTypes"),"BROWSER"); } Utils.isBrowser = function() { return gs.equals(gs.execStatic(Utils,"deviceType", this,[]), gs.gp(Utils.DeviceTypes,"BROWSER")); } Utils.isAndroid = function() { return gs.equals(gs.execStatic(Utils,"deviceType", this,[]), gs.gp(gs.gp(Utils,"DeviceTypes"),"ANDROID")); } Utils.isIos = function() { return gs.equals(gs.execStatic(Utils,"deviceType", this,[]), gs.gp(gs.gp(Utils,"DeviceTypes"),"IOS")); } Utils.isCordova = function() { return gs.mc(gs.execStatic(Utils,"userAgent", this,[]),"contains",["cordova"]); } Utils.cordovaDevice = function() { return gs.execStatic(Utils,"isCordova", this,[]); } Utils.post = function(file, parameter, objectName, id, callback) { return gs.mc(Socket,"post",[file, parameter, objectName, id, callback]); } Utils.validateEmail = function(text) { return "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[A-Za-z.]{2,}$".test(text); } Utils.validateCellphone = function(text) { var cleaned = (function(){var _o=(function(){var _o=(function(){var _o=text;return _o!=null?gs.mc(_o,"toString",[]):null;})();return _o!=null?gs.mc(_o,"trim",[]):null;})();return _o!=null?gs.mc(_o,"replaceAll",["[\\s\\-\\(\\)]", ""]):null;})(); if (!cleaned) { return false; } if (gs.mc(cleaned,"startsWith",["+"])) { return "^\\+[0-9]{7,15}$".test(cleaned); } return "^0[0-9]{9}$".test(cleaned); } Utils.dateString = function(date) { return gs.mc(date,"getDate",[]) + "/" + gs.mc(date,"getMonth",[]) + 1 + "/" + gs.mc(date,"getFullYear",[]); } Utils.clearTime = function(date) { if (date === undefined) date = Date(); return gs.mc(gs.mc(Utils,"moment",[date]),"startOf",["day"]); } Utils.utc = function(date) { if (date === undefined) date = Date(); return gs.mc(gs.mc(Utils,"moment",[date]),"utc",[]); } Utils.appendAppVersion = function(url) { if (gs.gp(Utils.session,"branchRevision")) { var appender = "?"; if (gs.mc(url,"contains",["?"])) { appender = "&"; } url += appender + "branchRevision=" + gs.gp(Utils.session,"branchRevision"); } return url; } Utils.findDeep = function(m, key) { if (m[key]) { return m[key]; } var foundValue = null; gs.mc(m,"each",[function(k, v) { if (foundValue) { return null; } if (v instanceof Object) { foundValue = gs.mc(Utils,"findDeep",[v, key]); } else if (v instanceof Array) { gs.mc(v,"each",[function(item) { if (foundValue) { return null; } if (item instanceof Object) { 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 (!value) { return value; } if (value instanceof Object || value instanceof Object || value instanceof Object) { 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 (value instanceof Array || value instanceof Array) { for (var listValue in value) { gs.execStatic(Utils,"removeMapKey", this,[listValue, removeKey, list]); } } return value; } Utils.iFrameById = function(id) { var x = gs.mc(Utils.document,"getElementById",[id]); return (gs.gp(x,"contentWindow") ? gs.gp(x,"contentWindow") : gs.gp(x,"contentDocument")); } Utils.embedTextInBlob = function(fileOrBlob, textToEmbed, callback) { gs.println("textToEmbed"); gs.println(textToEmbed); if (!textToEmbed) { return callback(fileOrBlob); } return gs.execStatic(Utils,"embedTextInBlobNative", this,[fileOrBlob, textToEmbed, callback]); } 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 callback(blob); }]); } Utils.take = function(string, len) { if (len === undefined) len = 40; if (!string || gs.mc(string,"size",[]) < len) { return string; } return string[gs.range(0, len, true)]; } Utils.session = gs.mc(Session,"instance",[]); 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 }); if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; ObjectRegistry.object = function(id) { return ObjectRegistry.objectRegistry[id]; } ObjectRegistry.register = function(objects) { if (!ObjectRegistry.enabled) { return objects; } if (objects instanceof Array) { 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 gs.execStatic(ObjectRegistry,"registerSingle", this,[objects]); } } ObjectRegistry.registerSingle = function(object, flatCopy) { if (flatCopy === undefined) flatCopy = true; if (!gs.execStatic(ObjectRegistry,"isDatabaseObject", this,[object])) { return object; } var oObject = ObjectRegistry.objectRegistry[gs.gp(object,"_id")]; if (!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]); gs.gp(oObject,"internalMap")[key] = gs.mc(newValue,"toJs",[]); } else if (!gs.equals(value, null) && value instanceof Array) { var oObjectList = gs.list([]); gs.mc(value,"eachWithIndex",[function(objectVal, index) { if (gs.mc(ObjectRegistry,"isDatabaseObject",[objectVal])) { gs.mc(oObjectList,"add",[gs.mc(gs.mc(ObjectRegistry,"registerSingle",[objectVal]),"toJs",[])]); } else { gs.mc(oObjectList,"add",[objectVal]); } }]); gs.gp(oObject,"internalMap")[key] = oObjectList; } }]); gs.mc(Utils,"setTimeout",[function(it) { return gs.mc(gs.mc(LocalDB,"getInstance",[]),"updateIfExists",[oObject]); }, 100]); return oObject; } ObjectRegistry.isDatabaseObject = function(object) { return !gs.equals(object, null) && object instanceof Object && 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.methodMissingName = null; gSobject.methodMissingArgs = null; gSobject.internalMap = gs.map(); gSobject.refresher = null; gSobject.updateCallback = function(it) { }; gSobject['subscribe'] = function(it) { return gs.mc(Utils,"subscribe",[gs.gp(gSobject.internalMap,"_id"), gSobject.updateCallback]); } gSobject['unsubscribe'] = function(it) { return gs.mc(Utils,"unsubscribe",[gs.gp(gSobject.internalMap,"_id")]); } gSobject['setRefresher'] = function(closure, update) { if (update === undefined) update = true; gs.mc(gSobject,"subscribe",[]); if (!gSobject.refresher || gSobject.refresher && update) { gSobject.refresher = closure; } } gSobject['merge'] = function(object, flatCopy) { if (flatCopy === undefined) flatCopy = true; if (object && object instanceof OObject) { object = gs.gp(object,"internalMap"); } gs.mc(object,"each",[function(key, value) { if (flatCopy) { gSobject.internalMap[key] = value; return null; } if (!!gs.equals(value, null) && value instanceof String && gs.mc(ObjectRegistry,"isDatabaseObject",[gSobject.internalMap[key]])) { gSobject.internalMap[key] = value; } else { gs.println("WARNING: skip overwrite of DatabaseObject with String"); gs.println("Key:" + key); gs.println("String:" + value); gs.println("internalMap[key]:"); gs.println(gSobject.internalMap[key]); gs.println("Object:"); gs.println(gSobject.internalMap); } }]); if (gSobject.refresher) { gs.mc(gSobject,"refresher",[gSobject]); } } 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 (args) { var successClosure = gs.mc(args,"last",[]); if (successClosure instanceof Function) { if (gs.equals(gs.mc(args,"size",[]), 1)) { args = null; } else { args = args[gs.range(0, -2, true)]; } gSobject.methodMissingArgs = args; gs.mc(gSobject,"then",[successClosure]); } } } gSobject['then'] = function(successClosure, fail) { if (successClosure === undefined) successClosure = function(it) { }; if (fail === undefined) fail = function(it) { }; return gs.mc(Utils,"callObject",[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(it) { return null; } gSobject['promise'] = function() { var self = this; return new Promise(function(resolve, reject) { self.then(resolve, function(err) { reject(err); }); }); }; var self = arguments[0]; gs.mc(gSobject,"merge",[self]); return gSobject; }; 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(gSobject.className + ":" + message); } catch (all) { } return gs.mc(gs.mc(gs.mc(gs.mc(ObjectFinder,"getInstance",[]),"propertyMissing",["log"]),"null",[message, gSobject.className]),"do",[]); } var className = arguments[0]; gs.sp(gSobject,"className",className); return gSobject; }; function ObjectFinder() { var gSobject = gs.init('ObjectFinder'); gSobject.clazz = { name: 'ObjectFinder', simpleName: 'ObjectFinder'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.log = RemoteLog("Transmission"); Object.defineProperty(gSobject, 'singleO', { get: function() { return ObjectFinder.singleO; }, set: function(gSval) { ObjectFinder.singleO = gSval; }, enumerable: true }); 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 (!file) { gs.println("No file selected"); return null; } gs.println("file: " + file); gs.println("parameter: " + parameter); gs.println("objectName: " + objectName); gs.println("id: " + id); return gs.mc(Utils,"post",[file, parameter, objectName, id, callback]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; ObjectFinder.getInstance = function() { if (ObjectFinder.singleO) { return ObjectFinder.singleO; } ObjectFinder.singleO = ObjectFinder(); return ObjectFinder.singleO; } ObjectFinder.singleO = null; 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 Exception("Maximum call stack size 16 exceeded"); } if (args) { var successClosure = gs.mc(args,"last",[]); var failClosure = function(it) { }; if (successClosure && successClosure instanceof Function) { if (gs.equals(gs.mc(args,"size",[]), 1)) { args = null; } else { args = args[gs.range(0, -2, true)]; if (gs.mc(args,"last",[]) && gs.mc(args,"last",[]) instanceof Function) { failClosure = successClosure; successClosure = gs.mc(args,"last",[]); if (gs.equals(gs.mc(args,"size",[]), 1)) { args = null; } else { args = args[gs.range(0, -2, true)]; } } } gs.mc(gSobject.argList,"add",[gs.map().add("method",name).add("args",args)]); gs.sp(gSobject,"successClosure",successClosure); gs.sp(gSobject,"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['propertyMissing'] = function(name) { if (gs.mc(gSobject.argList,"size",[]) > 16) { throw Exception("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(it) { return null; } gSobject['isUndefined'] = function(val) { return val === undefined }; gSobject['promise'] = function() { var self = this; return new Promise(function(resolve, reject) { self.then(resolve, function(err) { reject(err); }); }); }; var argList = arguments[0]; var cacheCallTracker = arguments[1]; gs.sp(gSobject,"cacheCallTracker",cacheCallTracker); gs.sp(gSobject,"argList",argList); return gSobject; }; 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 LocalDB() { var gSobject = gs.init('LocalDB'); gSobject.clazz = { name: 'LocalDB', simpleName: 'LocalDB'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.localO = LocalDB$LocalO(gSobject); 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['cacheObjects'] = function(key, objectsIn, ttl, callback) { var ttlInMs = (gs.equals(ttl, -1) ? null : gs.gp(Date(),"time") + ttl * 1000); key = "c:" + key; return gs.mc(LocalDB.db,"upsert",[gs.map().add("_id",key).add("_ttl",ttlInMs).add("stringValue",gs.mc(Utils,"mapToJsonString",[objectsIn])), function(it) { var callbackTmp = callback; callback = null; if (callbackTmp) { callbackTmp(); } }]); } gSobject['readCache'] = function(key) { key = "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.gp(keyObject,"_ttl") && gs.gp(keyObject,"_ttl") <= gs.gp(Date(),"time")) { gs.mc(LocalDB.db,"remove",[gs.map().add("_id",key)]); gs.mc(LocalDB.db,"save",[]); return null; } return gs.mc(Utils,"stringToJson",[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",[object]); gs.mc(gSobject,"fixDatesToDb",[object]); if (callback) { return gs.mc(LocalDB.db,"upsert",[object, function(it) { var callbackTmp = callback; callback = null; if (callbackTmp) { callbackTmp(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.gp(object,"_dateCreated") ? gs.gp(object,"_dateCreated") : Date())); gs.sp(object,"_lastUpdated",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 (var object in objects) { gs.mc(gSobject,"fixDatesToDb",[object]); } return gs.mc(LocalDB.db,"upsert",[objects, callback]); } gSobject['saveAll'] = function(objects, callback) { if (callback === undefined) callback = function(it) { }; for (var object in objects) { gs.sp(object,"_dateCreated",(gs.gp(object,"_dateCreated") ? gs.gp(object,"_dateCreated") : Date())); gs.sp(object,"_lastUpdated",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 (keyObject) { 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) { return gs.mc(LocalDB.instance,"getOne",[id, callback]); }).add("findOne",function(filter, callback) { return gs.mc(LocalDB.instance,"findOne",[gs.mc(filter,"leftShift",[staticFilter]), callback]); }).add("findOrCreate",function(filter, mapToSave, callback) { return gs.mc(LocalDB.instance,"findOrCreate",[gs.mc(filter,"leftShift",[staticFilter]), mapToSave, callback]); }).add("find",function(filter, params) { return gs.mc(LocalDB.instance,"find",[gs.mc(filter,"leftShift",[staticFilter]), params]); }).add("findAll",function(params) { return gs.mc(LocalDB.instance,"find",[staticFilter, params]); }).add("new",function(initParams) { var item = gs.mc(initParams,"leftShift",[staticFilter]); gs.sp(item,"_id",gs.mc(Utils,"uuid",[])); 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 (item) { if (callback) { return callback(item); } return item; } mapToSave = gs.mc(gs.mc(mapToSave,"clone",[]),"leftShift",[filter]); gs.sp(mapToSave,"_id",gs.mc(Utils,"uuid",[])); if (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 (expandableFields) { gs.mc(gSobject,"findOne",[gs.map().add("_id",id), callback, expandableFields, level]); } else { 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; if (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 (!item) { if (callback) { callback(gs.map()); } return gs.map(); } item = item[0]; gs.mc(gSobject,"decorate",[item]); if (callback) { callback(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.mc(gSobject,"getSkip",[params])]),"leftShift",[gs.mc(gSobject,"getSort",[params])]))]); var objectList = gs.list([]); gs.mc(dbList,"each",[function(dbItem) { var item = gs.mc(gs.map(),"leftShift",[dbItem]); gs.mc(gSobject,"fixDatesFromDb",[item]); gs.mc(gSobject,"decorate",[item]); if (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 (v instanceof Array) { 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",[expandResultItem]); gs.mc(gSobject,"fixDatesFromDb",[expandedItem]); if (level > 1) { expandedItem = gs.mc(gSobject,"expandItem",[expandedItem, expandableFields, level - 1]); } return gs.mc(expandResultObjects,"add",[expandedItem]); }]); item[k] = (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",[expandResult]); gs.mc(gSobject,"fixDatesFromDb",[expandedItem]); if (level > 1) { expandedItem = gs.mc(gSobject,"expandItem",[expandedItem, expandableFields, level - 1]); } item[k] = (expandedItem ? expandedItem : null); } } }]); return item; } gSobject['getLimit'] = function(params) { return gs.map().add("$limit",(gs.gp(params,"limit") ? gs.gp(params,"limit") : (gs.gp(params,"max") ? gs.gp(params,"max") : LocalDB.MAX_ROWS_PER_BATCH))); } gSobject['getSkip'] = function(params) { return gs.map().add("$skip",(gs.gp(params,"offset") ? gs.gp(params,"offset") : (gs.gp(params,"skip") ? gs.gp(params,"skip") : 0))); } gSobject['getSort'] = function(params) { var order = 1; if (gs.equals(gs.gp(params,"order"), "desc")) { order = -1; } if (gs.gp(params,"sort")) { return gs.map().add("$orderBy",gs.map().add(gs.gp(params,"sort"),order)); } return gs.map(); } gSobject['fixDatesToDb'] = function(object) { gs.mc(object,"each",[function(key, value) { if (value && value instanceof Object) { gs.mc(gSobject,"fixDatesToDb",[value]); } if (gs.mc(Utils,"isDate",[value])) { object[key] = gs.mc(LocalDB.db,"make",[value]); } }]); return object; } gSobject['fixDatesFromDb'] = function(object) { gs.mc(object,"each",[function(key, value) { if (value && value instanceof Object) { gs.mc(gSobject,"fixDatesFromDb",[value]); } if (gs.mc(Utils,"isDate",[value])) { object[key] = 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) { return gs.mc(LocalDB.instance,"save",[item, callback]); }); gs.sp(item,"delete",function(callback) { 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.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.getInstance = function(callback) { if (callback === undefined) callback = function(it) { }; if (!LocalDB.instance) { LocalDB.instance = LocalDB(); if (!LocalDB.db) { gs.execStatic(LocalDB,"initDb", this,[LocalDB.DB_NAME, function(it) { return gs.mc(LocalDB,"checkVersion",[function(it) { return gs.mc(LocalDB,"cleanupStaleData",[function(it) { LocalDB.startupCompleted = true; callback(LocalDB.instance); gs.mc(LocalDB.callbacks,"each",[function(it) { return it(LocalDB.instance); }]); return LocalDB.callbacks = gs.list([]); }]); }]); }]); } } else { if (!LocalDB.startupCompleted) { gs.mc(LocalDB.callbacks,"add",[callback]); return LocalDB.instance; } callback(LocalDB.instance); } return LocalDB.instance; } 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) { 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.equals(gs.gp(version[0],"version"), LocalDB.DB_VERSION_NO)) { gs.println("FOUND OLD DB:DROP DB"); gs.mc(LocalDB,"dropDatabase",[callback]); return null; } return callback(); }; LocalDB.cleanupStaleData = function(callback) { gs.println("LocalDB.cleanupStaleData"); var nowMs = gs.gp(Date(),"time"); return callback(); }; function CacheCallTracker() { var gSobject = gs.init('CacheCallTracker'); gSobject.clazz = { name: 'CacheCallTracker', simpleName: 'CacheCallTracker'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.ttl = 0; gSobject.remoteOnce = false; 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['callAndCache'] = function(argList, successClosure, fail) { if (successClosure === undefined) successClosure = function(it) { }; if (fail === undefined) fail = null; var argListString = gs.mc(argList,"toString",[]); if (!gSobject.ttl) { return gs.mc(Socket,"callChain",[argList, function(result) { return successClosure(result); }, fail]); } var objects = CacheCallTracker.resultCache[argListString]; return gs.mc(LocalDB,"getInstance",[function(localDB) { if (!objects) { objects = gs.mc(gs.mc(LocalDB,"getInstance",[]),"readCache",[argListString]); } if (objects) { gs.mc(ObjectRegistry,"register",[objects]); successClosure(objects); } return gs.mc(Utils,"setTimeout",[function(it) { if (objects) { CacheCallTracker.remoteOnceMap[argListString] = (CacheCallTracker.remoteOnceMap[argListString] ? CacheCallTracker.remoteOnceMap[argListString] + 1 : 1); if (gSobject.remoteOnce && CacheCallTracker.remoteOnceMap[argListString] > 1) { return null; } } return gs.mc(Socket,"callChain",[argList, function(result) { CacheCallTracker.resultCache[argListString] = result; successClosure(result); return gs.mc(Utils,"setTimeout",[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 (gSobject.ttl) { gs.mc(LocalDB,"getInstance",[function(it) { return gs.mc(gs.mc(LocalDB,"getInstance",[]),"cacheObjects",[argListString, objects, gSobject.ttl, callback]); }]); } } var ttl = arguments[0]; var remoteOnce = arguments[1]; gs.sp(gSobject,"ttl",ttl); gs.sp(gSobject,"remoteOnce",remoteOnce); 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'}; gSobject.gpsService = null; gSobject.lastLocation = null; gSobject.desiredAccuracy = GpsLocationTracker.HIGH_ACCURACY; 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 }); Object.defineProperty(gSobject, 'singletonInstance', { get: function() { return GpsLocationTracker.singletonInstance; }, set: function(gSval) { GpsLocationTracker.singletonInstance = gSval; }, enumerable: true }); gSobject['config'] = function(config) { gs.mc(gSobject.gpsService,"setConfig",[config]); return gSobject; } 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; successCallback(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 gSobject; } gSobject['onLocation'] = function(successCallback, failedCallback) { if (failedCallback === undefined) failedCallback = function(it) { }; var callbackWrapper = function(location) { gSobject.lastLocation = location; successCallback(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 gSobject; } gSobject['onStationary'] = function(stationaryCallback, failedCallback) { if (failedCallback === undefined) failedCallback = function(it) { }; gs.mc(gSobject.gpsService,"onStationary",[stationaryCallback, failedCallback]); return gSobject; } gSobject['start'] = function(it) { gs.mc(gSobject.gpsService,"start",[]); return gSobject; } gSobject['stop'] = function(it) { gs.mc(gSobject.gpsService,"stop",[]); return gSobject; } gSobject['sync'] = function(it) { gs.mc(gSobject.gpsService,"sync",[]); return gSobject; } gSobject['getName'] = function(it) { gs.mc(gSobject.gpsService,"getName",[]); return gSobject; } gSobject['backgroundGeoLocationDefined'] = function() { return typeof BackgroundGeolocation !== 'undefined'; }; if (gs.mc(gSobject,"backgroundGeoLocationDefined",[])) { gSobject.gpsService = GpsLocationTracker$CordovaBackgroundGeolocation(gSobject); } else if (gs.gp(gs.fs('navigator', this, gSobject),"geolocation")) { gSobject.gpsService = GpsLocationTracker$Html5Gps(gSobject); } else { throw Exception("GPS not supported"); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; GpsLocationTracker.instance = function() { if (!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(gSobject,"config"),"leftShift",[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 successCallback(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.mc(Utils,"uuid",[])).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.gp(location,"coords")]); return gs.mc(gSobject,"onLocationSuccessCallback",[gs.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 (gSobject.watchPositionId) { 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(gs.fs('BackgroundGeolocation', this, gSobject),"DISTANCE_FILTER_PROVIDER")).add("backgroundLocationProvider",gs.gp(gs.fs('BackgroundGeolocation', this, gSobject),"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",10 * 1000).add("url",((gs.gp(gs.fs('session', this, gSobject),"incomingUrl")) + "/cordovaWrapper/gps")).add("syncUrl",((gs.gp(gs.fs('session', this, gSobject),"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(gs.fs('session', this, gSobject),"userId")).add("uuid",gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"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",["BackgroundGeolocation:setConfig:" + config]); gs.mc(gs.gp(gSobject,"config"),"leftShift",[config]); gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"configure",[gs.gp(gSobject,"config")]); return gSobject; } 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",4 * 60 * 1000).add("timeout",60 * 1000),"leftShift",[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) { successCallback(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 gSobject; } gSobject['stop'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["BackgroundGeolocation:stop:" + gs.gp(gs.fs('session', this, gSobject),"userId")]); } gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"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(gs.fs('BackgroundGeolocation', this, gSobject),"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(gs.fs('BackgroundGeolocation', this, gSobject),"on",["authorization", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["BackgroundGeolocation:authorization:status: " + status]); if (!gs.equals(status, gs.gp(gs.fs('BackgroundGeolocation', this, gSobject),"AUTHORIZED"))) { gs.mc(Utils,"setTimeout",[function(it) { var showSettings = gs.mc(gSobject,"confirm",["App requires location tracking permission. Would you like to open app settings?"]); if (showSettings) { return gs.mc(gs.fs('BackgroundGeolocation', this, gSobject),"showAppSettings",[]); } }, 500]); } }]); 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) { onSuccess(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(); gs.execStatic(CordovaCamera,"hasCameraPermission", this,["android.permission.CAMERA", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["android.permission.CAMERA:" + gs.gp(status,"hasPermission")]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }]); gs.execStatic(CordovaCamera,"hasCameraPermission", this,["android.permission.ACTION_CREATE_DOCUMENT", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["android.permission.ACTION_CREATE_DOCUMENT:" + gs.gp(status,"hasPermission")]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }]); gs.execStatic(CordovaCamera,"hasCameraPermission", this,["android.permission.ACTION_OPEN_DOCUMENT", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["android.permission.ACTION_OPEN_DOCUMENT:" + gs.gp(status,"hasPermission")]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }]); gs.execStatic(CordovaCamera,"hasCameraPermission", this,["android.permission.READ_EXTERNAL_STORAGE", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["android.permission.READ_EXTERNAL_STORAGE:" + gs.gp(status,"hasPermission")]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }]); gs.execStatic(CordovaCamera,"hasCameraPermission", this,["android.permission.READ_MEDIA_IMAGES", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["android.permission.READ_MEDIA_IMAGES:" + gs.gp(status,"hasPermission")]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[status]); }]); gs.execStatic(CordovaCamera,"hasCameraPermission", this,["android.permission.READ_MEDIA_VIDEO", function(status) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["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",[config])]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["takePhoto2"]); } gSobject['clearCache'] = function(it) { return gs.mc(gs.fs('camera', this, gSobject),"cleanup",[]); } 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.initialised = false; 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['init'] = function(mountElement) { if (mountElement === undefined) mountElement = "#vue-app"; gs.println("VueApp.init"); if (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 (function(){var _o=gs.gp(component,"children");return _o!=null?gs.mc(_o,"each",[function(child) { return gs.mc(childComponents,"add",[gs.gp(child,"vueComponentName")]); }]):null;})(); }]); var buildRoute; 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.gp(component,"children")) { gs.sp(route,"children",gs.mc(gs.gp(component,"children"),"collect",[function(child) { return buildRoute(child); }])); } return route; }; gs.mc(gSobject.componentList,"each",[function(component) { if (!gs.mc(childComponents,"contains",[gs.gp(component,"vueComponentName")])) { if (gs.gp(component,"path") instanceof Array) { gs.mc(gs.gp(component,"path"),"each",[function(it) { if (it) { var cloned = gs.mc(Utils,"deepCopyMap",[component]); gs.sp(cloned,"path",it); gs.mc(routes,"add",[buildRoute(cloned)]); } }]); } else if (gs.gp(component,"path")) { gs.mc(routes,"add",[buildRoute(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 gSobject; } gSobject['registerComponent'] = function(component) { return gs.mc(gSobject.componentList,"add",[component]); } gSobject['registerAuthComponent'] = function(component) { var path = gs.gp(component,"path"); if (gs.gp(component,"path") instanceof Array) { path = path[0]; } return gSobject.authComponentPath = path; } gSobject['setQuasarTheme'] = function(it) { gs.sp(gs.fs('session', this, gSobject),"darkMode",(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.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]); 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.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; }; 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 callback(); }; gSobject.notify = function(message, type, 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",[map])]); }; gSobject.dialog = function(title, message, 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",[map])]); }; Object.defineProperty(gSobject, 'METHOD_EXCLUDE_LIST', { get: function() { return VueComponent.METHOD_EXCLUDE_LIST; }, set: function(gSval) { VueComponent.METHOD_EXCLUDE_LIST = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'notifyParams', { get: function() { return VueComponent.notifyParams; }, set: function(gSval) { VueComponent.notifyParams = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'dialogParams', { get: function() { return VueComponent.dialogParams; }, set: function(gSval) { VueComponent.dialogParams = gSval; }, enumerable: true }); gSobject['register'] = function(templateName, componentName) { if (templateName === undefined) templateName = ""; if (componentName === undefined) componentName = ""; gSobject.vueComponentName = (componentName ? componentName : gs.mc(gs.mc(gSobject,"getClass",[]),"getSimpleName",[])); if (!gSobject.template) { gSobject.template = (templateName ? "#" + templateName : "#" + gs.mc(gs.mc(gSobject,"getClass",[]),"getSimpleName",[]) + "View"); } gs.println(("VueComponent.register:" + (gSobject.vueComponentName) + ":" + (gSobject.template) + ":" + (gSobject.path))); var methodsMap = gs.map(); gs.mc(gs.mc(gs.gp(gs.gp(gSobject,"metaClass"),"methods"),"findAll",[function(method) { var name = gs.gp(method,"name"); return !gs.mc(name,"startsWith",["set"]) && !gs.mc(name,"startsWith",["get"]) && !gs.mc(name,"contains",["$"]) && !gs.mc(VueComponent.METHOD_EXCLUDE_LIST,"contains",[name]); }]),"each",[function(it) { return methodsMap[gs.gp(it,"name")] = gs.gp(this,"$it.name"); }]); gSobject.methods = gs.toJsObj(methodsMap); var watchMap = gs.map(); gs.mc(gs.mc(gs.gp(gs.gp(gSobject,"metaClass"),"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.mc(watchVar[0],"toLowerCase",[]) + gs.mc(watchVar,"substring",[1]); return watchMap[watchVar] = gs.gp(this,"$method.name"); }]); gSobject.watch = gs.toJsObj(watchMap); var computeMap = gs.map(); gs.mc(gs.mc(gs.gp(gs.gp(gSobject,"metaClass"),"methods"),"findAll",[function(method) { return gs.mc(gs.gp(method,"name"),"startsWith",["computed"]); }]),"each",[function(it) { return computeMap[gs.gp(it,"name")] = gs.gp(this,"$it.name"); }]); gSobject.compute = gs.toJsObj(computeMap); var eventsMap = gs.map(); gs.mc(gs.mc(gs.gp(gs.gp(gSobject,"metaClass"),"methods"),"findAll",[function(method) { return gs.mc(gs.gp(method,"name"),"startsWith",["event"]); }]),"each",[function(it) { return eventsMap[gs.gp(it,"name")] = gs.gp(this,"$it.name"); }]); gSobject.events = gs.toJsObj(eventsMap); gs.mc(gs.fs('vue', this, gSobject),"registerComponent",[gSobject]); return gSobject; } gSobject['registerAsAuthComponent'] = function(it) { gs.mc(gs.fs('vue', this, gSobject),"registerAuthComponent",[gSobject]); return gSobject; } gSobject['getRefs'] = function(it) { gs.sp(gSobject,"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 (!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['placeholder'] = function(value, placeholder) { return (value ? value : placeholder); } gSobject['onPaste'] = function(evt, reference) { var text = ""; var elem = gs.mc(gSobject,"getRefs",[])[reference][0]; if (!elem) { elem = gs.mc(gSobject,"getRefs",[])[reference]; } if (gs.gp(elem,"originalEvent") && 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.gp(evt,"clipboardData") && 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 update(function(it) { return gSobject.scope[filteredOptions] = gs.mc(gs.mc(gSobject.scope[options],"findAll",[function(option) { if (excludeSelected && gs.equals(gs.gp(option,"_id"), gs.gp(object,"_id"))) { return false; } if (!val) { return true; } return (function(){var _o=(function(){var _o=gs.gp(option,"name");return _o!=null?gs.mc(_o,"toLowerCase",[]):null;})();return _o!=null?gs.mc(_o,"contains",[(function(){var _o=val;return _o!=null?gs.mc(_o,"toLowerCase",[]):null;})()]):null;})(); }]),"sort",[]); }); } gSobject['enforceComponentRoles'] = function(it) { if (gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"embedded")) { gs.println("enforceComponentRoles skipped for embedded mode"); return true; } if (!gSobject.roles || gs.mc(gs.fs('session', this, gSobject),"hasRole",[gSobject.roles])) { return true; } if (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 Exception(((gSobject.vueComponentName) + " roles required: " + (gSobject.roles))); } gSobject['formatCurrency'] = function(value) { try { gs.mc(value,"split",["."]); gs.mc(gSobject,"parseFloat",[value]); } catch (all) { value = "0.00"; } if (!gs.mc(value,"contains",["."])) { value = "0.0" + value; } var newValue; var decPartSize = gs.mc(gs.mc(value,"split",["."])[1],"size",[]); if (decPartSize > 2) { newValue = gs.mc(gs.mc(gSobject,"parseFloat",[value]) * 10,"toFixed",[2]); } else if (gs.equals(decPartSize, 1)) { newValue = gs.mc(gs.mc(gSobject,"parseFloat",[value]) / 10,"toFixed",[2]); } else { newValue = gs.mc(gs.mc(gSobject,"parseFloat",[value]),"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 > decimals + 1) { return null; } } if (gs.mc(character,"isNumber",[]) || gs.equals(character, ".") && gs.equals(size, 0) || index <= size) { 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(gSobject,"Number",[gs.mc(gs.gp(parent,"$scopeName"),"toString",[])])); }]); } gSobject['formatCurrencyInput'] = function(scopeName, parent) { if (parent === undefined) parent = gSobject.scope; return gs.mc(gSobject,"formatNumberInput",[scopeName, 15, 2, parent]); } gSobject['moment'] = function(date) { return moment(date) }; if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; VueComponent.METHOD_EXCLUDE_LIST = gs.list(["equals", "hashCode", "notify", "notifyAll", "toString", "wait", "register", "invokeMethod", "data", "beforeCreate", "created", "mounted", "destroyed"]); 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); 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.mc(Utils,"isIos",[])); gs.sp(gSobject.scope,"showAndroid",gs.mc(Utils,"isAndroid",[])); 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.gp(gSobject.scope,"email") ? gs.gp(gSobject.scope,"email") : gs.gp(gSobject.scope,"phoneNumber"))); if (!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.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.mc(Utils,"isCordova",[])) { 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.mc(Utils,"isCordova",[])) { return gs.mc(gSobject,"notify",["Could not complete sign in", "negative"]); } return gs.execStatic(LegionLoginComponent,"signInWithAppleAuth", this,[function(result) { gs.println("signInWithAppleAuth result:"); gs.println(result); var jwt = gs.mc(Utils,"decodeJWT",[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['saveAppleCustomer'] = function(userId) { var user = gs.map(); if (gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"familyName")) { gs.sp(user,"surname",gs.gp(gs.gp(gSobject.appleAuth,"fullName"),"familyName")); } if (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 (authenticated) { return successCallback(authenticated); } return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"repairUser",[email, password, function(result) { if (!gs.gp(result,"success")) { failCallback("Registration Failed"); } return gs.mc(gs.fs('legionUserService', this, gSobject),"auth",[email, password, function(isAuthenticated) { if (isAuthenticated) { return successCallback(isAuthenticated); } return failCallback("Login Failed"); }]); }]); }]); } gSobject['errorNotification'] = function(notification) { return gs.mc(gSobject,"alert",[notification]); } 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 (!authData) { return callback(false); } if (gs.gp(authData,"authenticated")) { gs.mc(Utils,"updateAuthTokenToSession",[authData]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["User authdata:" + authData]); gs.mc(gSobject,"updateSession",[authData]); gs.mc(gSobject,"loadLegionUser",[function(it) { return callback(gs.gp(authData,"authenticated")); }]); return null; } return callback(gs.gp(authData,"authenticated")); }]); } gSobject['updateSession'] = function(authData) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["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")); gs.sp(gs.fs('session', this, gSobject),"userId",gs.gp(gs.gp(authData,"legionUser"),"_id")); if (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")); 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 (!authData) { return callback(false); } if (gs.gp(authData,"authenticated")) { gs.mc(Utils,"updateAuthTokenToSession",[authData]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["User authdata:" + authData]); gs.mc(gSobject,"updateSession",[authData]); gs.mc(gSobject,"loadLegionUser",[function(it) { return callback(gs.gp(authData,"authenticated")); }]); return null; } return callback(false); }, function(error) { return failCallback(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.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 callback(gs.gp(gs.fs('session', this, gSobject),"legionUser")); }]); return null; } if (gs.gp(gs.gp(gs.fs('session', this, gSobject),"zoner"),"id")) { 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 callback(gs.gp(gs.fs('session', this, gSobject),"legionUser")); }]); } return callback(); }]); } gSobject['loadLegionUser'] = function(callback, failCallback, resetCache) { if (callback === undefined) callback = function(it) { }; if (failCallback === undefined) failCallback = function(it) { }; if (resetCache === undefined) resetCache = false; if (gSobject.legionUser && !resetCache) { return callback(gSobject.legionUser); } if (gs.gp(gs.fs('session', this, gSobject),"authToken")) { gs.mc(gs.gp(gs.fs('transmission', this, gSobject),"onAuthReady"),"callback",[function(it) { if (!gs.gp(gs.fs('session', this, gSobject),"legionUser")) { throw Exception("Auth is authenticated, but legionUser not found"); } gSobject.legionUser = gs.gp(gs.fs('session', this, gSobject),"legionUser"); gs.mc(Utils,"subscribe",[gs.gp(gSobject.legionUser,"_id"), function(updatedlegionUser) { return gSobject.legionUser = updatedlegionUser; }]); return callback(gSobject.legionUser); }]); return null; } return failCallback(); } gSobject['registerPushDevice'] = function(data) { return gs.mc(gSobject,"loadLegionUser",[function(user) { gs.println(">>>>>>>>>>> Register Push Device"); gs.println("Data: " + gs.gp(user,"_id") + " " + gs.gp(data,"registrationId") + " " + gs.mc(Utils,"deviceType",[])); gs.println(data); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionPushService"),"registerDevice",[gs.gp(user,"_id"), gs.gp(data,"registrationId"), gs.mc(Utils,"deviceType",[]), 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 callback(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 callback(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",[]); }]); } gs.mc(gSobject,"loadLegionUserFromServer",[]); gs.mc(gSobject,"lookupCountry",[]); 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",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.userId = null; gSobject.onBackKeyDown = function(it) { }; gSobject['splashScreenHide'] = function(it) { if (gs.mc(Utils,"isCordova",[])) { try { (function(){var _o=gs.gp(gs.fs('navigator', this, gSobject),"splashscreen");return _o!=null?gs.mc(_o,"hide",[]):null;})(); if (gs.execStatic(CordovaDevice,"cordovaPluginStatusBarInstalled", this,[])) { 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 (p && gs.gp(p,"catch")) { gs.mc(p,"catch",[gs.mc(gSobject,"function",[function(it) { }])]); } } catch (e) { } } catch (all) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("splashScreenHide:" + (all))]); } } } 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.mc(Utils,"setTimeout",[function(it) { return gs.mc(gs.fs('OurCodeWorldpreventscreenshots', this, gSobject),"enable",[]); }, 1]); return gs.mc(Utils,"setTimeout",[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.mc(Utils,"setTimeout",[function(it) { return gs.mc(gs.fs('OurCodeWorldpreventscreenshots', this, gSobject),"disable",[]); }, 1]); return gs.mc(Utils,"setTimeout",[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 (!gs.equals(initialViewportWidth, gs.gp(gs.gp(gs.fs('window', this, gSobject),"visualViewport"),"width"))) { gs.mc(Utils,"setTimeout",[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"]); 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"]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["setupCordovaPluginKeyboard:keyboard.show"]); } }]); } gSobject['getOrientation'] = function(it) { return gs.gp(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.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",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 batteryUpdate("normal", state); }, false]); gs.mc(gs.fs('window', this, gSobject),"addEventListener",["batterylow", function(state) { return batteryUpdate("low", state); }, false]); return gs.mc(gs.fs('window', this, gSobject),"addEventListener",["batterycritical", function(state) { return batteryUpdate("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",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 networkUpdate("offline"); }, false]); gs.mc(gs.fs('document', this, gSobject),"addEventListener",["online", function(it) { return networkUpdate("online"); }, false]); return networkUpdate("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.mc(Utils,"setTimeout",[function(it) { return listner(event); }, 0]); }]); } gSobject['vibrate'] = function(timeMs) { return gs.mc(gs.fs('navigator', this, gSobject),"vibrate",[timeMs]); } gSobject['statusBarShow'] = function(it) { if (!gs.execStatic(CordovaDevice,"cordovaPluginStatusBarInstalled", this,[])) { 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: " + (e))]); } } gSobject['statusBarHide'] = function(it) { if (!gs.execStatic(CordovaDevice,"cordovaPluginStatusBarInstalled", this,[])) { 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: " + (e))]); } } gSobject['statusBarColor'] = function(hex) { if (!gs.execStatic(CordovaDevice,"cordovaPluginStatusBarInstalled", this,[])) { 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: " + (e))]); } } gSobject['statusBarStyleLight'] = function(it) { if (!gs.execStatic(CordovaDevice,"cordovaPluginStatusBarInstalled", this,[])) { 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: " + (e))]); } } gSobject['statusBarStyleDark'] = function(it) { if (!gs.execStatic(CordovaDevice,"cordovaPluginStatusBarInstalled", this,[])) { 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: " + (e))]); } } gSobject['statusBarOverlay'] = function(overlay) { if (!gs.execStatic(CordovaDevice,"cordovaPluginStatusBarInstalled", this,[])) { 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: " + (e))]); } } 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 { (function(){var _o=gs.gp(gs.fs('screen', this, gSobject),"orientation");return _o!=null?gs.mc(_o,"unlock",[]):null;})(); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("unlockOrientation: " + (e))]); } } gSobject['hasPermission'] = function(name, callback) { if (!gs.execStatic(CordovaDevice,"permissionsInstalled", this,[])) { callback(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 callback(gs.map().add("hasPermission",false).add("error",e)); }]); } catch (e) { callback(gs.map().add("hasPermission",false).add("error",e)); } } gSobject['requestPermission'] = function(name, callback) { if (!gs.execStatic(CordovaDevice,"permissionsInstalled", this,[])) { callback(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 callback(gs.map().add("hasPermission",false).add("error",e)); }]); } catch (e) { callback(gs.map().add("hasPermission",false).add("error",e)); } } gSobject['hasPermissions'] = function(names, callback) { if (!gs.execStatic(CordovaDevice,"permissionsInstalled", this,[])) { callback(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 callback(gs.map().add("hasPermission",false).add("error",e)); }]); } catch (e) { callback(gs.map().add("hasPermission",false).add("error",e)); } } 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['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['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['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['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",(gSobject.userId ? gSobject.userId : "")).add("uuid",(gs.gp(gSobject.device,"uuid") ? gs.gp(gSobject.device,"uuid") : "")).add("platform",(gs.gp(gSobject.device,"platform") ? gs.gp(gSobject.device,"platform") : "browser")).add("appVersion",(gs.gp(gSobject.device,"version") ? gs.gp(gSobject.device,"version") : "")).add("appBuild",(gs.gp(gSobject.device,"cordova") ? gs.gp(gSobject.device,"cordova") : ""))]); return gs.mc(gSobject,"nativeFlushErrors",[]); } 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 (!(function(){var _o=userMessage;return _o!=null?gs.mc(_o,"trim",[]):null;})()) { return error("userMessage is required"); } return gs.mc(gs.fs('cordovaScreenCapture', this, gSobject),"reportProblem",[userMessage, opts, success, error]); } 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['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['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['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['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['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['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); }; gs.mc(gSobject,"installErrorCapture",[]); gs.mc(gs.fs('document', this, gSobject),"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.mc(gSobject,"cordovaPluginDeviceInstalled",[])) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaDevice:NOT INSTALLED"]); gs.mc(gSobject,"enableErrorFlush",[]); return null; } if (!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",["CordovaDevice:init:ERROR:" + all]); } return gs.mc(gSobject,"enableErrorFlush",[]); }]); gs.mc(Utils,"setTimeout",[function(it) { return gs.mc(gSobject,"splashScreenHide",[]); }, 1000]); 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 callback(eventData); }]); } gs.mc(gs.fs('document', this, gSobject),"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(this,"openDeepLink")]); }, false]); if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function ChatComponent() { var gSobject = PetBaseComponent(); gSobject.clazz = { name: 'ChatComponent', simpleName: 'ChatComponent'}; gSobject.clazz.superclass = { name: 'PetBaseComponent', simpleName: 'PetBaseComponent'}; gSobject.path = "/chat"; gSobject.roles = gs.list(["ROLE_USER"]); gSobject['created'] = function(it) { gs.mc(gSobject,"configurePage",["Chat", false]); gs.sp(gs.fs('scope', this, gSobject),"channels",gs.list([])); gs.sp(gs.fs('scope', this, gSobject),"activeChannel",null); gs.sp(gs.fs('scope', this, gSobject),"messages",gs.list([])); gs.sp(gs.fs('scope', this, gSobject),"command",""); gs.sp(gs.fs('scope', this, gSobject),"busy",false); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"chatService"),"listAllChannels",[function(result) { gs.sp(gs.fs('scope', this, gSobject),"channels",(result ? result : gs.list([]))); if (gs.mc(gs.gp(gs.fs('scope', this, gSobject),"channels"),"size",[]) > 0) { var dm = gs.mc(gs.gp(gs.fs('scope', this, gSobject),"channels"),"find",[function(it) { return gs.equals(gs.gp(it,"name"), "DM:CEO_Agent↔Human_CEO"); }]); gs.mc(gSobject,"selectChannel",[(dm ? dm : gs.gp(gs.fs('scope', this, gSobject),"channels")[0])]); } }]); } gSobject['selectChannel'] = function(channel) { if (!channel) { return null; } gs.sp(gs.fs('scope', this, gSobject),"activeChannel",channel); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"chatService"),"recentMessages",[gs.gp(channel,"_id"), 80, function(result) { return gs.sp(gs.fs('scope', this, gSobject),"messages",gs.mc((result ? result : gs.list([])),"reverse",[])); }]); } gSobject['sendCommand'] = function(it) { if (gs.gp(gs.fs('scope', this, gSobject),"busy") || !(function(){var _o=gs.gp(gs.fs('scope', this, gSobject),"command");return _o!=null?gs.mc(_o,"trim",[]):null;})()) { return null; } gs.sp(gs.fs('scope', this, gSobject),"busy",true); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"commandService"),"process",[gs.gp(gs.fs('scope', this, gSobject),"command"), "Human_CEO", gs.gp(gs.gp(gs.fs('scope', this, gSobject),"activeChannel"),"name"), function(_) { gs.sp(gs.fs('scope', this, gSobject),"busy",false); gs.sp(gs.fs('scope', this, gSobject),"command",""); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"chatService"),"recentMessages",[gs.gp(gs.gp(gs.fs('scope', this, gSobject),"activeChannel"),"_id"), 80, function(result) { return gs.sp(gs.fs('scope', this, gSobject),"messages",gs.mc((result ? result : gs.list([])),"reverse",[])); }]); }]); } gSobject['author'] = function(msg) { var a = gs.gp(msg,"fromAgentId"); return (a ? gs.mc((((gs.gp(a,"avatar") ? gs.gp(a,"avatar") : "")) + " " + ((gs.gp(a,"displayName") ? gs.gp(a,"displayName") : gs.gp(a,"handle")))),"trim",[]) : "system"); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function LegionPinComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'LegionPinComponent', simpleName: 'LegionPinComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/legionPin"; gSobject['created'] = function(it) { gs.println("LegionPinComponent.created()"); gs.sp(gSobject.scope,"pin",""); return gs.sp(gSobject.scope,"processing",false); } gSobject['pinAuth'] = function(it) { if (!gs.gp(gSobject.scope,"pin")) { gs.mc(gSobject,"notify",["Please enter pin", "negative"]); return null; } if (!gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username")) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/login"]); } gs.sp(gSobject.scope,"processing",true); return gs.mc(gs.fs('legionUserService', this, gSobject),"authWithPin",[gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username"), gs.gp(gSobject.scope,"pin"), function(result) { gs.println("result"); gs.println(result); gs.sp(gs.fs('session', this, gSobject),"user",gs.gp(gs.fs('session', this, gSobject),"legionUser")); gs.sp(gs.fs('session', this, gSobject),"userId",gs.gp(gs.fs('session', this, gSobject),"legionUserId")); gs.sp(gSobject.scope,"processing",false); return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/"]); }, function(error) { gs.mc(gSobject,"notify",[gs.gp(error,"message"), "negative"]); return gs.sp(gSobject.scope,"processing",false); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function RootComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.roles = gs.list(["ROLE_USER"]); gSobject['init'] = function(it) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"logout",gSobject.logout); if (gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"appConfig")) { return null; } } gSobject['afterMounted'] = function(it) { return gs.mc(gSobject,"handleLoggedIn",[]); } gSobject['handleLoggedIn'] = function(it) { gs.println("session.zonerId"); gs.println(gs.gp(gs.fs('session', this, gSobject),"zonerId")); gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"loggedIn",!gs.equals(gs.gp(gs.fs('session', this, gSobject),"zonerId"), null)); gs.println("vue.scope.loggedIn"); return gs.println(gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"loggedIn")); } gSobject['logout'] = function(it) { return gs.mc(gs.mc(gs.gp(gs.fs('Quasar', this, gSobject),"Dialog"),"create",[gs.map().add("title","Sign Out?").add("message","Are you sure you wish to sign out?").add("cancel",true).add("persistent",true)]),"onOk",[function(it) { return gs.mc(Utils,"logout",[]); }]); } gSobject['back'] = function(it) { return gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"back",[]); } gSobject['configurePage'] = function(title, back) { if (title === undefined) title = "page_title"; if (back === undefined) back = true; gs.println(((gs.gp(gs.gp(gSobject,"class"),"name")) + ".created()")); gs.mc(gSobject,"setPageTitle",[title]); return gs.mc(gSobject,"showBackBtn",[back]); } gSobject['setPageTitle'] = function(title) { if (title === undefined) title = "page_title"; return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"pageTitle",title); } gSobject['showBackBtn'] = function(val) { if (val === undefined) val = true; return gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"showBack",val); } gSobject['formatNumber'] = function(val) { return (val ? val : "0"); } gSobject['formatDate'] = function(date, format) { if (format === undefined) format = "DD MMM YYYY HH:mm"; return (date ? gs.mc(gs.mc(gSobject,"moment",[date]),"format",[format]) : ""); } gSobject['formatCurrency'] = function(val) { return (val ? gs.mc(gs.mc(gs.mc(gSobject,"parseFloat",[val]),"toFixed",[2]),"replaceAll",[/\B(?=(\d{3})+(?!\d))/, ","]) : "0.00"); } gSobject['toggleDarkMode'] = function(it) { gs.sp(gSobject.scope,"darkMode",!gs.gp(gSobject.scope,"darkMode")); gs.mc(gs.gp(gSobject.q,"dark"),"set",[gs.gp(gSobject.scope,"darkMode")]); return gs.mc(gSobject,"saveDarkModePreference",[gs.gp(gSobject.scope,"darkMode")]); } gSobject['initDarkMode'] = function(scope) { try { var saved = localStorage.getItem('twf_darkMode'); if (saved !== null) { var isDark = (saved === '1'); scope.darkMode = isDark; q.dark.set(isDark); } } catch(e) {} }; gSobject['saveDarkModePreference'] = function(enabled) { try { localStorage.setItem('twf_darkMode', enabled ? '1' : '0'); } catch(e) {} }; 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'}); } ); }; gs.mc(gs.fs('document', this, gSobject),"addEventListener",["deviceReady", function(it) { if (!gs.mc(gSobject,"isAvailable",[])) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova-plugin-contacts: Not Available"]); return null; } else { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["cordova-plugin-contacts: Available"]); } }]); 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 PdfJsHandler() { var gSobject = gs.init('PdfJsHandler'); gSobject.clazz = { name: 'PdfJsHandler', simpleName: 'PdfJsHandler'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'rendering', { get: function() { return PdfJsHandler.rendering; }, set: function(gSval) { PdfJsHandler.rendering = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'numberPending', { get: function() { return PdfJsHandler.numberPending; }, set: function(gSval) { PdfJsHandler.numberPending = gSval; }, enumerable: true }); gSobject['build'] = function(filePath, callback) { if (callback === undefined) callback = function(it) { }; return gs.execStatic(PdfJsHandler,"paintWholePdf", this,[filePath, callback]); } var filePath = arguments[0]; if (!filePath) { return null; } gs.mc(gSobject,"paintWholePdf",[filePath]); return gSobject; }; PdfJsHandler.paintWholePdf = function(filePath, callback) { spinnerDiv = document.createElement('div'); spinnerDiv.setAttribute("id", "spinner"); spinnerDiv.setAttribute("class", "fixed-center") spinner = document.createElement('div'); spinner.setAttribute("class", "i3-media-pdf-spinner"); spinnerDiv.append(spinner); $('#pdf-viewer').append(spinnerDiv); pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.10.111/pdf.worker.min.js'; var loadPdf = pdfjsLib.getDocument(filePath); loadPdf.promise.then(function(pdf) { const maxPage = pdf._pdfInfo.numPages; for (var i = 1; i <= maxPage; i++) { PdfJsHandler.renderPageScroll(pdf, i); } document.getElementById('spinner').remove(); callback() }) }; PdfJsHandler.renderPageScroll = function(pdf, number) { pdf.getPage(number).then(function(page) { const canvasId = 'pdf_viewer-' + number; $('#pdf-viewer').append($('', {'id': canvasId, 'style': 'object-fit:contain', 'class':'full-width'})); // $('#pdf-viewer').append($('', {'id': canvasId})); const canvas = document.getElementById(canvasId); const viewport = page.getViewport({scale: 1}); const context = canvas.getContext("2d"); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; const renderTask = page.render(renderContext); }); }; PdfJsHandler.paintPdf = function(filePath, getPage) { pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.10.111/pdf.worker.min.js'; var loadPdf = pdfjsLib.getDocument(filePath); loadPdf.promise.then(function(pdf) { const minPage = 1; const maxPage = pdf._pdfInfo.numPages; let currentPage = 1; PdfJsHandler.rendering = false; PdfJsHandler.numberPending = null; PdfJsHandler.renderPage(pdf, currentPage); document.getElementById("pdfPageNumber").innerHTML = `Page ${currentPage} of ${maxPage}`; document.getElementById("pdfPrev").addEventListener("click", () => { if (currentPage > minPage) { currentPage = currentPage - 1 PdfJsHandler.renderPage(pdf, currentPage); document.getElementById("pdfPageNumber").innerHTML = `Page ${currentPage} of ${maxPage}`; } }) document.getElementById("pdfNext").addEventListener("click", () => { if (currentPage < maxPage) { currentPage = currentPage + 1 PdfJsHandler.renderPage(pdf, currentPage); document.getElementById("pdfPageNumber").innerHTML = `Page ${currentPage} of ${maxPage}`; } }) }) }; PdfJsHandler.renderPage = function(pdf, number) { console.log('renderPage with ' + number + ', ' + PdfJsHandler.rendering + ', ' + PdfJsHandler.numberPending) if (PdfJsHandler.rendering) { PdfJsHandler.numberPending = number; } else { PdfJsHandler.rendering = true; pdf.getPage(number).then(function(page) { const canvas = document.getElementById("pdf_canvas"); const viewport = page.getViewport({scale: 1}); const context = canvas.getContext("2d"); canvas.height = viewport.height; canvas.width = viewport.width; var renderContext = { canvasContext: context, viewport: viewport }; const renderTask = page.render(renderContext); renderTask.promise.then(function() { PdfJsHandler.rendering = false; if (PdfJsHandler.numberPending !== null) { PdfJsHandler.renderPage(pdf, number); PdfJsHandler.numberPending = null; } }); }); } }; PdfJsHandler.rendering = false; PdfJsHandler.numberPending = null; function CordovaBrowser() { var gSobject = gs.init('CordovaBrowser'); gSobject.clazz = { name: 'CordovaBrowser', simpleName: 'CordovaBrowser'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['openInApp'] = function(url, options) { if (options === undefined) options = gs.map(); if (!gs.execStatic(CordovaBrowser,"browserInstalled", this,[])) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBrowser: InAppBrowser not installed"]); return null; } try { return gs.mc(gs.gp(gs.fs('cordova', this, gSobject),"InAppBrowser"),"open",[url, "_blank", gs.mc(gSobject,"optionsString",[options])]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("openInApp: " + (e))]); return null; } } gSobject['openSystem'] = function(url) { if (!gs.execStatic(CordovaBrowser,"browserInstalled", this,[])) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBrowser: InAppBrowser not installed"]); return null; } try { return gs.mc(gs.gp(gs.fs('cordova', this, gSobject),"InAppBrowser"),"open",[url, "_system"]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("openSystem: " + (e))]); return null; } } gSobject['openHidden'] = function(url, onLoad) { if (onLoad === undefined) onLoad = function(it) { }; if (!gs.execStatic(CordovaBrowser,"browserInstalled", this,[])) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBrowser: InAppBrowser not installed"]); return null; } try { var ref = gs.mc(gs.gp(gs.fs('cordova', this, gSobject),"InAppBrowser"),"open",[url, "_blank", "hidden=yes"]); gs.mc(ref,"addEventListener",["loadstop", function(event) { onLoad(event); try { gs.mc(ref,"close",[]); } catch (e2) { } }]); gs.mc(ref,"addEventListener",["loaderror", function(event) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("openHidden loaderror: " + (event))]); try { gs.mc(ref,"close",[]); } catch (e2) { } }]); return ref; } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("openHidden: " + (e))]); return null; } } gSobject['open'] = function(url, target, options) { if (target === undefined) target = "_blank"; if (options === undefined) options = gs.map(); if (!gs.execStatic(CordovaBrowser,"browserInstalled", this,[])) { return null; } try { return gs.mc(gs.gp(gs.fs('cordova', this, gSobject),"InAppBrowser"),"open",[url, target, gs.mc(gSobject,"optionsString",[options])]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("open: " + (e))]); return null; } } gSobject['optionsString'] = function(opts) { if (gs.equals(opts, null) || opts instanceof Object && gs.mc(opts,"isEmpty",[])) { return ""; } if (opts instanceof String) { return opts; } var parts = gs.list([]); gs.mc(opts,"each",[function(k, v) { return gs.mc(parts,"add",[((k) + "=" + (v))]); }]); return gs.mc(parts,"join",[","]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaBrowser.browserInstalled = function() { return typeof cordova !== 'undefined' && typeof cordova.InAppBrowser !== 'undefined'; }; function CordovaPushNotification() { var gSobject = gs.init('CordovaPushNotification'); gSobject.clazz = { name: 'CordovaPushNotification', simpleName: 'CordovaPushNotification'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.pushService = null; gSobject.notificationListeners = gs.list([]); gSobject.pushConfig = gs.map().add("android",gs.map().add("icon","ic_notification")).add("ios",gs.map().add("alert","true").add("badge","true").add("sound","true")).add("windows",gs.map()); gSobject['toLocation'] = function(path) { return gs.mc(Utils,"setTimeout",[function(it) { if (!gs.mc(path,"startsWith",["http"])) { path = gs.mc(gs.mc(gs.gp(gs.gp(gs.fs('window', this, gSobject),"location"),"href"),"toString",[]),"split",["#"])[0] + "#" + path; gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("CordovaPushNotificationService:path:" + (path))]); } return gs.sp(gs.fs('window', this, gSobject),"location",path); }, 1000]); } gSobject['subscribe'] = function(callback) { return gs.mc(gSobject.notificationListeners,"add",[callback]); } gs.mc(gs.fs('document', this, gSobject),"addEventListener",["deviceready", function(it) { if (!gs.mc(gSobject,"pluginInstalled",[])) { return null; } return gs.mc(gs.fs('legionUserService', this, gSobject),"loadLegionUser",[function(user) { gSobject.pushService = gs.mc(gs.fs('PushNotification', this, gSobject),"init",[gSobject.pushConfig]); gs.mc(gSobject.pushService,"on",["registration", function(data) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("CordovaPushNotificationService:registration:START:" + (gs.gp(user,"_id")) + ":" + (gs.mc(Utils,"deviceType",[])) + ":" + (gs.gp(data,"registrationId")))]); gs.mc(gSobject,"hasNotificationPermission",[function(status) { return gs.println(("CordovaPushNotificationService:registration:STATUS:" + (gs.gp(user,"_id")) + ":" + (status))); }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"cordovaDeviceNotificationService"),"registerDevice",[gs.gp(user,"_id"), gs.gp(data,"registrationId"), gs.mc(Utils,"deviceType",[]), function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("CordovaPushNotificationService:registration:DONE:" + (gs.gp(user,"_id")) + ":" + (gs.mc(Utils,"deviceType",[])) + ":" + (gs.gp(data,"registrationId")))]); }]); }]); gs.mc(gSobject.pushService,"on",["error", function(error) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("CordovaPushNotificationService:error:" + (error))]); }]); return gs.mc(gSobject.pushService,"on",["notification", function(data) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("Notification received by device - " + (data))]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[data]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("CordovaPushNotificationService:notification:1:" + (gs.gp(data,"message")))]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("CordovaPushNotificationService:notification:2:" + (gs.gp(gs.gp(data,"additionalData"),"foreground")))]); gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("CordovaPushNotificationService:notification:3:" + (gs.gp(gs.gp(data,"additionalData"),"url")))]); if (gSobject.notificationListeners) { gs.mc(gSobject.notificationListeners,"each",[function(callback) { return callback(data); }]); return null; } if (gs.equals(gs.gp(gs.gp(data,"additionalData"),"foreground"), false) && gs.gp(gs.gp(data,"additionalData"),"url")) { gs.mc(gSobject,"toLocation",[gs.gp(gs.gp(data,"additionalData"),"url")]); } }]); }]); }, false]); if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaPushNotification.pluginInstalled = function() { return ( typeof PushNotification !== 'undefined') }; CordovaPushNotification.hasNotificationPermission = function(callback) { if (!Utils.isCordova()) return false; var permissions = cordova.plugins.permissions; if (!permissions) return false console.log('permissions', permissions) permissions.checkPermission(permissions.POST_NOTIFICATIONS, function( status ){ if ( status.hasPermission ) { return callback(true); } else { permissions.requestPermission(permissions.POST_NOTIFICATIONS, function( result ){ return callback(result) }); } }); }; function CompanyDashboardComponent() { var gSobject = PetBaseComponent(); gSobject.clazz = { name: 'CompanyDashboardComponent', simpleName: 'CompanyDashboardComponent'}; gSobject.clazz.superclass = { name: 'PetBaseComponent', simpleName: 'PetBaseComponent'}; gSobject.path = "/company2"; gSobject.roles = gs.list(["ROLE_USER"]); gSobject['created'] = function(it) { gs.mc(gSobject,"configurePage",["Company2 — Multi-Agent Ops", false]); gs.sp(gs.fs('scope', this, gSobject),"activeTab","chat"); gs.sp(gs.fs('scope', this, gSobject),"channels",gs.list([])); gs.sp(gs.fs('scope', this, gSobject),"activeChannel",null); gs.sp(gs.fs('scope', this, gSobject),"messages",gs.list([])); gs.sp(gs.fs('scope', this, gSobject),"agents",gs.list([])); gs.sp(gs.fs('scope', this, gSobject),"board",null); gs.sp(gs.fs('scope', this, gSobject),"approvals",gs.list([])); gs.sp(gs.fs('scope', this, gSobject),"activity",gs.list([])); gs.sp(gs.fs('scope', this, gSobject),"command",""); gs.sp(gs.fs('scope', this, gSobject),"busy",false); gs.sp(gs.fs('scope', this, gSobject),"error",""); gs.sp(gs.fs('scope', this, gSobject),"helpOpen",false); gs.sp(gs.fs('scope', this, gSobject),"lastResult",null); gs.sp(gs.fs('scope', this, gSobject),"memoryHandle","Human_CEO"); gs.sp(gs.fs('scope', this, gSobject),"memorySummary",null); gs.sp(gs.fs('scope', this, gSobject),"memoryEditing",null); gs.sp(gs.fs('scope', this, gSobject),"memoryNewKey",""); gs.sp(gs.fs('scope', this, gSobject),"memoryNewValue",""); gs.sp(gs.fs('scope', this, gSobject),"memoryNewCat","note"); gs.sp(gs.fs('scope', this, gSobject),"memoryNewTags",""); gs.sp(gs.fs('scope', this, gSobject),"memoryNewPinned",false); gs.mc(gSobject,"loadAll",[]); gs.mc(Utils,"subscribe",["company2.message.posted", function(data) { return gs.mc(gSobject,"loadAll",[]); }]); gs.mc(Utils,"subscribe",["company2.task.changed", function(data) { gs.mc(gSobject,"loadBoard",[]); return gs.mc(gSobject,"loadApprovals",[]); }]); gs.mc(Utils,"subscribe",["company2.approval.changed", function(data) { return gs.mc(gSobject,"loadApprovals",[]); }]); return gs.mc(Utils,"subscribe",["company2.memory.changed", function(data) { return gs.mc(gSobject,"loadMemory",[]); }]); } gSobject['destroyed'] = function(it) { gs.mc(Utils,"unsubscribe",["company2.message.posted"]); gs.mc(Utils,"unsubscribe",["company2.task.changed"]); gs.mc(Utils,"unsubscribe",["company2.approval.changed"]); return gs.mc(Utils,"unsubscribe",["company2.memory.changed"]); } gSobject['loadAll'] = function(it) { gs.mc(gSobject,"loadChannels",[]); gs.mc(gSobject,"loadAgents",[]); gs.mc(gSobject,"loadBoard",[]); gs.mc(gSobject,"loadApprovals",[]); gs.mc(gSobject,"loadActivity",[]); return gs.mc(gSobject,"loadMemory",[]); } gSobject['loadChannels'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"chatService"),"listAllChannels",[function(result) { gs.sp(gs.fs('scope', this, gSobject),"channels",(result ? result : gs.list([]))); if (!gs.gp(gs.fs('scope', this, gSobject),"activeChannel") && gs.mc(gs.gp(gs.fs('scope', this, gSobject),"channels"),"size",[]) > 0) { var general = (gs.mc(gs.gp(gs.fs('scope', this, gSobject),"channels"),"find",[function(it) { return gs.equals(gs.gp(it,"name"), "#general"); }]) ? gs.mc(gs.gp(gs.fs('scope', this, gSobject),"channels"),"find",[function(it) { return gs.equals(gs.gp(it,"name"), "#general"); }]) : gs.gp(gs.fs('scope', this, gSobject),"channels")[0]); gs.mc(gSobject,"selectChannel",[general]); } }]); } gSobject['selectChannel'] = function(channel) { if (!channel) { return null; } gs.sp(gs.fs('scope', this, gSobject),"activeChannel",channel); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"chatService"),"recentMessages",[gs.gp(channel,"_id"), 80, function(result) { gs.sp(gs.fs('scope', this, gSobject),"messages",gs.mc((result ? result : gs.list([])),"reverse",[])); return gs.mc(gSobject,"scrollToBottom",[]); }]); } gSobject['loadAgents'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"agentService"),"listAll",[function(result) { return gs.sp(gs.fs('scope', this, gSobject),"agents",(result ? result : gs.list([]))); }]); } gSobject['loadBoard'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"taskService"),"boardSummary",[function(result) { return gs.sp(gs.fs('scope', this, gSobject),"board",result); }]); } gSobject['loadApprovals'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"approvalService"),"listPending",[function(result) { return gs.sp(gs.fs('scope', this, gSobject),"approvals",(result ? result : gs.list([]))); }]); } gSobject['loadActivity'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"chatService"),"globalActivity",[40, function(result) { return gs.sp(gs.fs('scope', this, gSobject),"activity",(result ? result : gs.list([]))); }]); } gSobject['loadMemory'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"memoryService"),"summaryFor",[(gs.gp(gs.fs('scope', this, gSobject),"memoryHandle") ? gs.gp(gs.fs('scope', this, gSobject),"memoryHandle") : "Human_CEO"), function(result) { return gs.sp(gs.fs('scope', this, gSobject),"memorySummary",result); }]); } gSobject['sendCommand'] = function(it) { var text = gs.mc((gs.gp(gs.fs('scope', this, gSobject),"command") ? gs.gp(gs.fs('scope', this, gSobject),"command") : ""),"trim",[]); if (!text || gs.gp(gs.fs('scope', this, gSobject),"busy")) { return null; } gs.sp(gs.fs('scope', this, gSobject),"busy",true); gs.sp(gs.fs('scope', this, gSobject),"error",""); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"commandService"),"process",[text, "Human_CEO", gs.gp(gs.gp(gs.fs('scope', this, gSobject),"activeChannel"),"name"), function(result) { gs.sp(gs.fs('scope', this, gSobject),"busy",false); gs.sp(gs.fs('scope', this, gSobject),"command",""); gs.sp(gs.fs('scope', this, gSobject),"lastResult",result); if (!gs.gp(result,"ok")) { gs.sp(gs.fs('scope', this, gSobject),"error",(gs.gp(result,"reply") ? gs.gp(result,"reply") : "Error")); } return gs.mc(gSobject,"loadAll",[]); }]); } gSobject['quickCommand'] = function(text) { gs.sp(gs.fs('scope', this, gSobject),"command",text); return gs.mc(gSobject,"sendCommand",[]); } gSobject['approveTask'] = function(task) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"approvalService"),"approve",[gs.gp(task,"_id"), "Human_CEO", "OK", function(_) { gs.mc(gSobject,"loadApprovals",[]); gs.mc(gSobject,"loadBoard",[]); return gs.mc(gSobject,"loadActivity",[]); }]); } gSobject['rejectTask'] = function(task) { var reason = gs.mc(gSobject,"prompt",["Reason for rejection:", "Not aligned with current priorities"]); if (gs.equals(reason, null)) { return null; } return gs.mc(gs.gp(gs.fs('o', this, gSobject),"approvalService"),"reject",[gs.gp(task,"_id"), "Human_CEO", reason, function(_) { gs.mc(gSobject,"loadApprovals",[]); gs.mc(gSobject,"loadBoard",[]); return gs.mc(gSobject,"loadActivity",[]); }]); } gSobject['switchMemoryView'] = function(handle) { gs.sp(gs.fs('scope', this, gSobject),"memoryHandle",handle); return gs.mc(gSobject,"loadMemory",[]); } gSobject['saveNewMemory'] = function(it) { var key = gs.mc((gs.gp(gs.fs('scope', this, gSobject),"memoryNewKey") ? gs.gp(gs.fs('scope', this, gSobject),"memoryNewKey") : ""),"trim",[]); var value = gs.mc((gs.gp(gs.fs('scope', this, gSobject),"memoryNewValue") ? gs.gp(gs.fs('scope', this, gSobject),"memoryNewValue") : ""),"trim",[]); if (!key || !value) { gs.sp(gs.fs('scope', this, gSobject),"error","Memory needs both a key and a value"); return null; } var tags = gs.mc(gs.mc(gs.mc((gs.gp(gs.fs('scope', this, gSobject),"memoryNewTags") ? gs.gp(gs.fs('scope', this, gSobject),"memoryNewTags") : ""),"split",[","]),"collect",[function(it) { return gs.mc(it,"trim",[]); }]),"findAll",[function(it) { return it; }]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"memoryService"),"remember",[gs.gp(gs.fs('scope', this, gSobject),"memoryHandle"), key, value, gs.map().add("summary",gs.mc(value,"take",[120])).add("category",(gs.gp(gs.fs('scope', this, gSobject),"memoryNewCat") ? gs.gp(gs.fs('scope', this, gSobject),"memoryNewCat") : "note")).add("tags",tags).add("source","ui:dashboard").add("pinned",gs.equals(gs.gp(gs.fs('scope', this, gSobject),"memoryNewPinned"), true)), function(result) { if (result) { gs.sp(gs.fs('scope', this, gSobject),"memoryNewKey",""); gs.sp(gs.fs('scope', this, gSobject),"memoryNewValue",""); gs.sp(gs.fs('scope', this, gSobject),"memoryNewTags",""); gs.sp(gs.fs('scope', this, gSobject),"memoryNewPinned",false); gs.sp(gs.fs('scope', this, gSobject),"error",""); gs.mc(gSobject,"loadMemory",[]); } else { gs.sp(gs.fs('scope', this, gSobject),"error","Failed to save memory"); } }]); } gSobject['forgetMemory'] = function(memoryId) { var rec = gs.mc((gs.gp(gs.gp(gs.fs('scope', this, gSobject),"memorySummary"),"recent") ? gs.gp(gs.gp(gs.fs('scope', this, gSobject),"memorySummary"),"recent") : gs.list([])),"find",[function(it) { return gs.equals(gs.gp(it,"_id"), memoryId); }]); if (!rec) { return null; } return gs.mc(gs.gp(gs.fs('o', this, gSobject),"memoryService"),"forget",[gs.gp(gs.fs('scope', this, gSobject),"memoryHandle"), gs.gp(rec,"key"), function(_) { return gs.mc(gSobject,"loadMemory",[]); }]); } gSobject['togglePin'] = function(memoryId) { var rec = gs.mc((gs.gp(gs.gp(gs.fs('scope', this, gSobject),"memorySummary"),"recent") ? gs.gp(gs.gp(gs.fs('scope', this, gSobject),"memorySummary"),"recent") : gs.list([])),"find",[function(it) { return gs.equals(gs.gp(it,"_id"), memoryId); }]); if (!rec) { return null; } return gs.mc(gs.gp(gs.fs('o', this, gSobject),"memoryService"),"recall",[gs.gp(gs.fs('scope', this, gSobject),"memoryHandle"), gs.gp(rec,"key"), function(full) { if (!full) { return null; } return gs.mc(gs.gp(gs.fs('o', this, gSobject),"memoryService"),"remember",[gs.gp(gs.fs('scope', this, gSobject),"memoryHandle"), gs.gp(rec,"key"), gs.gp(full,"value"), gs.map().add("summary",gs.gp(full,"summary")).add("category",(gs.gp(full,"category") instanceof String ? gs.gp(full,"category") : (gs.gp(gs.gp(full,"category"),"value") ? gs.gp(gs.gp(full,"category"),"value") : "note"))).add("tags",gs.gp(full,"tags")).add("source",gs.gp(full,"source")).add("pinned",!gs.equals(gs.gp(full,"pinned"), true)).add("confidence",gs.gp(full,"confidence")), function(_) { return gs.mc(gSobject,"loadMemory",[]); }]); }]); } gSobject['startEditMemory'] = function(memoryId) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"memoryService"),"recall",[gs.gp(gs.fs('scope', this, gSobject),"memoryHandle"), gs.gp(gs.mc((gs.gp(gs.gp(gs.fs('scope', this, gSobject),"memorySummary"),"recent") ? gs.gp(gs.gp(gs.fs('scope', this, gSobject),"memorySummary"),"recent") : gs.list([])),"find",[function(it) { return gs.equals(gs.gp(it,"_id"), memoryId); }]),"key"), function(full) { if (full) { gs.sp(gs.fs('scope', this, gSobject),"memoryEditing",full); } }]); } gSobject['cancelEdit'] = function(it) { return gs.sp(gs.fs('scope', this, gSobject),"memoryEditing",null); } gSobject['saveEdit'] = function(it) { var m = gs.gp(gs.fs('scope', this, gSobject),"memoryEditing"); if (!m) { return null; } return gs.mc(gs.gp(gs.fs('o', this, gSobject),"memoryService"),"remember",[gs.gp(gs.fs('scope', this, gSobject),"memoryHandle"), gs.gp(m,"key"), gs.gp(m,"value"), gs.map().add("summary",(function(){var _o=gs.gp(m,"value");return _o!=null?gs.mc(_o,"take",[120]):null;})()).add("category",(gs.gp(m,"category") instanceof String ? gs.gp(m,"category") : (gs.gp(gs.gp(m,"category"),"value") ? gs.gp(gs.gp(m,"category"),"value") : "note"))).add("tags",gs.gp(m,"tags")).add("source",gs.gp(m,"source")).add("pinned",gs.equals(gs.gp(m,"pinned"), true)).add("confidence",gs.gp(m,"confidence")), function(_) { gs.sp(gs.fs('scope', this, gSobject),"memoryEditing",null); return gs.mc(gSobject,"loadMemory",[]); }]); } gSobject['setTab'] = function(name) { gs.sp(gs.fs('scope', this, gSobject),"activeTab",name); if (gs.equals(name, "board")) { gs.mc(gSobject,"loadBoard",[]); } if (gs.equals(name, "approvals")) { gs.mc(gSobject,"loadApprovals",[]); } if (gs.equals(name, "activity")) { gs.mc(gSobject,"loadActivity",[]); } if (gs.equals(name, "memory")) { gs.mc(gSobject,"loadMemory",[]); } } gSobject['author'] = function(msg) { var a = gs.gp(msg,"fromAgentId"); if (!a) { return "system"; } return gs.mc((((gs.gp(a,"avatar") ? gs.gp(a,"avatar") : "")) + " " + ((gs.gp(a,"displayName") ? gs.gp(a,"displayName") : gs.gp(a,"handle")))),"trim",[]); } gSobject['channelTag'] = function(ch) { return (gs.equals(gs.gp(ch,"kind"), "direct") ? "🔒" : (gs.gp(ch,"isPrivate") ? "🔒" : "#")); } gSobject['formatTime'] = function(dt) { if (!dt) { return ""; } return gs.mc(Date(dt),"format",["HH:mm"]); } gSobject['formatDateTime'] = function(dt) { if (!dt) { return ""; } return gs.mc(Date(dt),"format",["MMM d HH:mm"]); } gSobject['priorityClass'] = function(p) { return "pri-" + (p ? p : "P2"); } gSobject['statusClass'] = function(s) { return "st-" + (s ? s : "backlog"); } gSobject['taskPriority'] = function(task) { return (gs.gp(task,"priority") instanceof String ? gs.gp(task,"priority") : (gs.gp(gs.gp(task,"priority"),"value") ? gs.gp(gs.gp(task,"priority"),"value") : "P2")); } gSobject['taskStatus'] = function(task) { return (gs.gp(task,"status") instanceof String ? gs.gp(task,"status") : (gs.gp(gs.gp(task,"status"),"value") ? gs.gp(gs.gp(task,"status"),"value") : "backlog")); } gSobject['messageKindClass'] = function(msg) { return "mk-" + (gs.gp(msg,"kind") instanceof String ? gs.gp(msg,"kind") : (gs.gp(gs.gp(msg,"kind"),"value") ? gs.gp(gs.gp(msg,"kind"),"value") : "message")); } gSobject['memoryCategoryLabel'] = function(cat) { if (!cat) { return "note"; } return (cat instanceof String ? cat : (gs.gp(cat,"value") ? gs.gp(cat,"value") : "note")); } gSobject['scrollToBottom'] = function(it) { return gs.sp(gs.fs('scope', this, gSobject),"tick",(gs.gp(gs.fs('scope', this, gSobject),"tick") ? gs.gp(gs.fs('scope', this, gSobject),"tick") : 0) + 1); } gSobject['agentForHandle'] = function(handle) { return (function(){var _o=gs.gp(gs.fs('scope', this, gSobject),"agents");return _o!=null?gs.mc(_o,"find",[function(it) { return gs.equals(gs.gp(it,"handle"), handle); }]):null;})(); } gSobject['toggleHelp'] = function(it) { return gs.sp(gs.fs('scope', this, gSobject),"helpOpen",!gs.gp(gs.fs('scope', this, gSobject),"helpOpen")); } gSobject['memoryCategories'] = function(it) { return gs.list(["note", "plan", "decision", "context", "preference", "feedback", "reference", "people"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function AdminConfigComponent() { var gSobject = RootComponent(); gSobject.clazz = { name: 'AdminConfigComponent', simpleName: 'AdminConfigComponent'}; gSobject.clazz.superclass = { name: 'RootComponent', simpleName: 'RootComponent'}; gSobject.path = "/adminConfig"; gSobject['created'] = function(it) { gs.println("AdminConfigComponent.created()"); gs.mc(gSobject,"setPageTitle",["Admin Configuration"]); gs.sp(gSobject.scope,"appTab","settings"); gs.sp(gSobject.scope,"menuItemDialog",false); gs.sp(gSobject.scope,"menuItems",gs.list([])); gs.sp(gSobject.scope,"selectedMenuItem",null); gs.sp(gSobject.scope,"columns",gs.list([gs.map().add("name","order").add("label","Order").add("field","order").add("align","left"), gs.map().add("name","label").add("label","Label").add("field","label").add("align","left"), gs.map().add("name","icon").add("label","Icon").add("field","icon").add("align","left"), gs.map().add("name","call").add("label","Call").add("field","call").add("align","left"), gs.map().add("name","route").add("label","Route").add("field","route").add("align","left"), gs.map().add("name","parentKey").add("label","Parent").add("field","parentKey").add("align","left"), gs.map().add("name","_lastUpdated").add("label","Last Updated").add("field",function(row) { return gs.mc(gSobject,"formatDate",[gs.gp(row,"_lastUpdated")]); }).add("align","left")])); gs.sp(gSobject.scope,"appConfigLoaded",false); gs.sp(gSobject.scope,"splitter","400"); gs.sp(gSobject.scope,"activeProduct",gs.gp(gs.fs('session', this, gSobject),"activeProduct")); gs.sp(gSobject.scope,"clientProducts",gs.list([])); gs.sp(gSobject.scope,"menuProductOptions",gs.list([])); gs.sp(gSobject.scope,"appConfig",gs.map()); gs.sp(gSobject.scope,"loginConfig",null); gs.sp(gSobject.scope,"sizeOptions",gs.list([gs.map().add("label","XSmall").add("value","xs"), gs.map().add("label","Small").add("value","sm"), gs.map().add("label","Medium").add("value","md"), gs.map().add("label","Large").add("value","lg"), gs.map().add("label","XLarge").add("value","xl")])); gs.sp(gSobject.scope,"menubuttonOptions",gs.list([gs.map().add("label","Flat").add("value","flat"), gs.map().add("label","Unelevated").add("value","unelevated"), gs.map().add("label","No Caps").add("value","noCaps"), gs.map().add("label","Outline").add("value","outline"), gs.map().add("label","Rounded").add("value","rounded"), gs.map().add("label","Push").add("value","push"), gs.map().add("label","Square").add("value","square"), gs.map().add("label","Glossy").add("value","glossy"), gs.map().add("label","Dense").add("value","dense")])); gs.sp(gSobject.scope,"inputOptions",gs.list([gs.map().add("label","Filled").add("value","filled"), gs.map().add("label","Outlined").add("value","outlined"), gs.map().add("label","Standout").add("value","standout"), gs.map().add("label","Rounded").add("value","rounded"), gs.map().add("label","Borderless").add("value","borderless"), gs.map().add("label","Square").add("value","square"), gs.map().add("label","Dense").add("value","dense")])); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"appConfigService"),"fetchClientProducts",[function(data) { gs.sp(gSobject.scope,"clientProducts",data); gs.sp(gSobject.scope,"menuProductOptions",gs.list([gs.map().add("name","Global (all apps)").add("id","*")]) + data); if (!gs.gp(gs.fs('session', this, gSobject),"activeProduct")) { gs.sp(gs.fs('session', this, gSobject),"activeProduct",gs.gp((gs.mc(data,"find",[function(it) { return gs.gp(it,"current"); }]) ? gs.mc(data,"find",[function(it) { return gs.gp(it,"current"); }]) : data[0]),"id")); } gs.sp(gSobject.scope,"activeProduct",gs.gp(gs.fs('session', this, gSobject),"activeProduct")); gs.mc(gSobject,"loadMenuItems",[]); if (gs.gp(gs.fs('session', this, gSobject),"activeProduct")) { gs.mc(gSobject,"loadAppConfig",[]); gs.mc(gSobject,"loadLoginConfig",[]); } }]); } gSobject['loadMenuItems'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"i3AdminService"),"loadMenuItems",[gs.gp(gSobject.scope,"activeProduct"), function(data) { return gs.sp(gSobject.scope,"menuItems",data); }]); } gSobject['selectMenuItem'] = function(evt, menuItem, index) { return gs.mc(gSobject,"openMenuItemDialog",[menuItem]); } gSobject['addMenuItem'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"i3AdminService"),"newMenuItem",[function(menuItem) { if (gs.gp(gSobject.scope,"activeProduct")) { gs.sp(menuItem,"productId",gs.gp(gSobject.scope,"activeProduct")); } return gs.mc(gSobject,"openMenuItemDialog",[menuItem]); }]); } gSobject['saveMenuItem'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"i3AdminService"),"saveMenuItem",[gs.gp(gSobject.scope,"selectedMenuItem"), function(it) { gs.mc(gSobject,"resetMenuItemDialog",[]); return gs.mc(gSobject,"notify",["Menu Item Updated"]); }]); } gSobject['deleteMenuItem'] = function(it) { return gs.mc(gs.mc(gSobject.q,"dialog",[gs.map().add("title","Delete Menu Item?").add("message","Are you sure you wish to delete this menu item? This action is irreversible").add("cancel",true)]),"onOk",[function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"i3AdminService"),"deleteMenuItem",[gs.gp(gs.gp(gSobject.scope,"selectedMenuItem"),"_id"), function(it) { gs.mc(gSobject,"resetMenuItemDialog",[]); return gs.mc(gSobject,"notify",["Item Deleted", "negative"]); }]); }]); } gSobject['openMenuItemDialog'] = function(menuItem) { gs.sp(gSobject.scope,"selectedMenuItem",menuItem); return gs.sp(gSobject.scope,"menuItemDialog",true); } gSobject['resetMenuItemDialog'] = function(it) { gs.sp(gSobject.scope,"menuItemDialog",false); gs.sp(gSobject.scope,"selectedMenuItem",null); return gs.mc(gSobject,"loadMenuItems",[]); } gSobject['updateActiveProduct'] = function(it) { gs.sp(gs.fs('session', this, gSobject),"activeProduct",gs.gp(gSobject.scope,"activeProduct")); gs.mc(gSobject,"loadAppConfig",[]); gs.mc(gSobject,"loadMenuItems",[]); return gs.mc(gSobject,"loadLoginConfig",[]); } gSobject['loadAppConfig'] = function(it) { gs.mc(gSobject,"showLoading",[]); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"appConfigService"),"appConfig",[gs.gp(gs.fs('session', this, gSobject),"activeProduct"), function(data) { gs.mc(gSobject,"hideLoading",[]); gs.sp(gSobject.scope,"appConfig",data); gs.sp(gSobject.scope,"appConfigLoaded",true); return gs.mc(gs.gp(gs.gp(gSobject.scope,"appConfig"),"theme"),"each",[function(color, value) { return gs.mc(gSobject,"updateColor",[color, value]); }]); }]); } gSobject['updateColor'] = function(color, value) { if (value) { gs.mc(gs.fs('Quasar', this, gSobject),"setCssVar",[color, gs.mc(value,"toString",[])]); } } gSobject['logoSaved'] = function(logoName) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"appConfigService"),"logoSaved",[gs.gp(gs.fs('session', this, gSobject),"activeProduct"), logoName, function(result) { return gs.mc(gSobject,"notify",["Logo updated"]); }]); } gSobject['saveConfig'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"appConfigService"),"saveAppConfig",[gs.gp(gs.fs('session', this, gSobject),"activeProduct"), gs.gp(gSobject.scope,"appConfig"), function(data) { return gs.mc(gSobject,"notify",["Config Saved"]); }]); } gSobject['loadLoginConfig'] = function(it) { return gs.mc(gs.gp(gs.fs('o', this, gSobject),"i3AdminService"),"loadLoginConfig",[gs.gp(gSobject.scope,"activeProduct"), function(data) { return gs.sp(gSobject.scope,"loginConfig",data); }]); } gSobject['saveLoginConfig'] = function(it) { var payload = gs.map().add("productId",gs.gp(gSobject.scope,"activeProduct")).add("authMethod",gs.gp(gs.gp(gSobject.scope,"loginConfig"),"authMethod")).add("webauthnEnabled",gs.gp(gs.gp(gSobject.scope,"loginConfig"),"webauthnEnabled")).add("welcome",gs.gp(gs.gp(gSobject.scope,"loginConfig"),"welcome")); return gs.mc(gs.gp(gs.fs('o', this, gSobject),"i3AdminService"),"saveLoginConfig",[payload, function(data) { gs.sp(gSobject.scope,"loginConfig",data); return gs.mc(gSobject,"notify",["Login settings saved"]); }]); } gSobject['loginImageSaved'] = function(it) { gs.mc(gSobject,"loadLoginConfig",[]); return gs.mc(gSobject,"notify",["Image updated"]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; 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 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 = gSobject; } gSobject['afterMounted'] = function(it) { if (gs.gp(gSobject.self,"text")) { gs.mc(gSobject,"generateQrCode",[]); } } gSobject['watchText'] = function(it) { if (gs.gp(gSobject.self,"text") && gs.gp(gSobject.refs,"qrCodeRef")) { gs.mc(gSobject,"generateQrCode",[]); } } gSobject['generateQrCode'] = function(it) { if (!gs.gp(gSobject.refs,"qrCodeRef")) { return null; } if (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 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.gp(self,"optionLabel") ? gs.gp(self,"optionLabel") : "name")); }; gSobject['mounted'] = function(it) { var self = gSobject; } gSobject['watchValue'] = function(newValue, oldValue) { var self = gSobject; return gs.sp(self,"objectValue",newValue); } gSobject['lookupObjects'] = function(val, update, abort) { if (val === undefined) val = null; if (update === undefined) update = function(it) { return it(); }; if (abort === undefined) abort = null; var self = gSobject; if (gs.gp(self,"options")) { update(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 update(function(it) { gs.sp(self,"optionsList",dbOptionsList); return gs.mc(gSobject,"configLabel",[self]); }); }]); } gSobject['configLabel'] = function(self) { if (gs.gp(self,"onLabel")) { gs.sp(self,"optionLabel",gs.gp(self,"onLabel")); } } gSobject['objectSelected'] = function(it) { var self = gSobject; gs.mc(self,"$emit",["input", gs.gp(self,"objectValue")]); if (gs.gp(self,"onSelect")) { gs.mc(self,"onSelect",[gs.gp(self,"objectValue")]); } } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function HammerJsZoom() { var gSobject = gs.init('HammerJsZoom'); gSobject.clazz = { name: 'HammerJsZoom', simpleName: 'HammerJsZoom'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; var elmName = arguments[0]; gs.execStatic(HammerJsZoom,"showHammerZoom", this,[elmName]); return gSobject; }; HammerJsZoom.showHammerZoom = function(name) { var elm = document.getElementById(name); var hammertime = new Hammer(elm, {}); hammertime.get('pinch').set({ enable: true }); console.log('hammertime') console.log(hammertime) var posX = 0, posY = 0, scale = 1, last_scale = 1, last_posX = 0, last_posY = 0, max_pos_x = 0, max_pos_y = 0, transform = "", el = elm; hammertime.on('doubletap pinch pan panend pinchend', function(ev) { console.log('event') console.log(ev) if (ev.type == "doubletap") { console.log('doubletapped') transform = "translate3d(0, 0, 0) " + "sacle3d(2, 2, 1) "; scale = 2; last_sacle = 2; try{ if (window.getComputedStyle(el, null).getPropertyValue('-webkit-transform').toString() != "matrix(1, 0, 0, 1, 0, 0)") { transform = "translate3d(0, 0, 0) " + "scale3d(1, 1, 1) "; scale = 1; last_scale = 1; } } catch (err){} el.style.webkitTransform = transform; transform = "" } //pan if (scale != 1) { console.log('pan') posX = last_posX + ev.deltaX; posY = last_posY + ev.deltaY; max_pos_x = Math.ceil((scale - 1) * el.clientWidth / 2); max_pos_y = Math.ceil((scale - 1) * el.clientHeight / 2); if (posX > max_pos_x) { posX = max_pos_x; } if (posX < -max_pos_x) { posX = -max_pos_x; } if (posY > max_pos_y) { posY = max_pos_y; } if (posY < -max_pos_y) { posY = -max_pos_y; } } //pinch if (ev.type == "pinch") { console.log('pinch') scale = Math.max(.999, Math.min(last_scale * (ev.scale), 4)); } if(ev.type == "pinchend"){last_scale = scale;} //panend if(ev.type == "panend"){ console.log('panend') last_posX = posX < max_pos_x ? posX : max_pos_x; last_posY = posY < max_pos_y ? posY : max_pos_y; } if (scale != 1) { console.log('scale not 1') transform = "translate3d(" + posX + "px," + posY + "px, 0) " + "scale3d(" + scale + ", " + scale + ", 1)"; } if (transform) { console.log('transform') el.style.webkitTransform = transform; } }); }; function VueDocumentViewer() { var gSobject = VueComponent(); gSobject.clazz = { name: 'VueDocumentViewer', simpleName: 'VueDocumentViewer'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.props = gs.list(["oObject", "oName", "oPropName", "download", "filePreview", "displayName", "myStyle"]); gSobject.data = function(it) { return gs.map().add("showFullscreenDialog",false); }; gSobject['mounted'] = function(it) { var self = gSobject; var fileInfo = gs.gp(self,"oObject")[gs.gp(self,"oPropName")]; var lastUpdated = gs.gp(gs.gp(self,"oObject"),"_lastUpdated"); try { lastUpdated = gs.mc(lastUpdated,"getTime",[]); } catch (all) { } gs.sp(self,"pdfUrl",("/media-cache/file/" + (gs.gp(gs.gp(self,"oObject"),"_id")) + "/" + (gs.gp(self,"oPropName")) + "/" + (lastUpdated) + "/" + (gs.gp(fileInfo,"filename")))); gs.sp(self,"preview",("/media-cache/filePreview/" + (gs.gp(gs.gp(self,"oObject"),"_id")) + "/" + (gs.gp(self,"oPropName")) + "/" + (lastUpdated) + "/" + (gs.gp(fileInfo,"filename")))); if (!gs.gp(self,"download")) { gs.sp(self,"download",false); } if (!gs.gp(self,"filePreview")) { gs.sp(self,"filePreview",false); } if (!gs.gp(self,"displayName")) { gs.sp(self,"displayName",false); } return gs.sp(self,"showFullscreenDialog",false); } gSobject['objectLoaded'] = function(it) { var self = gSobject; if (!gs.gp(self,"oObject")) { return false; } return true; } gSobject['show'] = function(it) { var self = gSobject; if (!gs.gp(self,"filePreview")) { return null; } gs.mc(gs.gp(gs.mc(gSobject,"getRefs",[]),"dialog"),"show",[]); gs.mc(gSobject,"nextTick",[function(it) { PdfJsHandler(gs.gp(self,"pdfUrl")); return HammerJsZoom("pdf_canvas"); }]); if (gs.mc(Utils,"isCordova",[])) { gs.mc(gs.gp(gs.fs('screen', this, gSobject),"orientation"),"lock",["any"]); } } gSobject['hideFullscreenDialog'] = function(it) { gs.sp(gSobject.self,"showFullscreenDialog",false); if (gs.mc(Utils,"isCordova",[])) { gs.mc(gs.gp(gs.fs('screen', this, gSobject),"orientation"),"lock",["portrait"]); } } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaBle() { var gSobject = gs.init('CordovaBle'); gSobject.clazz = { name: 'CordovaBle', simpleName: 'CordovaBle'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject.initialized = false; gSobject.scanning = false; gSobject.discoveredDevices = gs.map(); gSobject.connectedDevices = gs.map(); Object.defineProperty(gSobject, 'singletonInstance', { get: function() { return CordovaBle.singletonInstance; }, set: function(gSval) { CordovaBle.singletonInstance = gSval; }, enumerable: true }); 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.execStatic(CordovaBle,"bleInstalled", this,[])) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",["CordovaBle: bluetoothle not installed"]); callback(gs.map().add("status","unavailable")); return gSobject; } try { gs.mc(gs.fs('bluetoothle', this, gSobject),"initialize",[function(result) { gSobject.initialized = gs.equals(gs.gp(result,"status"), "enabled"); return callback(result); }, params]); } catch (e) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"info",[("CordovaBle.initialize error: " + (e))]); callback(gs.map().add("status","error").add("message",((e)))); } return gSobject; } gSobject['isEnabled'] = function(callback) { if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { callback(gs.map().add("isEnabled",false)); return gSobject; } try { gs.mc(gs.fs('bluetoothle', this, gSobject),"isEnabled",[callback]); } catch (e) { callback(gs.map().add("isEnabled",false)); } return gSobject; } gSobject['enable'] = function(success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { error(gs.map().add("message","BLE not installed")); return gSobject; } try { gs.mc(gs.fs('bluetoothle', this, gSobject),"enable",[success, error]); } catch (e) { error(gs.map().add("message",((e)))); } return gSobject; } 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.execStatic(CordovaBle,"bleInstalled", this,[])) { onError(gs.map().add("message","BLE not installed")); return gSobject; } 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.mc(gSobject.discoveredDevices,"containsKey",[gs.gp(result,"address")])) { var dev = gs.map().add("name",(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; onDevice(dev); } } }, function(e) { gSobject.scanning = false; return onError(e); }, params]); } catch (e) { gSobject.scanning = false; onError(gs.map().add("message",((e)))); } return gSobject; } gSobject['stopScan'] = function(callback) { if (callback === undefined) callback = function(it) { }; if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { callback(gs.map()); return gSobject; } try { gs.mc(gs.fs('bluetoothle', this, gSobject),"stopScan",[function(r) { gSobject.scanning = false; return callback(r); }, function(e) { gSobject.scanning = false; return callback(gs.map().add("error",e)); }]); } catch (e) { gSobject.scanning = false; callback(gs.map().add("error",((e)))); } return gSobject; } gSobject['isScanning'] = function(callback) { if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { callback(gs.map().add("isScanning",false)); return gSobject; } try { gs.mc(gs.fs('bluetoothle', this, gSobject),"isScanning",[callback]); } catch (e) { callback(gs.map().add("isScanning",gSobject.scanning)); } return gSobject; } gSobject['getAdapterInfo'] = function(callback) { if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { callback(gs.map()); return gSobject; } try { gs.mc(gs.fs('bluetoothle', this, gSobject),"getAdapterInfo",[callback]); } catch (e) { callback(gs.map().add("error",((e)))); } return gSobject; } gSobject['connect'] = function(address, onStatus, onError) { if (onStatus === undefined) onStatus = function(it) { }; if (onError === undefined) onError = function(it) { }; if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { onError(gs.map().add("message","BLE not installed")); return gSobject; } 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 onStatus(result); }, onError, gs.map().add("address",address)]); } catch (e) { onError(gs.map().add("message",((e)))); } return gSobject; } gSobject['disconnect'] = function(address, success, error) { if (success === undefined) success = function(it) { }; if (error === undefined) error = function(it) { }; if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { error(gs.map().add("message","BLE not installed")); return gSobject; } 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 success(r); }, error, gs.map().add("address",address)]); } catch (e) { error(gs.map().add("message",((e)))); } return gSobject; } gSobject['discoverServices'] = function(address, callback) { if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { callback(gs.map()); return gSobject; } try { gs.mc(gs.fs('bluetoothle', this, gSobject),"discover",[callback, function(e) { return callback(gs.map().add("error",e)); }, gs.map().add("address",address)]); } catch (e) { callback(gs.map().add("error",((e)))); } return gSobject; } gSobject['read'] = function(address, service, characteristic, callback) { if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { callback(gs.map()); return gSobject; } try { gs.mc(gs.fs('bluetoothle', this, gSobject),"read",[callback, function(e) { return callback(gs.map().add("error",e)); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic)]); } catch (e) { callback(gs.map().add("error",((e)))); } return gSobject; } gSobject['write'] = function(address, service, characteristic, value, callback) { if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { callback(gs.map()); return gSobject; } try { gs.mc(gs.fs('bluetoothle', this, gSobject),"write",[callback, function(e) { return callback(gs.map().add("error",e)); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic).add("value",value)]); } catch (e) { callback(gs.map().add("error",((e)))); } return gSobject; } gSobject['subscribe'] = function(address, service, characteristic, onNotify) { if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { return gSobject; } 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: " + (e))]); } return gSobject; } gSobject['unsubscribe'] = function(address, service, characteristic, callback) { if (callback === undefined) callback = function(it) { }; if (!gs.execStatic(CordovaBle,"bleInstalled", this,[])) { callback(gs.map()); return gSobject; } try { gs.mc(gs.fs('bluetoothle', this, gSobject),"unsubscribe",[callback, function(e) { return callback(gs.map().add("error",e)); }, gs.map().add("address",address).add("service",service).add("characteristic",characteristic)]); } catch (e) { callback(gs.map().add("error",((e)))); } return gSobject; } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaBle.bleInstalled = function() { return typeof window.bluetoothle !== 'undefined'; }; CordovaBle.instance = function() { if (!CordovaBle.singletonInstance) { CordovaBle.singletonInstance = CordovaBle(); } return CordovaBle.singletonInstance; } CordovaBle.singletonInstance = null; 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) { onSuccess(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",[config]); return gs.execStatic(CordovaPhoto,"pick", this,[opts, function(result) { return onSuccess(gs.gp(result,"data")); }, onFail]); } 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 DevReload() { var gSobject = gs.init('DevReload'); gSobject.clazz = { name: 'DevReload', simpleName: 'DevReload'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; Object.defineProperty(gSobject, 'clientSaleStatus', { get: function() { return DevReload.clientSaleStatus; }, set: function(gSval) { DevReload.clientSaleStatus = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'devMode', { get: function() { return DevReload.devMode; }, set: function(gSval) { DevReload.devMode = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'tagName', { get: function() { return DevReload.tagName; }, set: function(gSval) { DevReload.tagName = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'productIdsRaw', { get: function() { return DevReload.productIdsRaw; }, set: function(gSval) { DevReload.productIdsRaw = gSval; }, enumerable: true }); Object.defineProperty(gSobject, 'productIds', { get: function() { return DevReload.productIds; }, set: function(gSval) { DevReload.productIds = gSval; }, enumerable: true }); if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; DevReload.init = function() { // Guard: only subscribe once per page lifetime. // The jsDynamo bundle is re-executed on every hot reload, so without this // guard each save would create a new setInterval and add duplicate subscriptions. if (window.__devReloadInitDone) return window.__devReloadInitDone = true // Resolve the server-injected simple-path values into runtime forms. DevReload.devMode = (DevReload.clientSaleStatus === 'Develop') DevReload.productIds = (DevReload.productIdsRaw || '').replace(/[\[\]]/g, '').split(',').map(function(s){ return s.trim() }).filter(function(s){ return s.length }) console.log('DevReload: init(), tag=' + DevReload.tagName + ', devMode=' + DevReload.devMode + ', productIds=' + JSON.stringify(DevReload.productIds)) if (!DevReload.devMode) return function handleMessage(message) { // Spring serialises via Jackson so body arrives JSON-quoted — unwrap first. var body = message.body || '' try { body = JSON.parse(body) } catch(e) {} console.log('DevReload: message received, body=' + body) if (body.indexOf('css:') === 0) { DevReload.reloadCss(body.substring(4)) } else if (body.indexOf('view:') === 0) { DevReload.reloadViews(body.substring(5)) } else if (body.indexOf('grooscript:') === 0) { DevReload.reloadGrooscript(body.substring(11)) } } // Track the last STOMP client we subscribed to. // On WebSocket reconnect, socketConnect() creates a NEW Stomp client and assigns // it to Socket.websocketClient. The old subscriptions are gone. By comparing // the reference we detect the reconnect and re-subscribe automatically. var subscribedClient = null setInterval(function() { if (typeof Socket === 'undefined' || !Socket.websocketClient || !Socket.websocketClient.connected) return if (Socket.websocketClient === subscribedClient) return // still the same connection — nothing to do subscribedClient = Socket.websocketClient var ids = DevReload.productIds || [] ids.forEach(function(pid) { Socket.websocketClient.subscribe('/topic/devReload/' + pid, handleMessage) console.log('DevReload: subscribed to /topic/devReload/' + pid + ' (tag=' + DevReload.tagName + ')') }) }, 500) }; DevReload.reloadCss = function(version) { console.log('DevReload: reloading CSS, v=' + version) document.querySelectorAll('link[rel="stylesheet"]').forEach(function(link) { if (!link.href.includes('/resourceBundle/')) return var base = link.href.split('?')[0] link.href = base + '?v=' + version console.log('DevReload: swapped CSS', base) }) }; DevReload.reloadViews = function(version) { console.log('DevReload: reloadViews v=' + version) fetch('/resourceBundle/packCode/htmlBody?v=' + version) .then(function(res) { return res.text() }) .then(function(html) { // Parse all x-template blocks and update the DOM var updatedHtmlMap = {} var regex = /]*type="text\/x-template"[^>]*id="([^"]+)"[^>]*>([\s\S]*?)<\/script>/gi var match while ((match = regex.exec(html)) !== null) { var el = document.getElementById(match[1]) if (el) { el.innerHTML = match[2] updatedHtmlMap[match[1]] = match[2] } } console.log('DevReload: updated DOM templates:', Object.keys(updatedHtmlMap)) DevReload.patchComponents(updatedHtmlMap) DevReload.forceRemount() }) .catch(function(err) { console.error('DevReload: reloadViews failed', err) }) }; DevReload.patchComponents = function(updatedHtmlMap) { var patched = [] function patchComp(comp) { if (!comp || patched.indexOf(comp) >= 0) return var tid = null // Strategy 1: comp.template is still the '#id' selector if (comp.template && comp.template.charAt(0) === '#') { var sel = comp.template.substring(1) if (updatedHtmlMap[sel]) tid = sel } // Strategy 2: comp.template is inline HTML from a previous reload — // identify by name convention (vueComponentName + 'View') if (!tid && comp.vueComponentName) { var nameId = comp.vueComponentName + 'View' if (updatedHtmlMap[nameId]) tid = nameId } if (!tid) return comp.template = updatedHtmlMap[tid] delete comp.render delete comp.__vccOpts patched.push(comp) console.log('DevReload: patched component', comp.vueComponentName, '(template', tid + ')') } if (vue && vue.componentList) { vue.componentList.forEach(function(c) { patchComp(c) }) } if (vue && vue.router && vue.router.getRoutes) { vue.router.getRoutes().forEach(function(route) { if (!route.components) return Object.keys(route.components).forEach(function(k) { patchComp(route.components[k]) }) }) } console.log('DevReload: patched', patched.length, 'component object(s)') if (patched.length === 0) { console.warn('DevReload: no components matched — possible naming mismatch') } }; DevReload.reloadGrooscript = function(payload) { var colonIdx = payload.indexOf(':') var version = colonIdx > 0 ? payload.substring(colonIdx + 1) : payload console.log('DevReload: reloading GrooScript, v=' + version) DevReload.reloadFullBundle(version) }; DevReload.reloadFullBundle = function(version) { console.log('DevReload: reloading jsDynamo bundle, v=' + version) vue.componentList.splice(0, vue.componentList.length) var script = document.createElement('script') script.src = '/resourceBundle/pack/jsDynamo?v=' + version script.onload = function() { console.log('DevReload: jsDynamo loaded —', vue.componentList.length, 'components') // Re-register all components globally vue.componentList.forEach(function(comp) { if (comp.vueComponentName) vue.vue.component(comp.vueComponentName, comp) }) // Build name → new component lookup var nameToComp = {} vue.componentList.forEach(function(comp) { if (comp.vueComponentName) nameToComp[comp.vueComponentName] = comp }) // Resync router route records to the new component objects var routesResynced = 0 if (vue && vue.router && vue.router.getRoutes) { vue.router.getRoutes().forEach(function(route) { if (!route.components) return Object.keys(route.components).forEach(function(k) { var oldComp = route.components[k] var name = oldComp && oldComp.vueComponentName if (name && nameToComp[name] && nameToComp[name] !== oldComp) { route.components[k] = nameToComp[name] routesResynced++ } }) }) } console.log('DevReload: resynced', routesResynced, 'router route record(s)') // Re-apply current DOM innerHTML to every new component to preserve // any view edits made before this Grooscript save var domSynced = 0 vue.componentList.forEach(function(comp) { if (!comp.template || comp.template.charAt(0) !== '#') return var el = document.getElementById(comp.template.substring(1)) if (!el) return comp.template = el.innerHTML delete comp.render delete comp.__vccOpts domSynced++ }) console.log('DevReload: re-applied current DOM to', domSynced, 'component(s)') DevReload.forceRemount() } script.onerror = function() { console.error('DevReload: failed to load jsDynamo bundle') } document.head.appendChild(script) }; DevReload.forceRemount = function() { if (typeof vue === 'undefined' || !vue.router) return var currentPath = vue.router.currentRoute.value.fullPath console.log('DevReload: remounting', currentPath) vue.router.replace('/__devreload__').then(function() { return vue.router.replace(currentPath) }).then(function() { var matched = vue.router.currentRoute.value.matched for (var i = 0; i < matched.length; i++) { var component = matched[i].components && matched[i].components.default if (component && typeof component.created === 'function') { var name = component.vueComponentName var formattedName = name.charAt(0).toLowerCase() + name.slice(1) eval(formattedName + '.created()') console.log('DevReload: called created() on', formattedName) } } }).catch(function(err) { console.error('DevReload: navigation error', err) }) }; DevReload.clientSaleStatus = "Live"; DevReload.devMode = false; DevReload.tagName = "dev"; DevReload.productIdsRaw = "[ff8080819edb5a7e019edbad46270024, 4028608871cff10901720fd0955917a4, 40286088768ac07801769d83ee64090a, ff8080819d7b7481019d81fdb9050514, ff8080818acc73dd018acca3523f01b7, 40286088611c6a51016156c363af36c5, ff808081915097e6019155913c5b0161, ff8080819551333d0195609f82110182, 40286088549b592b01549b5b569001f6, ff808081797511320179755dd9240012, 40286088611c6a510161479109ba2ee9, 402860886900527c01690b0cbd8c18eb, 2093f3837b9bdffb017b9fcb500504d6, 40286088549b592b01549b5be67302ec, 402860886705fd580167182933d7207e]"; DevReload.productIds = gs.list([]); 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]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; CordovaBiometrics.verifyBiometricsPlugin = function() { return ( window?.Fingerprint !== undefined) }; function LegionRegisterComponent() { var gSobject = VueComponent(); gSobject.clazz = { name: 'LegionRegisterComponent', simpleName: 'LegionRegisterComponent'}; gSobject.clazz.superclass = { name: 'VueComponent', simpleName: 'VueComponent'}; gSobject.path = "/register"; gSobject['created'] = function(it) { gs.println("LegionRegisterComponent.created()"); gs.sp(gSobject.scope,"email",""); gs.sp(gSobject.scope,"phoneNumber",""); return gs.sp(gSobject.scope,"processing",false); } gSobject['generatePin'] = function(it) { gs.sp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username",(gs.gp(gSobject.scope,"email") ? gs.gp(gSobject.scope,"email") : gs.gp(gSobject.scope,"phoneNumber"))); if (!gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username")) { gs.mc(gSobject,"notify",["Please enter details", "negative"]); return null; } gs.sp(gSobject.scope,"processing",true); return gs.mc(gs.mc(gs.gp(gs.fs('o', this, gSobject),"legionAuthService"),"generatePinForNewOrExistingUser",[gs.gp(gs.gp(gs.fs('vue', this, gSobject),"scope"),"username"), true, (gs.gp(gSobject.scope,"phoneNumber") ? true : false)]),"then",[function(it) { gs.mc(gs.gp(gs.fs('vue', this, gSobject),"router"),"push",["/legionPin"]); gs.mc(gSobject,"notify",["Pin Sent"]); return gs.sp(gSobject.scope,"processing",false); }, function(error) { gs.mc(gSobject,"notify",[gs.gp(error,"message"), "negative"]); return gs.sp(gSobject.scope,"processing",false); }]); } if (arguments.length == 1) {gs.passMapToObject(arguments[0],gSobject);}; return gSobject; }; function CordovaLocalNotification() { var gSobject = gs.init('CordovaLocalNotification'); gSobject.clazz = { name: 'CordovaLocalNotification', simpleName: 'CordovaLocalNotification'}; gSobject.clazz.superclass = { name: 'java.lang.Object', simpleName: 'Object'}; gSobject['hasPermission'] = function(callback) { return gs.mc(gSobject,"nativeHasPermission",[callback]); } gSobject['requestPermission'] = function(callback) { return gs.mc(gSobject,"nativeRequestPermission",[callback]); } gSobject['schedule'] = function(options, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gSobject,"nativeSchedule",[options, callback]); } gSobject['cancel'] = function(id, callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gSobject,"nativeCancel",[id, callback]); } gSobject['cancelAll'] = function(callback) { if (callback === undefined) callback = function(it) { }; return gs.mc(gSobject,"nativeCancelAll",[callback]); } gSobject['on'] = function(event, callback) { return gs.mc(gSobject,"nativeOn",[event, callback]); } gSobject['getAll'] = function(callback) { return gs.mc(gSobject,"nativeGetAll",[callback]); } gSobject['nativeHasPermission'] = function(callback) { var p = null; if (typeof cordova !== 'undefined' && cordova.plugins) { p = cordova.plugins.dymicoLocalNotification || (cordova.plugins.notification && cordova.plugins.notification.local); } if (p && p.hasPermission) { p.hasPermission(callback); } else { console.log('[LocalNotif] hasPermission: no plugin'); if (callback) callback(false); } }; gSobject['nativeRequestPermission'] = function(callback) { var p = null; if (typeof cordova !== 'undefined' && cordova.plugins) { p = cordova.plugins.dymicoLocalNotification || (cordova.plugins.notification && cordova.plugins.notification.local); } if (p && p.requestPermission) { p.requestPermission(callback); } else { console.log('[LocalNotif] requestPermission: no plugin'); if (callback) callback(false); } }; gSobject['nativeSchedule'] = function(options, callback) { var p = null; if (typeof cordova !== 'undefined' && cordova.plugins) { p = cordova.plugins.dymicoLocalNotification || (cordova.plugins.notification && cordova.plugins.notification.local); } if (p && p.schedule) { console.log('[LocalNotif] scheduling:', JSON.stringify(options)); p.schedule(options, callback); } else { console.log('[LocalNotif] schedule: no plugin. keys:', typeof cordova !== 'undefined' && cordova.plugins ? Object.keys(cordova.plugins).join(',') : 'n/a'); if (callback) callback(); } }; gSobject['nativeCancel'] = function(id, callback) { var p = null; if (typeof cordova !== 'undefined' && cordova.plugins) { p = cordova.plugins.dymicoLocalNotification || (cordova.plugins.notification && cordova.plugins.notification.local); } if (p && p.cancel) { p.cancel(id, callback); } else { if (callback) callback(); } }; gSobject['nativeCancelAll'] = function(callback) { var p = null; if (typeof cordova !== 'undefined' && cordova.plugins) { p = cordova.plugins.dymicoLocalNotification || (cordova.plugins.notification && cordova.plugins.notification.local); } if (p && p.cancelAll) { p.cancelAll(callback); } else { if (callback) callback(); } }; gSobject['nativeOn'] = function(event, callback) { var p = null; if (typeof cordova !== 'undefined' && cordova.plugins) { p = cordova.plugins.dymicoLocalNotification || (cordova.plugins.notification && cordova.plugins.notification.local); } if (p && p.on) { p.on(event, callback); } else { console.log('[LocalNotif] on(' + event + '): no plugin'); } }; gSobject['nativeGetAll'] = function(callback) { var p = null; if (typeof cordova !== 'undefined' && cordova.plugins) { p = cordova.plugins.dymicoLocalNotification || (cordova.plugins.notification && cordova.plugins.notification.local); } if (p && p.getScheduledIds) { p.getScheduledIds(callback); } else { if (callback) callback([]); } }; 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.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 (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",!gs.equals(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.gp(result,"id")) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",["CordovaScreenCapture:reportProblem:userProblem returned no id"]); return error("Failed to create problem report"); } if (!blob) { return success(gs.gp(result,"id")); } return gs.mc(Utils,"post",[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 success(gs.gp(result,"id")); }, function(uploadErr) { gs.mc(gs.gp(gs.fs('o', this, gSobject),"log"),"error",[("CordovaScreenCapture:reportProblem:screenshot upload failed: " + (uploadErr))]); return success(gs.gp(result,"id")); }]); }]); } gSobject['buildReportContext'] = function(userMessage, opts, meta) { var ctx = gs.mc(gSobject,"nativeGatherContext",[]); return gs.map().add("userMessage",(userMessage ? userMessage : "")).add("severity",(gs.gp(opts,"severity") ? gs.gp(opts,"severity") : "normal")).add("message",(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.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.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"version") ? gs.gp(gs.gp(gs.fs('cordovaDevice', this, gSobject),"device"),"version") : "")).add("appBuild",(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(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