Prepare for repo merge

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
This commit is contained in:
Michael Telatynski 2024-10-15 11:35:21 +01:00
parent 0f670b8dc0
commit b084ff2313
No known key found for this signature in database
GPG key ID: A2B008A5F49F5D0D
807 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,93 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 The Matrix.org Foundation C.I.C
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
*/
import { Beacon } from "matrix-js-sdk/src/matrix";
import { Bounds, getBeaconBounds } from "../../../src/utils/beacon/bounds";
import { makeBeaconEvent, makeBeaconInfoEvent } from "../../test-utils";
describe("getBeaconBounds()", () => {
const userId = "@user:server";
const roomId = "!room:server";
const makeBeaconWithLocation = (latLon: { lat: number; lon: number }) => {
const geoUri = `geo:${latLon.lat},${latLon.lon}`;
const beacon = new Beacon(makeBeaconInfoEvent(userId, roomId, { isLive: true }));
// @ts-ignore private prop, sets internal live property so addLocations works
beacon.checkLiveness();
const location = makeBeaconEvent(userId, {
beaconInfoId: beacon.beaconInfoId,
geoUri,
timestamp: Date.now() + 1,
});
beacon.addLocations([location]);
return beacon;
};
const geo = {
// northern hemi
// west of greenwich
london: { lat: 51.5, lon: -0.14 },
reykjavik: { lat: 64.08, lon: -21.82 },
// east of greenwich
paris: { lat: 48.85, lon: 2.29 },
// southern hemi
// east
auckland: { lat: -36.85, lon: 174.76 }, // nz
// west
lima: { lat: -12.013843, lon: -77.008388 }, // peru
};
const london = makeBeaconWithLocation(geo.london);
const reykjavik = makeBeaconWithLocation(geo.reykjavik);
const paris = makeBeaconWithLocation(geo.paris);
const auckland = makeBeaconWithLocation(geo.auckland);
const lima = makeBeaconWithLocation(geo.lima);
it("should return undefined when there are no beacons", () => {
expect(getBeaconBounds([])).toBeUndefined();
});
it("should return undefined when no beacons have locations", () => {
const beacon = new Beacon(makeBeaconInfoEvent(userId, roomId));
expect(getBeaconBounds([beacon])).toBeUndefined();
});
type TestCase = [string, Beacon[], Bounds];
it.each<TestCase>([
[
"one beacon",
[london],
{ north: geo.london.lat, south: geo.london.lat, east: geo.london.lon, west: geo.london.lon },
],
[
"beacons in the northern hemisphere, west of meridian",
[london, reykjavik],
{ north: geo.reykjavik.lat, south: geo.london.lat, east: geo.london.lon, west: geo.reykjavik.lon },
],
[
"beacons in the northern hemisphere, both sides of meridian",
[london, reykjavik, paris],
// reykjavik northmost and westmost, paris southmost and eastmost
{ north: geo.reykjavik.lat, south: geo.paris.lat, east: geo.paris.lon, west: geo.reykjavik.lon },
],
[
"beacons in the southern hemisphere",
[auckland, lima],
// lima northmost and westmost, auckland southmost and eastmost
{ north: geo.lima.lat, south: geo.auckland.lat, east: geo.auckland.lon, west: geo.lima.lon },
],
[
"beacons in both hemispheres",
[auckland, lima, paris],
{ north: geo.paris.lat, south: geo.auckland.lat, east: geo.auckland.lon, west: geo.lima.lon },
],
])("gets correct bounds for %s", (_description, beacons, expectedBounds) => {
expect(getBeaconBounds(beacons)).toEqual(expectedBounds);
});
});

View file

