SPB Git

Repository Public

Settings.swift 9.7 KB 214 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Music9// File             : Core/Sources/SPMusicCore/Settings/Settings.swift10// Description      : Preferences, network status and the data-use policy.11// Module           : SPMusicCore12// Repository       : https://git.spboucher.ai/sp-music-ios13// Created          : 2026-11-1714// Last Modified    : 2026-11-1715//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Network90import Observation91import Synchronization9293public enum Quality: String, Sendable, CaseIterable, Codable {94    case original   // the file as it is stored on MacLustr95    case compact    // the AAC 256 kbit/s rendition prepared by the server96    public var variant: AudioVariant { self == .original ? .original : .compat }97}9899public struct NetworkStatus: Sendable, Equatable {100    public enum Interface: String, Sendable { case wifi, cellular, wired, other, none }101    public var online: Bool102    public var interface: Interface103    /// Cellular or personal hotspot.104    public var expensive: Bool105    /// Low Data Mode is on for this network.106    public var constrained: Bool107    public init(online: Bool, interface: Interface, expensive: Bool = false, constrained: Bool = false) {108        self.online = online; self.interface = interface; self.expensive = expensive; self.constrained = constrained109    }110    public static let offline = NetworkStatus(online: false, interface: .none)111    public static let wifi = NetworkStatus(online: true, interface: .wifi)112}113114/// The listener's choices about data use, as a value the engines can read from any thread.115public struct TransferSettings: Sendable, Equatable, Codable {116    public var streamOnCellular = true117    public var downloadOnCellular = false118    public var streamQualityWifi = Quality.original119    public var streamQualityCellular = Quality.original120    public var downloadQuality = Quality.original121    /// New tracks of an album or playlist kept offline are fetched without asking.122    public var autoDownloadPinned = true123    /// Transfers running at the same time (1…4).124    public var maxConcurrentDownloads = 3125    /// Above this size a download started on cellular asks for confirmation.126    public var cellularConfirmBytes: Int64 = 200 * 1024 * 1024127    public init() {}128}129130public enum NetworkPolicy {131    public enum Blocked: String, Sendable, Equatable { case offline, cellularNotAllowed, lowDataMode }132    public enum Stream: Sendable, Equatable { case allowed(Quality), blocked(Blocked) }133134    public static func stream(_ s: TransferSettings, _ n: NetworkStatus) -> Stream {135        guard n.online else { return .blocked(.offline) }136        if n.expensive && !s.streamOnCellular { return .blocked(.cellularNotAllowed) }137        // Low Data Mode: streaming stays possible, in the light rendition.138        if n.constrained { return .allowed(.compact) }139        return .allowed(n.expensive ? s.streamQualityCellular : s.streamQualityWifi)140    }141142    /// nil = downloads may run now.143    public static func download(_ s: TransferSettings, _ n: NetworkStatus) -> Blocked? {144        guard n.online else { return .offline }145        if n.constrained { return .lowDataMode }146        if n.expensive && !s.downloadOnCellular { return .cellularNotAllowed }147        return nil148    }149150    public static func needsCellularConfirmation(_ s: TransferSettings, _ n: NetworkStatus, bytes: Int64) -> Bool {151        n.online && n.expensive && s.downloadOnCellular && bytes >= s.cellularConfirmBytes152    }153}154155/// Reachability from Network.framework. Observable on the main actor; `current` is readable from anywhere.156@MainActor @Observable157public final class NetworkMonitor {158    public private(set) var status = NetworkStatus.wifi159    @ObservationIgnored private let monitor = NWPathMonitor()160    @ObservationIgnored private let box = Mutex(NetworkStatus.wifi)161    @ObservationIgnored private var listeners: [@MainActor (NetworkStatus) -> Void] = []162163    public init() {164        monitor.pathUpdateHandler = { [weak self] path in165            let s = Self.status(of: path)166            Task { @MainActor in self?.update(s) }167        }168        monitor.start(queue: DispatchQueue(label: "ai.spboucher.spmusic.network"))169    }170    /// For tests and previews.171    public init(fixed: NetworkStatus) { status = fixed; box.withLock { $0 = fixed } }172173    public nonisolated var current: NetworkStatus { box.withLock { $0 } }174    public func onChange(_ f: @escaping @MainActor (NetworkStatus) -> Void) { listeners.append(f) }175    public func override(_ s: NetworkStatus) { update(s) }176177    private func update(_ s: NetworkStatus) {178        guard s != status else { return }179        box.withLock { $0 = s }180        status = s181        for l in listeners { l(s) }182    }183    private nonisolated static func status(of path: NWPath) -> NetworkStatus {184        let iface: NetworkStatus.Interface = path.usesInterfaceType(.wifi) ? .wifi : path.usesInterfaceType(.cellular) ? .cellular : path.usesInterfaceType(.wiredEthernet) ? .wired : (path.status == .satisfied ? .other : .none)185        return NetworkStatus(online: path.status == .satisfied, interface: iface, expensive: path.isExpensive, constrained: path.isConstrained)186    }187}188189/// Preferences kept in UserDefaults.190@MainActor @Observable191public final class AppSettings {192    @ObservationIgnored private let defaults: UserDefaults193    @ObservationIgnored private let box: Mutex<TransferSettings>194195    public var transfer: TransferSettings { didSet { box.withLock { $0 = transfer }; save() } }196    /// Face ID / Touch ID asked when the app comes to the front.197    public var biometricLock: Bool { didSet { defaults.set(biometricLock, forKey: "biometricLock") } }198    /// Show only what is on the device, even when the server is reachable.199    public var downloadedOnly: Bool { didSet { defaults.set(downloadedOnly, forKey: "downloadedOnly") } }200    public var albumSort: AlbumSort { didSet { defaults.set(albumSort.rawValue, forKey: "albumSort") } }201202    public init(defaults: UserDefaults = .standard) {203        self.defaults = defaults204        let t = defaults.data(forKey: "transfer").flatMap { try? JSONDecoder().decode(TransferSettings.self, from: $0) } ?? TransferSettings()205        transfer = t206        box = Mutex(t)207        biometricLock = defaults.bool(forKey: "biometricLock")208        downloadedOnly = defaults.bool(forKey: "downloadedOnly")209        albumSort = AlbumSort(rawValue: defaults.string(forKey: "albumSort") ?? "") ?? .artist210    }211    public nonisolated var transferSnapshot: TransferSettings { box.withLock { $0 } }212    private func save() { if let d = try? JSONEncoder().encode(transfer) { defaults.set(d, forKey: "transfer") } }213}214
Files main
Menu

Theme