This repository has been archived by the owner on Feb 10, 2024. It is now read-only.
/
SimpleMatrixClient.ts
1748 lines (1465 loc) · 65.7 KB
/
SimpleMatrixClient.ts
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
// Copyright (c) 2021 Sendanor. All rights reserved.
import { concat } from "../core/functions/concat";
import { forEach } from "../core/functions/forEach";
import { Observer, ObserverCallback, ObserverDestructor } from "../core/Observer";
import { RequestClient } from "../core/RequestClient";
import { LogService } from "../core/LogService";
import { JsonAny } from "../core/Json";
import { JsonAny as Json, isJsonObject, JsonObject } from "../core/Json";
import { createMatrixPasswordLoginRequestDTO, MatrixPasswordLoginRequestDTO } from "./types/request/passwordLogin/MatrixPasswordLoginRequestDTO";
import { createMatrixTextMessageDTO, MatrixTextMessageDTO } from "./types/message/textMessage/MatrixTextMessageDTO";
import { MatrixType } from "./types/core/MatrixType";
import { isMatrixLoginResponseDTO } from "./types/response/login/MatrixLoginResponseDTO";
import { MatrixCreateRoomDTO } from "./types/request/createRoom/MatrixCreateRoomDTO";
import { MatrixCreateRoomResponseDTO, isMatrixCreateRoomResponseDTO } from "./types/response/createRoom/MatrixCreateRoomResponseDTO";
import { isGetDirectoryRoomAliasResponseDTO } from "./types/response/directoryRoomAlias/GetDirectoryRoomAliasResponseDTO";
import { RequestError } from "../core/request/types/RequestError";
import { RequestStatus } from "../core/request/types/RequestStatus";
import { MatrixSyncPresence } from "./types/request/sync/types/MatrixSyncPresence";
import { MatrixSyncResponseDTO,
explainMatrixSyncResponseDTO,
isMatrixSyncResponseDTO
} from "./types/response/sync/MatrixSyncResponseDTO";
import { MatrixSyncResponseEventDTO } from "./types/response/sync/types/MatrixSyncResponseEventDTO";
import { MatrixSyncResponseAnyEventDTO } from "./types/response/sync/types/MatrixSyncResponseAnyEventDTO";
import { getEventsFromMatrixSyncResponsePresenceDTO } from "./types/response/sync/types/MatrixSyncResponsePresenceDTO";
import { getEventsFromMatrixSyncResponseAccountDataDTO } from "./types/response/sync/types/MatrixSyncResponseAccountDataDTO";
import { getEventsFromMatrixSyncResponseToDeviceDTO } from "./types/response/sync/types/MatrixSyncResponseToDeviceDTO";
import { MatrixRoomId, isMatrixRoomId } from "./types/core/MatrixRoomId";
import { MatrixSyncResponseJoinedRoomDTO, getEventsFromMatrixSyncResponseJoinedRoomDTO } from "./types/response/sync/types/MatrixSyncResponseJoinedRoomDTO";
import { MatrixSyncResponseInvitedRoomDTO, getEventsFromMatrixSyncResponseInvitedRoomDTO } from "./types/response/sync/types/MatrixSyncResponseInvitedRoomDTO";
import { MatrixSyncResponseLeftRoomDTO, getEventsFromMatrixSyncResponseLeftRoomDTO } from "./types/response/sync/types/MatrixSyncResponseLeftRoomDTO";
import { MatrixUserId, isMatrixUserId } from "./types/core/MatrixUserId";
import { MatrixJoinRoomRequestDTO } from "./types/request/joinRoom/MatrixJoinRoomRequestDTO";
import { MatrixJoinRoomResponseDTO, isMatrixJoinRoomResponseDTO } from "./types/response/joinRoom/MatrixJoinRoomResponseDTO";
import {
SimpleMatrixClientState,
stringifySimpleMatrixClientState
} from "./types/SimpleMatrixClientState";
import { PutRoomStateWithEventTypeResponseDTO, isPutRoomStateWithEventTypeResponseDTO } from "./types/response/setRoomStateByType/PutRoomStateWithEventTypeResponseDTO";
import { MatrixRoomJoinedMembersDTO, isMatrixRoomJoinedMembersDTO } from "./types/response/roomJoinedMembers/MatrixRoomJoinedMembersDTO";
import { MatrixRegisterKind } from "./types/request/register/types/MatrixRegisterKind";
import { MatrixRegisterRequestDTO } from "./types/request/register/MatrixRegisterRequestDTO";
import { MatrixRegisterResponseDTO, isMatrixRegisterResponseDTO } from "./types/response/register/MatrixRegisterResponseDTO";
import { isMatrixErrorDTO } from "./types/response/error/MatrixErrorDTO";
import { MatrixErrorCode } from "./types/response/error/types/MatrixErrorCode";
import { SynapseRegisterResponseDTO, isSynapseRegisterResponseDTO } from "./types/synapse/SynapseRegisterResponseDTO";
import { SynapseRegisterRequestDTO } from "./types/synapse/SynapseRegisterRequestDTO";
import { VoidCallback } from "../core/interfaces/callbacks";
import { LogLevel } from "../core/types/LogLevel";
import {
MATRIX_AUTHORIZATION_HEADER_NAME,
MATRIX_CREATE_ROOM_URL,
MATRIX_JOIN_ROOM_URL,
MATRIX_JOINED_MEMBERS_URL,
MATRIX_LOGIN_URL,
MATRIX_REGISTER_URL,
MATRIX_ROOM_DIRECTORY_URL,
MATRIX_ROOM_EVENT_STATE_FETCH_URL,
MATRIX_ROOM_EVENT_STATE_UPDATE_URL,
MATRIX_ROOM_FORGET_URL,
MATRIX_ROOM_INVITE_URL,
MATRIX_ROOM_LEAVE_URL,
MATRIX_ROOM_SEND_EVENT_URL,
MATRIX_SYNC_URL,
MATRIX_WHOAMI_URL,
MatrixSyncQueryParams,
SYNAPSE_REGISTER_URL
} from "./constants/matrix-routes";
import { AuthorizationUtils } from "../core/AuthorizationUtils";
import { isMatrixWhoAmIResponseDTO, MatrixWhoAmIResponseDTO } from "./types/response/whoami/MatrixWhoAmIResponseDTO";
import { createMatrixIdentifierDTO } from "./types/request/login/types/MatrixIdentifierDTO";
import { GetRoomStateByTypeResponseDTO, isGetRoomStateByTypeResponseDTO } from "./types/response/getRoomStateByType/GetRoomStateByTypeResponseDTO";
import { SetRoomStateByTypeRequestDTO } from "./types/request/setRoomStateByType/SetRoomStateByTypeRequestDTO";
import { RepositoryClient } from "../core/simpleRepository/types/RepositoryClient";
import { isString } from "../core/types/String";
import { keys } from "../core/functions/keys";
const LOG = LogService.createLogger('SimpleMatrixClient');
export enum SimpleMatrixClientEvent {
EVENT = "SimpleMatrixClient:event"
}
export type SimpleMatrixClientDestructor = ObserverDestructor;
const DEFAULT_WAIT_FOR_EVENTS_TIMEOUT = 30000;
/**
* Super lightweight Matrix client and simple event listener.
*
* Far from perfect, but works both on browser and on OpenWRT with NodeJS 8 and full POC takes only
* 50k as compiled single bundle file (including all the dependencies) :)
*/
export class SimpleMatrixClient implements RepositoryClient {
public static Event = SimpleMatrixClientEvent;
public static setLogLevel (level: LogLevel) {
LOG.setLogLevel(level);
}
private readonly _observer : Observer<SimpleMatrixClientEvent>;
private readonly _originalUrl : string;
private readonly _homeServerUrl : string;
private readonly _identityServerUrl : string;
private readonly _accessToken : string | undefined;
private readonly _syncAgainTimeMs : number;
private readonly _syncRequestTimeoutMs : number;
private readonly _syncAgainTimeoutCallback : VoidCallback;
private _state : SimpleMatrixClientState;
private _userId : string | undefined;
private _stopSyncOnNext : boolean;
private _nextSyncBatch : string | undefined;
private _syncAgainTimer : any | undefined;
private _initSyncAgainTimer : any | undefined;
/**
* Create an instance of SimpleMatrixClient.
*
* @param url The URL of the Matrix server to login
*
* @param homeServerUrl Optional. The Matrix server URL for a logged in session.
*
* @param identityServerUrl Optional. The Matrix identity server URL for a logged in session.
*
* @param accessToken Optional. The access key for a logged in session.
*
* @param userId Optional. The Matrix user ID for a logged in session.
*
* @param pollTimeout Optional. The default poll time in milliseconds to poll changes
* from upstream Matrix server.
*
* @param pollWaitTime Optional. The default wait time between polls, in milliseconds.
*
*/
public constructor (
url : string,
homeServerUrl : string | undefined = undefined,
identityServerUrl : string | undefined = undefined,
accessToken : string | undefined = undefined,
userId : MatrixUserId | undefined = undefined,
pollTimeout : number = 30000,
pollWaitTime : number = 1000
) {
this._stopSyncOnNext = false;
this._state = accessToken ? SimpleMatrixClientState.AUTHENTICATED : SimpleMatrixClientState.UNAUTHENTICATED;
this._originalUrl = url;
this._homeServerUrl = SimpleMatrixClient._normalizeUrl( homeServerUrl ?? url );
this._identityServerUrl = identityServerUrl ?? url;
this._nextSyncBatch = undefined;
this._accessToken = accessToken;
this._userId = userId;
this._syncRequestTimeoutMs = pollTimeout;
this._syncAgainTimeMs = pollWaitTime;
this._observer = new Observer<SimpleMatrixClientEvent>("SimpleMatrixClient");
this._syncAgainTimeoutCallback = this._onSyncAgainTimeout.bind(this);
}
/**
* Returns the current state of the client instance.
*/
public getState () : SimpleMatrixClientState {
return this._state;
}
/**
* Returns the current access token
*/
public getAccessToken () : string | undefined {
return this._accessToken;
}
/**
* Returns the current logged in Matrix user ID
*/
public getUserId () : MatrixUserId | undefined {
return this._userId;
}
/**
* Returns the URL of the current Matrix home server
*/
public getHomeServerUrl () : string {
return this._homeServerUrl;
}
/**
* Returns the hostname of the current Matrix home server
*/
public getHomeServerName () : string {
const u = new URL(this._homeServerUrl);
return u.hostname;
}
public isAlreadyInTheRoom (body: any) : boolean {
if (isMatrixErrorDTO(body)) {
const errCode : string = body?.errcode ?? '';
const errString : string = body?.error ?? '';
if ( errCode === MatrixErrorCode.M_FORBIDDEN
&& errString.indexOf('already in the room') >= 0
) {
return true;
}
}
return false;
}
public isUnauthenticated () : boolean {
return this._state === SimpleMatrixClientState.UNAUTHENTICATED;
}
public isAuthenticating () : boolean {
return this._state === SimpleMatrixClientState.AUTHENTICATING;
}
public isAuthenticated () : boolean {
return this._state === SimpleMatrixClientState.AUTHENTICATED;
}
public isStarting () : boolean {
return this._state === SimpleMatrixClientState.AUTHENTICATED_AND_STARTING;
}
public isRestarting () : boolean {
return this._state === SimpleMatrixClientState.AUTHENTICATED_AND_RESTARTING;
}
public isStarted () : boolean {
return this._state === SimpleMatrixClientState.AUTHENTICATED_AND_STARTED;
}
public isStopping () : boolean {
return this._stopSyncOnNext;
}
public isSyncing () : boolean {
return this._state === SimpleMatrixClientState.AUTHENTICATED_AND_SYNCING;
}
/**
* Destroys the current client instance, including all observers.
*
* You should not use this instance anymore after you call this method.
*/
public destroy (): void {
switch (this._state) {
case SimpleMatrixClientState.UNAUTHENTICATED:
case SimpleMatrixClientState.AUTHENTICATING:
case SimpleMatrixClientState.AUTHENTICATED:
break;
case SimpleMatrixClientState.AUTHENTICATED_AND_STARTING:
case SimpleMatrixClientState.AUTHENTICATED_AND_RESTARTING:
case SimpleMatrixClientState.AUTHENTICATED_AND_STARTED:
case SimpleMatrixClientState.AUTHENTICATED_AND_SYNCING:
this._stopSyncing();
break;
}
this._clearSyncAgainTimer();
this._clearInitSyncAgainTimer();
this._observer.destroy();
}
/**
* Start listening some events.
*
* @param name
* @param callback
*/
public on (
name: SimpleMatrixClientEvent,
callback: ObserverCallback<SimpleMatrixClientEvent>
): SimpleMatrixClientDestructor {
return this._observer.listenEvent(name, callback);
}
/**
* Start the long polling event listener from Matrix server.
*
* @FIXME: This could be started automatically from listeners in our own observer. If so, this
* method could be changed to private later.
*/
public start (triggerEvents : boolean = true) {
this._startSyncing(triggerEvents);
}
/**
* Stop the long polling event listener from Matrix server.
*
* It will not remove any listeners.
*
* @FIXME: This could be stopped automatically when listeners are removed from our own
* observer. If so, this method could be changed to private later.
*/
public stop () {
this._stopSyncing();
}
/**
*
* @param requestBody
* @param kind
* @param accessToken
*/
public async register (
requestBody : MatrixRegisterRequestDTO,
kind : MatrixRegisterKind | undefined = undefined,
accessToken ?: string
) : Promise<MatrixRegisterResponseDTO> {
try {
LOG.debug(`register: Registering user:`, requestBody, kind);
const access_token : string | undefined = this?._accessToken ?? accessToken ?? undefined;
const response : any = await this._postJson(
this._homeServerUrl + MATRIX_REGISTER_URL(kind),
requestBody as unknown as JsonAny,
access_token ? {
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(access_token)
} : undefined
);
if (!isMatrixRegisterResponseDTO(response)) {
LOG.debug(`Invalid response received: `, response);
throw new TypeError(`${this._observer.getName()}.register: Response was invalid`);
}
LOG.debug(`register: RegisterResponseDTO received: `, response);
return response;
} catch (err : any) {
LOG.warn(`register: Could not register user: `, err);
if (err instanceof RequestError) {
const statusCode = err?.getStatusCode();
if ( statusCode === 400 ) {
const errorBody: any = SimpleMatrixClient._getErrorBody(err);
if ( isMatrixErrorDTO(errorBody) ) {
switch (errorBody.errcode) {
case MatrixErrorCode.M_USER_IN_USE:
throw new RequestError(RequestStatus.Conflict, `User already exists`);
case MatrixErrorCode.M_INVALID_USERNAME:
throw new RequestError(RequestStatus.BadRequest, `Username invalid`);
case MatrixErrorCode.M_EXCLUSIVE:
throw new RequestError(RequestStatus.Conflict, `User name conflicts with exclusive namespace`);
default:
throw new RequestError(RequestStatus.InternalServerError, `Failed to register user`);
}
} else {
throw new RequestError(RequestStatus.InternalServerError, `Failed to register user`);
}
} else if ( statusCode === 401 ) {
throw new RequestError(RequestStatus.Unauthorized);
} else if ( statusCode === 403 ) {
throw new RequestError(RequestStatus.Forbidden);
} else if ( statusCode === 429 ) {
// Rate limited
// FIXME: implement special exception that contains the retry_after_ms property and/or handle it here
throw new RequestError(429);
} else {
throw new RequestError(RequestStatus.InternalServerError, `Failed to register user`);
}
} else {
throw new RequestError(RequestStatus.InternalServerError, `Failed to register user`);
}
}
}
public async whoamiDTO () : Promise<MatrixWhoAmIResponseDTO | undefined> {
const accessToken : string | undefined = this._accessToken;
if (!accessToken) {
throw new TypeError(`${this._observer.getName()}.whoamiDTO: Client did not have access token`);
}
LOG.debug(`whoamiDTO: Fetching account whoamiDTO... `);
const response : any = await this._getJson(
this._homeServerUrl + MATRIX_WHOAMI_URL,
{
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(accessToken)
}
);
LOG.debug(`whoamiDTO: response = `, response);
if (!isMatrixWhoAmIResponseDTO(response)) {
throw new TypeError(`${this._observer.getName()}.whoamiDTO: Response was not MatrixWhoAmIResponseDTO: ${JSON.stringify(response)}`);
}
LOG.debug(`whoamiDTO: response.user_id = `, response.user_id);
this._userId = response.user_id;
return response;
}
public async whoami () : Promise<string | undefined> {
LOG.debug(`whoami: Updating whoami state... `);
await this.whoamiDTO();
LOG.debug(`whoami: userId: ${this._userId}`);
return this._userId;
}
public async getRegisterNonce () : Promise<string> {
try {
LOG.debug(`Fetching nonce for registration...`);
const nonceResponse : any = await this._getJson(this._homeServerUrl + SYNAPSE_REGISTER_URL);
const nonce = nonceResponse?.nonce ?? undefined;
if (!nonce) throw new TypeError(`${this._observer.getName()}.getRegisterNonce: No nonce detected`);
return nonce;
} catch (err : any) {
LOG.debug(`Could not fetch nonce for registration: `, err);
throw new TypeError(`${this._observer.getName()}.getRegisterNonce: Could not fetch nonce for the register request. Is it Synapse?`);
}
}
/**
* This call requires correctly configured Synapse and a shared secret code.
*
* See `SynapseUtils.createRegisterDTO(...)` and `.getRegisterNonce()` to create a DTO.
* Note, it requires NodeJS crypto module.
*
* @param requestBody
* @see https://matrix-org.github.io/synapse/latest/admin_api/register_api.html
*/
public async registerWithSharedSecret (
requestBody : SynapseRegisterRequestDTO
) : Promise<SynapseRegisterResponseDTO> {
try {
LOG.debug(`registerWithSharedSecret: Registering user:`, requestBody);
const response : any = await this._postJson(
this._homeServerUrl + SYNAPSE_REGISTER_URL,
requestBody as unknown as JsonAny
);
if (!isSynapseRegisterResponseDTO(response)) {
LOG.debug(`registerWithSharedSecret: Invalid response received: `, response);
throw new TypeError(`${this._observer.getName()}.registerWithSharedSecret: Response was invalid`);
}
LOG.debug(`registerWithSharedSecret: RegisterResponseDTO received: `, response);
return response;
} catch (err : any) {
LOG.warn(`registerWithSharedSecret: Could not register user: `, err);
if (err instanceof RequestError) {
const statusCode = err?.getStatusCode();
if ( statusCode === 400 ) {
const errorBody: any = SimpleMatrixClient._getErrorBody(err);
if ( isMatrixErrorDTO(errorBody) ) {
switch (errorBody.errcode) {
case MatrixErrorCode.M_USER_IN_USE:
throw new RequestError(RequestStatus.Conflict, `User already exists`);
case MatrixErrorCode.M_INVALID_USERNAME:
throw new RequestError(RequestStatus.BadRequest, `Username invalid`);
case MatrixErrorCode.M_EXCLUSIVE:
throw new RequestError(RequestStatus.Conflict, `User name conflicts with exclusive namespace`);
default:
throw new RequestError(RequestStatus.InternalServerError, `Failed to register user`);
}
} else {
throw new RequestError(RequestStatus.InternalServerError, `Failed to register user`);
}
} else if ( statusCode === 401 ) {
throw new RequestError(RequestStatus.Unauthorized);
} else if ( statusCode === 403 ) {
throw new RequestError(RequestStatus.Forbidden);
} else if ( statusCode === 429 ) {
// Rate limited
// FIXME: implement special exception that contains the retry_after_ms property and/or handle it here
throw new RequestError(429);
} else {
throw new RequestError(RequestStatus.InternalServerError, `Failed to register user`);
}
} else {
throw new RequestError(RequestStatus.InternalServerError, `Failed to register user`);
}
}
}
/**
* Log in to the matrix server
*
* @param userId The Matrix user ID to log into
* @param password The Matrix user password
* @returns New instance of SimpleMatrixClient which is initialized in to the authenticated
* state
*/
public async login (
userId : MatrixUserId,
password : string
) : Promise<SimpleMatrixClient> {
try {
const requestBody : MatrixPasswordLoginRequestDTO = createMatrixPasswordLoginRequestDTO(
createMatrixIdentifierDTO(userId),
password
);
LOG.debug(`Sending login with userId:`, userId);
const response : any = await this._postJson(
this._homeServerUrl + MATRIX_LOGIN_URL,
requestBody as unknown as JsonAny
);
if (!isMatrixLoginResponseDTO(response)) {
LOG.debug(`Invalid response received: `, response);
throw new TypeError(`${this._observer.getName()}.login: Response was invalid`);
}
LOG.debug(`Login response received: `, response);
let originalUrl = this._originalUrl;
let homeServerUrl = this._homeServerUrl;
let identityServerUrl = this._identityServerUrl;
if (response?.well_known) {
const responseHomeServerUrl = response.well_known[MatrixType.M_HOMESERVER]?.base_url;
if (responseHomeServerUrl) {
homeServerUrl = responseHomeServerUrl;
} else {
homeServerUrl = originalUrl;
}
const responseIdentityServerUrl = response.well_known[MatrixType.M_IDENTITY_SERVER]?.base_url;
if (responseIdentityServerUrl) {
identityServerUrl = responseIdentityServerUrl;
} else {
identityServerUrl = homeServerUrl;
}
} else {
homeServerUrl = originalUrl;
identityServerUrl = originalUrl;
}
const access_token = response?.access_token;
if (!access_token) {
throw new TypeError(`${this._observer.getName()}.login: Response did not have access_token`);
}
const user_id = response?.user_id;
if (!user_id) {
throw new TypeError(`${this._observer.getName()}.login: Response did not have user_id`);
}
return new SimpleMatrixClient(
originalUrl,
homeServerUrl,
identityServerUrl,
access_token,
user_id,
this._syncRequestTimeoutMs,
this._syncAgainTimeMs
);
} catch (err : any) {
LOG.debug(`Could not login: `, err);
throw new RequestError(RequestStatus.Forbidden, `Access denied`);
}
}
/**
* Authenticate to the Matrix server using access key
*
* @param access_token The Matrix access key
* @returns New instance of SimpleMatrixClient which is initialized in to the authenticated
* state
*/
public async authenticate (
access_token : string
) : Promise<SimpleMatrixClient> {
try {
return new SimpleMatrixClient(
this._originalUrl,
undefined,
undefined,
access_token,
undefined,
this._syncRequestTimeoutMs,
this._syncAgainTimeMs
);
} catch (err : any) {
LOG.debug(`Could not login: `, err);
throw new RequestError(RequestStatus.Forbidden, `Access denied`);
}
}
/**
* Resolve room name (eg. alias) into room ID.
*
* Eg. if you say `'foo'` here, it will be converted to `'#foo:homeServerHostname'`.
*
* @param name
*/
public async resolveRoomId (name: string) : Promise<string | undefined> {
try {
const roomName : string = this._normalizeRoomName(name);
const response : any = await this._getJson(
this._homeServerUrl + MATRIX_ROOM_DIRECTORY_URL(roomName)
);
if (!isGetDirectoryRoomAliasResponseDTO(response)) {
LOG.debug(`resolveRoomId: response was not GetDirectoryRoomAliasResponseDTO: `, response);
throw new TypeError(`${this._observer.getName()}.resolveRoomId: Response was not GetDirectoryRoomAliasResponseDTO: ${response}`);
}
LOG.debug(`resolveRoomId: received: `, response);
return response.room_id;
} catch (err : any) {
if (err instanceof RequestError && err.getStatusCode() === RequestStatus.NotFound) {
return undefined;
} else {
LOG.warn(`resolveRoomId: Passing on error: `, err);
throw err;
}
}
}
/**
* Returns joined members from the homeserver
*
* @param roomId
*/
public async getJoinedMembers (roomId: MatrixRoomId) : Promise<MatrixRoomJoinedMembersDTO> {
const accessToken : string | undefined = this._accessToken;
if (!accessToken) {
throw new TypeError(`${this._observer.getName()}.getJoinedMembers: Client did not have access token`);
}
const response : any = await this._getJson(
this._homeServerUrl + MATRIX_JOINED_MEMBERS_URL(roomId),
{
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(accessToken)
}
);
if (!isMatrixRoomJoinedMembersDTO(response)) {
LOG.debug(`getJoinedMembers: response was not MatrixRoomJoinedMembersDTO: `, response);
throw new TypeError(`${this._observer.getName()}.getJoinedMembers: Response was not MatrixRoomJoinedMembersDTO: ${response}`);
}
LOG.debug(`getJoinedMembers: received: `, response);
return response;
}
/**
* Returns a room state value of tuple `roomId,eventType,StateKey`.
*
* @param roomId
* @param eventType
* @param stateKey
*/
public async getRoomStateByType (
roomId : string,
eventType : string,
stateKey : string
) : Promise<GetRoomStateByTypeResponseDTO | undefined> {
try {
const accessToken : string | undefined = this._accessToken;
if (!accessToken) {
throw new TypeError(`${this._observer.getName()}.getRoomStateByType: Client did not have access token`);
}
LOG.debug(`getRoomStateByType: roomId="${roomId}", eventType="${eventType}", stateKey="${stateKey}" `);
const response : any = await this._getJson(
this._homeServerUrl + MATRIX_ROOM_EVENT_STATE_FETCH_URL(roomId, eventType, stateKey),
{
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(accessToken)
}
);
if (!isGetRoomStateByTypeResponseDTO(response)) {
LOG.debug(`getRoomStateByType: response was not GetRoomStateByTypeResponseDTO: `, response);
throw new TypeError(`${this._observer.getName()}.getRoomStateByType: Response was not GetRoomStateByTypeResponseDTO: ${JSON.stringify(response)}`);
}
LOG.debug(`getRoomStateByType: received: `, response);
return response;
} catch (err : any) {
if (err instanceof RequestError && err.getStatusCode() === RequestStatus.NotFound) {
return undefined;
} else {
LOG.warn(`getRoomStateByType: Passing on error: `, err);
throw err;
}
}
}
/**
* Sets room state value of tuple `roomId,eventType,StateKey`
*
* @param roomId
* @param eventType
* @param stateKey
* @param body
*/
public async setRoomStateByType (
roomId : string,
eventType : string,
stateKey : string,
body : SetRoomStateByTypeRequestDTO,
) : Promise<PutRoomStateWithEventTypeResponseDTO> {
try {
const accessToken : string | undefined = this._accessToken;
if (!accessToken) {
throw new TypeError(`${this._observer.getName()}.setRoomStateByType: Client did not have access token`);
}
const response : JsonAny | undefined = await this._putJson(
this._homeServerUrl + MATRIX_ROOM_EVENT_STATE_UPDATE_URL(roomId, eventType, stateKey),
body as unknown as JsonObject,
{
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(accessToken)
}
);
if (!isPutRoomStateWithEventTypeResponseDTO(response)) {
LOG.debug(`setRoomStateByType: response was not PutRoomStateWithEventTypeDTO: `, response);
throw new TypeError(`${this._observer.getName()}.setRoomStateByType: Response was not PutRoomStateWithEventTypeDTO: ${JSON.stringify(response)}`);
}
LOG.debug(`setRoomStateByType: received: `, response);
// @ts-ignore
return response;
} catch (err : any) {
LOG.error(`setRoomStateByType: Passing on error: `, err);
throw err;
}
}
/**
* Forgets a room.
*
* Once every member has forgot it, the room will be marked for deletion in homeserver.
*
* @param roomId
*/
public async forgetRoom (
roomId : string
) : Promise<void> {
try {
const accessToken : string | undefined = this._accessToken;
if (!accessToken) {
throw new TypeError(`${this._observer.getName()}.forgetRoom: Client did not have access token`);
}
const response : JsonAny | undefined = await this._postJson(
this._homeServerUrl + MATRIX_ROOM_FORGET_URL(roomId),
{},
{
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(accessToken)
}
);
LOG.debug(`forgetRoom: received: `, response);
} catch (err : any) {
LOG.warn(`forgetRoom: Passing on error: `, err);
throw err;
}
}
/**
* Leave from a room.
*
* @param roomId
*/
public async leaveRoom (
roomId : string
) : Promise<void> {
try {
const accessToken : string | undefined = this._accessToken;
if (!accessToken) {
throw new TypeError(`${this._observer.getName()}.leaveRoom: Client did not have access token`);
}
const response : JsonAny | undefined = await this._postJson(
this._homeServerUrl + MATRIX_ROOM_LEAVE_URL(roomId),
{},
{
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(accessToken)
}
);
LOG.debug(`leaveRoom: received: `, response);
} catch (err : any) {
LOG.warn(`leaveRoom: Passing on error: `, err);
throw err;
}
}
/**
* Invite user to a room.
*
* @param roomId
* @param userId
*/
public async inviteToRoom (
roomId : MatrixRoomId,
userId : MatrixUserId
) : Promise<void> {
try {
if (!isMatrixRoomId(roomId)) {
throw new TypeError(`${this._observer.getName()}.inviteToRoom: roomId invalid: ${roomId}`);
}
if (!isMatrixUserId(userId)) {
throw new TypeError(`${this._observer.getName()}.inviteToRoom: userId invalid: ${userId}`);
}
LOG.info(`Inviting user ${userId} to ${roomId}`);
const accessToken : string | undefined = this._accessToken;
if (!accessToken) {
throw new TypeError(`${this._observer.getName()}.inviteToRoom: Client did not have access token`);
}
const response : JsonAny | undefined = await this._postJson(
this._homeServerUrl + MATRIX_ROOM_INVITE_URL(roomId),
{
user_id: userId
},
{
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(accessToken)
}
);
LOG.debug(`inviteToRoom: received: `, response);
} catch (err : any) {
if ( this.isAlreadyInTheRoom(err?.body) ) return;
LOG.warn(`inviteToRoom: Passing on error: `, err);
throw err;
}
}
/**
* Send text message to the room.
*
* @param roomId The room ID
* @param body The message string
*/
public async sendTextMessage (roomId: string, body: string) : Promise<void> {
const accessToken : string | undefined = this._accessToken;
if (!accessToken) {
throw new TypeError(`${this._observer.getName()}.sendTextMessage: Client did not have access token`);
}
const requestBody : MatrixTextMessageDTO = createMatrixTextMessageDTO(body);
LOG.debug(`Sending message with body:`, requestBody);
const response : Json | undefined = await this._postJson(
this._homeServerUrl + MATRIX_ROOM_SEND_EVENT_URL(roomId, MatrixType.M_ROOM_MESSAGE),
requestBody as unknown as JsonAny,
{
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(accessToken)
}
);
LOG.debug(`sendTextMessage response received: `, response);
}
/**
* Create a room.
*
* @param body
*/
public async createRoom (
body: MatrixCreateRoomDTO
) : Promise<MatrixCreateRoomResponseDTO> {
const accessToken : string | undefined = this._accessToken;
if (!accessToken) {
throw new TypeError(`${this._observer.getName()}.createRoom: Client did not have access token`);
}
LOG.debug(`Creating room with body:`, body);
const response : MatrixCreateRoomResponseDTO | any = await this._postJson(
this._homeServerUrl + MATRIX_CREATE_ROOM_URL,
body as unknown as JsonAny,
{
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(accessToken)
}
);
if (!isMatrixCreateRoomResponseDTO(response)) {
LOG.debug(`response = `, response);
throw new TypeError(`${this._observer.getName()}.createRoom: Response was not MatrixCreateRoomResponseDTO: ` + response);
}
LOG.debug(`Create room response received: `, response);
return response;
}
/**
* Join to a room.
*
* @param roomId
* @param body
*/
public async joinRoom (
roomId : MatrixRoomId,
body : MatrixJoinRoomRequestDTO | undefined = undefined
) : Promise<MatrixJoinRoomResponseDTO> {
try {
const accessToken : string | undefined = this._accessToken;
if (!accessToken) {
throw new TypeError(`${this._observer.getName()}.joinRoom: Client did not have access token`);
}
LOG.debug(`joinRoom: Joining to room "${roomId}" with body:`, body);
const response : MatrixCreateRoomResponseDTO | any = await this._postJson(
this._homeServerUrl + MATRIX_JOIN_ROOM_URL( roomId ),
(body ?? {}) as unknown as JsonAny,
{
[MATRIX_AUTHORIZATION_HEADER_NAME]: AuthorizationUtils.createBearerHeader(accessToken)
}
);
if (!isMatrixJoinRoomResponseDTO(response)) {
LOG.debug(`response = `, response);
throw new TypeError(`${this._observer.getName()}.joinRoom: Could not join to "${roomId}": Response was not MatrixJoinRoomResponseDTO: ` + response);
}
LOG.debug(`joinRoom: Joined to room "${roomId}": `, response);
return response;
} catch (err : any) {
LOG.warn(`joinRoom: Error: `, err);
if ( this.isAlreadyInTheRoom(err?.body) ) {
return {room_id: roomId};
}
const body: any = SimpleMatrixClient._getErrorBody(err);
if ( isMatrixErrorDTO(body) && body.errcode === MatrixErrorCode.M_FORBIDDEN ) {
LOG.warn(`joinRoom: Passing on error: Could not join to room "${roomId}": ${body?.errcode}: ${body?.error}`);
throw err;
} else {
LOG.warn(`joinRoom: Passing on error: Could not join to room "${roomId}": `, err);
throw err;
}
}
}
/**
* Create the sync request.
*
* Note! This is the raw method for the Matrix HTTP request, and is not related to the internal
* sync states.
*
* @param options
*/
public async sync (options : {
filter ?: string | JsonObject,
since ?: string,
full_state ?: boolean,
set_presence ?: MatrixSyncPresence,
timeout ?: number
}) : Promise<MatrixSyncResponseDTO> {
LOG.debug(`sync with `, options);