Stop live location shares when they expire, even without location updates

Expiry was only checked when a location update arrived. A phone that
doesn't move gets none, so an expired share kept GPS, the location
indicator and the room banner on.

Each account's service now schedules one task for the next share to
expire, rescheduled whenever its shares change and re-armed if the wall
clock lags behind the sleep. Shares that expired while the app wasn't
running are dropped when the service starts. Time comes from an
injected TimeProvider so the tests drive it with ManualClock.

Closes #6367
This commit is contained in:
Mauro Romito
2026-10-19 17:03:11 +02:00
committed by Mauro
parent 3e9f44e944
commit 2fb5c4c316
2 changed files with 178 additions and 12 deletions
@@ -13,6 +13,7 @@ import CoreLocation
final class LiveLocationService: LiveLocationServiceProtocol { final class LiveLocationService: LiveLocationServiceProtocol {
private let clientProxy: ClientProxyProtocol private let clientProxy: ClientProxyProtocol
private let userSettings: UserSettings private let userSettings: UserSettings
private let timeProvider: TimeProvider
private let actionsSubject = PassthroughSubject<LiveLocationServiceAction, Never>() private let actionsSubject = PassthroughSubject<LiveLocationServiceAction, Never>()
var actionsPublisher: AnyPublisher<LiveLocationServiceAction, Never> { var actionsPublisher: AnyPublisher<LiveLocationServiceAction, Never> {
@@ -49,13 +50,19 @@ final class LiveLocationService: LiveLocationServiceProtocol {
private var lastLocation: CLLocationCoordinate2D? 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<Void, Never>?
private var cancellables = Set<AnyCancellable>() private var cancellables = Set<AnyCancellable>()
init(clientProxy: ClientProxyProtocol, userSettings: UserSettings) { init(clientProxy: ClientProxyProtocol, userSettings: UserSettings, timeProvider: TimeProvider? = nil) {
self.clientProxy = clientProxy self.clientProxy = clientProxy
self.userSettings = userSettings self.userSettings = userSettings
self.timeProvider = timeProvider ?? TimeProvider(clock: ContinuousClock(), now: Date.init)
isSharingSubject = .init(!userSettings.account.liveLocationSharingSessionsByRoomID.isEmpty) isSharingSubject = .init(!userSettings.account.liveLocationSharingSessionsByRoomID.isEmpty)
// Before subscribing, so shares that expired while the app wasn't running never count as sharing.
stopExpiredLiveLocations()
setupSubscriptions() setupSubscriptions()
} }
@@ -94,7 +101,7 @@ final class LiveLocationService: LiveLocationServiceProtocol {
return .failure(.startFailed) 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) startingLiveLocationSharingSessionsByRoomID[roomID] = LiveLocationSession(eventID: eventID, expirationDate: expirationDate)
return .success(()) return .success(())
@@ -155,6 +162,7 @@ final class LiveLocationService: LiveLocationServiceProtocol {
.sink { [weak self] sessions in .sink { [weak self] sessions in
guard let self else { return } guard let self else { return }
syncActiveRoomProxies(with: sessions) syncActiveRoomProxies(with: sessions)
scheduleExpiry(of: sessions)
if sessions.isEmpty { if sessions.isEmpty {
lastLocation = nil 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: /// Kicks off a send cycle if one isn't already running. Each cycle:
/// 1. Takes the latest pending location and clears it. /// 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). /// 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) let geoURI = GeoURI(coordinate: coordinate, uncertainty: nil)
for (roomID, session) in sessions { for (roomID, session) in sessions {
if Date() >= session.expirationDate { if timeProvider.now() >= session.expirationDate {
MXLog.info("Live location session expired for room: \(roomID)") MXLog.info("Live location session expired for room: \(roomID)")
await stopLiveLocation(roomID: roomID) await stopLiveLocation(roomID: roomID)
continue continue
@@ -17,6 +17,9 @@ final class LiveLocationServiceTests {
private var service: LiveLocationService! private var service: LiveLocationService!
private var userSettings: UserSettings! private var userSettings: UserSettings!
private var beaconInfoSubject: PassthroughSubject<LiveLocationOwnInfoUpdate, Never>! private var beaconInfoSubject: PassthroughSubject<LiveLocationOwnInfoUpdate, Never>!
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 // MARK: - startLiveLocation
@@ -120,18 +123,12 @@ final class LiveLocationServiceTests {
let roomProxy = makeRoomProxy(roomID: "!room:matrix.org") let roomProxy = makeRoomProxy(roomID: "!room:matrix.org")
clientProxy.roomForIdentifierClosure = { _ in .joined(roomProxy) } clientProxy.roomForIdentifierClosure = { _ in .joined(roomProxy) }
let duration = Duration.seconds(300) _ = await service.startLiveLocation(roomID: "!room:matrix.org", duration: .seconds(300))
let beforeStart = Date()
_ = await service.startLiveLocation(roomID: "!room:matrix.org", duration: duration)
let afterStart = Date()
try await simulateBeaconEcho(roomID: "!room:matrix.org", eventID: "$event:matrix.org") try await simulateBeaconEcho(roomID: "!room:matrix.org", eventID: "$event:matrix.org")
let storedSession = try #require(userSettings.account.liveLocationSharingSessionsByRoomID["!room:matrix.org"]) let storedSession = try #require(userSettings.account.liveLocationSharingSessionsByRoomID["!room:matrix.org"])
let expectedMinTimeout = beforeStart.addingTimeInterval(TimeInterval(duration.seconds)) #expect(storedSession.expirationDate == currentDate.addingTimeInterval(300))
let expectedMaxTimeout = afterStart.addingTimeInterval(TimeInterval(duration.seconds))
#expect((expectedMinTimeout...expectedMaxTimeout).contains(storedSession.expirationDate))
#expect(storedSession.eventID == "$event:matrix.org") #expect(storedSession.eventID == "$event:matrix.org")
} }
@@ -240,6 +237,121 @@ final class LiveLocationServiceTests {
#expect(!service.isSharingPublisher.value) #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 // MARK: - Authorization
@Test @Test
@@ -287,7 +399,14 @@ final class LiveLocationServiceTests {
clientProxy = ClientProxyMock(.init()) clientProxy = ClientProxyMock(.init())
beaconInfoSubject = PassthroughSubject<LiveLocationOwnInfoUpdate, Never>() beaconInfoSubject = PassthroughSubject<LiveLocationOwnInfoUpdate, Never>()
clientProxy.liveLocationOwnInfoUpdatesPublisher = beaconInfoSubject.eraseToAnyPublisher() 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 { private func simulateBeaconEcho(roomID: String, eventID: String) async throws {