forked from openiap/opencore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommonControllers.ts
More file actions
362 lines (345 loc) · 15.6 KB
/
Copy pathCommonControllers.ts
File metadata and controls
362 lines (345 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
module openflow {
"use strict";
class messagequeue {
constructor(
public msg: QueueMessage,
public callback: any) { }
}
interface IHashTable<T> {
[key: string]: T;
}
export type mapFunc = () => void;
export type reduceFunc = (key: string, values: any[]) => any;
export type finalizeFunc = (key: string, value: any) => any;
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
export class api {
static $inject = ["$rootScope", "$location", "WebSocketClient"];
public messageQueue: IHashTable<messagequeue> = {};
constructor(public $rootScope: ng.IRootScopeService, public $location, public WebSocketClient: WebSocketClient) {
var formerlog = console.log.bind(window.console);
var formerwarn = console.warn.bind(window.console);
var formerdebug = console.debug.bind(window.console);
console.log = (msg) => {
formerlog.apply(console, { arguments: arguments });
var log = { message: msg, _type: "message" };
this.Insert("jslog", log);
}
console.warn = (msg) => {
formerwarn.apply(console, { arguments: arguments });
var log = { message: msg, _type: "warning" };
this.Insert("jslog", log);
}
console.debug = (msg) => {
formerdebug.apply(console, { arguments: arguments });
var log = { message: msg, _type: "debug" };
this.Insert("jslog", log);
}
window.onerror = (message, url, linenumber) => {
var log = { message: message, url: url, linenumber: linenumber, _type: "error" };
this.Insert("jslog", log);
}
var cleanup = $rootScope.$on('queuemessage', (event, data: QueueMessage) => {
if (event && data) { }
if (this.messageQueue[data.correlationId] !== undefined) {
this.messageQueue[data.correlationId].callback(data);
delete this.messageQueue[data.correlationId];
}
});
}
async Query(collection: string, query: any, projection: any = null, orderby: any = { _created: -1 }, top: number = 500, skip: number = 0): Promise<any[]> {
var q: QueryMessage = new QueryMessage();
q.collectionname = collection; q.query = query;
q.projection = projection; q.orderby = orderby; q.top = top; q.skip = skip;
var msg: Message = new Message(); msg.command = "query"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<QueryMessage>(msg);
return q.result;
}
async MapReduce(collection: string, map: mapFunc, reduce: reduceFunc, finalize: finalizeFunc, query: any, out: string | any, scope: any): Promise<any> {
var q: MapReduceMessage = new MapReduceMessage(map, reduce, finalize, query, out);
q.collectionname = collection; q.scope = scope;
var msg: Message = new Message(); msg.command = "mapreduce"; q.out = out;
// msg.data = JSON.stringify(q);
msg.data = JSONfn.stringify(q);
q = await this.WebSocketClient.Send<MapReduceMessage>(msg);
return q.result;
}
async Insert(collection: string, model: any): Promise<any> {
var q: InsertOneMessage = new InsertOneMessage();
q.collectionname = collection; q.item = model;
var msg: Message = new Message(); msg.command = "insertone"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<InsertOneMessage>(msg);
return q.result;
}
async Update(collection: string, model: any): Promise<any> {
var q: UpdateOneMessage = new UpdateOneMessage();
q.collectionname = collection; q.item = model;
var msg: Message = new Message(); msg.command = "updateone"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<UpdateOneMessage>(msg);
return q.result;
}
async Delete(collection: string, model: any): Promise<void> {
var q: DeleteOneMessage = new DeleteOneMessage();
q.collectionname = collection; q._id = model._id;
var msg: Message = new Message(); msg.command = "deleteone"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<DeleteOneMessage>(msg);
}
async RegisterQueue(queuename: string = undefined): Promise<void> {
var q: RegisterQueueMessage = new RegisterQueueMessage();
q.queuename = queuename;
var msg: Message = new Message(); msg.command = "registerqueue"; msg.data = JSON.stringify(q);
await this.WebSocketClient.Send(msg);
}
async _QueueMessage(queuename: string, data: any): Promise<QueueMessage> {
return new Promise<QueueMessage>(async (resolve, reject) => {
var q: QueueMessage = new QueueMessage();
q.correlationId = Math.random().toString(36).substr(2, 9);
q.queuename = queuename; q.data = JSON.stringify(data);
var msg: Message = new Message(); msg.command = "queuemessage"; msg.data = JSON.stringify(q);
this.messageQueue[q.correlationId] = new messagequeue(q, (msgresult: QueueMessage) => {
resolve(msgresult);
});
await this.WebSocketClient.Send(msg);
});
}
async QueueMessage(queuename: string, data: any): Promise<any> {
var result: any = await this._QueueMessage(queuename, data);
var msg = result.data;
try {
result.data = JSON.parse(result.data);
} catch (error) {
}
return msg;
}
}
export class JSONfn {
public static stringify(obj) {
return JSON.stringify(obj, function (key, value) {
return (typeof value === 'function') ? value.toString() : value;
});
}
public static parse(str) {
return JSON.parse(str, function (key, value) {
if (typeof value != 'string') return value;
return (value.substring(0, 8) == 'function') ? eval('(' + value + ')') : value;
});
}
}
function _timeSince(timeStamp) {
var now: Date = new Date(),
secondsPast: number = (now.getTime() - timeStamp.getTime()) / 1000;
if (secondsPast < 60) {
return parseInt(secondsPast.toString()) + 's';
}
if (secondsPast < 3600) {
return parseInt((secondsPast / 60).toString()) + 'm';
}
if (secondsPast <= 86400) {
return parseInt((secondsPast / 3600).toString()) + 'h';
}
if (secondsPast > 86400) {
let day = timeStamp.getDate();
let month = timeStamp.toDateString().match(/ [a-zA-Z]*/)[0].replace(" ", "");
let year = timeStamp.getFullYear() == now.getFullYear() ? "" : " " + timeStamp.getFullYear();
return day + " " + month + year;
}
}
export class timesince implements ng.IDirective {
// restrict = 'E';
require = 'ngModel';
replace = true;
constructor(public $location: ng.ILocationService, public $timeout: ng.ITimeoutService) {
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attr: ng.IAttributes, ngModelCtrl: any) => {
scope.$watch(() => {
if (ngModelCtrl.$viewValue === null || ngModelCtrl.$viewValue === undefined) { return; }
var timeStamp = ngModelCtrl.$viewValue;
element.text(_timeSince(new Date(timeStamp)));
});
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService) => new timesince($location, $timeout);
directive.$inject = ['$location', '$timeout'];
return directive;
}
}
async function getString(locale: any, lib: string, key: string): Promise<any> {
return new Promise((resolve) => {
try {
if (locale === null || locale === undefined) { return resolve(); }
locale.ready(lib).then(function () {
var value = locale.getString(lib + "." + key);
if (value !== null && value !== undefined && value !== "") {
resolve(value);
} else {
resolve(key);
}
});
} catch (error) {
}
});
}
var global_translate_notfound: string[] = [];
export class translate implements ng.IDirective {
require = '?ngModel';
replace = true;
constructor(public $location: ng.ILocationService, public $timeout: ng.ITimeoutService, public locale) {
}
link: ng.IDirectiveLinkFn = (scope: ng.IScope, element: ng.IAugmentedJQuery, attr: ng.IAttributes, ngModelCtrl: any) => {
var calculateValue = (value: string): string => {
if (value === null || value === undefined || value === "") return value;
var lib = (attr.lib ? attr.lib : "common");
if ((value.toString()).startsWith(lib + ".")) { return; }
var key: string = (lib + "." + value).toLowerCase();
var result = this.locale.getString(key);
if (result.startsWith(lib + ".")) { result = result.slice((lib + ".").length); }
// var result = await getString(this.locale, lib, value);
if (result == "%%KEY_NOT_FOUND%%" || result == "") {
if (global_translate_notfound.indexOf(lib + "." + value) === -1) {
global_translate_notfound.push(lib + "." + value);
console.log("KEY_NOT_FOUND " + lib + "." + value);
}
result = value;
}
return result;
};
var lib = (attr.lib ? attr.lib : "common");
this.locale.ready(lib).then(() => {
var value: string = null;
if (ngModelCtrl !== null) {
ngModelCtrl.$formatters.push(function (value) {
return calculateValue(value);
});
// value = calculateValue(ngModelCtrl.$viewValue);
// ngModelCtrl.$setViewValue(this.result);
// ngModelCtrl.$render();
} else {
var hashCode = (s: string) => {
return s.split("").reduce(function (a, b) { a = ((a << 5) - a) + b.charCodeAt(0); return a & a }, 0);
}
var watchFunction = () => {
if (attr.value !== null && attr.value !== undefined) {
return hashCode(attr.value);
} else {
var value = element.text();
if (value !== null || value !== undefined) {
return hashCode(value);
}
return value;
}
};
// attrs.$observe('i18n', function (newVal, oldVal) {
// });
//scope.$watch(watchFunction, () => {
if (attr.value !== null && attr.value !== undefined) {
value = calculateValue(attr.value);
attr.$set('value', value);
} else {
value = element.text();
if (value !== null || value !== undefined) {
var result = calculateValue(value);
// console.log(value + "=" + result);
element.text(result);
}
}
//});
}
});
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService, locale) => new translate($location, $timeout, locale);
directive.$inject = ['$location', '$timeout', 'locale'];
return directive;
}
}
export class entitiesCtrl<T> {
public basequery: any = {};
public baseprojection: any = {};
public collection: string = "entities";
public models: T[] = [];
public orderby: any = { _created: -1 };
public static $inject = [
"$scope",
"$location",
"$routeParams",
"WebSocketClient",
"api"
];
constructor(
public $scope: ng.IScope,
public $location: ng.ILocationService,
public $routeParams: ng.route.IRouteParamsService,
public WebSocketClient: WebSocketClient,
public api: api
) {
}
async loadData(): Promise<void> {
var q: QueryMessage = new QueryMessage();
q.collectionname = this.collection; q.query = this.basequery;
q.projection = this.baseprojection; q.orderby = this.orderby;
var msg: Message = new Message(); msg.command = "query"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<QueryMessage>(msg);
this.models = q.result;
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
ToggleOrder(field: string) {
if (this.orderby[field] == undefined) {
this.orderby = {};
}
if (this.orderby[field] == -1) {
this.orderby[field] = 1;
} else {
this.orderby[field] = -1;
}
if (field === '_type') {
this.orderby["type"] = this.orderby[field];
}
this.loadData();
}
}
export class entityCtrl<T> {
public basequery: any = {};
public baseprojection: any = {};
public collection: string = "entities";
public model: T = null;
public id: string = null;
public keys: string[] = [];
public static $inject = [
"$scope",
"$location",
"$routeParams",
"WebSocketClient",
"api"
];
constructor(
public $scope: ng.IScope,
public $location: ng.ILocationService,
public $routeParams: ng.route.IRouteParamsService,
public WebSocketClient: WebSocketClient,
public api: api
) {
this.id = $routeParams.id;
this.basequery = { _id: this.id };
}
async loadData(): Promise<void> {
var q: QueryMessage = new QueryMessage();
q.collectionname = this.collection; q.query = this.basequery;
q.projection = this.baseprojection; q.top = 1;
var msg: Message = new Message(); msg.command = "query"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<QueryMessage>(msg);
if (q.result.length > 0) { this.model = q.result[0]; }
this.keys = Object.keys(this.model);
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
}
}