This repository was archived by the owner on Sep 11, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 823
/
Copy pathOwnBeaconStore-test.ts
1246 lines (1029 loc) · 54 KB
/
OwnBeaconStore-test.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 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 {
Room,
Beacon,
BeaconEvent,
getBeaconInfoIdentifier,
MatrixEvent,
RoomStateEvent,
RoomMember,
} from "matrix-js-sdk/src/matrix";
import { makeBeaconContent, makeBeaconInfoContent } from "matrix-js-sdk/src/content-helpers";
import { M_BEACON } from "matrix-js-sdk/src/@types/beacon";
import { logger } from "matrix-js-sdk/src/logger";
import { Mocked } from "jest-mock";
import { OwnBeaconStore, OwnBeaconStoreEvent } from "../../src/stores/OwnBeaconStore";
import {
advanceDateAndTime,
flushPromisesWithFakeTimers,
makeMembershipEvent,
resetAsyncStoreWithClient,
setupAsyncStoreWithClient,
} from "../test-utils";
import { makeBeaconInfoEvent, mockGeolocation, watchPositionMockImplementation } from "../test-utils/beacon";
import { getMockClientWithEventEmitter } from "../test-utils/client";
import SettingsStore from "../../src/settings/SettingsStore";
// modern fake timers and lodash.debounce are a faff
// short circuit it
jest.mock("lodash", () => ({
...(jest.requireActual("lodash") as object),
debounce: jest.fn().mockImplementation((callback) => callback),
}));
jest.useFakeTimers();
describe("OwnBeaconStore", () => {
let geolocation: Mocked<Geolocation>;
// 14.03.2022 16:15
const now = 1647270879403;
const HOUR_MS = 3600000;
const aliceId = "@alice:server.org";
const bobId = "@bob:server.org";
const mockClient = getMockClientWithEventEmitter({
getUserId: jest.fn().mockReturnValue(aliceId),
getVisibleRooms: jest.fn().mockReturnValue([]),
unstable_setLiveBeacon: jest.fn().mockResolvedValue({ event_id: "1" }),
sendEvent: jest.fn().mockResolvedValue({ event_id: "1" }),
unstable_createLiveBeacon: jest.fn().mockResolvedValue({ event_id: "1" }),
isGuest: jest.fn().mockReturnValue(false),
});
const room1Id = "$room1:server.org";
const room2Id = "$room2:server.org";
// returned by default geolocation mocks
const defaultLocationUri = "geo:54.001927,-8.253491;u=1";
// beacon_info events
// created 'an hour ago'
// with timeout of 3 hours
// event creation sets timestamp to Date.now()
jest.spyOn(global.Date, "now").mockReturnValue(now - HOUR_MS);
const alicesRoom1BeaconInfo = makeBeaconInfoEvent(aliceId, room1Id, { isLive: true }, "$alice-room1-1");
const alicesRoom2BeaconInfo = makeBeaconInfoEvent(aliceId, room2Id, { isLive: true }, "$alice-room2-1");
const alicesOldRoomIdBeaconInfo = makeBeaconInfoEvent(aliceId, room1Id, { isLive: false }, "$alice-room1-2");
const bobsRoom1BeaconInfo = makeBeaconInfoEvent(bobId, room1Id, { isLive: true }, "$bob-room1-1");
const bobsOldRoom1BeaconInfo = makeBeaconInfoEvent(bobId, room1Id, { isLive: false }, "$bob-room1-2");
// make fresh rooms every time
// as we update room state
const makeRoomsWithStateEvents = (stateEvents: MatrixEvent[] = []): [Room, Room] => {
const room1 = new Room(room1Id, mockClient, aliceId);
const room2 = new Room(room2Id, mockClient, aliceId);
room1.currentState.setStateEvents(stateEvents);
room2.currentState.setStateEvents(stateEvents);
mockClient.getVisibleRooms.mockReturnValue([room1, room2]);
return [room1, room2];
};
const makeOwnBeaconStore = async () => {
const store = OwnBeaconStore.instance;
await setupAsyncStoreWithClient(store, mockClient);
return store;
};
const expireBeaconAndEmit = (store: OwnBeaconStore, beaconInfoEvent: MatrixEvent): void => {
const beacon = store.getBeaconById(getBeaconInfoIdentifier(beaconInfoEvent))!;
// time travel until beacon is expired
advanceDateAndTime(beacon.beaconInfo!.timeout + 100);
// force an update on the beacon
// @ts-ignore
beacon.setBeaconInfo(beaconInfoEvent);
mockClient.emit(BeaconEvent.LivenessChange, false, beacon);
};
const updateBeaconLivenessAndEmit = (
store: OwnBeaconStore,
beaconInfoEvent: MatrixEvent,
isLive: boolean,
): void => {
const beacon = store.getBeaconById(getBeaconInfoIdentifier(beaconInfoEvent))!;
// matches original state of event content
// except for live property
const updateEvent = makeBeaconInfoEvent(
beaconInfoEvent.getSender()!,
beaconInfoEvent.getRoomId()!,
{ isLive, timeout: beacon.beaconInfo!.timeout },
"update-event-id",
);
beacon.update(updateEvent);
mockClient.emit(BeaconEvent.Update, beaconInfoEvent, beacon);
mockClient.emit(BeaconEvent.LivenessChange, false, beacon);
};
const addNewBeaconAndEmit = (beaconInfoEvent: MatrixEvent): void => {
const beacon = new Beacon(beaconInfoEvent);
mockClient.emit(BeaconEvent.New, beaconInfoEvent, beacon);
};
const localStorageGetSpy = jest.spyOn(localStorage.__proto__, "getItem").mockReturnValue(undefined);
const localStorageSetSpy = jest.spyOn(localStorage.__proto__, "setItem").mockImplementation(() => {});
beforeEach(() => {
geolocation = mockGeolocation();
mockClient.getVisibleRooms.mockReturnValue([]);
mockClient.unstable_setLiveBeacon.mockClear().mockResolvedValue({ event_id: "1" });
mockClient.sendEvent.mockReset().mockResolvedValue({ event_id: "1" });
jest.spyOn(global.Date, "now").mockReturnValue(now);
jest.spyOn(OwnBeaconStore.instance, "emit").mockRestore();
jest.spyOn(logger, "error").mockRestore();
localStorageGetSpy.mockClear().mockReturnValue(undefined);
localStorageSetSpy.mockClear();
});
afterEach(async () => {
await resetAsyncStoreWithClient(OwnBeaconStore.instance);
jest.clearAllTimers();
});
afterAll(() => {
localStorageGetSpy.mockRestore();
});
describe("onReady()", () => {
it("initialises correctly with no beacons", async () => {
makeRoomsWithStateEvents();
const store = await makeOwnBeaconStore();
expect(store.hasLiveBeacons()).toBe(false);
expect(store.getLiveBeaconIds()).toEqual([]);
});
it("does not add other users beacons to beacon state", async () => {
makeRoomsWithStateEvents([bobsRoom1BeaconInfo, bobsOldRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
expect(store.hasLiveBeacons()).toBe(false);
expect(store.getLiveBeaconIds()).toEqual([]);
});
it("adds own users beacons to state", async () => {
makeRoomsWithStateEvents([
alicesRoom1BeaconInfo,
alicesRoom2BeaconInfo,
bobsRoom1BeaconInfo,
bobsOldRoom1BeaconInfo,
]);
const store = await makeOwnBeaconStore();
expect(store.beaconsByRoomId.get(room1Id)).toEqual(
new Set([getBeaconInfoIdentifier(alicesRoom1BeaconInfo)]),
);
expect(store.beaconsByRoomId.get(room2Id)).toEqual(
new Set([getBeaconInfoIdentifier(alicesRoom2BeaconInfo)]),
);
});
it("updates live beacon ids when users own beacons were created on device", async () => {
localStorageGetSpy.mockReturnValue(
JSON.stringify([alicesRoom1BeaconInfo.getId(), alicesRoom2BeaconInfo.getId()]),
);
makeRoomsWithStateEvents([
alicesRoom1BeaconInfo,
alicesRoom2BeaconInfo,
bobsRoom1BeaconInfo,
bobsOldRoom1BeaconInfo,
]);
const store = await makeOwnBeaconStore();
expect(store.hasLiveBeacons(room1Id)).toBeTruthy();
expect(store.getLiveBeaconIds()).toEqual([
getBeaconInfoIdentifier(alicesRoom1BeaconInfo),
getBeaconInfoIdentifier(alicesRoom2BeaconInfo),
]);
});
it("does not do any geolocation when user has no live beacons", async () => {
makeRoomsWithStateEvents([bobsRoom1BeaconInfo, bobsOldRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
expect(store.hasLiveBeacons()).toBe(false);
await flushPromisesWithFakeTimers();
expect(geolocation.watchPosition).not.toHaveBeenCalled();
expect(mockClient.sendEvent).not.toHaveBeenCalled();
});
it("does geolocation and sends location immediately when user has live beacons", async () => {
localStorageGetSpy.mockReturnValue(
JSON.stringify([alicesRoom1BeaconInfo.getId(), alicesRoom2BeaconInfo.getId()]),
);
makeRoomsWithStateEvents([alicesRoom1BeaconInfo, alicesRoom2BeaconInfo]);
await makeOwnBeaconStore();
await flushPromisesWithFakeTimers();
expect(geolocation.watchPosition).toHaveBeenCalled();
expect(mockClient.sendEvent).toHaveBeenCalledWith(
room1Id,
M_BEACON.name,
makeBeaconContent(defaultLocationUri, now, alicesRoom1BeaconInfo.getId()!),
);
expect(mockClient.sendEvent).toHaveBeenCalledWith(
room2Id,
M_BEACON.name,
makeBeaconContent(defaultLocationUri, now, alicesRoom2BeaconInfo.getId()!),
);
});
});
describe("onNotReady()", () => {
it("removes listeners", async () => {
const store = await makeOwnBeaconStore();
const removeSpy = jest.spyOn(mockClient, "removeListener");
// @ts-ignore
store.onNotReady();
expect(removeSpy.mock.calls[0]).toEqual(expect.arrayContaining([BeaconEvent.LivenessChange]));
expect(removeSpy.mock.calls[1]).toEqual(expect.arrayContaining([BeaconEvent.New]));
expect(removeSpy.mock.calls[2]).toEqual(expect.arrayContaining([BeaconEvent.Update]));
expect(removeSpy.mock.calls[3]).toEqual(expect.arrayContaining([BeaconEvent.Destroy]));
expect(removeSpy.mock.calls[4]).toEqual(expect.arrayContaining([RoomStateEvent.Members]));
});
it("destroys beacons", async () => {
const [room1] = makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const beacon = room1.currentState.beacons.get(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))!;
const destroySpy = jest.spyOn(beacon, "destroy");
// @ts-ignore
store.onNotReady();
expect(destroySpy).toHaveBeenCalled();
});
});
describe("hasLiveBeacons()", () => {
beforeEach(() => {
makeRoomsWithStateEvents([
alicesRoom1BeaconInfo,
alicesRoom2BeaconInfo,
bobsRoom1BeaconInfo,
bobsOldRoom1BeaconInfo,
]);
localStorageGetSpy.mockReturnValue(
JSON.stringify([alicesRoom1BeaconInfo.getId(), alicesRoom2BeaconInfo.getId()]),
);
});
it("returns true when user has live beacons", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo, bobsRoom1BeaconInfo, bobsOldRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
expect(store.hasLiveBeacons()).toBe(true);
});
it("returns false when user does not have live beacons", async () => {
makeRoomsWithStateEvents([alicesOldRoomIdBeaconInfo, bobsOldRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
expect(store.hasLiveBeacons()).toBe(false);
});
it("returns true when user has live beacons for roomId", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo, bobsRoom1BeaconInfo, bobsOldRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
expect(store.hasLiveBeacons(room1Id)).toBe(true);
});
it("returns false when user does not have live beacons for roomId", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo, bobsRoom1BeaconInfo, bobsOldRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
expect(store.hasLiveBeacons(room2Id)).toBe(false);
});
});
describe("getLiveBeaconIds()", () => {
beforeEach(() => {
makeRoomsWithStateEvents([
alicesRoom1BeaconInfo,
alicesRoom2BeaconInfo,
bobsRoom1BeaconInfo,
bobsOldRoom1BeaconInfo,
]);
localStorageGetSpy.mockReturnValue(
JSON.stringify([alicesRoom1BeaconInfo.getId(), alicesRoom2BeaconInfo.getId()]),
);
});
it("returns live beacons when user has live beacons", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo, bobsRoom1BeaconInfo, bobsOldRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
expect(store.getLiveBeaconIds()).toEqual([getBeaconInfoIdentifier(alicesRoom1BeaconInfo)]);
});
it("returns empty array when user does not have live beacons", async () => {
makeRoomsWithStateEvents([alicesOldRoomIdBeaconInfo, bobsOldRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
expect(store.getLiveBeaconIds()).toEqual([]);
});
it("returns beacon ids for room when user has live beacons for roomId", async () => {
makeRoomsWithStateEvents([
alicesRoom1BeaconInfo,
alicesRoom2BeaconInfo,
bobsRoom1BeaconInfo,
bobsOldRoom1BeaconInfo,
]);
const store = await makeOwnBeaconStore();
expect(store.getLiveBeaconIds(room1Id)).toEqual([getBeaconInfoIdentifier(alicesRoom1BeaconInfo)]);
expect(store.getLiveBeaconIds(room2Id)).toEqual([getBeaconInfoIdentifier(alicesRoom2BeaconInfo)]);
});
it("returns empty array when user does not have live beacons for roomId", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo, bobsRoom1BeaconInfo, bobsOldRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
expect(store.getLiveBeaconIds(room2Id)).toEqual([]);
});
});
describe("on new beacon event", () => {
// assume all beacons were created on this device
beforeEach(() => {
localStorageGetSpy.mockReturnValue(
JSON.stringify([alicesRoom1BeaconInfo.getId(), alicesRoom2BeaconInfo.getId()]),
);
});
it("ignores events for irrelevant beacons", async () => {
makeRoomsWithStateEvents([]);
const store = await makeOwnBeaconStore();
const bobsLiveBeacon = new Beacon(bobsRoom1BeaconInfo);
const monitorSpy = jest.spyOn(bobsLiveBeacon, "monitorLiveness");
mockClient.emit(BeaconEvent.New, bobsRoom1BeaconInfo, bobsLiveBeacon);
// we dont care about bob
expect(monitorSpy).not.toHaveBeenCalled();
expect(store.hasLiveBeacons()).toBe(false);
});
it("adds users beacons to state and monitors liveness", async () => {
makeRoomsWithStateEvents([]);
const store = await makeOwnBeaconStore();
const alicesLiveBeacon = new Beacon(alicesRoom1BeaconInfo);
const monitorSpy = jest.spyOn(alicesLiveBeacon, "monitorLiveness");
mockClient.emit(BeaconEvent.New, alicesRoom1BeaconInfo, alicesLiveBeacon);
expect(monitorSpy).toHaveBeenCalled();
expect(store.hasLiveBeacons()).toBe(true);
expect(store.hasLiveBeacons(room1Id)).toBe(true);
});
it("emits a liveness change event when new beacons change live state", async () => {
makeRoomsWithStateEvents([]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const alicesLiveBeacon = new Beacon(alicesRoom1BeaconInfo);
mockClient.emit(BeaconEvent.New, alicesRoom1BeaconInfo, alicesLiveBeacon);
expect(emitSpy).toHaveBeenCalledWith(OwnBeaconStoreEvent.LivenessChange, [alicesLiveBeacon.identifier]);
});
it("emits a liveness change event when new beacons do not change live state", async () => {
makeRoomsWithStateEvents([alicesRoom2BeaconInfo]);
const store = await makeOwnBeaconStore();
// already live
expect(store.hasLiveBeacons()).toBe(true);
const emitSpy = jest.spyOn(store, "emit");
const alicesLiveBeacon = new Beacon(alicesRoom1BeaconInfo);
mockClient.emit(BeaconEvent.New, alicesRoom1BeaconInfo, alicesLiveBeacon);
expect(emitSpy).toHaveBeenCalled();
});
});
describe("on liveness change event", () => {
// assume all beacons were created on this device
beforeEach(() => {
localStorageGetSpy.mockReturnValue(
JSON.stringify([
alicesRoom1BeaconInfo.getId(),
alicesRoom2BeaconInfo.getId(),
alicesOldRoomIdBeaconInfo.getId(),
"update-event-id",
]),
);
});
it("ignores events for irrelevant beacons", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const oldLiveBeaconIds = store.getLiveBeaconIds();
const bobsLiveBeacon = new Beacon(bobsRoom1BeaconInfo);
mockClient.emit(BeaconEvent.LivenessChange, true, bobsLiveBeacon);
expect(emitSpy).not.toHaveBeenCalled();
// strictly equal
expect(store.getLiveBeaconIds()).toBe(oldLiveBeaconIds);
});
it("updates state and emits beacon liveness changes from true to false", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
// live before
expect(store.hasLiveBeacons()).toBe(true);
const emitSpy = jest.spyOn(store, "emit");
await expireBeaconAndEmit(store, alicesRoom1BeaconInfo);
expect(store.hasLiveBeacons()).toBe(false);
expect(store.hasLiveBeacons(room1Id)).toBe(false);
expect(emitSpy).toHaveBeenCalledWith(OwnBeaconStoreEvent.LivenessChange, []);
});
it("stops beacon when liveness changes from true to false and beacon is expired", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const prevEventContent = alicesRoom1BeaconInfo.getContent();
await expireBeaconAndEmit(store, alicesRoom1BeaconInfo);
// matches original state of event content
// except for live property
const expectedUpdateContent = {
...prevEventContent,
live: false,
};
expect(mockClient.unstable_setLiveBeacon).toHaveBeenCalledWith(room1Id, expectedUpdateContent);
});
it("updates state and when beacon liveness changes from false to true", async () => {
makeRoomsWithStateEvents([alicesOldRoomIdBeaconInfo]);
const store = await makeOwnBeaconStore();
// not live before
expect(store.hasLiveBeacons()).toBe(false);
const emitSpy = jest.spyOn(store, "emit");
updateBeaconLivenessAndEmit(store, alicesOldRoomIdBeaconInfo, true);
expect(store.hasLiveBeacons()).toBe(true);
expect(store.hasLiveBeacons(room1Id)).toBe(true);
expect(emitSpy).toHaveBeenCalledWith(OwnBeaconStoreEvent.LivenessChange, [
getBeaconInfoIdentifier(alicesOldRoomIdBeaconInfo),
]);
});
});
describe("on room membership changes", () => {
// assume all beacons were created on this device
beforeEach(() => {
localStorageGetSpy.mockReturnValue(
JSON.stringify([alicesRoom1BeaconInfo.getId(), alicesRoom2BeaconInfo.getId()]),
);
});
it("ignores events for rooms without beacons", async () => {
const membershipEvent = makeMembershipEvent(room2Id, aliceId);
// no beacons for room2
const [, room2] = makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const oldLiveBeaconIds = store.getLiveBeaconIds();
mockClient.emit(
RoomStateEvent.Members,
membershipEvent,
room2.currentState,
new RoomMember(room2Id, aliceId),
);
expect(emitSpy).not.toHaveBeenCalled();
// strictly equal
expect(store.getLiveBeaconIds()).toBe(oldLiveBeaconIds);
});
it("ignores events for membership changes that are not current user", async () => {
// bob joins room1
const membershipEvent = makeMembershipEvent(room1Id, bobId);
const member = new RoomMember(room1Id, bobId);
member.setMembershipEvent(membershipEvent);
const [room1] = makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const oldLiveBeaconIds = store.getLiveBeaconIds();
mockClient.emit(RoomStateEvent.Members, membershipEvent, room1.currentState, member);
expect(emitSpy).not.toHaveBeenCalled();
// strictly equal
expect(store.getLiveBeaconIds()).toBe(oldLiveBeaconIds);
});
it("ignores events for membership changes that are not leave/ban", async () => {
// alice joins room1
const membershipEvent = makeMembershipEvent(room1Id, aliceId);
const member = new RoomMember(room1Id, aliceId);
member.setMembershipEvent(membershipEvent);
const [room1] = makeRoomsWithStateEvents([alicesRoom1BeaconInfo, alicesRoom2BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const oldLiveBeaconIds = store.getLiveBeaconIds();
mockClient.emit(RoomStateEvent.Members, membershipEvent, room1.currentState, member);
expect(emitSpy).not.toHaveBeenCalled();
// strictly equal
expect(store.getLiveBeaconIds()).toBe(oldLiveBeaconIds);
});
it("destroys and removes beacons when current user leaves room", async () => {
// alice leaves room1
const membershipEvent = makeMembershipEvent(room1Id, aliceId, "leave");
const member = new RoomMember(room1Id, aliceId);
member.setMembershipEvent(membershipEvent);
const [room1] = makeRoomsWithStateEvents([alicesRoom1BeaconInfo, alicesRoom2BeaconInfo]);
const store = await makeOwnBeaconStore();
const room1BeaconInstance = store.beacons.get(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))!;
const beaconDestroySpy = jest.spyOn(room1BeaconInstance, "destroy");
const emitSpy = jest.spyOn(store, "emit");
mockClient.emit(RoomStateEvent.Members, membershipEvent, room1.currentState, member);
expect(emitSpy).toHaveBeenCalledWith(
OwnBeaconStoreEvent.LivenessChange,
// other rooms beacons still live
[getBeaconInfoIdentifier(alicesRoom2BeaconInfo)],
);
expect(beaconDestroySpy).toHaveBeenCalledTimes(1);
expect(store.getLiveBeaconIds(room1Id)).toEqual([]);
});
});
describe("on destroy event", () => {
// assume all beacons were created on this device
beforeEach(() => {
localStorageGetSpy.mockReturnValue(
JSON.stringify([
alicesRoom1BeaconInfo.getId(),
alicesRoom2BeaconInfo.getId(),
alicesOldRoomIdBeaconInfo.getId(),
"update-event-id",
]),
);
});
it("ignores events for irrelevant beacons", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const oldLiveBeaconIds = store.getLiveBeaconIds();
const bobsLiveBeacon = new Beacon(bobsRoom1BeaconInfo);
mockClient.emit(BeaconEvent.Destroy, bobsLiveBeacon.identifier);
expect(emitSpy).not.toHaveBeenCalled();
// strictly equal
expect(store.getLiveBeaconIds()).toBe(oldLiveBeaconIds);
});
it("updates state and emits beacon liveness changes from true to false", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
// live before
expect(store.hasLiveBeacons()).toBe(true);
const emitSpy = jest.spyOn(store, "emit");
const beacon = store.getBeaconById(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))!;
beacon.destroy();
mockClient.emit(BeaconEvent.Destroy, beacon.identifier);
expect(store.hasLiveBeacons()).toBe(false);
expect(store.hasLiveBeacons(room1Id)).toBe(false);
expect(emitSpy).toHaveBeenCalledWith(OwnBeaconStoreEvent.LivenessChange, []);
});
});
describe("stopBeacon()", () => {
beforeEach(() => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo, alicesOldRoomIdBeaconInfo]);
});
it("does nothing for an unknown beacon id", async () => {
const store = await makeOwnBeaconStore();
await store.stopBeacon("randomBeaconId");
expect(mockClient.unstable_setLiveBeacon).not.toHaveBeenCalled();
});
it("does nothing for a beacon that is already not live", async () => {
const store = await makeOwnBeaconStore();
await store.stopBeacon(getBeaconInfoIdentifier(alicesOldRoomIdBeaconInfo));
expect(mockClient.unstable_setLiveBeacon).not.toHaveBeenCalled();
});
it("updates beacon to live:false when it is unexpired", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const prevEventContent = alicesRoom1BeaconInfo.getContent();
await store.stopBeacon(getBeaconInfoIdentifier(alicesRoom1BeaconInfo));
// matches original state of event content
// except for live property
const expectedUpdateContent = {
...prevEventContent,
live: false,
};
expect(mockClient.unstable_setLiveBeacon).toHaveBeenCalledWith(room1Id, expectedUpdateContent);
});
it("records error when stopping beacon event fails to send", async () => {
jest.spyOn(logger, "error").mockImplementation(() => {});
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const error = new Error("oups");
mockClient.unstable_setLiveBeacon.mockRejectedValue(error);
await expect(store.stopBeacon(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).rejects.toEqual(error);
expect(store.beaconUpdateErrors.get(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).toEqual(error);
expect(emitSpy).toHaveBeenCalledWith(
OwnBeaconStoreEvent.BeaconUpdateError,
getBeaconInfoIdentifier(alicesRoom1BeaconInfo),
true,
);
});
it("clears previous error and emits when stopping beacon works on retry", async () => {
jest.spyOn(logger, "error").mockImplementation(() => {});
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
const error = new Error("oups");
mockClient.unstable_setLiveBeacon.mockRejectedValueOnce(error);
await expect(store.stopBeacon(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).rejects.toEqual(error);
expect(store.beaconUpdateErrors.get(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).toEqual(error);
await store.stopBeacon(getBeaconInfoIdentifier(alicesRoom1BeaconInfo));
// error cleared
expect(store.beaconUpdateErrors.get(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).toBeFalsy();
// emit called for error clearing
expect(emitSpy).toHaveBeenCalledWith(
OwnBeaconStoreEvent.BeaconUpdateError,
getBeaconInfoIdentifier(alicesRoom1BeaconInfo),
false,
);
});
it("does not emit BeaconUpdateError when stopping succeeds and beacon did not have errors", async () => {
jest.spyOn(logger, "error").mockImplementation(() => {});
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
// error cleared
expect(store.beaconUpdateErrors.get(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).toBeFalsy();
// emit called for error clearing
expect(emitSpy).not.toHaveBeenCalledWith(
OwnBeaconStoreEvent.BeaconUpdateError,
getBeaconInfoIdentifier(alicesRoom1BeaconInfo),
false,
);
});
it("updates beacon to live:false when it is expired but live property is true", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const prevEventContent = alicesRoom1BeaconInfo.getContent();
// time travel until beacon is expired
advanceDateAndTime(HOUR_MS * 3);
await store.stopBeacon(getBeaconInfoIdentifier(alicesRoom1BeaconInfo));
// matches original state of event content
// except for live property
const expectedUpdateContent = {
...prevEventContent,
live: false,
};
expect(mockClient.unstable_setLiveBeacon).toHaveBeenCalledWith(room1Id, expectedUpdateContent);
});
it("removes beacon event id from local store", async () => {
localStorageGetSpy.mockReturnValue(
JSON.stringify([alicesRoom1BeaconInfo.getId(), alicesRoom2BeaconInfo.getId()]),
);
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
await store.stopBeacon(getBeaconInfoIdentifier(alicesRoom1BeaconInfo));
expect(localStorageSetSpy).toHaveBeenCalledWith(
"mx_live_beacon_created_id",
// stopped beacon's event_id was removed
JSON.stringify([alicesRoom2BeaconInfo.getId()]),
);
});
});
describe("publishing positions", () => {
// assume all beacons were created on this device
beforeEach(() => {
localStorageGetSpy.mockReturnValue(
JSON.stringify([
alicesRoom1BeaconInfo.getId(),
alicesRoom2BeaconInfo.getId(),
alicesOldRoomIdBeaconInfo.getId(),
"update-event-id",
]),
);
});
it("stops watching position when user has no more live beacons", async () => {
// geolocation is only going to emit 1 position
geolocation.watchPosition.mockImplementation(watchPositionMockImplementation([0]));
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
// wait for store to settle
await flushPromisesWithFakeTimers();
// two locations were published
expect(mockClient.sendEvent).toHaveBeenCalledTimes(1);
// expire the beacon
// user now has no live beacons
await expireBeaconAndEmit(store, alicesRoom1BeaconInfo);
// stop watching location
expect(geolocation.clearWatch).toHaveBeenCalled();
expect(store.isMonitoringLiveLocation).toEqual(false);
});
describe("when store is initialised with live beacons", () => {
it("starts watching position", async () => {
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
// wait for store to settle
await flushPromisesWithFakeTimers();
expect(geolocation.watchPosition).toHaveBeenCalled();
expect(store.isMonitoringLiveLocation).toEqual(true);
});
it("kills live beacon when geolocation is unavailable", async () => {
const errorLogSpy = jest.spyOn(logger, "error").mockImplementation(() => {});
// remove the mock we set
// @ts-ignore
navigator.geolocation = undefined;
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
// wait for store to settle
await flushPromisesWithFakeTimers();
expect(store.isMonitoringLiveLocation).toEqual(false);
expect(errorLogSpy).toHaveBeenCalledWith("Geolocation failed", "Unavailable");
});
it("kills live beacon when geolocation permissions are not granted", async () => {
// similar case to the test above
// but these errors are handled differently
// above is thrown by element, this passed to error callback by geolocation
// return only a permission denied error
geolocation.watchPosition.mockImplementation(watchPositionMockImplementation([0], [1]));
const errorLogSpy = jest.spyOn(logger, "error").mockImplementation(() => {});
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
// wait for store to settle
await flushPromisesWithFakeTimers();
expect(store.isMonitoringLiveLocation).toEqual(false);
expect(errorLogSpy).toHaveBeenCalledWith("Geolocation failed", "PermissionDenied");
});
});
describe("adding a new beacon", () => {
it("publishes position for new beacon immediately", async () => {
makeRoomsWithStateEvents([]);
const store = await makeOwnBeaconStore();
// wait for store to settle
await flushPromisesWithFakeTimers();
addNewBeaconAndEmit(alicesRoom1BeaconInfo);
// wait for store to settle
await flushPromisesWithFakeTimers();
expect(mockClient.sendEvent).toHaveBeenCalled();
expect(store.isMonitoringLiveLocation).toEqual(true);
});
it("kills live beacons when geolocation is unavailable", async () => {
jest.spyOn(logger, "error").mockImplementation(() => {});
// @ts-ignore
navigator.geolocation = undefined;
makeRoomsWithStateEvents([]);
const store = await makeOwnBeaconStore();
// wait for store to settle
await flushPromisesWithFakeTimers();
addNewBeaconAndEmit(alicesRoom1BeaconInfo);
// wait for store to settle
await flushPromisesWithFakeTimers();
// stop beacon
expect(mockClient.unstable_setLiveBeacon).toHaveBeenCalled();
expect(store.isMonitoringLiveLocation).toEqual(false);
});
it("publishes position for new beacon immediately when there were already live beacons", async () => {
makeRoomsWithStateEvents([alicesRoom2BeaconInfo]);
await makeOwnBeaconStore();
// wait for store to settle
await flushPromisesWithFakeTimers();
expect(mockClient.sendEvent).toHaveBeenCalledTimes(1);
addNewBeaconAndEmit(alicesRoom1BeaconInfo);
// wait for store to settle
await flushPromisesWithFakeTimers();
expect(geolocation.getCurrentPosition).toHaveBeenCalled();
// once for original event,
// then both live beacons get current position published
// after new beacon is added
expect(mockClient.sendEvent).toHaveBeenCalledTimes(3);
});
});
describe("when publishing position fails", () => {
beforeEach(() => {
geolocation.watchPosition.mockImplementation(
watchPositionMockImplementation([0, 1000, 3000, 3000, 3000]),
);
// eat expected console error logs
jest.spyOn(logger, "error").mockImplementation(() => {});
});
// we need to advance time and then flush promises
// individually for each call to sendEvent
// otherwise the sendEvent doesn't reject/resolve and update state
// before the next call
// advance and flush every 1000ms
// until given ms is 'elapsed'
const advanceAndFlushPromises = async (timeMs: number) => {
while (timeMs > 0) {
jest.advanceTimersByTime(1000);
await flushPromisesWithFakeTimers();
timeMs -= 1000;
}
};
it("continues publishing positions after one publish error", async () => {
// fail to send first event, then succeed
mockClient.sendEvent.mockRejectedValueOnce(new Error("oups")).mockResolvedValue({ event_id: "1" });
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
// wait for store to settle
await flushPromisesWithFakeTimers();
await advanceAndFlushPromises(50000);
// called for each position from watchPosition
expect(mockClient.sendEvent).toHaveBeenCalledTimes(5);
expect(store.beaconHasLocationPublishError(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).toBe(false);
expect(store.getLiveBeaconIdsWithLocationPublishError()).toEqual([]);
expect(store.hasLocationPublishErrors()).toBe(false);
});
it("continues publishing positions when a beacon fails intermittently", async () => {
// every second event rejects
// meaning this beacon has more errors than the threshold
// but they are not consecutive
mockClient.sendEvent
.mockRejectedValueOnce(new Error("oups"))
.mockResolvedValueOnce({ event_id: "1" })
.mockRejectedValueOnce(new Error("oups"))
.mockResolvedValueOnce({ event_id: "1" })
.mockRejectedValueOnce(new Error("oups"));
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
// wait for store to settle
await flushPromisesWithFakeTimers();
await advanceAndFlushPromises(50000);
// called for each position from watchPosition
expect(mockClient.sendEvent).toHaveBeenCalledTimes(5);
expect(store.beaconHasLocationPublishError(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).toBe(false);
expect(store.hasLocationPublishErrors()).toBe(false);
expect(emitSpy).not.toHaveBeenCalledWith(
OwnBeaconStoreEvent.LocationPublishError,
getBeaconInfoIdentifier(alicesRoom1BeaconInfo),
);
});
it("stops publishing positions when a beacon fails consistently", async () => {
// always fails to send events
mockClient.sendEvent.mockRejectedValue(new Error("oups"));
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
const emitSpy = jest.spyOn(store, "emit");
// wait for store to settle
await flushPromisesWithFakeTimers();
// 5 positions from watchPosition in this period
await advanceAndFlushPromises(50000);
// only two allowed failures
expect(mockClient.sendEvent).toHaveBeenCalledTimes(2);
expect(store.beaconHasLocationPublishError(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).toBe(true);
expect(store.getLiveBeaconIdsWithLocationPublishError()).toEqual([
getBeaconInfoIdentifier(alicesRoom1BeaconInfo),
]);
expect(store.getLiveBeaconIdsWithLocationPublishError(room1Id)).toEqual([
getBeaconInfoIdentifier(alicesRoom1BeaconInfo),
]);
expect(store.hasLocationPublishErrors()).toBe(true);
expect(emitSpy).toHaveBeenCalledWith(
OwnBeaconStoreEvent.LocationPublishError,
getBeaconInfoIdentifier(alicesRoom1BeaconInfo),
);
});
it("stops publishing positions when a beacon has a stopping error", async () => {
// reject stopping beacon
const error = new Error("oups");
mockClient.unstable_setLiveBeacon.mockRejectedValue(error);
makeRoomsWithStateEvents([alicesRoom1BeaconInfo]);
const store = await makeOwnBeaconStore();
// wait for store to settle
await flushPromisesWithFakeTimers();
// 2 positions from watchPosition in this period
await advanceAndFlushPromises(5000);
// attempt to stop the beacon
await expect(store.stopBeacon(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).rejects.toEqual(error);
expect(store.beaconUpdateErrors.get(getBeaconInfoIdentifier(alicesRoom1BeaconInfo))).toEqual(error);
// 2 more positions in this period
await advanceAndFlushPromises(50000);