diff --git a/ElementX/Sources/Services/Location/LiveLocationService.swift b/ElementX/Sources/Services/Location/LiveLocationService.swift index 5394f9975..ab2eceee3 100644 --- a/ElementX/Sources/Services/Location/LiveLocationService.swift +++ b/ElementX/Sources/Services/Location/LiveLocationService.swift @@ -13,6 +13,7 @@ import CoreLocation final class LiveLocationService: LiveLocationServiceProtocol { private let clientProxy: ClientProxyProtocol private let userSettings: UserSettings + private let timeProvider: TimeProvider private let actionsSubject = PassthroughSubject() var actionsPublisher: AnyPublisher { @@ -49,13 +50,19 @@ final class LiveLocationService: LiveLocationServiceProtocol { private var lastLocation: CLLocationCoordinate2D? + /// Stops the next share to expire. A phone that doesn't move gets no location updates to notice it. + @CancellableTask private var expiryTask: Task? + private var cancellables = Set() - init(clientProxy: ClientProxyProtocol, userSettings: UserSettings) { + init(clientProxy: ClientProxyProtocol, userSettings: UserSettings, timeProvider: TimeProvider? = nil) { self.clientProxy = clientProxy self.userSettings = userSettings + self.timeProvider = timeProvider ?? TimeProvider(clock: ContinuousClock(), now: Date.init) isSharingSubject = .init(!userSettings.account.liveLocationSharingSessionsByRoomID.isEmpty) + // Before subscribing, so shares that expired while the app wasn't running never count as sharing. + stopExpiredLiveLocations() setupSubscriptions() } @@ -94,7 +101,7 @@ final class LiveLocationService: LiveLocationServiceProtocol { return .failure(.startFailed) } - let expirationDate = Date().addingTimeInterval(TimeInterval(duration.seconds)) + let expirationDate = timeProvider.now().addingTimeInterval(TimeInterval(duration.seconds)) startingLiveLocationSharingSessionsByRoomID[roomID] = LiveLocationSession(eventID: eventID, expirationDate: expirationDate) return .success(()) @@ -155,6 +162,7 @@ final class LiveLocationService: LiveLocationServiceProtocol { .sink { [weak self] sessions in guard let self else { return } syncActiveRoomProxies(with: sessions) + scheduleExpiry(of: sessions) if sessions.isEmpty { lastLocation = nil @@ -199,6 +207,45 @@ final class LiveLocationService: LiveLocationServiceProtocol { } } + private func scheduleExpiry(of sessions: [String: LiveLocationSession]) { + guard let nextExpirationDate = sessions.values.map(\.expirationDate).min() else { + expiryTask = nil + return + } + + let delay = nextExpirationDate.timeIntervalSince(timeProvider.now()) + expiryTask = Task { [weak self, clock = timeProvider.clock] in + try? await clock.sleep(for: .seconds(delay)) + guard !Task.isCancelled, let self else { return } + + // The wall clock can lag behind the sleep's clock, so wait out whatever is left. + if !stopExpiredLiveLocations() { + scheduleExpiry(of: userSettings.account.liveLocationSharingSessionsByRoomID) + } + } + } + + /// Returns whether any share had expired. + @discardableResult + private func stopExpiredLiveLocations() -> Bool { + let now = timeProvider.now() + let sessions = userSettings.account.liveLocationSharingSessionsByRoomID + let expiredRoomIDs = sessions.filter { now >= $0.value.expirationDate }.map(\.key) + guard !expiredRoomIDs.isEmpty else { return false } + + MXLog.info("Live location sessions expired for rooms: \(expiredRoomIDs)") + // Forgotten straight away so sharing stops now, their stop events follow. + userSettings.account.liveLocationSharingSessionsByRoomID = sessions.filter { now < $0.value.expirationDate } + + Task { [weak self] in + for roomID in expiredRoomIDs { + await self?.stopLiveLocation(roomID: roomID) + } + } + + return true + } + /// Kicks off a send cycle if one isn't already running. Each cycle: /// 1. Takes the latest pending location and clears it. /// 2. Sends the location to all active rooms **and** waits a minimum 3-second delay (in parallel). @@ -239,7 +286,7 @@ final class LiveLocationService: LiveLocationServiceProtocol { let geoURI = GeoURI(coordinate: coordinate, uncertainty: nil) for (roomID, session) in sessions { - if Date() >= session.expirationDate { + if timeProvider.now() >= session.expirationDate { MXLog.info("Live location session expired for room: \(roomID)") await stopLiveLocation(roomID: roomID) continue diff --git a/UnitTests/Sources/LiveLocationServiceTests.swift b/UnitTests/Sources/LiveLocationServiceTests.swift index 29339d203..8e4131ae7 100644 --- a/UnitTests/Sources/LiveLocationServiceTests.swift +++ b/UnitTests/Sources/LiveLocationServiceTests.swift @@ -17,6 +17,9 @@ final class LiveLocationServiceTests { private var service: LiveLocationService! private var userSettings: UserSettings! private var beaconInfoSubject: PassthroughSubject! + private let clock = ManualClock() + /// Whole seconds, so the expiry delays the service works out are exact. + private var currentDate = Date(timeIntervalSinceReferenceDate: 800_000_000) // MARK: - startLiveLocation @@ -120,18 +123,12 @@ final class LiveLocationServiceTests { let roomProxy = makeRoomProxy(roomID: "!room:matrix.org") clientProxy.roomForIdentifierClosure = { _ in .joined(roomProxy) } - let duration = Duration.seconds(300) - let beforeStart = Date() - _ = await service.startLiveLocation(roomID: "!room:matrix.org", duration: duration) - let afterStart = Date() + _ = await service.startLiveLocation(roomID: "!room:matrix.org", duration: .seconds(300)) try await simulateBeaconEcho(roomID: "!room:matrix.org", eventID: "$event:matrix.org") let storedSession = try #require(userSettings.account.liveLocationSharingSessionsByRoomID["!room:matrix.org"]) - let expectedMinTimeout = beforeStart.addingTimeInterval(TimeInterval(duration.seconds)) - let expectedMaxTimeout = afterStart.addingTimeInterval(TimeInterval(duration.seconds)) - - #expect((expectedMinTimeout...expectedMaxTimeout).contains(storedSession.expirationDate)) + #expect(storedSession.expirationDate == currentDate.addingTimeInterval(300)) #expect(storedSession.eventID == "$event:matrix.org") } @@ -240,6 +237,121 @@ final class LiveLocationServiceTests { #expect(!service.isSharingPublisher.value) } + // MARK: - Expiry + + @Test + func aShareStopsWhenItExpiresWithoutLocationUpdates() async { + setUp() + let roomProxy = makeRoomProxy(roomID: "!room:matrix.org") + clientProxy.roomForIdentifierClosure = { _ in .joined(roomProxy) } + userSettings.account.liveLocationSharingSessionsByRoomID["!room:matrix.org"] = LiveLocationSession(eventID: "$event:matrix.org", expirationDate: currentDate.addingTimeInterval(60)) + #expect(await clock.waitForScheduledSleep() == .seconds(60)) + + await waitForConfirmation("Wait for the share to stop") { confirm in + roomProxy.stopLiveLocationShareClosure = { + confirm() + return .success(()) + } + advanceTime(by: 60) + } + + #expect(userSettings.account.liveLocationSharingSessionsByRoomID.isEmpty) + #expect(!service.isSharingPublisher.value) + } + + @Test + func aShareStillStopsWhenTheWallClockLagsBehindTheTimer() async { + setUp() + let roomProxy = makeRoomProxy(roomID: "!room:matrix.org") + clientProxy.roomForIdentifierClosure = { _ in .joined(roomProxy) } + userSettings.account.liveLocationSharingSessionsByRoomID["!room:matrix.org"] = LiveLocationSession(eventID: "$event:matrix.org", expirationDate: currentDate.addingTimeInterval(60)) + #expect(await clock.waitForScheduledSleep() == .seconds(60)) + + currentDate = currentDate.addingTimeInterval(59) + clock.advance(by: .seconds(60)) + + #expect(await clock.waitForScheduledSleep() == .seconds(1)) + #expect(service.isSharingPublisher.value) + + await waitForConfirmation("Wait for the share to stop") { confirm in + roomProxy.stopLiveLocationShareClosure = { + confirm() + return .success(()) + } + advanceTime(by: 1) + } + + #expect(userSettings.account.liveLocationSharingSessionsByRoomID.isEmpty) + } + + @Test + func onlyTheExpiredShareStops() async { + setUp() + let roomProxy = makeRoomProxy(roomID: "!room1:matrix.org") + clientProxy.roomForIdentifierClosure = { _ in .joined(roomProxy) } + userSettings.account.liveLocationSharingSessionsByRoomID = [ + "!room1:matrix.org": LiveLocationSession(eventID: "$event1:matrix.org", expirationDate: currentDate.addingTimeInterval(60)), + "!room2:matrix.org": LiveLocationSession(eventID: "$event2:matrix.org", expirationDate: currentDate.addingTimeInterval(120)) + ] + #expect(await clock.waitForScheduledSleep() == .seconds(60)) + + await waitForConfirmation("Wait for the first share to stop") { confirm in + roomProxy.stopLiveLocationShareClosure = { + confirm() + return .success(()) + } + advanceTime(by: 60) + } + + #expect(Array(userSettings.account.liveLocationSharingSessionsByRoomID.keys) == ["!room2:matrix.org"]) + #expect(service.isSharingPublisher.value) + #expect(await clock.waitForScheduledSleep() == .seconds(60)) + + await waitForConfirmation("Wait for the second share to stop") { confirm in + roomProxy.stopLiveLocationShareClosure = { + confirm() + return .success(()) + } + advanceTime(by: 60) + } + + #expect(userSettings.account.liveLocationSharingSessionsByRoomID.isEmpty) + #expect(!service.isSharingPublisher.value) + } + + @Test + func sharesThatExpiredBeforeLaunchAreStopped() async { + let userSettings = UserSettings.mock() + userSettings.account.liveLocationSharingSessionsByRoomID["!room:matrix.org"] = LiveLocationSession(eventID: "$event:matrix.org", expirationDate: currentDate.addingTimeInterval(-60)) + let roomProxy = makeRoomProxy(roomID: "!room:matrix.org") + + await waitForConfirmation("Wait for the share to stop") { confirm in + roomProxy.stopLiveLocationShareClosure = { + confirm() + return .success(()) + } + setUp(userSettings: userSettings) + clientProxy.roomForIdentifierClosure = { _ in .joined(roomProxy) } + + #expect(!service.isSharingPublisher.value) + } + + #expect(userSettings.account.liveLocationSharingSessionsByRoomID.isEmpty) + } + + @Test + func stoppingTheLastShareCancelsItsExpiry() async { + setUp() + let roomProxy = makeRoomProxy(roomID: "!room:matrix.org") + clientProxy.roomForIdentifierClosure = { _ in .joined(roomProxy) } + userSettings.account.liveLocationSharingSessionsByRoomID["!room:matrix.org"] = LiveLocationSession(eventID: "$event:matrix.org", expirationDate: currentDate.addingTimeInterval(60)) + await clock.waitForScheduledSleep() + + await service.stopLiveLocation(roomID: "!room:matrix.org") + + #expect(!clock.hasPendingSleep) + } + // MARK: - Authorization @Test @@ -287,7 +399,14 @@ final class LiveLocationServiceTests { clientProxy = ClientProxyMock(.init()) beaconInfoSubject = PassthroughSubject() clientProxy.liveLocationOwnInfoUpdatesPublisher = beaconInfoSubject.eraseToAnyPublisher() - service = LiveLocationService(clientProxy: clientProxy, userSettings: userSettings) + service = LiveLocationService(clientProxy: clientProxy, + userSettings: userSettings, + timeProvider: TimeProvider(clock: clock) { self.currentDate }) + } + + private func advanceTime(by seconds: TimeInterval) { + currentDate = currentDate.addingTimeInterval(seconds) + clock.advance(by: .seconds(seconds)) } private func simulateBeaconEcho(roomID: String, eventID: String) async throws {