-
-
Notifications
You must be signed in to change notification settings - Fork 616
/
Copy pathmatrix-client-methods.spec.ts
2207 lines (1937 loc) · 83.6 KB
/
matrix-client-methods.spec.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 2022 - 2023 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import HttpBackend from "matrix-mock-request";
import { Mocked } from "jest-mock";
import * as utils from "../test-utils/test-utils";
import { CRYPTO_ENABLED, IStoredClientOpts, MatrixClient } from "../../src/client";
import { MatrixEvent } from "../../src/models/event";
import {
Filter,
JoinRule,
KnockRoomOpts,
MemoryStore,
Method,
Room,
RoomSummary,
SERVICE_TYPES,
} from "../../src/matrix";
import { TestClient } from "../TestClient";
import { THREAD_RELATION_TYPE } from "../../src/models/thread";
import { IFilterDefinition } from "../../src/filter";
import { ISearchResults } from "../../src/@types/search";
import { IStore } from "../../src/store";
import { CryptoBackend } from "../../src/common-crypto/CryptoBackend";
import { SetPresence } from "../../src/sync";
import { KnownMembership } from "../../src/@types/membership";
describe("MatrixClient", function () {
const userId = "@alice:localhost";
const accessToken = "aseukfgwef";
const idServerDomain = "identity.localhost"; // not a real server
const identityAccessToken = "woop-i-am-a-secret";
let client: MatrixClient;
let httpBackend: HttpBackend;
let store: MemoryStore;
const defaultClientOpts: IStoredClientOpts = {
threadSupport: false,
};
const setupTests = (): [MatrixClient, HttpBackend, MemoryStore] => {
const store = new MemoryStore();
const testClient = new TestClient(userId, "aliceDevice", accessToken, undefined, {
store: store as IStore,
identityServer: {
getAccessToken: () => Promise.resolve(identityAccessToken),
},
idBaseUrl: `https://${idServerDomain}`,
});
return [testClient.client, testClient.httpBackend, store];
};
beforeEach(function () {
[client, httpBackend, store] = setupTests();
});
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
return httpBackend.stop();
});
describe("uploadContent", function () {
const buf = Buffer.from("hello world");
const file = buf;
const opts = {
type: "text/plain",
name: "hi.txt",
};
it("should upload the file", function () {
httpBackend
.when("POST", "/_matrix/media/v3/upload")
.check(function (req) {
expect(req.rawData).toEqual(buf);
expect(req.queryParams?.filename).toEqual("hi.txt");
expect(req.headers["Authorization"]).toBe("Bearer " + accessToken);
expect(req.headers["Content-Type"]).toEqual("text/plain");
// @ts-ignore private property
expect(req.opts.json).toBeFalsy();
// @ts-ignore private property
expect(req.opts.timeout).toBe(undefined);
})
.respond(200, '{"content_uri": "content"}', true);
const prom = client.uploadContent(file, opts);
expect(prom).toBeTruthy();
const uploads = client.getCurrentUploads();
expect(uploads.length).toEqual(1);
expect(uploads[0].promise).toBe(prom);
expect(uploads[0].loaded).toEqual(0);
const prom2 = prom.then(function (response) {
expect(response.content_uri).toEqual("content");
const uploads = client.getCurrentUploads();
expect(uploads.length).toEqual(0);
});
httpBackend.flush("");
return prom2;
});
it("should parse errors into a MatrixError", function () {
httpBackend
.when("POST", "/_matrix/media/v3/upload")
.check(function (req) {
expect(req.rawData).toEqual(buf);
// @ts-ignore private property
expect(req.opts.json).toBeFalsy();
})
.respond(400, {
errcode: "M_SNAFU",
error: "broken",
});
const prom = client.uploadContent(file, opts).then(
function (response) {
throw Error("request not failed");
},
function (error) {
expect(error.httpStatus).toEqual(400);
expect(error.errcode).toEqual("M_SNAFU");
expect(error.message).toEqual("MatrixError: [400] broken");
},
);
httpBackend.flush("");
return prom;
});
it("should return a promise which can be cancelled", async () => {
const prom = client.uploadContent(file, opts);
const uploads = client.getCurrentUploads();
expect(uploads.length).toEqual(1);
expect(uploads[0].promise).toBe(prom);
expect(uploads[0].loaded).toEqual(0);
const r = client.cancelUpload(prom);
expect(r).toBe(true);
await expect(prom).rejects.toThrow("Aborted");
expect(client.getCurrentUploads()).toHaveLength(0);
});
});
describe("joinRoom", function () {
it("should no-op given the ID of a room you've already joined", async () => {
const roomId = "!foo:bar";
const room = new Room(roomId, client, userId);
client.fetchRoomEvent = () =>
Promise.resolve({
type: "test",
content: {},
});
room.addLiveEvents(
[
utils.mkMembership({
user: userId,
room: roomId,
mship: KnownMembership.Join,
event: true,
}),
],
{ addToState: true },
);
httpBackend.verifyNoOutstandingRequests();
store.storeRoom(room);
const joinPromise = client.joinRoom(roomId);
httpBackend.verifyNoOutstandingRequests();
expect(await joinPromise).toBe(room);
});
it("should no-op given the alias of a room you've already joined", async () => {
const roomId = "!roomId:server";
const roomAlias = "#my-fancy-room:server";
const room = new Room(roomId, client, userId);
room.addLiveEvents(
[
utils.mkMembership({
user: userId,
room: roomId,
mship: KnownMembership.Join,
event: true,
}),
],
{ addToState: true },
);
store.storeRoom(room);
// The method makes a request to resolve the alias
httpBackend.when("POST", "/join/" + encodeURIComponent(roomAlias)).respond(200, { room_id: roomId });
const joinPromise = client.joinRoom(roomAlias);
await httpBackend.flushAllExpected();
expect(await joinPromise).toBe(room);
});
it("should send request to inviteSignUrl if specified", async () => {
const roomId = "!roomId:server";
const inviteSignUrl = "https://id.server/sign/this/for/me";
const viaServers = ["a", "b", "c"];
const signature = {
sender: "sender",
mxid: "@sender:foo",
token: "token",
signatures: {},
};
httpBackend
.when("POST", inviteSignUrl)
.check((request) => {
expect(request.queryParams?.mxid).toEqual(client.getUserId());
})
.respond(200, signature);
httpBackend
.when("POST", "/join/" + encodeURIComponent(roomId))
.check((request) => {
expect(request.data.third_party_signed).toEqual(signature);
})
.respond(200, { room_id: roomId });
const prom = client.joinRoom(roomId, {
inviteSignUrl,
viaServers,
});
await httpBackend.flushAllExpected();
expect((await prom).roomId).toBe(roomId);
});
});
describe("knockRoom", function () {
const roomId = "!some-room-id:example.org";
const reason = "some reason";
const viaServers = "example.com";
type TestCase = [string, KnockRoomOpts];
const testCases: TestCase[] = [
["should knock a room", {}],
["should knock a room for a reason", { reason }],
["should knock a room via given servers", { viaServers }],
["should knock a room for a reason via given servers", { reason, viaServers }],
];
it.each(testCases)("%s", async (_, opts) => {
httpBackend
.when("POST", "/knock/" + encodeURIComponent(roomId))
.check((request) => {
expect(request.data).toEqual({ reason: opts.reason });
expect(request.queryParams).toEqual({ server_name: opts.viaServers, via: opts.viaServers });
})
.respond(200, { room_id: roomId });
const prom = client.knockRoom(roomId, opts);
await httpBackend.flushAllExpected();
expect((await prom).room_id).toBe(roomId);
});
it("should no-op if you've already knocked a room", function () {
const room = new Room(roomId, client, userId);
client.fetchRoomEvent = () =>
Promise.resolve({
type: "test",
content: {},
});
room.addLiveEvents(
[
utils.mkMembership({
user: userId,
room: roomId,
mship: KnownMembership.Knock,
event: true,
}),
],
{ addToState: true },
);
httpBackend.verifyNoOutstandingRequests();
store.storeRoom(room);
client.knockRoom(roomId);
httpBackend.verifyNoOutstandingRequests();
});
describe("errors", function () {
type TestCase = [number, { errcode: string; error?: string }, string];
const testCases: TestCase[] = [
[
403,
{ errcode: "M_FORBIDDEN", error: "You don't have permission to knock" },
"[M_FORBIDDEN: MatrixError: [403] You don't have permission to knock]",
],
[
500,
{ errcode: "INTERNAL_SERVER_ERROR" },
"[INTERNAL_SERVER_ERROR: MatrixError: [500] Unknown message]",
],
];
it.each(testCases)("should handle %s error", async (code, { errcode, error }, snapshot) => {
httpBackend.when("POST", "/knock/" + encodeURIComponent(roomId)).respond(code, { errcode, error });
const prom = client.knockRoom(roomId);
await Promise.all([
httpBackend.flushAllExpected(),
expect(prom).rejects.toMatchInlineSnapshot(snapshot),
]);
});
});
});
describe("getFilter", function () {
const filterId = "f1lt3r1d";
it("should return a filter from the store if allowCached", async () => {
const filter = Filter.fromJson(userId, filterId, {
event_format: "client",
});
store.storeFilter(filter);
const gotFilter = await client.getFilter(userId, filterId, true);
expect(gotFilter).toEqual(filter);
httpBackend.verifyNoOutstandingRequests();
});
it("should do an HTTP request if !allowCached even if one exists", async () => {
const httpFilterDefinition = {
event_format: "federation",
};
httpBackend
.when("GET", "/user/" + encodeURIComponent(userId) + "/filter/" + filterId)
.respond(200, httpFilterDefinition);
const storeFilter = Filter.fromJson(userId, filterId, {
event_format: "client",
});
store.storeFilter(storeFilter);
const [gotFilter] = await Promise.all([client.getFilter(userId, filterId, false), httpBackend.flush("")]);
expect(gotFilter.getDefinition()).toEqual(httpFilterDefinition);
});
it("should do an HTTP request if nothing is in the cache and then store it", async () => {
const httpFilterDefinition = {
event_format: "federation",
};
expect(store.getFilter(userId, filterId)).toBe(null);
httpBackend
.when("GET", "/user/" + encodeURIComponent(userId) + "/filter/" + filterId)
.respond(200, httpFilterDefinition);
const [gotFilter] = await Promise.all([client.getFilter(userId, filterId, true), httpBackend.flush("")]);
expect(gotFilter.getDefinition()).toEqual(httpFilterDefinition);
expect(store.getFilter(userId, filterId)).toBeTruthy();
});
});
describe("createFilter", function () {
const filterId = "f1llllllerid";
it("should do an HTTP request and then store the filter", async () => {
expect(store.getFilter(userId, filterId)).toBe(null);
const filterDefinition = {
event_format: "client" as IFilterDefinition["event_format"],
};
httpBackend
.when("POST", "/user/" + encodeURIComponent(userId) + "/filter")
.check(function (req) {
expect(req.data).toEqual(filterDefinition);
})
.respond(200, {
filter_id: filterId,
});
const [gotFilter] = await Promise.all([client.createFilter(filterDefinition), httpBackend.flush("")]);
expect(gotFilter.getDefinition()).toEqual(filterDefinition);
expect(store.getFilter(userId, filterId)).toEqual(gotFilter);
});
});
describe("searching", function () {
it("searchMessageText should perform a /search for room_events", function () {
const response = {
search_categories: {
room_events: {
count: 24,
results: [
{
rank: 0.1,
result: {
event_id: "$flibble:localhost",
type: "m.room.message",
user_id: "@alice:localhost",
room_id: "!feuiwhf:localhost",
content: {
body: "a result",
msgtype: "m.text",
},
},
},
],
},
},
};
client.searchMessageText({
query: "monkeys",
});
httpBackend
.when("POST", "/search")
.check(function (req) {
expect(req.data).toEqual({
search_categories: {
room_events: {
search_term: "monkeys",
},
},
});
})
.respond(200, response);
return httpBackend.flush("");
});
describe("should filter out context from different timelines (threads)", () => {
it("filters out thread replies when result is in the main timeline", async () => {
const response = {
search_categories: {
room_events: {
count: 24,
highlights: [],
results: [
{
rank: 0.1,
result: {
event_id: "$flibble:localhost",
type: "m.room.message",
sender: "@test:locahost",
origin_server_ts: 123,
user_id: "@alice:localhost",
room_id: "!feuiwhf:localhost",
content: {
body: "main timeline",
msgtype: "m.text",
},
},
context: {
profile_info: {},
events_after: [
{
event_id: "$ev-after:server",
type: "m.room.message",
sender: "@test:locahost",
origin_server_ts: 123,
user_id: "@alice:localhost",
room_id: "!feuiwhf:localhost",
content: {
"body": "thread reply",
"msgtype": "m.text",
"m.relates_to": {
event_id: "$some-thread:server",
rel_type: THREAD_RELATION_TYPE.name,
},
},
},
],
events_before: [
{
event_id: "$ev-before:server",
type: "m.room.message",
sender: "@test:locahost",
origin_server_ts: 123,
user_id: "@alice:localhost",
room_id: "!feuiwhf:localhost",
content: {
body: "main timeline again",
msgtype: "m.text",
},
},
],
},
},
],
},
},
};
const data: ISearchResults = {
results: [],
highlights: [],
};
client.processRoomEventsSearch(data, response);
expect(data.results).toHaveLength(1);
expect(data.results[0].context.getTimeline()).toHaveLength(2);
expect(data.results[0].context.getTimeline().find((e) => e.getId() === "$ev-after:server")).toBeFalsy();
});
it("filters out thread replies from threads other than the thread the result replied to", () => {
const response = {
search_categories: {
room_events: {
count: 24,
highlights: [],
results: [
{
rank: 0.1,
result: {
event_id: "$flibble:localhost",
type: "m.room.message",
sender: "@test:locahost",
origin_server_ts: 123,
user_id: "@alice:localhost",
room_id: "!feuiwhf:localhost",
content: {
"body": "thread 1 reply 1",
"msgtype": "m.text",
"m.relates_to": {
event_id: "$thread1:server",
rel_type: THREAD_RELATION_TYPE.name,
},
},
},
context: {
profile_info: {},
events_after: [
{
event_id: "$ev-after:server",
type: "m.room.message",
sender: "@test:locahost",
origin_server_ts: 123,
user_id: "@alice:localhost",
room_id: "!feuiwhf:localhost",
content: {
"body": "thread 2 reply 2",
"msgtype": "m.text",
"m.relates_to": {
event_id: "$thread2:server",
rel_type: THREAD_RELATION_TYPE.name,
},
},
},
],
events_before: [],
},
},
],
},
},
};
const data: ISearchResults = {
results: [],
highlights: [],
};
client.processRoomEventsSearch(data, response);
expect(data.results).toHaveLength(1);
expect(data.results[0].context.getTimeline()).toHaveLength(1);
expect(
data.results[0].context.getTimeline().find((e) => e.getId() === "$flibble:localhost"),
).toBeTruthy();
});
it("filters out main timeline events when result is a thread reply", () => {
const response = {
search_categories: {
room_events: {
count: 24,
highlights: [],
results: [
{
rank: 0.1,
result: {
event_id: "$flibble:localhost",
sender: "@test:locahost",
origin_server_ts: 123,
type: "m.room.message",
user_id: "@alice:localhost",
room_id: "!feuiwhf:localhost",
content: {
"body": "thread 1 reply 1",
"msgtype": "m.text",
"m.relates_to": {
event_id: "$thread1:server",
rel_type: THREAD_RELATION_TYPE.name,
},
},
},
context: {
events_after: [
{
event_id: "$ev-after:server",
sender: "@test:locahost",
origin_server_ts: 123,
type: "m.room.message",
user_id: "@alice:localhost",
room_id: "!feuiwhf:localhost",
content: {
body: "main timeline",
msgtype: "m.text",
},
},
],
events_before: [],
profile_info: {},
},
},
],
},
},
};
const data: ISearchResults = {
results: [],
highlights: [],
};
client.processRoomEventsSearch(data, response);
expect(data.results).toHaveLength(1);
expect(data.results[0].context.getTimeline()).toHaveLength(1);
expect(
data.results[0].context.getTimeline().find((e) => e.getId() === "$flibble:localhost"),
).toBeTruthy();
});
});
});
describe("downloadKeys", function () {
if (!CRYPTO_ENABLED) {
return;
}
beforeEach(function () {
// running initLegacyCrypto should trigger a key upload
httpBackend.when("POST", "/keys/upload").respond(200, {});
return Promise.all([client.initLegacyCrypto(), httpBackend.flush("/keys/upload", 1)]);
});
afterEach(() => {
client.stopClient();
});
it("should do an HTTP request and then store the keys", function () {
const ed25519key = "7wG2lzAqbjcyEkOP7O4gU7ItYcn+chKzh5sT/5r2l78";
// ed25519key = client.getDeviceEd25519Key();
const borisKeys = {
dev1: {
algorithms: ["1"],
device_id: "dev1",
keys: { "ed25519:dev1": ed25519key },
signatures: {
boris: {
"ed25519:dev1":
"RAhmbNDq1efK3hCpBzZDsKoGSsrHUxb25NW5/WbEV9R" +
"JVwLdP032mg5QsKt/pBDUGtggBcnk43n3nBWlA88WAw",
},
},
unsigned: { abc: "def" },
user_id: "boris",
},
};
const chazKeys = {
dev2: {
algorithms: ["2"],
device_id: "dev2",
keys: { "ed25519:dev2": ed25519key },
signatures: {
chaz: {
"ed25519:dev2":
"FwslH/Q7EYSb7swDJbNB5PSzcbEO1xRRBF1riuijqvL" +
"EkrK9/XVN8jl4h7thGuRITQ01siBQnNmMK9t45QfcCQ",
},
},
unsigned: { ghi: "def" },
user_id: "chaz",
},
};
/*
function sign(o) {
var anotherjson = require('another-json');
var b = JSON.parse(JSON.stringify(o));
delete(b.signatures);
delete(b.unsigned);
return client.crypto.olmDevice.sign(anotherjson.stringify(b));
};
logger.log("Ed25519: " + ed25519key);
logger.log("boris:", sign(borisKeys.dev1));
logger.log("chaz:", sign(chazKeys.dev2));
*/
httpBackend
.when("POST", "/keys/query")
.check(function (req) {
expect(req.data).toEqual({
device_keys: {
boris: [],
chaz: [],
},
});
})
.respond(200, {
device_keys: {
boris: borisKeys,
chaz: chazKeys,
},
});
const prom = client.downloadKeys(["boris", "chaz"]).then(function (res) {
assertObjectContains(res.get("boris")!.get("dev1")!, {
verified: 0, // DeviceVerification.UNVERIFIED
keys: { "ed25519:dev1": ed25519key },
algorithms: ["1"],
unsigned: { abc: "def" },
});
assertObjectContains(res.get("chaz")!.get("dev2")!, {
verified: 0, // DeviceVerification.UNVERIFIED
keys: { "ed25519:dev2": ed25519key },
algorithms: ["2"],
unsigned: { ghi: "def" },
});
});
httpBackend.flush("");
return prom;
});
});
describe("deleteDevice", function () {
const auth = { identifier: 1 };
it("should pass through an auth dict", function () {
httpBackend
.when("DELETE", "/_matrix/client/v3/devices/my_device")
.check(function (req) {
expect(req.data).toEqual({ auth: auth });
})
.respond(200);
const prom = client.deleteDevice("my_device", auth);
httpBackend.flush("");
return prom;
});
});
describe("partitionThreadedEvents", function () {
let room: Room;
beforeEach(() => {
room = new Room("!STrMRsukXHtqQdSeHa:matrix.org", client, userId);
});
it("returns empty arrays when given an empty arrays", function () {
const events: MatrixEvent[] = [];
const [timeline, threaded] = room.partitionThreadedEvents(events);
expect(timeline).toEqual([]);
expect(threaded).toEqual([]);
});
it("should not copy pre-thread in-timeline vote events onto both timelines", function () {
// @ts-ignore setting private property
client.clientOpts = {
...defaultClientOpts,
threadSupport: true,
};
const eventPollResponseReference = buildEventPollResponseReference();
const eventPollStartThreadRoot = buildEventPollStartThreadRoot();
const eventMessageInThread = buildEventMessageInThread(eventPollStartThreadRoot);
const events = [eventPollStartThreadRoot, eventMessageInThread, eventPollResponseReference];
// Vote has no threadId yet
// @ts-ignore private property
expect(eventPollResponseReference.threadId).toBeFalsy();
const [timeline, threaded] = room.partitionThreadedEvents(events);
expect(timeline).toEqual([
// The message that was sent in a thread is missing
eventPollStartThreadRoot,
eventPollResponseReference,
]);
// The vote event has been copied into the thread
const eventRefWithThreadId = withThreadId(eventPollResponseReference, eventPollStartThreadRoot.getId()!);
expect(eventRefWithThreadId.threadRootId).toBeTruthy();
expect(threaded).toEqual([eventPollStartThreadRoot, eventMessageInThread]);
});
it("should not copy pre-thread in-timeline reactions onto both timelines", function () {
// @ts-ignore setting private property
client.clientOpts = {
...defaultClientOpts,
threadSupport: true,
};
const eventPollStartThreadRoot = buildEventPollStartThreadRoot();
const eventMessageInThread = buildEventMessageInThread(eventPollStartThreadRoot);
const eventReaction = buildEventReaction(eventPollStartThreadRoot);
const events = [eventPollStartThreadRoot, eventMessageInThread, eventReaction];
const [timeline, threaded] = room.partitionThreadedEvents(events);
expect(timeline).toEqual([eventPollStartThreadRoot, eventReaction]);
expect(threaded).toEqual([eventPollStartThreadRoot, eventMessageInThread]);
});
it("should not copy post-thread in-timeline vote events onto both timelines", function () {
// @ts-ignore setting private property
client.clientOpts = {
...defaultClientOpts,
threadSupport: true,
};
const eventPollResponseReference = buildEventPollResponseReference();
const eventPollStartThreadRoot = buildEventPollStartThreadRoot();
const eventMessageInThread = buildEventMessageInThread(eventPollStartThreadRoot);
const events = [eventPollStartThreadRoot, eventPollResponseReference, eventMessageInThread];
const [timeline, threaded] = room.partitionThreadedEvents(events);
expect(timeline).toEqual([eventPollStartThreadRoot, eventPollResponseReference]);
expect(threaded).toEqual([eventPollStartThreadRoot, eventMessageInThread]);
});
it("should not copy post-thread in-timeline reactions onto both timelines", function () {
// @ts-ignore setting private property
client.clientOpts = {
...defaultClientOpts,
threadSupport: true,
};
const eventPollStartThreadRoot = buildEventPollStartThreadRoot();
const eventMessageInThread = buildEventMessageInThread(eventPollStartThreadRoot);
const eventReaction = buildEventReaction(eventPollStartThreadRoot);
const events = [eventPollStartThreadRoot, eventMessageInThread, eventReaction];
const [timeline, threaded] = room.partitionThreadedEvents(events);
expect(timeline).toEqual([eventPollStartThreadRoot, eventReaction]);
expect(threaded).toEqual([eventPollStartThreadRoot, eventMessageInThread]);
});
it("sends room state events to the main timeline only", function () {
// @ts-ignore setting private property
client.clientOpts = {
...defaultClientOpts,
threadSupport: true,
};
// This is based on recording the events in a real room:
const eventPollStartThreadRoot = buildEventPollStartThreadRoot();
const eventPollResponseReference = buildEventPollResponseReference();
const eventMessageInThread = buildEventMessageInThread(eventPollStartThreadRoot);
const eventRoomName = buildEventRoomName();
const eventEncryption = buildEventEncryption();
const eventGuestAccess = buildEventGuestAccess();
const eventHistoryVisibility = buildEventHistoryVisibility();
const eventJoinRules = buildEventJoinRules();
const eventPowerLevels = buildEventPowerLevels();
const eventMember = buildEventMember();
const eventCreate = buildEventCreate();
const events = [
eventPollStartThreadRoot,
eventPollResponseReference,
eventMessageInThread,
eventRoomName,
eventEncryption,
eventGuestAccess,
eventHistoryVisibility,
eventJoinRules,
eventPowerLevels,
eventMember,
eventCreate,
];
const [timeline, threaded] = room.partitionThreadedEvents(events);
expect(timeline).toEqual([
// The message that was sent in a thread is missing
eventPollStartThreadRoot,
eventPollResponseReference,
eventRoomName,
eventEncryption,
eventGuestAccess,
eventHistoryVisibility,
eventJoinRules,
eventPowerLevels,
eventMember,
eventCreate,
]);
// Thread should contain only stuff that happened in the thread - no room state events
expect(threaded).toEqual([eventPollStartThreadRoot, eventMessageInThread]);
});
it("sends redactions of reactions to thread responses to thread timeline only", () => {
// @ts-ignore setting private property
client.clientOpts = {
...defaultClientOpts,
threadSupport: true,
};
const threadRootEvent = buildEventPollStartThreadRoot();
const eventMessageInThread = buildEventMessageInThread(threadRootEvent);
const threadedReaction = buildEventReaction(eventMessageInThread);
const threadedReactionRedaction = buildEventRedaction(threadedReaction);
const events = [threadRootEvent, eventMessageInThread, threadedReaction, threadedReactionRedaction];
const [timeline, threaded] = room.partitionThreadedEvents(events);
expect(timeline).toEqual([threadRootEvent]);
expect(threaded).toEqual([
threadRootEvent,
eventMessageInThread,
threadedReaction,
threadedReactionRedaction,
]);
});
it("sends reply to reply to thread root outside of thread to main timeline only", () => {
// @ts-ignore setting private property
client.clientOpts = {
...defaultClientOpts,
threadSupport: true,
};
const threadRootEvent = buildEventPollStartThreadRoot();
const eventMessageInThread = buildEventMessageInThread(threadRootEvent);
const directReplyToThreadRoot = buildEventReply(threadRootEvent);
const replyToReply = buildEventReply(directReplyToThreadRoot);
const events = [threadRootEvent, eventMessageInThread, directReplyToThreadRoot, replyToReply];
const [timeline, threaded] = room.partitionThreadedEvents(events);
expect(timeline).toEqual([threadRootEvent, directReplyToThreadRoot, replyToReply]);
expect(threaded).toEqual([threadRootEvent, eventMessageInThread]);
});
it("sends reply to thread responses to main timeline only", () => {
// @ts-ignore setting private property
client.clientOpts = {
...defaultClientOpts,
threadSupport: true,
};
const threadRootEvent = buildEventPollStartThreadRoot();
const eventMessageInThread = buildEventMessageInThread(threadRootEvent);
const replyToThreadResponse = buildEventReply(eventMessageInThread);
const events = [threadRootEvent, eventMessageInThread, replyToThreadResponse];
const [timeline, threaded] = room.partitionThreadedEvents(events);
expect(timeline).toEqual([threadRootEvent]);
expect(threaded).toEqual([threadRootEvent, eventMessageInThread, replyToThreadResponse]);
});
});
describe("getThirdpartyUser", () => {
it("should hit the expected API endpoint", async () => {
const response = [
{
userid: "@Bob",
protocol: "irc",
fields: {},
},
];