@ -0,0 +1,106 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 The Matrix.org Foundation C.I.C
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
*/
import { M_TIMESTAMP, Beacon } from "matrix-js-sdk/src/matrix";
import { msUntilExpiry, sortBeaconsByLatestExpiry, sortBeaconsByLatestCreation } from "../../../src/utils/beacon";
import { makeBeaconInfoEvent } from "../../test-utils";
describe("beacon utils", () => {
// 14.03.2022 16:15
const now = 1647270879403;
const HOUR_MS = 3600000;
beforeEach(() => {
jest.spyOn(global.Date, "now").mockReturnValue(now);
});
afterAll(() => {
jest.spyOn(global.Date, "now").mockRestore();
});
describe("msUntilExpiry", () => {
it("returns remaining duration", () => {
const start = now - HOUR_MS;
const durationMs = HOUR_MS * 3;
expect(msUntilExpiry(start, durationMs)).toEqual(HOUR_MS * 2);
});
it("returns 0 when expiry has already passed", () => {
// created 3h ago
const start = now - HOUR_MS * 3;
// 1h durations
const durationMs = HOUR_MS;
expect(msUntilExpiry(start, durationMs)).toEqual(0);
});
});
describe("sortBeaconsByLatestExpiry()", () => {
const roomId = "!room:server";
const aliceId = "@alive:server";
// 12h old, 12h left
const beacon1 = new Beacon(
makeBeaconInfoEvent(aliceId, roomId, { timeout: HOUR_MS * 24, timestamp: now - 12 * HOUR_MS }, "$1"),
);
// 10h left
const beacon2 = new Beacon(
makeBeaconInfoEvent(aliceId, roomId, { timeout: HOUR_MS * 10, timestamp: now }, "$2"),
);
// 1ms left
const beacon3 = new Beacon(
makeBeaconInfoEvent(aliceId, roomId, { timeout: HOUR_MS + 1, timestamp: now - HOUR_MS }, "$3"),
);
const noTimestampEvent = makeBeaconInfoEvent(
aliceId,
roomId,
{ timeout: HOUR_MS + 1, timestamp: undefined },
"$3",
);
// beacon info helper defaults to date when timestamp is falsy
// hard set it to undefined
// @ts-ignore
noTimestampEvent.event.content[M_TIMESTAMP.name] = undefined;
const beaconNoTimestamp = new Beacon(noTimestampEvent);
it("sorts beacons by descending expiry time", () => {
expect([beacon2, beacon3, beacon1].sort(sortBeaconsByLatestExpiry)).toEqual([beacon1, beacon2, beacon3]);
});
it("sorts beacons with timestamps before beacons without", () => {
expect([beaconNoTimestamp, beacon3].sort(sortBeaconsByLatestExpiry)).toEqual([beacon3, beaconNoTimestamp]);
});
});
describe("sortBeaconsByLatestCreation()", () => {
const roomId = "!room:server";
const aliceId = "@alive:server";
// 12h old, 12h left
const beacon1 = new Beacon(
makeBeaconInfoEvent(aliceId, roomId, { timeout: HOUR_MS * 24, timestamp: now - 12 * HOUR_MS }, "$1"),
);
// 10h left
const beacon2 = new Beacon(
makeBeaconInfoEvent(aliceId, roomId, { timeout: HOUR_MS * 10, timestamp: now }, "$2"),
);
// 1ms left
const beacon3 = new Beacon(
makeBeaconInfoEvent(aliceId, roomId, { timeout: HOUR_MS + 1, timestamp: now - HOUR_MS }, "$3"),
);
it("sorts beacons by descending creation time", () => {
expect([beacon1, beacon2, beacon3].sort(sortBeaconsByLatestCreation)).toEqual([beacon2, beacon3, beacon1]);
});
});
});

View file

