SPB Git

Repository Public

Calls.swift 23.3 KB 280 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Next/Calls.swift3// Description: SPDriveNext — one async call per endpoint of the SP Drive 2.0 API (API-NEXT.md §2–§8): capabilities, sync events, search, document intelligence, private sharing (owner and grantee routes, including downloads and resumable uploads through a grant), collections, activity, storage, duplicates, versions, upload history, sessions, account, administration.4import CryptoKit5import Foundation67extension NextClient {8    // MARK: §2 Capabilities, sessions, account9    /// What the server can do. A 1.0 server (404) is reported as `ServerMeta.v1`.10    public func meta() async throws -> ServerMeta {11        do { return try await get("/meta", authenticated: false) }12        catch let e as NextError where e.isNotFound { return .v1 }13    }14    public func sessions() async throws -> [NextSession] { try await get("/account/sessions") }15    public func revokeSession(_ id: String) async throws { let _: OK = try await send("DELETE", "/account/sessions/\(id)") }16    public func updateAccount(_ patch: AccountPatch) async throws { let _: OK = try await send("PATCH", "/account", body: patch) }17    /// The account's own switch for external AI providers.18    public func setExternalAI(_ allowed: Bool) async throws { try await updateAccount(AccountPatch(aiExternal: allowed)) }1920    // MARK: §3 Sync events21    /// One connection to `GET /sync/events`. Finishes when the server closes it, throws when it fails; reconnecting22    /// (exponential back-off with jitter, 1 s → 60 s) and the polling fallback are the caller's.23    /// - Parameter idleTimeout: the server pings every 25 s; a stream silent for longer than this is treated as dead.24    public func syncEvents(idleTimeout: Double = 60) -> AsyncThrowingStream<SyncEvent, Error> {25        AsyncThrowingStream { continuation in26            let task = Task {27                do {28                    struct Head: Decodable { var head: Int64 }; struct Kind: Decodable { var kind: String }29                    let req = try await request("GET", "/sync/events")30                    for try await m in events(req, idleTimeout: idleTimeout) {31                        let d = Data(m.data.utf8)32                        switch m.event {33                        case "hello": if let h = try? JSONDecoder().decode(Head.self, from: d) { continuation.yield(.hello(head: h.head)) }34                        case "change": if let h = try? JSONDecoder().decode(Head.self, from: d) { continuation.yield(.change(head: h.head)) }35                        case "notify": if let k = try? JSONDecoder().decode(Kind.self, from: d) { continuation.yield(.notify(kind: k.kind)) }36                        default: break37                        }38                    }39                    continuation.finish()40                } catch { continuation.finish(throwing: NextError.wrap(error)) }41            }42            continuation.onTermination = { _ in task.cancel() }43        }44    }4546    // MARK: §4 Search47    /// Names and content of the caller's own files (shared folders are browsed, not searched). Every hit carries `match`.48    public func search(_ p: SearchParameters) async throws -> SearchResults {49        try await get("/search", query: ["q": p.q, "in": p.scope.rawValue, "kind": p.kind, "starred": p.starred == true ? "1" : nil,50                                         "from": p.from.map(NextClient.isoString), "to": p.to.map(NextClient.isoString),51                                         "minSize": p.minSize.map(String.init), "maxSize": p.maxSize.map(String.init), "sort": p.sort, "dir": p.dir])52    }53    public func search(_ q: String, in scope: SearchScope = .all) async throws -> SearchResults { try await search(SearchParameters(q: q, scope: scope)) }54    /// Nearest passages by meaning. `available == false` when the server has no embedding model right now; the server55    /// may also answer `503 busy` (thrown as `NextError`, see `retryAfterSeconds`) when its local model has a queue.56    public func semanticSearch(_ q: String, limit: Int = 10) async throws -> SemanticResults { try await get("/search/semantic", query: ["q": q, "limit": String(limit)]) }57    public func fileText(_ fileID: String) async throws -> FileTextStatus { try await get("/files/\(fileID)/text") }58    public func indexStatus() async throws -> IndexStatus { try await get("/index/status") }5960    // MARK: §5 Document intelligence61    public func aiProviders() async throws -> AIProviders { try await get("/ai/providers") }62    /// Asks a question about files, a folder or the whole Drive. Errors before the answer starts are thrown as63    /// `NextError` (`ai_unavailable`, `ai_external_disabled`, `provider_not_configured`…); a failure of the model64    /// during the answer arrives as `.error`. Cancelling the consuming task cancels the model call.65    public func aiAsk(_ ask: AIAskRequest) -> AsyncThrowingStream<AIEvent, Error> {66        AsyncThrowingStream { continuation in67            let task = Task {68                do {69                    struct Notice: Decodable { var unindexed: [AIUnindexed] }; struct Delta: Decodable { var text: String }; struct Failure: Decodable { var code: String; var message: String? }70                    let req = try await request("POST", "/ai/ask", body: try NextClient.encoder.encode(ask))71                    for try await m in events(req) {72                        let d = Data(m.data.utf8)73                        switch m.event {74                        case "notice": if let n = try? JSONDecoder().decode(Notice.self, from: d) { continuation.yield(.notice(unindexed: n.unindexed)) }75                        case "sources": continuation.yield(.sources((try? JSONDecoder().decode([AISource].self, from: d)) ?? []))76                        case "delta": if let t = try? JSONDecoder().decode(Delta.self, from: d) { continuation.yield(.delta(t.text)) }77                        case "done": continuation.yield(.done((try? JSONDecoder().decode(AIDone.self, from: d)) ?? AIDone(empty: nil)))78                        case "error": let f = try? JSONDecoder().decode(Failure.self, from: d); continuation.yield(.error(code: f?.code ?? "provider_error", message: f?.message ?? ""))79                        default: break80                        }81                    }82                    continuation.finish()83                } catch { continuation.finish(throwing: NextError.wrap(error)) }84            }85            continuation.onTermination = { _ in task.cancel() }86        }87    }88    /// Proposals of name, tags, folder and category. Nothing is applied by the server.89    public func aiSuggest(fileIDs: [String], provider: String? = nil, model: String? = nil) async throws -> AISuggestions {90        struct B: Encodable { var fileIds: [String]; var provider: String?; var model: String? }91        return try await send("POST", "/ai/suggest", body: B(fileIds: fileIDs, provider: provider, model: model))92    }9394    // MARK: §6.1 Private sharing — the owner's side95    /// Finds an account by its exact e-mail address (rate-limited; 404 for an unknown address or one's own).96    public func resolveUser(email: String) async throws -> ResolvedUser { struct B: Encodable { var email: String }; return try await send("POST", "/collab/resolve", body: B(email: email)) }97    public func members(of folderID: String) async throws -> FolderMembers { try await get("/folders/\(folderID)/members") }98    /// Gives an account access to a folder, **by its e-mail address** (API-NEXT D18: the server no longer accepts an99    /// account identifier here). `userID` is kept in the signature for source compatibility and is ignored: a call100    /// without `email` throws `invalid_request` without reaching the server.101    public func addMember(to folderID: String, userID: String? = nil, email: String? = nil, role: GrantRole, workspaceName: String? = nil) async throws -> FolderMember {102        guard let email, !email.isEmpty else { throw NextError.server(status: 400, code: "invalid_request", message: "an e-mail address is required to add a member", extra: [:]) }103        struct B: Encodable { var email: String; var role: GrantRole; var workspaceName: String? }104        return try await send("POST", "/folders/\(folderID)/members", body: B(email: email, role: role, workspaceName: workspaceName))105    }106    /// Gives an account access to a folder by its exact e-mail address.107    public func addMember(to folderID: String, email: String, as role: GrantRole, workspaceName: String? = nil) async throws -> FolderMember {108        try await addMember(to: folderID, userID: nil, email: email, role: role, workspaceName: workspaceName)109    }110    public func updateMember(of folderID: String, userID: String, role: GrantRole) async throws -> FolderMember {111        struct B: Encodable { var role: GrantRole }112        return try await send("PATCH", "/folders/\(folderID)/members/\(userID)", body: B(role: role))113    }114    public func removeMember(of folderID: String, userID: String) async throws { let _: OK = try await send("DELETE", "/folders/\(folderID)/members/\(userID)") }115    /// Names the shared folder as a workspace (nil removes the name).116    public func setWorkspaceName(of folderID: String, _ name: String?) async throws -> NextFolder {117        let body = try JSONSerialization.data(withJSONObject: ["name": name as Any? ?? NSNull()])118        return try decode(NextFolder.self, try await data(for: try await request("PATCH", "/folders/\(folderID)/workspace", body: body)).0)119    }120    /// Folders the caller shares with members.121    public func outgoingShares() async throws -> [OutgoingShare] { try await get("/collab/outgoing") }122123    // MARK: §6.2 Private sharing — the member's side124    public func sharedWithMe() async throws -> [SharedGrant] { try await get("/shared-with-me") }125    /// The reduced activity feed a member may read (API-NEXT D19): a few actions, since the grant, live items only,126    /// people by display name (`actor.userId` is nil), almost no `meta`.127    /// Lists a folder of a grant (nil = the granted folder). Viewer and editor; an uploader gets 403 (`isForbidden`).128    public func sharedChildren(grant: String, folderID: String? = nil) async throws -> SharedListing { try await get("/shared/\(grant)/children", query: ["folderId": folderID]) }129    public func sharedFile(grant: String, fileID: String) async throws -> SharedFileDetails { try await get("/shared/\(grant)/files/\(fileID)") }130    /// Request for the bytes of a shared file (`Range` supported through `from`).131    public func sharedContentRequest(grant: String, fileID: String, from offset: Int64 = 0, download: Bool = true) async throws -> URLRequest {132        var r = try await request("GET", "/shared/\(grant)/files/\(fileID)/content", query: ["download": download ? "1" : nil], headers: offset > 0 ? ["Range": "bytes=\(offset)-"] : [:])133        r.setValue("*/*", forHTTPHeaderField: "Accept"); return r134    }135    /// kind: thumb, image, pdf…136    public func sharedPreviewRequest(grant: String, fileID: String, kind: String = "thumb") async throws -> URLRequest {137        var r = try await request("GET", "/shared/\(grant)/files/\(fileID)/preview/\(kind)"); r.setValue("*/*", forHTTPHeaderField: "Accept"); return r138    }139    /// Downloads a shared file to `destination` (streamed to disk by URLSession, moved into place) and returns its SHA-256.140    @discardableResult public func downloadShared(grant: String, fileID: String, to destination: URL) async throws -> String {141        try await download(try await sharedContentRequest(grant: grant, fileID: fileID), to: destination)142    }143    public func sharedActivity(grant: String, before: String? = nil, limit: Int = 50) async throws -> ActivityPage { try await get("/shared/\(grant)/activity", query: ["before": before, "limit": String(limit)]) }144    public func sharedCreateFolder(grant: String, parentID: String? = nil, name: String, onConflict: String = "rename") async throws -> NextFolder {145        struct B: Encodable { var parentId: String?; var name: String; var onConflict: String }146        return try await send("POST", "/shared/\(grant)/folders", body: B(parentId: parentID, name: name, onConflict: onConflict))147    }148    /// Renames and/or moves a file or a folder inside the grant (editor).149    public func sharedUpdateItem(grant: String, itemID: String, name: String? = nil, parentID: String? = nil, onConflict: String? = nil) async throws -> SharedItem {150        struct B: Encodable { var name: String?; var parentId: String?; var onConflict: String? }151        let d = try await data(for: try await request("PATCH", "/shared/\(grant)/items/\(itemID)", body: try NextClient.encoder.encode(B(name: name, parentId: parentID, onConflict: onConflict)))).0152        struct T: Decodable { var type: String? }153        if (try? JSONDecoder().decode(T.self, from: d))?.type == "folder" { return .folder(try decode(NextFolder.self, d)) }154        return .file(try decode(NextFile.self, d))155    }156    /// Sends items of the grant to the OWNER's trash (editor). Only the owner restores or purges.157    public func sharedTrash(grant: String, fileIDs: [String] = [], folderIDs: [String] = []) async throws {158        struct B: Encodable { var fileIds: [String]; var folderIds: [String] }159        let _: OK = try await send("POST", "/shared/\(grant)/trash", body: B(fileIds: fileIDs, folderIds: folderIDs))160    }161    // resumable uploads through a grant (editor, uploader) — the same protocol as the owner's /uploads162    /// - Parameter onConflict: rename (default) | fail | version. An uploader may only use rename.163    public func sharedCreateUpload(grant: String, folderID: String? = nil, name: String, size: Int64, onConflict: String? = nil) async throws -> NextUpload {164        struct B: Encodable { var folderId: String?; var name: String; var size: Int64; var onConflict: String? }165        return try await send("POST", "/shared/\(grant)/uploads", body: B(folderId: folderID, name: name, size: size, onConflict: onConflict))166    }167    public func sharedUpload(grant: String, id: String) async throws -> NextUpload { try await get("/shared/\(grant)/uploads/\(id)") }168    public func sharedAppend(grant: String, id: String, offset: Int64, chunk: Data) async throws -> NextUpload {169        let r = try await request("PATCH", "/shared/\(grant)/uploads/\(id)", query: ["offset": String(offset)], body: chunk, contentType: "application/octet-stream",170                                  headers: ["X-Chunk-SHA256": SHA256.hash(data: chunk).map { String(format: "%02x", $0) }.joined()])171        return try decode(NextUpload.self, try await data(for: r).0)172    }173    public func sharedCompleteUpload(grant: String, id: String, sha256: String?) async throws -> NextUploadResult {174        struct B: Encodable { var sha256: String? }175        return try await send("POST", "/shared/\(grant)/uploads/\(id)/complete", body: B(sha256: sha256))176    }177    public func sharedAbortUpload(grant: String, id: String) async throws { let _: OK = try await send("DELETE", "/shared/\(grant)/uploads/\(id)") }178    /// Sends a local file into a grant: read block by block, each block with its SHA-256, the whole-file SHA-256179    /// confirmed by the server at the end. `resume` continues an upload opened earlier (same file) from the offset the180    /// server reports. Bytes count against the owner's quota.181    @discardableResult public func uploadShared(grant: String, file url: URL, folderID: String? = nil, name: String? = nil, onConflict: String? = nil, resume uploadID: String? = nil,182                                               chunkSize: Int = 4 * 1024 * 1024, progress: @escaping @Sendable (Int64, Int64) -> Void = { _, _ in }) async throws -> NextUploadResult {183        let size = ((try FileManager.default.attributesOfItem(atPath: url.path))[.size] as? NSNumber)?.int64Value ?? 0184        var upload: NextUpload185        if let uploadID, let known = try? await sharedUpload(grant: grant, id: uploadID), known.size == size, known.status == "active" { upload = known }186        else { upload = try await sharedCreateUpload(grant: grant, folderID: folderID, name: name ?? url.lastPathComponent, size: size, onConflict: onConflict) }187        let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }188        var hasher = SHA256()189        // the whole-file hash covers what was sent before a resume too190        var hashed: Int64 = 0191        while hashed < upload.received, let d = try handle.read(upToCount: Int(min(Int64(chunkSize), upload.received - hashed))), !d.isEmpty { hasher.update(data: d); hashed += Int64(d.count) }192        var offset = upload.received193        progress(offset, size)194        while offset < size {195            try Task.checkCancellation()196            try handle.seek(toOffset: UInt64(offset))197            guard let chunk = try handle.read(upToCount: Int(min(Int64(chunkSize), size - offset))), !chunk.isEmpty else { throw NextError.invalidResponse("file shorter than announced") }198            do { upload = try await sharedAppend(grant: grant, id: upload.id, offset: offset, chunk: chunk) }199            catch let e as NextError where e.code == "offset_mismatch" {200                // the server knows where it is: follow it (hash again from the start to stay exact)201                guard let r = e.extra["received"]?.double.map({ Int64($0) }) else { throw e }202                offset = r; hasher = SHA256(); try handle.seek(toOffset: 0); hashed = 0203                while hashed < offset, let d = try handle.read(upToCount: Int(min(Int64(chunkSize), offset - hashed))), !d.isEmpty { hasher.update(data: d); hashed += Int64(d.count) }204                continue205            }206            hasher.update(data: chunk); offset = upload.received207            progress(offset, size)208        }209        return try await sharedCompleteUpload(grant: grant, id: upload.id, sha256: hasher.finalize().map { String(format: "%02x", $0) }.joined())210    }211212    // MARK: §7.1 Collections213    public func collections() async throws -> [SmartCollection] { try await get("/collections") }214    public func createCollection(_ draft: CollectionDraft) async throws -> SmartCollection { try await send("POST", "/collections", body: draft) }215    public func updateCollection(_ id: String, _ draft: CollectionDraft) async throws -> SmartCollection { try await send("PATCH", "/collections/\(id)", body: draft) }216    public func deleteCollection(_ id: String) async throws { let _: OK = try await send("DELETE", "/collections/\(id)") }217    public func collectionItems(_ id: String, limit: Int = 200, offset: Int = 0) async throws -> CollectionItems { try await get("/collections/\(id)/items", query: ["limit": String(limit), "offset": String(offset)]) }218    /// Runs a rule without saving it.219    public func previewCollection(_ rule: CollectionRule, limit: Int = 50) async throws -> CollectionItems {220        struct B: Encodable { var rule: CollectionRule; var limit: Int }221        return try await send("POST", "/collections/preview", body: B(rule: rule, limit: limit))222    }223224    // MARK: §7.2 Activity225    public func fileActivity(_ fileID: String, before: String? = nil, limit: Int = 50) async throws -> ActivityPage { try await get("/files/\(fileID)/activity", query: ["before": before, "limit": String(limit)]) }226    public func accountActivity(before: String? = nil, limit: Int = 50) async throws -> ActivityPage { try await get("/activity", query: ["before": before, "limit": String(limit)]) }227    /// The folder and everything below it, members' actions included (owner only).228    public func folderActivity(_ folderID: String, before: String? = nil, limit: Int = 50) async throws -> ActivityPage { try await get("/folders/\(folderID)/activity", query: ["before": before, "limit": String(limit)]) }229230    // MARK: §7.3 Storage, §7.4 Duplicates231    public func storageOverview() async throws -> StorageOverview { try await get("/storage/overview") }232    /// `folderID` or "root".233    public func storageFolder(_ folderID: String = "root") async throws -> StorageFolder { try await get("/storage/folder/\(folderID)") }234    /// Never deletes anything. `distance` (0–16, default 6) applies to similar images.235    public func duplicates(_ mode: DuplicateMode = .exact, distance: Int? = nil) async throws -> Duplicates { try await get("/duplicates", query: ["mode": mode.rawValue, "distance": distance.map(String.init)]) }236237    // MARK: §7.5 Versions, §7.6 Upload history238    public func versions(of fileID: String) async throws -> VersionList { try await get("/files/\(fileID)/versions") }239    public func versionContentRequest(fileID: String, versionID: String, download: Bool = false) async throws -> URLRequest {240        var r = try await request("GET", "/files/\(fileID)/versions/\(versionID)/content", query: ["download": download ? "1" : nil]); r.setValue("*/*", forHTTPHeaderField: "Accept"); return r241    }242    /// Downloads one version to `destination`; returns its SHA-256 (compare with `VersionInfo.sha256`).243    @discardableResult public func downloadVersion(fileID: String, versionID: String, to destination: URL) async throws -> String {244        try await download(try await versionContentRequest(fileID: fileID, versionID: versionID), to: destination)245    }246    /// The old content becomes a NEW current version; every existing version is kept. Returns the file.247    public func restoreVersion(fileID: String, versionID: String) async throws -> NextFile { try await send("POST", "/files/\(fileID)/versions/\(versionID)/restore") }248    /// state: recent | active249    public func uploadHistory(state: String = "recent", limit: Int = 200) async throws -> [NextUpload] {250        let h: UploadHistory = try await get("/uploads", query: ["state": state, "limit": String(limit)]); return h.uploads251    }252253    // MARK: §8 Administration254    /// Administrators only (404 for anyone else).255    public func adminSystem() async throws -> AdminSystem {256        let d = try await data(for: try await request("GET", "/admin/system")).0257        let raw = try decode([String: NextJSON].self, d)258        func part<T: Decodable>(_ key: String, _ type: T.Type) -> T? { raw[key].flatMap { try? JSONEncoder().encode($0) }.flatMap { try? JSONDecoder().decode(T.self, from: $0) } }259        return AdminSystem(version: raw["version"]?.string, features: raw["features"]?.array?.compactMap(\.string) ?? [], worker: part("worker", AdminSystem.Worker.self),260                           jobs: part("jobs", [AdminSystem.Job].self) ?? [], previewFailures: part("previewFailures", [AdminSystem.PreviewFailure].self) ?? [], raw: raw)261    }262263    // MARK: Downloads264    /// Streams a response body to a temporary file, moves it to `destination`, and returns the SHA-256 of what was stored.265    @discardableResult public func download(_ request: URLRequest, to destination: URL) async throws -> String {266        do {267            let (tmp, response) = try await transport.session.download(for: request)268            defer { try? FileManager.default.removeItem(at: tmp) }269            if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { try NextClient.check((try? Data(contentsOf: tmp)) ?? Data(), response) }270            var hasher = SHA256()271            let h = try FileHandle(forReadingFrom: tmp); defer { try? h.close() }272            while let d = try h.read(upToCount: 1 << 20), !d.isEmpty { hasher.update(data: d) }273            try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)274            try? FileManager.default.removeItem(at: destination)275            try FileManager.default.moveItem(at: tmp, to: destination)276            return hasher.finalize().map { String(format: "%02x", $0) }.joined()277        } catch { throw NextError.wrap(error) }278    }279}280
Files main
Menu

Theme