Repository Public
1// SP Drive iOS2// File: App/DeviceConditions.swift3// Description: What the sync engine needs to know about the device: network path (Network.framework), Low Power Mode and battery4// (UIKit). Thread-safe snapshot read by the engine's `conditions` closure; changes are published so the engine re-evaluates.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Synchronization10import UIKit1112final class DeviceConditions: Sendable {13 static let shared = DeviceConditions()14 private let power = Mutex<(lowPower: Bool, level: Double?, charging: Bool)>((false, nil, false))15 private let listeners = Mutex<[UUID: AsyncStream<Void>.Continuation]>([:])1617 /// The current picture. Callable from any thread.18 var current: TransferConditions {19 let n = NetworkMonitor.shared.status20 let p = power.withLock { $0 }21 #if DEBUG22 // the simulator has neither cellular nor Low Power Mode: UI tests put the device in those conditions by name23 if let fake = ProcessInfo.processInfo.environment["SPDRIVE_FAKE_CONDITIONS"], !fake.isEmpty {24 return TransferConditions(online: n.online, expensive: fake.contains("cellular"), constrained: fake.contains("lowdata"), lowPowerMode: fake.contains("lowpower"),25 batteryLevel: fake.contains("lowbattery") ? 0.05 : nil, charging: false)26 }27 #endif28 return TransferConditions(online: n.online, expensive: n.expensive, constrained: n.constrained, lowPowerMode: p.lowPower, batteryLevel: p.level, charging: p.charging)29 }3031 /// The user's choices, from the app's preferences (Settings → Synchronisation).32 static var policy: TransferPolicy {33 let d = UserDefaults.standard34 // `bool(forKey:)` also understands values given on the command line ("NO"), which `as? Bool` does not35 func flag(_ key: String, _ fallback: Bool) -> Bool { d.object(forKey: key) == nil ? fallback : d.bool(forKey: key) }36 return TransferPolicy(allowCellular: flag("transfers.cellular", true), backgroundInLowDataMode: flag("transfers.lowData", false),37 pauseBackgroundInLowPowerMode: flag("transfers.lowPower", true), batteryFloor: d.object(forKey: "transfers.batteryFloor") as? Double ?? 0.2,38 bandwidthLimit: Int64(d.integer(forKey: "transfers.bandwidthKB")) * 1024)39 }4041 /// Starts observing power state. Yields once per change (the network path has its own stream in `NetworkMonitor`).42 @MainActor func start() {43 UIDevice.current.isBatteryMonitoringEnabled = true44 refresh()45 let center = NotificationCenter.default46 for name in [Notification.Name.NSProcessInfoPowerStateDidChange, UIDevice.batteryStateDidChangeNotification, UIDevice.batteryLevelDidChangeNotification] {47 center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.refresh() } }48 }49 }5051 @MainActor private func refresh() {52 let d = UIDevice.current53 // the simulator reports -1 / .unknown: the battery rule then never applies54 let level = d.batteryLevel >= 0 ? Double(d.batteryLevel) : nil55 let new = (ProcessInfo.processInfo.isLowPowerModeEnabled, level, d.batteryState == .charging || d.batteryState == .full)56 let changed = power.withLock { old -> Bool in57 // battery level ticks every percent: only crossing the floor matters58 let floor = Self.policy.batteryFloor59 let crossed = ((old.level ?? 1) < floor) != ((new.1 ?? 1) < floor)60 defer { old = new }61 return old.lowPower != new.0 || old.charging != new.2 || crossed62 }63 if changed { for l in listeners.withLock({ Array($0.values) }) { l.yield() } }64 }6566 func changes() -> AsyncStream<Void> {67 AsyncStream { c in68 let id = UUID()69 listeners.withLock { $0[id] = c }70 c.onTermination = { [weak self] _ in self?.listeners.withLock { _ = $0.removeValue(forKey: id) } }71 }72 }73}74