@ -0,0 +1,229 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
*/
import { logger } from "matrix-js-sdk/src/logger";
import { Mocked } from "jest-mock";
import {
GenericPosition,
GeolocationError,
getGeoUri,
mapGeolocationError,
mapGeolocationPositionToTimedGeo,
watchPosition,
} from "../../../src/utils/beacon";
import { getCurrentPosition } from "../../../src/utils/beacon/geolocation";
import { makeGeolocationPosition, mockGeolocation, getMockGeolocationPositionError } from "../../test-utils";
describe("geolocation utilities", () => {
let geolocation: Mocked<Geolocation>;
const defaultPosition = makeGeolocationPosition({});
// 14.03.2022 16:15
const now = 1647270879403;
beforeEach(() => {
geolocation = mockGeolocation();
jest.spyOn(Date, "now").mockReturnValue(now);
});
afterEach(() => {
jest.spyOn(Date, "now").mockRestore();
jest.spyOn(logger, "error").mockRestore();
});
describe("getGeoUri", () => {
it("Renders a URI with only lat and lon", () => {
const pos: GenericPosition = {
latitude: 43.2,
longitude: 12.4,
altitude: undefined,
accuracy: undefined,
timestamp: 12334,
};
expect(getGeoUri(pos)).toEqual("geo:43.2,12.4");
});
it("Nulls in location are not shown in URI", () => {
const pos: GenericPosition = {
latitude: 43.2,
longitude: 12.4,
timestamp: 12334,
};
expect(getGeoUri(pos)).toEqual("geo:43.2,12.4");
});
it("Renders a URI with 3 coords", () => {
const pos: GenericPosition = {
latitude: 43.2,
longitude: 12.4,
altitude: 332.54,
accuracy: undefined,
timestamp: 12334,
};
expect(getGeoUri(pos)).toEqual("geo:43.2,12.4,332.54");
});
it("Renders a URI with accuracy", () => {
const pos: GenericPosition = {
latitude: 43.2,
longitude: 12.4,
altitude: undefined,
accuracy: 21,
timestamp: 12334,
};
expect(getGeoUri(pos)).toEqual("geo:43.2,12.4;u=21");
});
it("Renders a URI with accuracy and altitude", () => {
const pos = {
latitude: 43.2,
longitude: 12.4,
altitude: 12.3,
accuracy: 21,
timestamp: 12334,
};
expect(getGeoUri(pos)).toEqual("geo:43.2,12.4,12.3;u=21");
});
});
describe("mapGeolocationError", () => {
beforeEach(() => {
// suppress expected errors from test log
jest.spyOn(logger, "error").mockImplementation(() => {});
});
it("returns default for other error", () => {
const error = new Error("oh no..");
expect(mapGeolocationError(error)).toEqual(GeolocationError.Default);
});
it("returns unavailable for unavailable error", () => {
const error = new Error(GeolocationError.Unavailable);
expect(mapGeolocationError(error)).toEqual(GeolocationError.Unavailable);
});
it("maps geo error permissiondenied correctly", () => {
const error = getMockGeolocationPositionError(1, "message");
expect(mapGeolocationError(error)).toEqual(GeolocationError.PermissionDenied);
});
it("maps geo position unavailable error correctly", () => {
const error = getMockGeolocationPositionError(2, "message");
expect(mapGeolocationError(error)).toEqual(GeolocationError.PositionUnavailable);
});
it("maps geo timeout error correctly", () => {
const error = getMockGeolocationPositionError(3, "message");
expect(mapGeolocationError(error)).toEqual(GeolocationError.Timeout);
});
});
describe("mapGeolocationPositionToTimedGeo()", () => {
it("maps geolocation position correctly", () => {
expect(mapGeolocationPositionToTimedGeo(defaultPosition)).toEqual({
timestamp: now,
geoUri: "geo:54.001927,-8.253491;u=1",
});
});
});
describe("watchPosition()", () => {
it("throws with unavailable error when geolocation is not available", () => {
// suppress expected errors from test log
jest.spyOn(logger, "error").mockImplementation(() => {});
// remove the mock we added
// @ts-ignore illegal assignment to readonly property
navigator.geolocation = undefined;
const positionHandler = jest.fn();
const errorHandler = jest.fn();
expect(() => watchPosition(positionHandler, errorHandler)).toThrow(GeolocationError.Unavailable);
});
it("sets up position handler with correct options", () => {
const positionHandler = jest.fn();
const errorHandler = jest.fn();
watchPosition(positionHandler, errorHandler);
const [, , options] = geolocation.watchPosition.mock.calls[0];
expect(options).toEqual({
maximumAge: 60000,
timeout: 10000,
});
});
it("returns clearWatch function", () => {
const watchId = 1;
geolocation.watchPosition.mockReturnValue(watchId);
const positionHandler = jest.fn();
const errorHandler = jest.fn();
const clearWatch = watchPosition(positionHandler, errorHandler);
clearWatch();
expect(geolocation.clearWatch).toHaveBeenCalledWith(watchId);
});
it("calls position handler with position", () => {
const positionHandler = jest.fn();
const errorHandler = jest.fn();
watchPosition(positionHandler, errorHandler);
expect(positionHandler).toHaveBeenCalledWith(defaultPosition);
});
it("maps geolocation position error and calls error handler", () => {
// suppress expected errors from test log
jest.spyOn(logger, "error").mockImplementation(() => {});
geolocation.watchPosition.mockImplementation((_callback, error) => {
error!(getMockGeolocationPositionError(1, "message"));
return -1;
});
const positionHandler = jest.fn();
const errorHandler = jest.fn();
watchPosition(positionHandler, errorHandler);
expect(errorHandler).toHaveBeenCalledWith(GeolocationError.PermissionDenied);
});
});
describe("getCurrentPosition()", () => {
it("throws with unavailable error when geolocation is not available", async () => {
// suppress expected errors from test log
jest.spyOn(logger, "error").mockImplementation(() => {});
// remove the mock we added
// @ts-ignore illegal assignment to readonly property
navigator.geolocation = undefined;
await expect(() => getCurrentPosition()).rejects.toThrow(GeolocationError.Unavailable);
});
it("throws with geolocation error when geolocation.getCurrentPosition fails", async () => {
// suppress expected errors from test log
jest.spyOn(logger, "error").mockImplementation(() => {});
const timeoutError = getMockGeolocationPositionError(3, "message");
geolocation.getCurrentPosition.mockImplementation((callback, error) => error!(timeoutError));
await expect(() => getCurrentPosition()).rejects.toThrow(GeolocationError.Timeout);
});
it("resolves with current location", async () => {
geolocation.getCurrentPosition.mockImplementation((callback, error) => callback(defaultPosition));
const result = await getCurrentPosition();
expect(result).toEqual(defaultPosition);
});
});
});

