SPB Git

Repository Public

Endpoints.swift 12.3 KB 149 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/API/Endpoints.swift3// Description: One method per route of the SP Drive API: account, tree, change feed, content, resumable uploads at block level, share links, deposit portals, versions, notifications.4import Foundation56public enum ConflictPolicy: String, Codable, Sendable { case fail, rename, version }7public struct Selection: Codable, Sendable {8    public var fileIds: [String]; public var folderIds: [String]9    public init(fileIds: [String] = [], folderIds: [String] = []) { self.fileIds = fileIds; self.folderIds = folderIds }10    public init(_ items: [DriveItem]) { fileIds = items.filter { !$0.isFolder }.map(\.id); folderIds = items.filter(\.isFolder).map(\.id) }11    public var isEmpty: Bool { fileIds.isEmpty && folderIds.isEmpty }12}13/// State of a resumable upload on the server.14public struct UploadSession: Decodable, Sendable {15    public var id: String; public var name: String; public var size: Int64; public var received: Int64; public var status: String; public var fileId: String?16}17public struct UploadResult: Decodable, Sendable { public var id: String; public var status: String; public var file: DriveItem; public var created: Bool? }18public struct SearchQuery: Sendable {19    public var text = ""; public var kind = "any"; public var starred = false; public var from: Date?; public var to: Date?; public var minSize: Int64?; public var maxSize: Int64?20    public init(text: String = "") { self.text = text }21}2223extension APIClient {24    // MARK: Account25    public func authState() async throws -> AuthState { try await get("/auth/state") }26    public func logout() async throws { let _: OK = try await send("POST", "/auth/logout") }27    public func sessions() async throws -> [DeviceSession] { try await get("/account/sessions") }28    public func revokeSession(_ id: String) async throws { let _: OK = try await send("DELETE", "/account/sessions/\(id)") }29    public func notifications() async throws -> [ServerNotification] { try await get("/notifications") }30    public func markNotificationsRead(_ ids: [String]? = nil) async throws {31        struct B: Encodable { var ids: [String]? }32        let _: OK = try await send("POST", "/notifications/read", body: B(ids: ids))33    }3435    // MARK: Tree36    public func listFolder(_ id: String = "root") async throws -> FolderListing { try await get("/folders/\(id)") }37    public func createFolder(parent: String, name: String, onConflict: ConflictPolicy = .fail) async throws -> DriveItem {38        struct B: Encodable { var parentId: String; var name: String; var onConflict: ConflictPolicy }39        return try await send("POST", "/folders", body: B(parentId: parent, name: name, onConflict: onConflict))40    }41    private struct Patch: Encodable { var name: String?; var starred: Bool? }42    public func updateFolder(_ id: String, name: String? = nil, starred: Bool? = nil) async throws -> DriveItem { try await send("PATCH", "/folders/\(id)", body: Patch(name: name, starred: starred)) }43    public func updateFile(_ id: String, name: String? = nil, starred: Bool? = nil) async throws -> DriveItem { try await send("PATCH", "/files/\(id)", body: Patch(name: name, starred: starred)) }44    public func update(_ item: DriveItem, name: String? = nil, starred: Bool? = nil) async throws -> DriveItem {45        item.isFolder ? try await updateFolder(item.id, name: name, starred: starred) : try await updateFile(item.id, name: name, starred: starred)46    }47    public func fileDetails(_ id: String) async throws -> FileDetails { try await get("/files/\(id)") }48    public func move(_ sel: Selection, to destination: String, onConflict: ConflictPolicy = .fail) async throws {49        struct B: Encodable { var fileIds: [String]; var folderIds: [String]; var destinationId: String; var onConflict: ConflictPolicy }50        let _: OK = try await send("POST", "/move", body: B(fileIds: sel.fileIds, folderIds: sel.folderIds, destinationId: destination, onConflict: onConflict))51    }52    public struct CopyCount: Decodable, Sendable { public var files: Int; public var folders: Int }53    @discardableResult public func copy(_ sel: Selection, to destination: String) async throws -> CopyCount {54        struct B: Encodable { var fileIds: [String]; var folderIds: [String]; var destinationId: String }55        return try await send("POST", "/copy", body: B(fileIds: sel.fileIds, folderIds: sel.folderIds, destinationId: destination))56    }57    public func trash(_ sel: Selection) async throws { let _: OK = try await send("POST", "/trash", body: sel) }58    public func restore(_ sel: Selection) async throws { let _: OK = try await send("POST", "/restore", body: sel) }59    /// Deletes trashed items for good. Only ever called after an explicit confirmation by the person.60    public func purge(_ sel: Selection) async throws { let _: OK = try await send("POST", "/purge", body: sel) }61    public func emptyTrash() async throws { struct B: Encodable { var all = true }; let _: OK = try await send("POST", "/purge", body: B()) }62    public func trashList() async throws -> ItemList { try await get("/trash") }63    public func recent() async throws -> ItemList { try await get("/recent") }64    public func starred() async throws -> ItemList { try await get("/starred") }65    public func search(_ q: SearchQuery) async throws -> ItemList {66        let day: (Date) -> String = { $0.formatted(.iso8601.year().month().day()) }67        return try await get("/search", query: ["q": q.text, "kind": q.kind, "starred": q.starred ? "1" : nil, "from": q.from.map(day), "to": q.to.map(day),68                                                 "minSize": q.minSize.map(String.init), "maxSize": q.maxSize.map(String.init)])69    }7071    // MARK: Change feed72    public func syncCursor() async throws -> SyncCursor { try await get("/sync/cursor") }73    public func changes(since: Int64, limit: Int = 1000) async throws -> ChangePage { try await get("/sync/changes", query: ["since": String(since), "limit": String(limit)]) }74    /// Current state of the given items, trashed ones included; unknown identifiers are absent from the answer.75    public func items(_ sel: Selection) async throws -> ItemList { try await send("POST", "/sync/items", body: sel) }76    public func item(_ id: String, kind: ItemKind) async throws -> DriveItem? {77        try await items(kind == .file ? Selection(fileIds: [id]) : Selection(folderIds: [id])).all.first78    }7980    // MARK: Content81    /// Request for a file's bytes. `from` resumes a partial download: the `If-Range` condition makes the server send the82    /// whole file again when the content changed meanwhile (the ETag is the SHA-256 of the content).83    public func contentRequest(fileID: String, versionID: String? = nil, from offset: Int64 = 0, etag: String? = nil) throws -> URLRequest {84        var headers: [String: String] = [:]85        if offset > 0 { headers["Range"] = "bytes=\(offset)-"; if let etag { headers["If-Range"] = "\"\(etag)\"" } }86        var r = try request("GET", "/files/\(fileID)/content", query: ["download": "1", "v": versionID], headers: headers)87        r.setValue("*/*", forHTTPHeaderField: "Accept")88        return r89    }90    public func thumbnailRequest(fileID: String) throws -> URLRequest {91        var r = try request("GET", "/files/\(fileID)/preview/thumb"); r.setValue("image/jpeg", forHTTPHeaderField: "Accept"); return r92    }9394    // MARK: Resumable uploads (block level)95    /// Opens an upload. With `fileID` the bytes become a new version of that file; `baseVersionID` is the version they were96    /// derived from, and the server answers `version_conflict` when it is no longer the current one.97    public func createUpload(folderID: String, name: String, size: Int64, onConflict: ConflictPolicy = .rename, fileID: String? = nil, baseVersionID: String? = nil) async throws -> UploadSession {98        struct B: Encodable { var folderId: String; var name: String; var size: Int64; var onConflict: ConflictPolicy; var fileId: String?; var baseVersionId: String? }99        return try await send("POST", "/uploads", body: B(folderId: folderID, name: name, size: size, onConflict: onConflict, fileId: fileID, baseVersionId: baseVersionID))100    }101    public func uploadStatus(_ id: String) async throws -> UploadSession { try await get("/uploads/\(id)") }102    /// Request that appends one block at `offset`. The body is given separately (`upload(for:from:)` or a background upload task from a file).103    public func chunkRequest(uploadID: String, offset: Int64, sha256: String?) throws -> URLRequest {104        var r = try request("PATCH", "/uploads/\(uploadID)", query: ["offset": String(offset)])105        r.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")106        if let sha256 { r.setValue(sha256, forHTTPHeaderField: "X-Chunk-SHA256") }107        return r108    }109    public func completeUpload(_ id: String, sha256: String) async throws -> UploadResult {110        struct B: Encodable { var sha256: String }111        return try await send("POST", "/uploads/\(id)/complete", body: B(sha256: sha256))112    }113    /// Turns a refused new version into a separate file next to the original (the bytes already received are kept).114    public func convertUploadToNewFile(_ id: String, name: String) async throws {115        struct N: Encodable { var name: String }; struct B: Encodable { var asNewFile: N }116        let _: OK = try await send("PATCH", "/uploads/\(id)/options", body: B(asNewFile: N(name: name)))117    }118    public func abortUpload(_ id: String) async throws { let _: OK = try await send("DELETE", "/uploads/\(id)") }119120    // MARK: Versions121    public func restoreVersion(fileID: String, versionID: String) async throws -> DriveItem { try await send("POST", "/files/\(fileID)/versions/\(versionID)/restore") }122    public func deleteVersion(fileID: String, versionID: String) async throws { let _: OK = try await send("DELETE", "/files/\(fileID)/versions/\(versionID)") }123124    // MARK: Share links125    public struct CreatedShare: Decodable, Sendable { public var share: ShareLink; public var url: URL }126    public struct LinkURL: Decodable, Sendable { public var url: URL }127    public func shares(of item: DriveItem? = nil) async throws -> [ShareLink] {128        try await get("/shares", query: ["fileId": item?.isFolder == false ? item?.id : nil, "folderId": item?.isFolder == true ? item?.id : nil])129    }130    private struct ShareBody: Encodable { var settings: ShareSettings; var target: (kind: ItemKind, id: String)?; func encode(to e: Encoder) throws { try settings.encode(to: e, target: target) } }131    /// Creates a link. Its address is returned here and never again: only a hash is kept by the server.132    public func createShare(for item: DriveItem, settings: ShareSettings) async throws -> CreatedShare {133        try await send("POST", "/shares", body: ShareBody(settings: settings, target: (item.kind, item.id)))134    }135    public func updateShare(_ id: String, settings: ShareSettings) async throws -> ShareLink { try await send("PATCH", "/shares/\(id)", body: ShareBody(settings: settings, target: nil)) }136    public func revokeShare(_ id: String, delete: Bool = false) async throws { let _: OK = try await send("DELETE", "/shares/\(id)", query: ["purge": delete ? "1" : nil]) }137    public func rotateShare(_ id: String) async throws -> URL { let r: LinkURL = try await send("POST", "/shares/\(id)/rotate"); return r.url }138    public func shareEvents(_ id: String) async throws -> [ShareAccessEvent] { try await get("/shares/\(id)/events") }139140    // MARK: Deposit portals141    public struct CreatedPortal: Decodable, Sendable { public var request: DepositPortal; public var url: URL }142    public func portals() async throws -> [DepositPortal] { try await get("/requests") }143    public func createPortal(_ settings: PortalSettings) async throws -> CreatedPortal { try await send("POST", "/requests", body: settings) }144    public func updatePortal(_ id: String, _ settings: PortalSettings) async throws -> DepositPortal { try await send("PATCH", "/requests/\(id)", body: settings) }145    public func revokePortal(_ id: String, delete: Bool = false) async throws { let _: OK = try await send("DELETE", "/requests/\(id)", query: ["purge": delete ? "1" : nil]) }146    public func rotatePortal(_ id: String) async throws -> URL { let r: LinkURL = try await send("POST", "/requests/\(id)/rotate"); return r.url }147    public func portalSubmissions(_ id: String) async throws -> [PortalSubmission] { try await get("/requests/\(id)/submissions") }148}149
Files main
Menu

Theme