Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Apps/ORIXMaps/Sources/Regions/RegionsModel.swift10// Module : Regions11// Repository : https://git.spboucher.ai/orix-maps12// Created : 2026-11-2513// Last Modified : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Observation90import ORIXGeoCore91import ORIXMapPackage92import ORIXPrivacy9394/// The public keys this build accepts for map packages. Packages signed by any other key are refused.95enum PackageTrust {96 static var store: TrustStore {97 var keys: [TrustedKey] = []98 for (base64, label) in productionKeys {99 if let data = Data(base64Encoded: base64), let key = TrustedKey(publicKey: data, label: label) { keys.append(key) }100 }101 #if DEBUG102 // Development key: accepted by debug builds only, for packages built on a developer machine.103 if let data = Data(base64Encoded: "lUcyXfQbaeYNo4yD7WAqHJCOtZCd9qob5quvBS00mdo="), let key = TrustedKey(publicKey: data, label: "development") { keys.append(key) }104 #endif105 return TrustStore(keys: keys)106 }107108 /// ORIX Labs publication keys (raw Ed25519 public keys, base64). The private keys never leave the build node.109 static let productionKeys: [(String, String)] = [110 // Key id fd36c9d7c73db7e3, generated on the build node on 2026-11-25.111 ("h60XK+BAi6VRKEIgvY+qXmQVlV2P5PvLt5lyzyyysGA=", "ORIX Labs maps 2026"),112 ]113}114115/// An HTTP transport that refuses any request the privacy policy does not allow before it reaches the network.116struct PolicedTransport: HTTPTransport {117 let inner: any HTTPTransport118 let policy: NetworkPolicy119 let allowLoopback: Bool120121 func send(_ request: HTTPRequest) async throws(TransportError) -> HTTPResponse {122 var check = URLRequest(url: request.url)123 for (k, v) in request.headers { check.setValue(v, forHTTPHeaderField: k) }124 do { try policy.validate(check, allowLoopbackHTTP: allowLoopback) } catch { throw TransportError.other(code: -1) }125 return try await inner.send(request)126 }127}128129/// Installed regions, the online catalog and running downloads, for the interface.130@Observable131final class RegionsModel {132 private(set) var installed: [InstalledRegion] = []133 private(set) var catalog: CatalogSnapshot<Catalog>?134 private(set) var catalogError: CatalogError?135 private(set) var isLoadingCatalog = false136 private(set) var downloads: [String: DownloadState] = [:]137 private(set) var storeError: RegionStoreError?138 /// Message of the last failed import or installation, for an alert.139 var lastFailure: String?140141 @ObservationIgnored private var store: RegionStore?142 @ObservationIgnored private var client: CatalogClient?143 @ObservationIgnored private var manager: DownloadManager?144 @ObservationIgnored var onRegionsChanged: (([InstalledRegion]) -> Void)?145146 init(root: URL, caches: URL, catalogURL: URL?) {147 let base = catalogURL ?? CatalogClient.defaultBaseURL148 let loopback = ["127.0.0.1", "localhost"].contains(base.host ?? "")149 let transport = PolicedTransport(inner: URLSessionTransport(userAgent: "ORIXMaps/\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0")"),150 policy: NetworkPolicy(allowedHosts: [base.host ?? "www.orixlab.dev"]), allowLoopback: loopback)151 do {152 var configuration = RegionStore.Configuration(trustStore: PackageTrust.store)153 if let v = (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String).flatMap(AppVersion.init) {154 configuration.compatibility = PackageCompatibility(appVersion: v, supportedComponentFormats: [.map: 3...3, .terrain: 3...3, .search: 1...1, .routing: 1...1])155 }156 let store = try RegionStore(root: root, configuration: configuration)157 self.store = store158 client = CatalogClient(baseURL: base, transport: transport, cacheDirectory: caches.appending(path: "catalog", directoryHint: .isDirectory))159 var dc = DownloadManager.Configuration()160 dc.baseURL = base161 manager = DownloadManager(store: store, transport: transport, configuration: dc)162 } catch {163 storeError = error164 }165 }166167 /// Loads the installed regions and starts listening to store changes and download events.168 func start() async {169 guard let store, let manager else { return }170 installed = await store.regions().sorted { $0.id < $1.id }171 onRegionsChanged?(installed)172 for pending in manager.pendingDownloads() {173 downloads[pending.request.regionId] = .paused(receivedBytes: pending.receivedBytes, totalBytes: pending.request.size)174 }175 Task { [weak self] in176 for await _ in await store.changes() {177 guard let self else { return }178 self.installed = await store.regions().sorted { $0.id < $1.id }179 self.onRegionsChanged?(self.installed)180 }181 }182 Task { [weak self] in183 for await event in await manager.events() {184 guard let self else { return }185 self.downloads[event.regionId] = event.state186 if case .completed = event.state { self.downloads[event.regionId] = nil }187 if case .cancelled = event.state { self.downloads[event.regionId] = nil }188 }189 }190 if let cached = try? await client?.catalog(refresh: .cacheOnly) { catalog = cached }191 }192193 func refreshCatalog(force: Bool = false) async {194 guard let client, !isLoadingCatalog else { return }195 isLoadingCatalog = true196 defer { isLoadingCatalog = false }197 do {198 catalog = try await client.catalog(refresh: force ? .always : .ifOlderThan(seconds: 300))199 catalogError = nil200 } catch {201 catalogError = error202 }203 }204205 func installedRegion(_ id: String) -> InstalledRegion? { installed.first { $0.id == id } }206207 /// True when the catalog offers a newer data version than the installed one.208 func hasUpdate(_ region: CatalogRegion) -> Bool {209 guard let local = installedRegion(region.id) else { return false }210 return region.latest.dataVersion > local.dataVersion211 }212213 /// Bytes missing on the device to download and install a region, nil when there is enough room.214 func missingSpace(for region: CatalogRegion) -> UInt64? {215 guard let store else { return nil }216 do { _ = try store.checkSpace(downloadSize: region.latest.downloadSize, installedSize: region.latest.installedSize, alreadyDownloaded: 0); return nil }217 catch RegionStoreError.notEnoughSpace(_, _, let missing) { return missing }218 catch { return nil }219 }220221 func download(_ region: CatalogRegion) {222 guard let manager else { return }223 downloads[region.id] = .verifying224 Task { await manager.start(DownloadRequest(region: region), options: InstallOptions()) }225 }226227 func pause(_ id: String) { Task { await manager?.pause(regionId: id) } }228229 func resume(_ id: String) {230 Task { [weak self] in231 guard let manager = self?.manager else { return }232 do { try await manager.resume(regionId: id, options: InstallOptions()) } catch { self?.downloads[id] = .failed((error as? DownloadError) ?? .nothingToResume(regionId: id)) }233 }234 }235236 func cancel(_ id: String) {237 Task { [weak self] in238 await self?.manager?.cancel(regionId: id)239 self?.downloads[id] = nil240 }241 }242243 func dismissFailure(_ id: String) { downloads[id] = nil }244245 func delete(_ id: String) {246 Task { [weak self] in247 guard let store = self?.store else { return }248 do { try await store.delete(regionId: id) } catch { self?.lastFailure = Self.describe((error as? RegionStoreError) ?? .regionNotInstalled(regionId: id)) }249 }250 }251252 func rollback(_ id: String) {253 Task { [weak self] in254 guard let store = self?.store else { return }255 do { _ = try await store.rollback(regionId: id) } catch { self?.lastFailure = Self.describe((error as? RegionStoreError) ?? .noPreviousVersion(regionId: id)) }256 }257 }258259 func removePreviousVersion(_ id: String) {260 Task { [weak self] in261 _ = try? await self?.store?.removePreviousVersion(regionId: id)262 if let store = self?.store { self?.installed = await store.regions().sorted { $0.id < $1.id } }263 }264 }265266 /// Installs a `.orixmap` file picked in Files or opened from another app. It goes through the same verification267 /// as a download: signature, checksums, compatibility, free space.268 func importPackage(from url: URL) async -> Bool {269 guard let store else { return false }270 let scoped = url.startAccessingSecurityScopedResource()271 defer { if scoped { url.stopAccessingSecurityScopedResource() } }272 do {273 _ = try await store.importPackage(from: url, options: InstallOptions(), progress: nil)274 return true275 } catch {276 lastFailure = Self.describe(error)277 return false278 }279 }280281 var totalInstalledBytes: UInt64 { installed.reduce(0) { $0 + $1.totalSizeOnDisk } }282283 // MARK: Messages284285 static func describe(_ error: RegionStoreError) -> String {286 switch error {287 case .notEnoughSpace(_, _, let missing):288 String(localized: "Not enough free space: \(ByteCountFormatter.string(fromByteCount: Int64(missing), countStyle: .file)) more is needed.")289 case .downgradeRefused: String(localized: "This file contains older map data than the installed version.")290 case .alreadyInstalled: String(localized: "This version is already installed.")291 case .appTooOld: String(localized: "This map needs a newer version of ORIX Maps.")292 case .unsupportedComponentFormat: String(localized: "This map uses a format this version of ORIX Maps cannot read.")293 case .package(let p): describe(p)294 case .installedDataCorrupted: String(localized: "The installed map is damaged. Delete it and download it again.")295 case .cancelled: String(localized: "Cancelled.")296 case .regionNotInstalled, .noPreviousVersion, .io: String(localized: "The operation could not be completed on this device's storage.")297 }298 }299300 static func describe(_ error: PackageError) -> String {301 switch error {302 case .unknownSigningKey, .revokedSigningKey, .expiredSigningKey, .signingKeyNotYetValid, .signingKeyMismatch, .invalidSignature:303 String(localized: "This file is not signed by ORIX Labs. It was not installed.")304 case .componentChecksumMismatch, .truncated:305 String(localized: "This file is damaged or incomplete. It was not installed.")306 default:307 String(localized: "This file is not a valid ORIX Maps region. It was not installed.")308 }309 }310311 static func describe(_ error: DownloadError) -> String {312 switch error {313 case .offline: String(localized: "No internet connection. The download will resume where it stopped.")314 case .rateLimited: String(localized: "The server is busy. Try again in a moment.")315 case .httpStatus(let code): String(localized: "The server answered with an error (\(code)).")316 case .notEnoughSpace(_, _, let missing): String(localized: "Not enough free space: \(ByteCountFormatter.string(fromByteCount: Int64(missing), countStyle: .file)) more is needed.")317 case .checksumMismatch, .sizeMismatch, .serverFileChanged, .interrupted, .invalidResponse: String(localized: "The download was incomplete or altered. Try again.")318 case .invalidPackage(let p): describe(p)319 case .install(let e): describe(e)320 case .packageMismatch: String(localized: "The downloaded file is not the map that was requested. It was not installed.")321 case .paused: String(localized: "Paused.")322 case .cancelled: String(localized: "Cancelled.")323 case .network, .invalidRequest, .io, .nothingToResume: String(localized: "The download failed. Try again.")324 }325 }326327 static func describe(_ error: CatalogError) -> String {328 switch error {329 case .unsupportedSchema: String(localized: "The map catalog needs a newer version of ORIX Maps.")330 default: String(localized: "The map catalog could not be loaded. Check the connection and try again.")331 }332 }333}334335extension InstalledRegion {336 /// The region as the map, search and routing layers use it.337 var mapRegion: MapRegion? {338 guard let mapURL else { return nil }339 return MapRegion(id: id, nameEN: manifest.names["en"] ?? id, nameFR: manifest.names["fr"] ?? manifest.names["en"] ?? id, bounds: manifest.bbox,340 dataVersion: manifest.dataVersion.rawValue, dataDate: Timestamp.parse(manifest.dataTimestamp),341 minZoom: manifest.mapZoom?.minZoom ?? 0, maxZoom: manifest.mapZoom?.maxZoom ?? 15,342 mapURL: mapURL, searchURL: searchURL, routingURL: routingURL, installedBytes: Int64(sizeOnDisk),343 attributions: manifest.licences.map(\.attribution))344 }345}346