View file

@ -0,0 +1,38 @@
/*
Copyright 2024 New Vector Ltd.
Copyright 2022 The Matrix.org Foundation C.I.C.
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
Please see LICENSE files in the repository root for full details.
*/
import { EventType, MatrixEvent, Room } from "matrix-js-sdk/src/matrix";
import { shouldDisplayAsBeaconTile } from "../../../src/utils/beacon/timeline";
import { makeBeaconInfoEvent, stubClient } from "../../test-utils";
describe("shouldDisplayAsBeaconTile", () => {
const userId = "@user:server";
const roomId = "!room:server";
const liveBeacon = makeBeaconInfoEvent(userId, roomId, { isLive: true });
const notLiveBeacon = makeBeaconInfoEvent(userId, roomId, { isLive: false });
const memberEvent = new MatrixEvent({ type: EventType.RoomMember });
const redactedBeacon = makeBeaconInfoEvent(userId, roomId, { isLive: false });
redactedBeacon.makeRedacted(redactedBeacon, new Room(roomId, stubClient(), userId));
it("returns true for a beacon with live property set to true", () => {
expect(shouldDisplayAsBeaconTile(liveBeacon)).toBe(true);
});
it("returns true for a redacted beacon", () => {
expect(shouldDisplayAsBeaconTile(redactedBeacon)).toBe(true);
});
it("returns false for a beacon with live property set to false", () => {
expect(shouldDisplayAsBeaconTile(notLiveBeacon)).toBe(false);
});
it("returns false for a non beacon event", () => {
expect(shouldDisplayAsBeaconTile(memberEvent)).toBe(false);
});
});