SPB Git

Repository Public

NFTGallery.swift 17.1 KB 358 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet for macOS9// File             : Features/NFTs/NFTGallery.swift10// Description      : State of the NFT gallery: the inventory as the server11//                    stores it (read page by page, spam included so nothing is12//                    hidden silently), the capability matrix that says which13//                    provider discovered what and when, the synchronisation the14//                    backend offers, and the local filters / search / sort /15//                    grouping over the served fields. The last inventory read16//                    is kept as an offline snapshot with its date; offline,17//                    nothing is fetched and nothing can be started.18// Module           : Features19// Repository       : https://git.spboucher.ai/sp-wallet-macos20// Created          : 2026-11-1821// Last Modified    : 2026-11-1822//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author           : Simon-Pierre Boucher28// Position         : Professor of Finance29// Institution      : Université du Québec en Outaouais (UQO)30// Department       : Département des sciences administratives31// Organization     : SP Boucher32//33// Website          : https://spboucher.ai34// Git              : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General          : info@spboucher.ai41// Professional     : contact@spboucher.ai42// Direct           : simon@spboucher.ai43// Research         : research@spboucher.ai44// Development      : dev@spboucher.ai45// Support          : support@spboucher.ai46// Security/Admin   : admin@spboucher.ai47// Notifications    : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification   : Public74// Distribution     : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License          : None specified (no license file in this repository)88// Maintainer       : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import Foundation96import SPWalletCore9798/// What is kept for offline reading: the rows exactly as served, and the matrix that explains where they come from.99struct NFTInventorySnapshot: Codable, Sendable {100    var items: [NFTSummary]101    var total: Int102    var complete: Bool103    var capabilities: NFTCapabilities?104    var lastSyncedAt: [String: Date]105}106107struct NFTGallerySection: Identifiable {108    let id: String109    let title: String110    /// A collection key when the section is one collection (its page can be opened).111    let collectionKey: String?112    let items: [NFTSummary]113}114115@MainActor @Observable final class NFTGallery {116    enum Status: String, CaseIterable, Identifiable {117        case all, inWallet, left, tracked118        var id: String { rawValue }119        var label: String {120            switch self { case .all: "Tout l’inventaire"; case .inWallet: "Détenus"; case .left: "Sortis du portefeuille"; case .tracked: "Suivis à la main" }121        }122    }123    enum Spam: String, CaseIterable, Identifiable {124        case hide, show, only125        var id: String { rawValue }126        var label: String { switch self { case .hide: "Masquer les signalés"; case .show: "Tout afficher"; case .only: "Signalés seulement" } }127    }128    enum Sort: String, CaseIterable, Identifiable {129        case recent, name, collection, network130        var id: String { rawValue }131        var label: String { switch self { case .recent: "Plus récents"; case .name: "Nom"; case .collection: "Collection"; case .network: "Réseau" } }132    }133    enum Grouping: String, CaseIterable, Identifiable {134        case none, collection, network135        var id: String { rawValue }136        var label: String { switch self { case .none: "Sans regroupement"; case .collection: "Par collection"; case .network: "Par réseau" } }137    }138139    static let snapshotKey = "nft-inventory"140    /// The server never stores more than `NFT_INVENTORY_MAX` (at most 5 000) items; this is only a guard against an endless cursor.141    private static let maxItems = 6_000142143    let model: AppModel144    let api: NFTAPI145146    var chain = "" { didSet { refilter() } }147    var collection = "" { didSet { refilter() } }148    var status: Status = .all { didSet { refilter() } }149    var spam: Spam = .hide { didSet { refilter() } }150    var sort: Sort = .recent { didSet { refilter() } }151    var grouping: Grouping = .none { didSet { refilter() } }152    var search = "" { didSet { refilter() } }153154    private(set) var items: [NFTSummary] = []155    private(set) var total = 0156    private(set) var complete = true157    private(set) var capabilities: NFTCapabilities?158    private(set) var lastSyncedAt: [String: Date] = [:]159    private(set) var syncRunning: [String] = []160    private(set) var fetchedAt: Date?161    private(set) var fromCache = false162    private(set) var loading = false163    private(set) var loadedOnce = false164    private(set) var syncStarting = false165    var error: String?166    var syncError: String?167168    private(set) var sections: [NFTGallerySection] = []169    private(set) var visibleCount = 0170    private(set) var hiddenSpam = 0171172    private var haystacks: [String: String] = [:]173    private var snapshotRead = false174    private var syncTask: Task<Void, Never>?175176    init(model: AppModel) { self.model = model; api = NFTAPI(model.client) }177178    /// Reads need a session; whether the wallet answers is found by asking.179    var canFetch: Bool { model.phase == .signedIn }180    var mediaAPI: NFTAPI? { model.canOperate ? api : nil }181    var mediaLimit: Int { NFTMediaStore.limit(capabilities?.mediaMaxBytes) }182183    func networkName(_ id: String) -> String { model.network(id)?.name ?? capabilities?.chain(id)?.name ?? id }184    func summary(_ key: String) -> NFTSummary? { items.first { $0.key == key } }185    func items(inCollection key: String) -> [NFTSummary] { items.filter { $0.collection?.key == key } }186187    /// Networks that appear in the inventory, in the server's registry order when known.188    var chainsPresent: [String] {189        let present = Set(items.map(\.chain))190        let ordered = (capabilities?.chains.map(\.network) ?? []).filter(present.contains)191        return ordered + present.subtracting(ordered).sorted()192    }193    /// Collections of the inventory (optionally of one network) with the number of rows held, largest first.194    var collectionsPresent: [(key: String, name: String, count: Int)] {195        var counts: [String: (String, Int)] = [:]196        for i in items where chain.isEmpty || i.chain == chain {197            guard let c = i.collection else { continue }198            counts[c.key] = (NFTClean.line(c.name) ?? Fmt.short(c.key, head: 18, tail: 8), (counts[c.key]?.1 ?? 0) + 1)199        }200        return counts.map { (key: $0.key, name: $0.value.0, count: $0.value.1) }.sorted { $0.count != $1.count ? $0.count > $1.count : $0.name < $1.name }201    }202203    // MARK: - Loading204205    func load() async {206        if !snapshotRead {207            snapshotRead = true208            if items.isEmpty, let s: Snapshot<NFTInventorySnapshot> = await SnapshotStore.shared.load(Self.snapshotKey) {209                apply(s.value.items, total: s.value.total, complete: s.value.complete)210                capabilities = s.value.capabilities; lastSyncedAt = s.value.lastSyncedAt211                fetchedAt = s.savedAt; fromCache = true212            }213        }214        guard canFetch, !loading else { loadedOnce = true; return }215        loading = true; defer { loading = false; loadedOnce = true }216        do {217            async let caps = api.capabilities()218            var all: [NFTSummary] = [], seen = Set<String>(), cursor: Int? = 0, last: NFTList?219            while let c = cursor, all.count < Self.maxItems {220                let page = try await api.list(NFTListQuery(sort: .recent, spam: .show, cursor: c, limit: 100))221                for i in page.items where seen.insert(i.key).inserted { all.append(i) }222                last = page223                cursor = page.items.isEmpty ? nil : page.cursor224                try Task.checkCancellation()225            }226            let matrix = try? await caps227            apply(all, total: last?.total ?? all.count, complete: cursor == nil)228            if let matrix { capabilities = matrix }229            if let s = last?.sync { syncRunning = s.running; if let l = s.lastSyncedAt { lastSyncedAt = l } }230            fetchedAt = Date(); fromCache = false; error = nil231            await SnapshotStore.shared.save(NFTInventorySnapshot(items: items, total: total, complete: complete, capabilities: capabilities, lastSyncedAt: lastSyncedAt), as: Self.snapshotKey)232            if !syncRunning.isEmpty { followSync() }233        } catch is CancellationError {234        } catch let e as APIError where e.code == "nft_disabled" || e.code == "nft_misconfigured" {235            self.error = e.code == "nft_disabled"236                ? "Le module NFT est désactivé sur ce serveur (réglage NFT_ENABLED) : aucun inventaire, aucun transfert ni aucune donnée de marché n’y sont servis."237                : "La configuration NFT du serveur est invalide : le module NFT ne répond pas."238            if !items.isEmpty { fromCache = true }239        } catch {240            self.error = model.describe(error)241            if !items.isEmpty { fromCache = true }242        }243    }244245    func refresh() async {246        await NFTMediaStore.shared.forgetFailures()247        await load()248    }249250    private func apply(_ rows: [NFTSummary], total: Int, complete: Bool) {251        items = rows; self.total = total; self.complete = complete252        haystacks = Dictionary(uniqueKeysWithValues: rows.map { ($0.key, NFTText.haystack($0)) })253        if !collection.isEmpty, !rows.contains(where: { $0.collection?.key == collection }) { collection = "" }254        if !chain.isEmpty, !rows.contains(where: { $0.chain == chain }) { chain = "" }255        refilter()256    }257258    // MARK: - Filters (over the served fields; the predicates are those of the server's own `status` and `spam` filters)259260    private func refilter() {261        let needle = search.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()262        var hidden = 0263        var rows = items.filter { i in264            if !chain.isEmpty, i.chain != chain { return false }265            if !collection.isEmpty, i.collection?.key != collection { return false }266            switch status {267            case .all: break268            case .inWallet: if !i.inWallet { return false }269            case .left: if i.inWallet || i.origin != "discovered" { return false }270            case .tracked: if i.origin != "manual" { return false }271            }272            if !needle.isEmpty, haystacks[i.key]?.contains(needle) != true { return false }273            switch spam {274            case .hide: if i.spam != nil { hidden += 1; return false }275            case .only: if i.spam == nil { return false }276            case .show: break277            }278            return true279        }280        func name(_ i: NFTSummary) -> String { (i.displayName ?? "\u{10FFFF}").lowercased() }281        func collectionName(_ i: NFTSummary) -> String { (i.collection?.name ?? i.collection?.key ?? "\u{10FFFF}").lowercased() }282        switch sort {283        case .recent: break // the server's order: held first, then most recently seen284        case .name: rows.sort { name($0) != name($1) ? name($0) < name($1) : $0.key < $1.key }285        case .collection: rows.sort { collectionName($0) != collectionName($1) ? collectionName($0) < collectionName($1) : name($0) < name($1) }286        case .network: rows.sort { $0.chain != $1.chain ? networkName($0.chain) < networkName($1.chain) : name($0) < name($1) }287        }288        hiddenSpam = hidden; visibleCount = rows.count289        switch grouping {290        case .none: sections = rows.isEmpty ? [] : [NFTGallerySection(id: "all", title: "", collectionKey: nil, items: rows)]291        case .network:292            var order: [String] = [], groups: [String: [NFTSummary]] = [:]293            for i in rows { if groups[i.chain] == nil { order.append(i.chain) }; groups[i.chain, default: []].append(i) }294            sections = order.map { NFTGallerySection(id: "n:\($0)", title: networkName($0), collectionKey: nil, items: groups[$0] ?? []) }295        case .collection:296            var order: [String] = [], groups: [String: [NFTSummary]] = [:]297            for i in rows { let k = i.collection?.key ?? ""; if groups[k] == nil { order.append(k) }; groups[k, default: []].append(i) }298            sections = order.map { k in299                let first = groups[k]?.first300                let title = k.isEmpty ? "Sans collection" : "\(NFTClean.line(first?.collection?.name) ?? Fmt.short(k, head: 18, tail: 8)) · \(networkName(first?.chain ?? ""))"301                return NFTGallerySection(id: "c:\(k)", title: title, collectionKey: k.isEmpty ? nil : k, items: groups[k] ?? [])302            }303        }304    }305306    // MARK: - Synchronisation (the server's own job; this app only starts it and reports its state)307308    func startSync(chain: String?) async {309        guard model.canOperate, !syncStarting else { return }310        syncStarting = true; syncError = nil; defer { syncStarting = false }311        do {312            syncRunning = try await api.sync(chain: chain).running313            followSync()314        } catch { syncError = model.describe(error) }315    }316317    /// Reads the server's sync state until it reports no running job (or two minutes passed), then reloads the inventory.318    private func followSync() {319        syncTask?.cancel()320        syncTask = Task { [weak self] in321            for _ in 0..<40 {322                try? await Task.sleep(for: .seconds(3))323                guard let self, !Task.isCancelled else { return }324                guard AppActivity.isActive, self.model.canOperate else { continue }325                guard let page = try? await self.api.list(NFTListQuery(limit: 1)), let s = page.sync else { continue }326                self.syncRunning = s.running327                if let l = s.lastSyncedAt { self.lastSyncedAt = l }328                if s.running.isEmpty { break }329            }330            guard let self, !Task.isCancelled else { return }331            await self.load()332        }333    }334335    func stop() { syncTask?.cancel(); syncTask = nil }336}337338/// Creator-controlled text is untrusted: before it is displayed (always as plain text), control characters and bidirectional overrides are removed and its length is bounded.339enum NFTClean {340    static func text(_ s: String?, max: Int) -> String? {341        guard let s else { return nil }342        var out = String.UnicodeScalarView()343        var n = 0344        for u in s.unicodeScalars {345            if n >= max { out.append("…"); break }346            if u == "\n" || u == "\t" { out.append(u); n += 1; continue }347            switch u.properties.generalCategory {348            case .control, .format, .privateUse, .surrogate, .unassigned, .lineSeparator, .paragraphSeparator: continue349            default: out.append(u); n += 1350            }351        }352        let t = String(out).trimmingCharacters(in: .whitespacesAndNewlines)353        return t.isEmpty ? nil : t354    }355    /// One line (names, collection names, trait labels).356    static func line(_ s: String?, max: Int = 120) -> String? { text(s?.replacingOccurrences(of: "\n", with: " ").replacingOccurrences(of: "\t", with: " "), max: max) }357}358
Files main
Menu

Theme