SPB Git

Repository Public

NextBridge.swift 8.2 KB 155 lines swift

1// SP Drive iOS2// File: NextKit/NextBridge.swift3// Description: Where the app meets the shared `SPDriveNext` package (SP Drive 2.0 endpoints): a transport built on the app's own session4//              (base URL, device token, client header), the server's event stream as a `ChangeEventSource` for the sync engine, capability5//              discovery with a 1.0 fallback, tags (a 1.0 route family the package has no typed call for), and a line diff for the6//              comparison of text versions. Foundation only: tested on the Mac against the real backend.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPDriveNext1213/// `NextTransport` on top of the app's API client: same server, same device token, same client header.14public struct DriveNextTransport: NextTransport {15    public let baseURL: URL16    public let session: URLSession17    public let clientHeader: String?18    let tokens: TokenStore19    public init(api: DriveAPI, session: URLSession = BasicNextTransport.defaultSession()) {20        baseURL = api.baseURL; tokens = api.tokens; self.session = session; clientHeader = DriveAPI.clientHeader21    }22    public func bearerToken() async throws -> String? { tokens.token() }23}2425extension DriveAPI {26    /// The 2.0 client for this account.27    public func next(session: URLSession = BasicNextTransport.defaultSession()) -> NextClient { NextClient(DriveNextTransport(api: self, session: session)) }28}2930/// The server's event stream (`GET /sync/events`) as hints for the change listener. Events carry no data: the listener then reads the31/// change feed. When the stream ends or fails, the listener polls and reconnects with its own back-off.32public struct SSEChangeSource: ChangeEventSource {33    let client: NextClient34    let idleTimeout: Double35    public init(client: NextClient, idleTimeout: Double = 60) { self.client = client; self.idleTimeout = idleTimeout }3637    public func hints() -> AsyncThrowingStream<ChangeHint, Error> {38        let events = client.syncEvents(idleTimeout: idleTimeout)39        return AsyncThrowingStream { continuation in40            let task = Task {41                do {42                    for try await e in events {43                        switch e {44                        case .hello(let head): continuation.yield(.connected(head: head))45                        case .change(let head): continuation.yield(.changed(head: head))46                        case .notify(let kind): continuation.yield(.notify(kind: kind))47                        }48                    }49                    // the server closed the stream (shutdown, API-NEXT D17): for the listener that is a lost connection50                    continuation.finish(throwing: NextError.offline("stream closed"))51                } catch { continuation.finish(throwing: error) }52            }53            continuation.onTermination = { _ in task.cancel() }54        }55    }56}5758extension NextClient {59    /// What the server can do. A 1.0 server has no `/meta` (404): it is described as such instead of being an error.60    public func capabilities() async throws -> ServerMeta {61        do { return try await meta() } catch let e as NextError where e.isNotFound { return .v1 }62    }63}6465// MARK: Tags (1.0 routes `/tags` and `PATCH /files/:id { tagIds }`; no typed call in SPDriveNext)6667public struct DriveTag: Codable, Sendable, Identifiable, Hashable {68    public var id: String; public var name: String; public var color: String; public var files: Int?69    public static let colors = ["slate", "red", "orange", "amber", "green", "teal", "blue", "violet", "pink"]70}7172extension NextClient {73    public func tags() async throws -> [DriveTag] { try await get("/tags") }74    public func createTag(name: String, color: String) async throws -> DriveTag {75        struct B: Encodable { var name: String; var color: String }76        return try await send("POST", "/tags", body: B(name: name, color: color))77    }78    public func updateTag(_ id: String, name: String? = nil, color: String? = nil) async throws {79        struct B: Encodable { var name: String?; var color: String? }; struct OK: Decodable { var ok: Bool? }80        let _: OK = try await send("PATCH", "/tags/\(id)", body: B(name: name, color: color))81    }82    public func deleteTag(_ id: String) async throws { struct OK: Decodable { var ok: Bool? }; let _: OK = try await send("DELETE", "/tags/\(id)") }83    /// Replaces the tags of a file.84    public func setTags(of fileID: String, to tagIDs: [String]) async throws {85        struct B: Encodable { var tagIds: [String] }; struct Any_: Decodable {}86        let _: Any_ = try await send("PATCH", "/files/\(fileID)", body: B(tagIds: tagIDs))87    }88    /// The tags of one file (the device mirror does not store them).89    public func tagIDs(of fileID: String) async throws -> [String] {90        struct W: Decodable { var file: NextFile }91        let w: W = try await get("/files/\(fileID)")92        return w.file.tagIds93    }94}9596// MARK: Text comparison9798/// Line-by-line comparison of two texts (longest common subsequence), for the versions screen.99public enum TextDiff {100    public enum Kind: Sendable, Equatable { case same, removed, added }101    public struct Line: Sendable, Equatable, Identifiable {102        public var id: Int103        public var kind: Kind104        public var text: String105        /// Line numbers in the old and in the new text (nil on the side where the line does not exist).106        public var old: Int?, new: Int?107    }108    public struct Summary: Sendable, Equatable { public var added = 0, removed = 0, unchanged = 0 }109110    /// Above this many lines on either side the quadratic table is not built: the caller shows the two texts side by side instead.111    public static let maxLines = 4000112113    public static func lines(old: String, new: String) -> [Line]? {114        let a = old.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).map(String.init)115        let b = new.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).map(String.init)116        guard a.count <= maxLines, b.count <= maxLines else { return nil }117        // common prefix and suffix first: most edits touch a few lines of a long file118        var start = 0119        while start < a.count, start < b.count, a[start] == b[start] { start += 1 }120        var endA = a.count, endB = b.count121        while endA > start, endB > start, a[endA - 1] == b[endB - 1] { endA -= 1; endB -= 1 }122        let x = Array(a[start..<endA]), y = Array(b[start..<endB])123        var table = [[Int32]](repeating: [Int32](repeating: 0, count: y.count + 1), count: x.count + 1)124        if !x.isEmpty, !y.isEmpty {125            for i in stride(from: x.count - 1, through: 0, by: -1) {126                for j in stride(from: y.count - 1, through: 0, by: -1) { table[i][j] = x[i] == y[j] ? table[i + 1][j + 1] + 1 : max(table[i + 1][j], table[i][j + 1]) }127            }128        }129        var out: [Line] = []130        func push(_ kind: Kind, _ text: String, _ o: Int?, _ n: Int?) { out.append(Line(id: out.count, kind: kind, text: text, old: o, new: n)) }131        for i in 0..<start { push(.same, a[i], i + 1, i + 1) }132        var i = 0, j = 0133        while i < x.count, j < y.count {134            if x[i] == y[j] { push(.same, x[i], start + i + 1, start + j + 1); i += 1; j += 1 }135            else if table[i + 1][j] >= table[i][j + 1] { push(.removed, x[i], start + i + 1, nil); i += 1 }136            else { push(.added, y[j], nil, start + j + 1); j += 1 }137        }138        while i < x.count { push(.removed, x[i], start + i + 1, nil); i += 1 }139        while j < y.count { push(.added, y[j], nil, start + j + 1); j += 1 }140        for k in 0..<(a.count - endA) { push(.same, a[endA + k], endA + k + 1, endB + k + 1) }141        return out142    }143144    public static func summary(_ lines: [Line]) -> Summary {145        var s = Summary()146        for l in lines { switch l.kind { case .same: s.unchanged += 1; case .added: s.added += 1; case .removed: s.removed += 1 } }147        return s148    }149150    /// Whether a file of this extension is compared as text.151    public static func isText(extension ext: String) -> Bool {152        ["txt", "md", "markdown", "json", "csv", "tsv", "xml", "yaml", "yml", "toml", "log", "tex", "bib", "html", "htm", "css", "js", "ts", "py", "swift", "sh", "sql", "c", "h", "cpp", "java", "go", "rs", "rb", "php"].contains(ext.lowercased())153    }154}155
Files main
Menu

Theme