SPB Git

Repository Public BSD-3-Clause

LibraryModel.swift 10.5 KB 256 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Apps/ORIXMaps/Sources/Places/LibraryModel.swift10// Module           : Places11// 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 ORIXGeoExchange92import ORIXMapRenderer93import ORIXMapStyle94import ORIXPlaces9596/// The user's saved places, collections and history, mirrored for the interface and drawn as pins on the map.97@Observable98final class LibraryModel {99    private(set) var collections: [PlaceCollection] = []100    private(set) var places: [SavedPlace] = []101    private(set) var history: [HistoryEntry] = []102    private(set) var isAvailable = false103    /// Collections whose pins are hidden on the map.104    var hiddenCollections: Set<UUID> = [] { didSet { drawPins() } }105106    @ObservationIgnored private var store: PlacesStore?107    @ObservationIgnored private weak var map: MapController?108    @ObservationIgnored private let settings: AppSettings109110    init(databaseURL: URL?, map: MapController, settings: AppSettings) {111        self.map = map112        self.settings = settings113        store = try? PlacesStore(url: databaseURL, defaultCollectionName: String(localized: "Favourites"))114        isAvailable = store != nil115    }116117    func reload() async {118        guard let store else { return }119        collections = (try? await store.collections()) ?? []120        places = (try? await store.places()) ?? []121        history = settings.historyEnabled ? ((try? await store.history(limit: 30)) ?? []) : []122        drawPins()123    }124125    func collection(_ id: UUID) -> PlaceCollection? { collections.first { $0.id == id } }126    func places(in collection: UUID) -> [SavedPlace] { places.filter { $0.collectionID == collection } }127128    /// The saved place at a coordinate (within 15 m), if any.129    func savedPlace(near c: Coordinate) -> SavedPlace? {130        places.map { ($0, Geodesy.fastDistance($0.coordinate, c)) }.filter { $0.1 <= 15 }.min { $0.1 < $1.1 }?.0131    }132133    private func drawPins() {134        let features = places.filter { !hiddenCollections.contains($0.collectionID) }.map { p -> OverlayFeature in135            let c = collection(p.collectionID)136            let symbol = p.symbol ?? c?.symbol ?? "bookmark.fill"137            let color = p.colorHex ?? c?.colorHex ?? "#00A896"138            return OverlayFeature(.point(p.coordinate), properties: ["title": .string(p.name), "id": .string(p.id.uuidString), "icon": .string("orix-pin-\(symbol)|\(color)")])139        }140        map?.setOverlay(OverlayID.pins, features: features)141    }142143    // MARK: Places144145    @discardableResult146    func save(_ place: SavedPlace) async -> SavedPlace? {147        var p = place148        p.updatedAt = Date()149        let saved = try? await store?.save(p)150        await reload()151        return saved152    }153154    func delete(_ place: SavedPlace) async {155        try? await store?.deletePlace(place.id)156        await reload()157    }158159    // MARK: Collections160161    func createCollection(name: String, symbol: String, colorHex: String) async {162        _ = try? await store?.createCollection(name: name, symbol: symbol, colorHex: colorHex)163        await reload()164    }165166    func update(_ c: PlaceCollection) async {167        try? await store?.update(c)168        await reload()169    }170171    /// Returns false when the collection is the last one (it cannot be deleted).172    func deleteCollection(_ id: UUID) async -> Bool {173        do { try await store?.deleteCollection(id) } catch { return false }174        await reload()175        return true176    }177178    func moveCollections(from: IndexSet, to: Int) async {179        var ids = collections.map(\.id)180        ids.move(fromOffsets: from, toOffset: to)181        try? await store?.reorderCollections(ids)182        await reload()183    }184185    // MARK: Exchange186187    /// Writes a collection (or everything) to a temporary file for the share sheet.188    func exportFile(collection: UUID?, format: ExchangeFormat) async -> URL? {189        guard let store, let doc = try? await store.exportDocument(collection: collection), !doc.waypoints.isEmpty else { return nil }190        let name = (collection.flatMap { self.collection($0)?.name } ?? "ORIX Maps places").components(separatedBy: CharacterSet(charactersIn: "/\\:?%*|\"<>")).joined()191        return Self.temporaryFile(named: "\(name).\(format.fileExtension)", data: ExchangeCodec.encode(doc, format: format))192    }193194    func backupFile() async -> URL? {195        guard let data = try? await store?.backup() else { return nil }196        return Self.temporaryFile(named: "ORIX Maps places backup.json", data: data)197    }198199    enum ImportResult: Equatable { case places(Int), restored(Int), failed(String) }200201    /// Imports GPX, GeoJSON or KML waypoints into a collection, or restores a backup file.202    func importFile(_ url: URL, into collection: UUID) async -> ImportResult {203        guard let store else { return .failed(String(localized: "The library is not available.")) }204        let scoped = url.startAccessingSecurityScopedResource()205        defer { if scoped { url.stopAccessingSecurityScopedResource() } }206        let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0207        guard size <= ExchangeLimits.maxBytes, let data = try? Data(contentsOf: url) else { return .failed(String(localized: "The file is too large or could not be read.")) }208        if let restored = try? await store.restore(data) {209            await reload()210            return .restored(restored)211        }212        do {213            let (doc, _) = try ExchangeCodec.decode(data, fileExtension: url.pathExtension)214            guard !doc.waypoints.isEmpty else { return .failed(String(localized: "This file contains no places (it may contain tracks: import it from Tracks).")) }215            let added = try await store.importDocument(doc, into: collection)216            await reload()217            return .places(added)218        } catch ExchangeError.unsupportedFormat {219            return .failed(String(localized: "This file format is not supported. Use GPX, GeoJSON or KML."))220        } catch {221            return .failed(String(localized: "The file could not be read: it is damaged or not a GPX, GeoJSON or KML file."))222        }223    }224225    static func temporaryFile(named name: String, data: Data) -> URL? {226        let dir = FileManager.default.temporaryDirectory.appending(path: "export-\(UUID().uuidString)", directoryHint: .isDirectory)227        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)228        let out = dir.appending(path: name.isEmpty ? "export" : name)229        return (try? data.write(to: out, options: .atomic)) == nil ? nil : out230    }231232    // MARK: History233234    func record(search text: String) async {235        guard settings.historyEnabled else { return }236        try? await store?.record(.search, title: text)237        await reload()238    }239240    func record(place: PlaceSelection) async {241        guard settings.historyEnabled else { return }242        try? await store?.record(.place, title: place.title, subtitle: place.subtitle, coordinate: place.coordinate)243        await reload()244    }245246    func deleteHistory(_ entry: HistoryEntry) async {247        try? await store?.deleteHistoryEntry(entry.id)248        await reload()249    }250251    func eraseHistory() async {252        try? await store?.eraseHistory()253        await reload()254    }255}256
Files main
Menu

Theme