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
863 lines (830 loc) · 40.4 KB
/
Copy pathCommonControllers.ts
File metadata and controls
863 lines (830 loc) · 40.4 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
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 cleanup1 = this.$rootScope.$on('socketopen', (event, data) => {
if (event && data) { }
this.gettoken();
// cleanup();
});
//['log', 'warn', 'debug', 'error'].forEach((methodName) => {
['error2'].forEach((methodName) => {
const originalMethod = console[methodName];
console[methodName] = (...args) => {
let initiator = 'unknown place';
try {
throw new Error();
} catch (e) {
if (typeof e.stack === 'string') {
let isFirst = true;
for (const line of e.stack.split('\n')) {
const matches = line.match(/^\s+at\s+(.*)/);
if (matches) {
if (!isFirst) { // first line - current function
// second line - caller (what we are looking for)
initiator = matches[1];
break;
}
isFirst = false;
}
}
}
}
initiator = (initiator.length > 100) ? initiator.substr(0, 100 - 1) : initiator;
var _type = "message";
if (methodName == "warn") _type = "warning";
if (methodName == "debug") _type = "debug";
if (methodName == "error") _type = "error";
var a = args[0];
try {
if (a == "[object Object]") {
a = JSON.stringify(args[0]);
}
} catch (error) {
}
var log = { message: a, _type: _type, host: window.location.hostname, initiator: initiator };
this.Insert("jslog", log).catch(() => { });
//originalMethod.apply(console, [...args, `\n at ${initiator}`]);
originalMethod.apply(console, [...args]);
};
});
window.onerror = (message, url, linenumber) => {
var log = { message: message, url: url, linenumber: linenumber, _type: "error", host: window.location.hostname };
this.Insert("jslog", log).catch(() => { });
}
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];
}
});
}
gettoken() {
this.WebSocketClient.getJSON("/jwt", async (error: any, data: any) => {
try {
if (data !== null && data !== undefined) {
if (data.jwt === null || data.jwt === undefined || data.jwt.trim() === "") { data.jwt = null; }
if (data.rawAssertion === null || data.rawAssertion === undefined || data.rawAssertion.trim() === "") { data.rawAssertion = null; }
if (data.jwt === null && data.rawAssertion === null) {
console.debug("data.jwt and data.rawAssertion is null");
data = null;
}
}
if (data === null || data === undefined) {
if (this.$location.path() !== "/Login" && this.$location.path() !== "/Signup") {
var _url = this.$location.absUrl();
this.setCookie("url", _url, 365);
this.$location.path("/Login");
this.$rootScope.$apply();
}
return;
}
await this.SigninWithToken(data.jwt, data.rawAssertion, null);
} catch (error) {
this.WebSocketClient.user = null;
console.error(error);
this.$location.path("/Login");
this.$rootScope.$apply();
}
});
}
async SigninWithToken(jwt: string, rawAssertion: string, impersonate: string): Promise<SigninMessage> {
var q: SigninMessage = new SigninMessage();
q.jwt = jwt;
q.rawAssertion = rawAssertion;
q.realm = "browser";
q.clientagent = "webapp";
q.clientversion = this.WebSocketClient.version;
if (this.WebSocketClient.usingCordova) {
q.realm = "mobile";
q.clientagent = "mobileapp";
}
q.impersonate = impersonate;
q.onesignalid = this.WebSocketClient.oneSignalId;
q.device = this.WebSocketClient.device;
q.gpslocation = this.WebSocketClient.location;
var msg: Message = new Message(); msg.command = "signin"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<SigninMessage>(msg);
this.WebSocketClient.user = q.user;
this.WebSocketClient.jwt = q.jwt;
this.$rootScope.$broadcast("signin", q);
return q;
}
async SigninWithUsername(username: string, password: string, impersonate: string): Promise<SigninMessage> {
var q: SigninMessage = new SigninMessage();
q.username = username;
q.password = password;
q.realm = "browser";
q.clientagent = "webapp";
q.clientversion = this.WebSocketClient.version;
if (this.WebSocketClient.usingCordova) {
q.realm = "mobile";
q.clientagent = "mobileapp";
}
q.impersonate = impersonate;
q.onesignalid = this.WebSocketClient.oneSignalId;
q.device = this.WebSocketClient.device;
q.gpslocation = this.WebSocketClient.location;
var msg: Message = new Message(); msg.command = "signin"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<SigninMessage>(msg);
this.WebSocketClient.user = q.user;
this.WebSocketClient.jwt = q.jwt;
this.$rootScope.$broadcast("signin", q);
return q;
}
async ListCollections(): Promise<any[]> {
var q: ListCollectionsMessage = new ListCollectionsMessage();
var msg: Message = new Message(); msg.command = "listcollections"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<ListCollectionsMessage>(msg);
return q.result;
}
async DropCollection(collectionname: string): Promise<void> {
var q: DropCollectionMessage = new DropCollectionMessage();
q.collectionname = collectionname;
var msg: Message = new Message(); msg.command = "dropcollection"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<DropCollectionMessage>(msg);
}
async Query(collection: string, query: any, projection: any = null, orderby: any = { _id: -1 }, top: number = 100, skip: number = 0, queryas: string = null): Promise<any[]> {
var q: QueryMessage = new QueryMessage();
q.collectionname = collection; q.query = query; q.queryas = queryas;
q.query = JSON.stringify(query, (key, value) => {
if (value instanceof RegExp)
return ("__REGEXP " + value.toString());
else
return value;
});
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 Aggregate(collection: string, aggregates: object[]): Promise<any> {
var q: AggregateMessage = new AggregateMessage();
q.collectionname = collection; q.aggregates = aggregates;
var msg: Message = new Message(); msg.command = "aggregate";
msg.data = JSONfn.stringify(q);
var result = await this.WebSocketClient.Send<QueryMessage>(msg);
return result.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<string> {
var q: RegisterQueueMessage = new RegisterQueueMessage();
q.queuename = queuename;
var msg: Message = new Message(); msg.command = "registerqueue"; msg.data = JSON.stringify(q);
var result: RegisterQueueMessage = await this.WebSocketClient.Send(msg);
return result.queuename;
}
async _QueueMessage(queuename: string, replyto: string, data: any, expiration: number): Promise<QueueMessage> {
return new Promise<QueueMessage>(async (resolve, reject) => {
try {
var q: QueueMessage = new QueueMessage();
q.correlationId = Math.random().toString(36).substr(2, 9);
q.expiration = expiration;
q.queuename = queuename; q.data = JSON.stringify(data);
q.replyto = replyto;
var msg: Message = new Message(); msg.command = "queuemessage"; msg.data = JSON.stringify(q);
this.messageQueue[q.correlationId] = new messagequeue(q, (msgresult: QueueMessage) => {
resolve(msgresult);
delete this.messageQueue[q.correlationId];
});
var res = await this.WebSocketClient.Send(msg);
} catch (error) {
reject(error);
}
});
}
async QueueMessage(queuename: string, replyto: string, data: any, expiration: number): Promise<any> {
var result: any = await this._QueueMessage(queuename, replyto, data, expiration);
var msg = result.data;
try {
result.data = JSON.parse(result.data);
} catch (error) {
}
return msg;
}
async GetNoderedInstance(_id: string, name: string): Promise<any[]> {
var q: GetNoderedInstanceMessage = new GetNoderedInstanceMessage(); q.name = name; q._id = _id;
var msg: Message = new Message(); msg.command = "getnoderedinstance"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<GetNoderedInstanceMessage>(msg);
return q.results;
}
async GetNoderedInstanceLog(_id: string, name: string): Promise<string> {
var q: GetNoderedInstanceLogMessage = new GetNoderedInstanceLogMessage(); q.name = name; q._id = _id;
var msg: Message = new Message(); msg.command = "getnoderedinstancelog"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<GetNoderedInstanceLogMessage>(msg);
return q.result;
}
async EnsureNoderedInstance(_id: string, name: string): Promise<void> {
var q: EnsureNoderedInstanceMessage = new EnsureNoderedInstanceMessage(); q.name = name; q._id = _id;
var msg: Message = new Message(); msg.command = "ensurenoderedinstance"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<EnsureNoderedInstanceMessage>(msg);
}
async DeleteNoderedInstance(_id: string, name: string): Promise<void> {
var q: DeleteNoderedInstanceMessage = new DeleteNoderedInstanceMessage(); q.name = name; q._id = _id;
var msg: Message = new Message(); msg.command = "deletenoderedinstance"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<DeleteNoderedInstanceMessage>(msg);
}
async DeleteNoderedPod(_id: string, name: string): Promise<void> {
var q: DeleteNoderedPodMessage = new DeleteNoderedPodMessage(); q.name = name; q._id = _id;
var msg: Message = new Message(); msg.command = "deletenoderedpod"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<DeleteNoderedPodMessage>(msg);
}
async RestartNoderedInstance(_id: string, name: string): Promise<void> {
var q: RestartNoderedInstanceMessage = new RestartNoderedInstanceMessage(); q.name = name; q._id = _id;
var msg: Message = new Message(); msg.command = "restartnoderedinstance"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<RestartNoderedInstanceMessage>(msg);
}
async StartNoderedInstance(_id: string, name: string): Promise<void> {
var q: StartNoderedInstanceMessage = new StartNoderedInstanceMessage(); q.name = name; q._id = _id;
var msg: Message = new Message(); msg.command = "startnoderedinstance"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<StartNoderedInstanceMessage>(msg);
}
async StopNoderedInstance(_id: string, name: string): Promise<void> {
var q: StopNoderedInstanceMessage = new StopNoderedInstanceMessage(); q.name = name; q._id = _id;
var msg: Message = new Message(); msg.command = "stopnoderedinstance"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<StopNoderedInstanceMessage>(msg);
}
async GetFile(filename: string, id: string, status: QueuedMessageStatusCallback = null): Promise<GetFileMessage> {
var q: GetFileMessage = new GetFileMessage(); q.filename = filename;
q.id = id;
var msg: Message = new Message(); msg.command = "getfile";
msg.data = JSONfn.stringify(q);
var result: GetFileMessage = await this.WebSocketClient.Send<GetFileMessage>(msg, status);
return result;
}
async SaveFile(filename: string, mimeType: string, metadata: any, file: string, status: QueuedMessageStatusCallback = null): Promise<SaveFileMessage> {
var q: SaveFileMessage = new SaveFileMessage();
q.filename = filename;
q.mimeType = mimeType; q.file = file;
q.metadata = metadata;
var msg: Message = new Message(); msg.command = "savefile";
msg.data = JSONfn.stringify(q);
var result: SaveFileMessage = await this.WebSocketClient.Send<SaveFileMessage>(msg, status);
return result;
}
async UpdateFile(id: string, metadata: any): Promise<void> {
var q: UpdateFileMessage = new UpdateFileMessage();
q.metadata = metadata; q.id = id;
var msg: Message = new Message(); msg.command = "updatefile";
msg.data = JSONfn.stringify(q);
var result: UpdateFileMessage = await this.WebSocketClient.Send<UpdateFileMessage>(msg);
return;
}
async Stripe<T extends stripe_base>(method: string, object: string, customerid: string, id: string, payload: stripe_base): Promise<T> {
var q: StripeMessage = new StripeMessage();
q.method = method; q.object = object; q.customerid = customerid; q.id = id; q.payload = payload;
var msg: Message = new Message(); msg.command = "stripemessage"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<StripeMessage>(msg);
return (q.payload as any);
}
async EnsureStripeCustomer(billing: Billing, userid: string): Promise<stripe_customer> {
var q: EnsureStripeCustomerMessage = new EnsureStripeCustomerMessage();
q.billing = billing; q.userid = userid;
var msg: Message = new Message(); msg.command = "ensurestripecustomer"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<EnsureStripeCustomerMessage>(msg);
return q.customer;
}
async StripeAddPlan(userid: string, planid: string, subplanid: string): Promise<StripeAddPlanMessage> {
var q: StripeAddPlanMessage = new StripeAddPlanMessage();
q.userid = userid; q.planid = planid; q.subplanid = subplanid;
var msg: Message = new Message(); msg.command = "stripeaddplan"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<StripeAddPlanMessage>(msg);
return q;
}
async StripeCancelPlan(userid: string, planid: string): Promise<StripeAddPlanMessage> {
var q: StripeAddPlanMessage = new StripeAddPlanMessage();
q.userid = userid; q.planid = planid;
var msg: Message = new Message(); msg.command = "stripecancelplan"; msg.data = JSON.stringify(q);
q = await this.WebSocketClient.Send<StripeAddPlanMessage>(msg);
return q;
}
setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
deleteCookie(cname) {
document.cookie = cname + "=;Thu, 01 Jan 1970 00:00:00 UTC;path=/";
}
}
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;
}
}
export class textarea 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) => {
if (!element.hasClass("autogrow")) {
// no autogrow for you today
return;
}
// get possible minimum height style
var minHeight = parseInt(window.getComputedStyle(element[0]).getPropertyValue("min-height")) || 0;
// prevent newlines in textbox
// element.on("keydown", function (evt) {
// if (evt.which === 13) {
// evt.preventDefault();
// }
// });
element.on("input", function (evt) {
var contentHeight2 = (this as any).scrollHeight;
var firstrun = element.attr("firstrun");
if (contentHeight2 > 1000) {
if (firstrun === null || firstrun === undefined) {
element.attr("firstrun", "false");
} else {
return;
}
}
var currentContentHeight = (this as any).scrollHeight;
var currentBorderHeight = (this as any).offsetHeight;
{
element.css({
paddingTop: 0,
height: 0,
minHeight: 0
});
var contentHeight = (this as any).scrollHeight;
var borderHeight = (this as any).offsetHeight;
element.css({
paddingTop: ~~Math.max(0, minHeight - contentHeight) / 2 + "px",
minHeight: null, // remove property
height: contentHeight + borderHeight + "px" // because we're using border-box
});
contentHeight = (this as any).scrollHeight;
borderHeight = (this as any).offsetHeight;
}
});
// watch model changes from the outside to adjust height
scope.$watch(attr.ngModel, trigger);
// set initial size
trigger();
function trigger() {
setTimeout(element.triggerHandler.bind(element, "input"), 1);
}
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService) => new textarea($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 => {
try {
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;
} catch (error) {
console.error(error);
return "error";
}
};
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);
});
} else {
var hashCode = (s: string) => {
return s.split("").reduce(function (a, b) { a = ((a << 5) - a) + b.charCodeAt(0); return a & a }, 0);
}
if (attr.value !== null && attr.value !== undefined && element[0].tagName !== "OPTION") {
value = calculateValue(attr.value);
attr.$set('value', value);
} else {
value = element.text();
if (value !== null || value !== undefined) {
var result = calculateValue(value);
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 userdata {
public data: any;
constructor() {
this.data = {};
}
}
export class fileread implements ng.IDirective {
restrict = 'A';
require = '?ngModel';
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) => {
if (!ngModelCtrl) return;
ngModelCtrl.$render = function () { };
element.bind('change', function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
scope.$apply(function () {
var base64result = ((loadEvent.target as any).result as string).split(',')[1];
ngModelCtrl.$setViewValue(base64result);
(scope as any).filename = (changeEvent.target as any).files[0].name;
(scope as any).type = (changeEvent.target as any).files[0].type;
});
}
if ((changeEvent.target as any).files != null && (changeEvent.target as any).files.length > 0) {
reader.readAsDataURL((changeEvent.target as any).files[0]);
}
}); //change
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, $timeout: ng.ITimeoutService, locale) => new fileread($location, $timeout, locale);
directive.$inject = ['$location', '$timeout', 'locale'];
return directive;
}
}
export class entitiesCtrl<T> {
public loading: boolean = false;
public basequery: any = {};
public baseprojection: any = {};
public collection: string = "entities";
public models: T[] = [];
public orderby: any = { _id: -1 };
public autorefresh: boolean = false;
public autorefreshinterval: number = 30 * 1000;
public autorefreshpromise: any = null;
public preloadData: any = null;
public postloadData: any = null;
public searchstring: string = "";
public searchfields: string[] = ["name"];
public basequeryas: string = null;
public errormessage: string = "";
public static $inject = [
"$scope",
"$location",
"$routeParams",
"$interval",
"WebSocketClient",
"api",
"userdata"
];
constructor(
public $scope: ng.IScope,
public $location: ng.ILocationService,
public $routeParams: ng.route.IRouteParamsService,
public $interval: ng.IIntervalService,
public WebSocketClient: WebSocketClient,
public api: api,
public userdata: userdata
) {
if (this.userdata.data != null && this.userdata.data) {
if (this.userdata.data.basequery != null) {
this.basequery = this.userdata.data.basequery;
delete this.userdata.data.basequery;
}
if (this.userdata.data.searchstring != null) {
this.searchstring = this.userdata.data.searchstring;
delete this.userdata.data.searchstring;
}
if (this.userdata.data.basequeryas != null) {
this.basequeryas = this.userdata.data.basequeryas;
delete this.userdata.data.basequeryas;
}
}
}
async loadData(): Promise<void> {
try {
if (this.loading == true) { console.log("allready loading data, exit"); return; }
this.errormessage = "";
this.loading = true;
if (this.preloadData != null) {
this.preloadData();
}
var query = this.basequery;
if (this.searchstring !== "") {
var finalor = [];
for (var i = 0; i < this.searchfields.length; i++) {
var newq: any = {};
// exact match case sensitive
// newq[this.searchfields[i]] = this.searchstring;
// exact match case insensitive
newq[this.searchfields[i]] = new RegExp(["^", this.searchstring, "$"].join(""), "i");
// exact match string contains
newq[this.searchfields[i]] = new RegExp([this.searchstring].join(""), "i");
finalor.push(newq);
}
if (Object.keys(query).length == 0) {
query = { $or: finalor.concat() };
} else {
query = { $and: [query, { $or: finalor.concat() }] };
}
}
this.models = await this.api.Query(this.collection, query, this.baseprojection, this.orderby, 100, 0, this.basequeryas);
this.loading = false;
if (this.autorefresh) {
if (this.models.length >= 100) {
// console.warn("Disabling auto refresh, result has more than 100 entries");
} else {
if (this.autorefreshpromise == null && this.searchstring === "") {
//if (this.autorefreshpromise == null) {
this.autorefreshpromise = this.$interval(() => {
this.loadData();
}, this.autorefreshinterval);
this.$scope.$on('$destroy', () => {
this.$interval.cancel(this.autorefreshpromise);
});
}
}
}
if (this.postloadData != null) {
this.postloadData();
} else {
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
} catch (error) {
this.loading = false;
this.errormessage = JSON.stringify(error);
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();
}
async DeleteOne(model: any): Promise<any> {
this.loading = true;
await this.api.Delete(this.collection, model);
this.models = this.models.filter(function (m: any): boolean { return m._id !== model._id; });
this.loading = false;
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
async Search() {
await this.loadData();
}
}
export function nestedassign(target, source) {
if (source === null || source === undefined) return null;
var keys = Object.keys(source);
for (var i = 0; i < keys.length; i++) {
var sourcekey = keys[i];
if (Object.keys(source).find(targetkey => targetkey === sourcekey) !== undefined &&
Object.keys(source).find(targetkey => targetkey === sourcekey) !== null
&& typeof source === "object" && typeof source[sourcekey] === "object") {
target[sourcekey] = nestedassign(target[sourcekey], source[sourcekey]);
} else {
target[sourcekey] = source[sourcekey];
}
}
return target;
}
export class entityCtrl<T> {
public loading: boolean = false;
public basequery: any = {};
public baseprojection: any = {};
public collection: string = "entities";
public model: T = null;
public id: string = null;
public keys: string[] = [];
public autorefresh: boolean = false;
public autorefreshinterval: number = 30 * 1000;
public autorefreshpromise: any = null;
public preloadData: any = null;
public postloadData: any = null;
public errormessage: string = "";
public static $inject = [
"$scope",
"$location",
"$routeParams",
"$interval",
"WebSocketClient",
"api"
];
constructor(
public $scope: ng.IScope,
public $location: ng.ILocationService,
public $routeParams: ng.route.IRouteParamsService,
public $interval: ng.IIntervalService,
public WebSocketClient: WebSocketClient,
public api: api
) {
this.id = $routeParams.id;
this.basequery = { _id: this.id };
}
async loadData(): Promise<void> {
try {
if (this.loading == true) { console.log("allready loading data, exit"); return; }
this.errormessage = "";
var updated: boolean = false;
this.loading = true;
if (this.preloadData != null) {
this.preloadData();
}
var result = await this.api.Query(this.collection, this.basequery, this.baseprojection, null, 1);
if (result.length > 0) {
if (this.model == null) {
this.model = result[0];
updated = true;
} else {
if (!angular.equals(this.model, result[0])) {
this.model = result[0];
updated = true;
}
}
}
if (updated) {
this.keys = Object.keys(this.model);
for (var i: number = this.keys.length - 1; i >= 0; i--) {
if (this.keys[i].startsWith('_')) this.keys.splice(i, 1);
}
}
this.loading = false;
if (this.postloadData != null) {
this.postloadData();
} else {
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
if (this.autorefresh) {
if (this.autorefreshpromise == null) {
this.autorefreshpromise = this.$interval(() => {
this.loadData();
}, this.autorefreshinterval);
this.$scope.$on('$destroy', () => {
this.$interval.cancel(this.autorefreshpromise);
});
}
}
} catch (error) {
this.loading = false;
this.errormessage = JSON.stringify(error);
if (!this.$scope.$$phase) { this.$scope.$apply(); }
}
}
}
}