This repository was archived by the owner on Jun 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtinode.ts
More file actions
1341 lines (1201 loc) · 42.6 KB
/
tinode.ts
File metadata and controls
1341 lines (1201 loc) · 42.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
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ConnectionOptions, Connection, LPConnection, WSConnection, AutoReconnectData, OnDisconnetData } from './connection';
import { AppSettings, AppInfo, TopicNames, PacketTypes, AuthenticationScheme } from './constants';
import { Utilities } from './utilities';
import { Packet } from './packet';
import {
HiPacketData,
AccPacketData,
SubPacketData,
GetPacketData,
DelPacketData,
PubPacketData,
SetPacketData,
NotePacketData,
LeavePacketData,
LoginPacketData,
} from './models/packet-data';
import { Message } from './message';
import { Topic } from './topic/topic';
import { TopicMe } from './topic/topic-me';
import { TopicFnd } from './topic/topic-fnd';
import { Subject, Subscription } from 'rxjs';
import { GetQuery } from './models/get-query';
import { DelRange } from './models/del-range';
import { SetParams } from './models/set-params';
import { AuthToken } from './models/auth-token';
import { OnLoginData } from './models/tinode-events';
import { LargeFileHelper } from './large-file-helper';
import { AccountParams } from './models/account-params';
export class Tinode {
/**
* Connection config used to initiate a connection
*/
connectionConfig: ConnectionOptions;
/**
* Client's platform
*/
private hardwareOS = 'Undefined';
/**
* Client's language
*/
private humanLanguage = 'en-US';
/**
* Specified platform by user
*/
private platform = 'Undefined';
/**
* Specified app name by user
*/
private appName = 'Undefined';
/**
* If this code is running on a browser, which one?
*/
private browser = '';
/**
* Logging to console enabled
*/
private loggingEnabled = false;
/**
* When logging, trip long strings (base64-encoded images) for readability
*/
private trimLongStrings = false;
/**
* UID of the currently authenticated user.
*/
private myUserID = null;
/**
* Status of connection: authenticated or not.
*/
private authenticated = false;
/**
* Login used in the last successful basic authentication
*/
private lastLogin = null;
/**
* Token which can be used for login instead of login/password.
*/
authToken: AuthToken = null;
/**
* Counter of received packets
*/
private inPacketCount = 0;
/**
* Counter for generating unique message IDs
*/
private messageId = Math.floor((Math.random() * 0xFFFF) + 0xFFFF);
/**
* Information about the server, if connected
*/
private serverInfo = null;
/**
* Push notification token. Called deviceToken for consistency with the Android SDK.
*/
private deviceToken = null;
/**
* Cache of pending promises by message id.
*/
private pendingPromises = {};
/**
* A connection object
*/
private connection: Connection = null;
/**
* Tinode's cache of objects
*/
private cache = {};
/**
* Stores interval to clear later
*/
private checkExpiredPromisesInterval: any;
/**
* Subject to report login completion.
*/
onLogin = new Subject<OnLoginData>();
/**
* Subject to receive server responses to network probes
*/
onRawMessage = new Subject<string>();
/**
* Subject to receive server responses to network probes
*/
onNetworkProbe = new Subject();
/**
* Subject to receive all messages as objects.
*/
onMessage = new Subject();
/**
* Subject to receive {ctrl} (control) messages.
*/
onCtrlMessage = new Subject();
/**
* Subject to receive {meta} messages.
*/
onMetaMessage = new Subject();
/**
* Subject to receive {data} messages.
*/
onDataMessage = new Subject();
/**
* Subject to receive {pres} messages.
*/
onPresMessage = new Subject();
/**
* Subject to receive {info} messages.
*/
onInfoMessage = new Subject();
/**
* Subject for connect event
*/
onConnect = new Subject();
/**
* Subject for disconnect event
*/
onDisconnect = new Subject();
/**
* Wrapper for the reconnect iterator callback.
*/
onAutoReconnectIteration = new Subject<AutoReconnectData>();
/**
* Connection events subscriptions
*/
private connectionEventsSubscriptions: Subscription[] = [];
/**
* Return information about the current version of this Tinode client library.
*/
static getVersion(): string {
return AppInfo.VERSION;
}
/**
* Return information about the current name and version of this Tinode library.
*/
static getLibrary(): string {
return AppInfo.LIBRARY;
}
/**
* To use Tinode in a non browser context, supply WebSocket and XMLHttpRequest providers.
*/
static setNetworkProviders(ws: any, xmlhttprequest: any): void {
Utilities.initializeNetworkProviders(ws, xmlhttprequest);
}
constructor(appName: string, platform: string, connectionConfig: ConnectionOptions) {
Utilities.initializeNetworkProviders();
this.connectionConfig = connectionConfig;
if (appName) {
this.appName = appName;
}
if (platform) {
this.platform = platform;
}
if (typeof navigator !== 'undefined') {
this.browser = Utilities.getBrowserInfo(navigator.userAgent, navigator.product);
this.hardwareOS = navigator.platform;
this.humanLanguage = navigator.language || 'en-US';
}
switch (connectionConfig.transport) {
case 'lp':
this.connection = new LPConnection(this.connectionConfig);
break;
case 'ws':
this.connection = new WSConnection(this.connectionConfig);
break;
default:
throw new Error('Invalid transport method is selected! It can be "lp" or "ws"');
}
if (this.connection) {
this.connection.logger = this.logger;
this.doConnectionSubscriptions();
}
setInterval(() => {
this.checkExpiredPromises();
}, AppSettings.EXPIRE_PROMISES_PERIOD);
}
/**
* Subscribe and handle connection events
*/
private doConnectionSubscriptions(): void {
const onMessageSubs = this.connection.onMessage.subscribe((data) => this.onConnectionMessage(data));
this.connectionEventsSubscriptions.push(onMessageSubs);
const onOpenSubs = this.connection.onOpen.subscribe(() => this.hello());
this.connectionEventsSubscriptions.push(onOpenSubs);
const onAutoReconnectSubs = this.connection.onAutoReconnectIteration.subscribe((data) => this.onAutoReconnectIteration.next(data));
this.connectionEventsSubscriptions.push(onAutoReconnectSubs);
const onDisconnectSubs = this.connection.onDisconnect.subscribe((data) => this.onConnectionDisconnect(data));
this.connectionEventsSubscriptions.push(onDisconnectSubs);
}
/**
* Toggle console logging. Logging is off by default.
* @param enabled - Set to to enable logging to console.
* @param trimLongStrings - Options to trim long strings
*/
enableLogging(enabled: boolean, trimLongStrings?: boolean): void {
this.loggingEnabled = enabled;
this.trimLongStrings = enabled && trimLongStrings;
}
/**
* Generator of packets stubs
*/
initPacket(type: PacketTypes, topicName?: string): Packet<any> {
switch (type) {
case PacketTypes.Hi:
const hiData: HiPacketData = {
ver: AppInfo.VERSION,
ua: this.getUserAgent(),
dev: this.deviceToken,
lang: this.humanLanguage,
platf: this.platform,
};
return new Packet(type, hiData, this.getNextUniqueId());
case PacketTypes.Acc:
const accData: AccPacketData = {
user: null,
scheme: null,
secret: null,
login: false,
tags: null,
desc: {},
cred: {},
token: null,
};
return new Packet(type, accData, this.getNextUniqueId());
case PacketTypes.Login:
const loginData: LoginPacketData = {
scheme: null,
secret: null,
cred: null,
};
return new Packet(type, loginData, this.getNextUniqueId());
case PacketTypes.Sub:
const subData: SubPacketData = {
topic: topicName,
set: {},
get: {},
};
return new Packet(type, subData, this.getNextUniqueId());
case PacketTypes.Leave:
const leaveData: LeavePacketData = {
topic: topicName,
unsub: false,
};
return new Packet(type, leaveData, this.getNextUniqueId());
case PacketTypes.Pub:
const pubData: PubPacketData = {
topic: topicName,
noecho: false,
head: null,
content: {},
from: null,
seq: null,
ts: null,
};
return new Packet(type, pubData, this.getNextUniqueId());
case PacketTypes.Get:
const getData: GetPacketData = {
topic: topicName,
what: null,
desc: {},
sub: {},
data: {},
};
return new Packet(type, getData, this.getNextUniqueId());
case PacketTypes.Set:
const setData: SetPacketData = {
topic: topicName,
desc: {},
sub: {},
tags: [],
};
return new Packet(type, setData, this.getNextUniqueId());
case PacketTypes.Del:
const delData: DelPacketData = {
topic: topicName,
what: null,
delseq: null,
hard: false,
user: null,
cred: null,
};
return new Packet(type, delData, this.getNextUniqueId());
case PacketTypes.Note:
const noteData: NotePacketData = {
topic: topicName,
seq: undefined,
what: null,
};
return new Packet(type, noteData, null);
default:
throw new Error('Unknown packet type requested: ' + type);
}
}
/**
* Console logger
* @param str - String to log
* @param args - arguments
*/
logger(str: string, ...args: any[]): void {
if (this.loggingEnabled) {
const d = new Date();
const dateString = ('0' + d.getUTCHours()).slice(-2) + ':' +
('0' + d.getUTCMinutes()).slice(-2) + ':' +
('0' + d.getUTCSeconds()).slice(-2) + '.' +
('00' + d.getUTCMilliseconds()).slice(-3);
console.log('[' + dateString + ']', str, args.join(' '));
}
}
/**
* Put an object into cache
* @param type - cache type
* @param name - cache name
* @param obj - cache object
*/
private cachePut(type: string, name: string, obj: any): void {
this.cache[type + ':' + name] = obj;
}
/**
* Get an object from cache
* @param type - cache type
* @param name - cache name
*/
private cacheGet(type: string, name: string): any {
return this.cache[type + ':' + name];
}
/**
* Delete an object from cache
* @param type - cache type
* @param name - cache name
*/
cacheDel(type: string, name: string): void {
delete this.cache[type + ':' + name];
}
/**
* Enumerate all items in cache, call func for each item.
* Enumeration stops if func returns true.
* @param func - function to call for each item
* @param context - function context
*/
private cacheMap(func: any, context?: any): void {
for (const idx in this.cache) {
if (func(this.cache[idx], idx, context)) {
break;
}
}
}
/**
* Make limited cache management available to topic.
* Caching user.public only. Everything else is per-topic.
* @param topic - Topic to attach cache
*/
private attachCacheToTopic(topic: Topic): void {
topic.tinode = this;
topic.cacheGetUser = (uid) => {
const pub = this.cacheGet('user', uid);
if (pub) {
return {
user: uid,
public: Utilities.mergeObj({}, pub)
};
}
return undefined;
};
topic.cachePutUser = (uid, user) => {
return this.cachePut('user', uid, Utilities.mergeObj({}, user.public));
};
topic.cacheDelUser = (uid) => {
return this.cacheDel('user', uid);
};
topic.cachePutSelf = () => {
return this.cachePut('topic', topic.name, topic);
};
topic.cacheDelSelf = () => {
return this.cacheDel('topic', topic.name);
};
}
/**
* Resolve or reject a pending promise.
* Unresolved promises are stored in _pendingPromises.
*/
private execPromise(id: string, code: number, onOK: any, errorText: string): void {
const callbacks = this.pendingPromises[id];
if (callbacks) {
delete this.pendingPromises[id];
if (code >= 200 && code < 400) {
if (callbacks.resolve) {
callbacks.resolve(onOK);
}
} else if (callbacks.reject) {
callbacks.reject(new Error(errorText + ' (' + code + ')'));
}
}
}
/**
* Stored callbacks will be called when the response packet with this Id arrives
* @param id - Id of new promise
*/
private makePromise(id: string): Promise<any> {
let promise = null;
if (id) {
promise = new Promise((resolve, reject) => {
this.pendingPromises[id] = {
resolve,
reject,
ts: new Date(),
};
});
}
return promise;
}
/**
* Reject promises which have not been resolved for too long.
*/
private checkExpiredPromises(): void {
const err = new Error('Timeout (504)');
const expires = new Date(new Date().getTime() - AppSettings.EXPIRE_PROMISES_TIMEOUT);
for (const id in this.pendingPromises) {
if (id) {
const callbacks = this.pendingPromises[id];
if (callbacks && callbacks.ts < expires) {
this.logger('Promise expired', id);
delete this.pendingPromises[id];
if (callbacks.reject) {
callbacks.reject(err);
}
}
}
}
}
/**
* Generates unique message IDs
*/
getNextUniqueId(): string {
return (this.messageId !== 0) ? '' + this.messageId++ : undefined;
}
/**
* Get User Agent string
*/
private getUserAgent(): string {
return this.appName + ' (' + (this.browser ? this.browser + '; ' : '') + this.hardwareOS + '); ' + AppInfo.LIBRARY;
}
/**
* Send a packet. If packet id is provided return a promise.
* @param pkt - Packet
* @param id - Message ID
*/
private send(pkt: Packet<any>, id?: string) {
let promise: any;
if (id) {
promise = this.makePromise(id);
}
let formattedPkt = {};
formattedPkt[pkt.name] = { ...pkt.data, id: pkt.id };
formattedPkt = Utilities.simplify(formattedPkt);
const msg = JSON.stringify(formattedPkt);
this.logger('out: ' + (this.trimLongStrings ? JSON.stringify(formattedPkt, Utilities.jsonLoggerHelper) : msg));
try {
this.connection.sendText(msg);
} catch (err) {
// If sendText throws, wrap the error in a promise or rethrow.
if (id) {
this.execPromise(id, AppSettings.NETWORK_ERROR, null, err.message);
} else {
throw err;
}
}
return promise;
}
/**
* REVIEW: types
* On successful login save server-provided data.
* @param ctrl - Server response
*/
private loginSuccessful(ctrl: any): void {
if (!ctrl.params || !ctrl.params.user) {
return;
}
// This is a response to a successful login,
// extract UID and security token, save it in Tinode module
this.myUserID = ctrl.params.user;
this.authenticated = (ctrl && ctrl.code >= 200 && ctrl.code < 300);
if (ctrl.params && ctrl.params.token && ctrl.params.expires) {
this.authToken = {
token: ctrl.params.token,
expires: new Date(ctrl.params.expires)
};
} else {
this.authToken = null;
}
this.onLogin.next({ code: ctrl.code, text: ctrl.text });
}
/**
* The main message dispatcher.
* @param data - Server message data
*/
private onConnectionMessage(data: string): void {
// Skip empty response. This happens when LP times out.
if (!data) {
return;
}
this.inPacketCount++;
// Send raw message to listener
this.onRawMessage.next(data);
if (data === '0') {
// Server response to a network probe.
this.onNetworkProbe.next();
return;
}
const pkt = JSON.parse(data, Utilities.jsonParseHelper);
if (!pkt) {
this.logger('in: ' + data);
this.logger('ERROR: failed to parse data');
return;
}
this.logger('in: ' + (this.trimLongStrings ? JSON.stringify(pkt, Utilities.jsonLoggerHelper) : data));
// Send complete packet to listener
this.onMessage.next(pkt);
switch (true) {
case Boolean(pkt.ctrl):
this.handleCtrlMessage(pkt);
break;
case Boolean(pkt.meta):
this.handleMetaMessage(pkt);
break;
case Boolean(pkt.data):
this.handleDataMessage(pkt);
break;
case Boolean(pkt.pres):
this.handlePresMessage(pkt);
break;
case Boolean(pkt.info):
this.handleInfoMessage(pkt);
break;
default: this.logger('ERROR: Unknown packet received.');
}
}
/**
* REVIEW: types
* Handle ctrl type messages
* @param pkt - Server message data
*/
private handleCtrlMessage(pkt: any): void {
this.onCtrlMessage.next(pkt.ctrl);
// Resolve or reject a pending promise, if any
if (pkt.ctrl.id) {
this.execPromise(pkt.ctrl.id, pkt.ctrl.code, pkt.ctrl, pkt.ctrl.text);
}
if (pkt.ctrl.code === 205 && pkt.ctrl.text === 'evicted') {
// User evicted from topic.
const topic: Topic = this.cacheGet('topic', pkt.ctrl.topic);
if (topic) {
topic.resetSub();
}
}
if (pkt.ctrl.params && pkt.ctrl.params.what === 'data') {
// All messages received: "params":{"count":11,"what":"data"},
const topic: Topic = this.cacheGet('topic', pkt.ctrl.topic);
if (topic) {
topic.allMessagesReceived(pkt.ctrl.params.count);
}
}
if (pkt.ctrl.params && pkt.ctrl.params.what === 'sub') {
// The topic has no subscriptions.
const topic: Topic = this.cacheGet('topic', pkt.ctrl.topic);
if (topic) {
// Trigger topic.onSubsUpdated.
topic.processMetaSub([]);
}
}
}
/**
* REVIEW: types
* Handle meta type messages
* @param pkt - Server message data
*/
private handleMetaMessage(pkt: any) {
this.onMetaMessage.next(pkt.meta);
// Preferred API: Route meta to topic, if one is registered
const topic: Topic = this.cacheGet('topic', pkt.meta.topic);
if (topic) {
topic.routeMeta(pkt.meta);
}
if (pkt.meta.id) {
this.execPromise(pkt.meta.id, 200, pkt.meta, 'META');
}
}
/**
* REVIEW: types
* Handle data type messages
* @param pkt - Server message data
*/
private handleDataMessage(pkt: any) {
this.onDataMessage.next(pkt.data);
// Preferred API: Route data to topic, if one is registered
const topic: Topic = this.cacheGet('topic', pkt.data.topic);
if (topic) {
topic.routeData(pkt.data);
}
}
/**
* REVIEW: types
* Handle pres type messages
* @param pkt - Server message data
*/
private handlePresMessage(pkt: any) {
this.onPresMessage.next(pkt.pres);
// Preferred API: Route presence to topic, if one is registered
const topic: Topic = this.cacheGet('topic', pkt.pres.topic);
if (topic) {
topic.routePres(pkt.pres);
}
}
/**
* REVIEW: types
* Handle info type messages
* @param pkt - Server message data
*/
private handleInfoMessage(pkt: any) {
this.onInfoMessage.next(pkt.info);
// Preferred API: Route {info}} to topic, if one is registered
const topic: Topic = this.cacheGet('topic', pkt.info.topic);
if (topic) {
topic.routeInfo(pkt.info);
}
}
/**
* Reset all variables and unsubscribe from all events and topics
* @param onDisconnectData - Data from connection disconnect event
*/
private onConnectionDisconnect(onDisconnectData: OnDisconnetData): any {
this.inPacketCount = 0;
this.serverInfo = null;
this.authenticated = false;
// Mark all topics as unsubscribed
this.cacheMap((obj: any, key: string) => {
if (key.lastIndexOf('topic:', 0) === 0) {
obj.resetSub();
}
});
// Reject all pending promises
for (const key in this.pendingPromises) {
if (key) {
const callbacks = this.pendingPromises[key];
if (callbacks && callbacks.reject) {
callbacks.reject(onDisconnectData);
}
}
}
// Unsubscribe from connection events
for (const subs of this.connectionEventsSubscriptions) {
subs.unsubscribe();
}
this.connectionEventsSubscriptions = [];
this.pendingPromises = {};
this.onDisconnect.next(onDisconnectData);
}
/**
* Connect to the server.
* @param host - name of the host to connect to
*/
connect(host?: string): Promise<void> {
if (!this.connectionEventsSubscriptions.length) {
this.doConnectionSubscriptions();
}
return this.connection.connect(host);
}
/**
* Attempt to reconnect to the server immediately.
* @param force - reconnect even if there is a connection already.
*/
reconnect(force?: boolean): Promise<any> {
return this.connection.connect(null, force);
}
/**
* Disconnect from the server.
*/
disconnect(): void {
this.connection.disconnect();
}
/**
* Check for live connection to server.
*/
isConnected(): boolean {
return this.connection.isConnected();
}
/**
* Check if connection is authenticated (last login was successful).
*/
isAuthenticated(): boolean {
return this.authenticated;
}
/**
* Send handshake to the server.
*/
async hello(): Promise<any> {
const pkt: Packet<HiPacketData> = this.initPacket(PacketTypes.Hi);
try {
const ctrl = await this.send(pkt, pkt.id);
// Reset backoff counter on successful connection.
this.connection.backoffReset();
// Server response contains server protocol version, build, constraints,
// session ID for long polling. Save them.
if (ctrl.params) {
this.serverInfo = ctrl.params;
}
this.onConnect.next();
return ctrl;
} catch (error) {
this.connection.reconnect(true);
this.onDisconnect.next(error);
throw error;
}
}
/**
* Create or update an account
* @param userId - User id to update
* @param scheme - Authentication scheme; "basic" and "anonymous" are the currently supported schemes.
* @param secret - Authentication secret, assumed to be already base64 encoded.
* @param login - Use new account to authenticate current session
* @param params - User data to pass to the server.
*/
account(userId: string, scheme: AuthenticationScheme, secret: string, login: boolean, params?: AccountParams): Promise<any> {
const pkt: Packet<AccPacketData> = this.initPacket(PacketTypes.Acc);
pkt.data.user = userId;
pkt.data.scheme = scheme;
pkt.data.secret = secret;
pkt.data.login = login;
if (params) {
pkt.data.tags = params.tags;
pkt.data.cred = params.cred;
pkt.data.token = params.token;
pkt.data.desc.defacs = params.defacs;
pkt.data.desc.public = params.public;
pkt.data.desc.private = params.private;
}
return this.send(pkt, pkt.id);
}
/**
* Create a new user. Wrapper for `account`.
* @param scheme - Authentication scheme; "basic" is the only currently supported scheme.
* @param secret - Authentication secret
* @param login - Use new account to authenticate current session
* @param params - User data to pass to the server
*/
createAccount(scheme: AuthenticationScheme, secret: string, login: boolean, params?: AccountParams): Promise<any> {
let promise = this.account(TopicNames.USER_NEW, scheme, secret, login, params);
if (login) {
promise = promise.then((ctrl) => {
this.loginSuccessful(ctrl);
return ctrl;
});
}
return promise;
}
/**
* Create user with 'basic' authentication scheme and immediately
* use it for authentication. Wrapper for `account`
* @param username - Using this username you can log into your account
* @param password - User's password
* @param params - User data to pass to the server
*/
createAccountBasic(username: string, password: string, login: boolean, params?: AccountParams): Promise<any> {
username = username || '';
password = password || '';
const secret = Utilities.base64encode(username + ':' + password);
return this.createAccount(AuthenticationScheme.Basic, secret, login, params);
}
/**
* Update user's credentials for 'basic' authentication scheme. Wrapper for `account`
* @param userId - User ID to update
* @param username - Using this username you can log into your account
* @param password - User's password
* @param params - Data to pass to the server.
*/
updateAccountBasic(userId: string, username: string, password: string, params?: AccountParams): Promise<any> {
// Make sure we are not using 'null' or 'undefined';
username = username || '';
password = password || '';
return this.account(userId, AuthenticationScheme.Basic, Utilities.base64encode(username + ':' + password), false, params);
}
/**
* Authenticate current session.
* @param scheme - Authentication scheme; <tt>"basic"</tt> is the only currently supported scheme.
* @param secret - Authentication secret, assumed to be already base64 encoded.
* @param cred - cred
* @returns Promise which will be resolved/rejected when server reply is received
*/
async login(scheme: AuthenticationScheme, secret: string, cred?: any): Promise<any> {
const pkt: Packet<LoginPacketData> = this.initPacket(PacketTypes.Login);
pkt.data.scheme = scheme;
pkt.data.secret = secret;
pkt.data.cred = cred;
const ctrl = await this.send(pkt, pkt.id);
this.loginSuccessful(ctrl);
return ctrl;
}
/**
* Wrapper for `login` with basic authentication
* @param username - User name
* @param password - Password
* @param cred - cred
* @returns Promise which will be resolved/rejected on receiving server reply.
*/
async loginBasic(username: string, password: string, cred?: any) {
const ctrl = this.login(AuthenticationScheme.Basic, Utilities.base64encode(username + ':' + password), cred);
this.lastLogin = username;
return ctrl;
}
/**
* Wrapper for `login` with token authentication
* @param token - Token received in response to earlier login.
* @param cred - cred
* @returns Promise which will be resolved/rejected on receiving server reply.
*/
loginToken(token: string, cred?: any): Promise<any> {
return this.login(AuthenticationScheme.Token, token, cred);
}
/**
* Send a request for resetting an authentication secret.
* @param scheme - authentication scheme to reset.
* @param method - method to use for resetting the secret, such as "email" or "tel".
* @param value - value of the credential to use, a specific email address or a phone number.
*/
requestResetAuthSecret(scheme: AuthenticationScheme, method: string, value: string): Promise<any> {
return this.login(AuthenticationScheme.Reset, Utilities.base64encode(scheme + ':' + method + ':' + value));
}
/**
* Get stored authentication token.
*/
getAuthToken(): AuthToken {
if (this.authToken && (this.authToken.expires.getTime() > Date.now())) {
return this.authToken;
} else {
this.authToken = null;
}
}
/**
* Application may provide a saved authentication token.
*/
setAuthToken(token: AuthToken) {
this.authToken = token;
}
/**
* Set or refresh the push notifications/device token. If the client is connected,
* the deviceToken can be sent to the server.
* @param deviceToken - token obtained from the provider
* @param sendToServer - if true, send deviceToken to server immediately.
* @returns true if attempt was made to send the token to the server.
*/
setDeviceToken(deviceToken: string, sendToServer: boolean): boolean {
let sent = false;
if (deviceToken && deviceToken !== this.deviceToken) {
this.deviceToken = deviceToken;
if (sendToServer && this.isConnected() && this.isAuthenticated()) {
const pkt: Packet<HiPacketData> = this.initPacket(PacketTypes.Hi);
pkt.data.dev = deviceToken;
this.send(pkt, pkt.id);
sent = true;
}
}
return sent;
}