SPB Git

Repository Public

DriveAPI+Account.swift 9.4 KB 161 lines swift

1// SP Drive iOS2// File: Core/API/DriveAPI+Account.swift3// Description: Account side of the API: sign-in ceremonies (passkey, device linking), sessions, quota, notifications, search, versions.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public struct AccountState: Sendable, Equatable, Decodable {10    public struct User: Sendable, Equatable, Decodable {11        public let id: String; public let email: String; public let displayName: String; public let role: String12        enum CodingKeys: String, CodingKey { case id, email, role; case displayName = "display_name" }13    }14    public struct Quota: Sendable, Equatable, Decodable { public let limit: Int64; public let used: Int64 }15    public let authenticated: Bool16    public let user: User?17    public let quota: Quota?18    public let freshAuth: Bool?19}2021public struct DeviceLink: Sendable, Decodable {22    public let deviceCode: String; public let userCode: String; public let verifyUrl: String; public let expiresInS: Int; public let intervalS: Int23}24public enum DeviceLinkStatus: Sendable, Equatable { case pending, denied, expired, approved }2526public struct SessionInfo: Sendable, Identifiable, Decodable {27    public let id: String; public let createdAt: Date; public let lastSeenAt: Date; public let ip: String; public let userAgent: String28    public let current: Bool; public let kind: String?; public let deviceName: String?29}30public struct PasskeyInfo: Sendable, Identifiable, Decodable {31    public let id: String; public let label: String; public let deviceType: String; public let backedUp: Bool; public let createdAt: Date; public let lastUsedAt: Date?32}33public struct ServerNotification: Sendable, Identifiable {34    public let id: String; public let kind: String; public let read: Bool; public let createdAt: Date; public let data: [String: String]35}36public struct FileVersion: Sendable, Identifiable, Decodable, Hashable {37    public let id: String; public let seq: Int; public let size: Int64; public let sha256: String; public let createdAt: Date; public let note: String; public let current: Bool38}39public struct FileDetail: Sendable {40    public let item: DriveItem41    public let path: [PathCrumb]42    public let shareCount: Int43    public let versions: [FileVersion]44}45public struct PathCrumb: Sendable, Decodable, Hashable, Identifiable { public let id: String; public let name: String }4647public struct SearchQuery: Sendable, Equatable {48    public var text = ""49    /// any, folder, image, pdf, document, sheet, video, audio, archive, text50    public var kind = "any"51    public var starredOnly = false52    public var from: Date?53    public var to: Date?54    public var minSize: Int64?55    public var maxSize: Int64?56    public init() {}57}5859extension DriveAPI {60    // MARK: Session6162    public func accountState() async throws -> AccountState { try decode(AccountState.self, await call("GET", "api/v1/auth/state")) }6364    /// Starts a passkey sign-in: returns the challenge identifier and the WebAuthn options (raw JSON for the system authenticator).65    public func loginOptions() async throws -> (challengeID: String, options: Data) {66        try Self.splitOptions(await call("POST", "api/v1/auth/login/options", authenticated: false))67    }68    /// Finishes the sign-in as a native client: the server opens a device session and its token is stored for all processes.69    public func loginVerify(challengeID: String, response: Data, deviceName: String) async throws {70        let resp = try JSONSerialization.jsonObject(with: response)71        let data = try await call("POST", "api/v1/auth/login/verify", json: ["challengeId": challengeID, "response": resp, "client": ["kind": "native", "name": deviceName]], authenticated: false)72        struct W: Decodable { let token: String? }73        guard let token = try decode(W.self, data).token else { throw RemoteError.server(status: 200, code: "no_token", message: "le serveur n’a pas ouvert de session d’appareil") }74        tokens.setToken(token)75    }7677    public func deviceLinkStart(name: String) async throws -> DeviceLink { try decode(DeviceLink.self, await call("POST", "api/v1/auth/device/start", json: ["name": name], authenticated: false)) }78    /// Polls a device link. On approval the token is stored and `.approved` returned.79    public func deviceLinkPoll(deviceCode: String) async throws -> DeviceLinkStatus {80        struct W: Decodable { let status: String; let token: String? }81        let w = try decode(W.self, await call("POST", "api/v1/auth/device/poll", json: ["deviceCode": deviceCode], authenticated: false))82        switch w.status {83        case "approved": if let t = w.token { tokens.setToken(t); return .approved }; return .expired84        case "denied": return .denied85        case "pending": return .pending86        default: return .expired87        }88    }8990    /// Revokes the device session on the server (best effort) and forgets the token on this device (always).91    public func logout() async {92        if tokens.token() != nil { _ = try? await call("POST", "api/v1/auth/logout") }93        tokens.setToken(nil)94    }9596    public func reauthOptions() async throws -> (challengeID: String, options: Data) { try Self.splitOptions(await call("POST", "api/v1/auth/reauth/options")) }97    public func reauthVerify(challengeID: String, response: Data) async throws {98        _ = try await call("POST", "api/v1/auth/reauth/verify", json: ["challengeId": challengeID, "response": try JSONSerialization.jsonObject(with: response)])99    }100    public func addPasskeyOptions() async throws -> (challengeID: String, options: Data) { try Self.splitOptions(await call("POST", "api/v1/account/passkeys/options")) }101    public func addPasskeyVerify(challengeID: String, response: Data, label: String) async throws {102        _ = try await call("POST", "api/v1/account/passkeys/verify", json: ["challengeId": challengeID, "response": try JSONSerialization.jsonObject(with: response), "label": label])103    }104105    static func splitOptions(_ data: Data) throws -> (challengeID: String, options: Data) {106        guard let o = try JSONSerialization.jsonObject(with: data) as? [String: Any], let id = o["challengeId"] as? String, let opt = o["options"] else {107            throw RemoteError.server(status: 200, code: "decode", message: "réponse inattendue du serveur")108        }109        return (id, try JSONSerialization.data(withJSONObject: opt))110    }111112    public func sessions() async throws -> [SessionInfo] { try decode([SessionInfo].self, await call("GET", "api/v1/account/sessions")) }113    public func revokeSession(id: String) async throws { _ = try await call("DELETE", "api/v1/account/sessions/\(id)") }114    public func passkeys() async throws -> [PasskeyInfo] { try decode([PasskeyInfo].self, await call("GET", "api/v1/account/passkeys")) }115116    // MARK: Notifications117118    public func notifications() async throws -> [ServerNotification] {119        let raw = try JSONSerialization.jsonObject(with: await call("GET", "api/v1/notifications")) as? [[String: Any]] ?? []120        return raw.compactMap { n in121            guard let id = n["id"] as? String, let kind = n["kind"] as? String, let at = (n["createdAt"] as? String).flatMap(Self.parseDate) else { return nil }122            var data: [String: String] = [:]123            for (k, v) in n["data"] as? [String: Any] ?? [:] { data[k] = (v as? String) ?? (v as? NSNumber)?.stringValue }124            return ServerNotification(id: id, kind: kind, read: n["read"] as? Bool ?? false, createdAt: at, data: data)125        }126    }127    public func markNotificationsRead(ids: [String]? = nil) async throws {128        _ = try await call("POST", "api/v1/notifications/read", json: ids.map { ["ids": $0] } ?? [:])129    }130131    // MARK: Search and details132133    struct ListingWire: Decodable { let folders: [ItemWire]; let files: [ItemWire] }134135    public func search(_ q: SearchQuery) async throws -> [DriveItem] {136        let day = Date.ISO8601FormatStyle().year().month().day()137        let w = try decode(ListingWire.self, await call("GET", "api/v1/search", query: [138            "q": q.text, "kind": q.kind, "starred": q.starredOnly ? "1" : nil, "from": q.from.map { $0.formatted(day) }, "to": q.to.map { $0.formatted(day) },139            "minSize": q.minSize.map(String.init), "maxSize": q.maxSize.map(String.init),140        ]))141        return (w.folders + w.files).map(\.item)142    }143144    /// Sub-folders of a folder, straight from the server (folder pickers in the extensions, which keep no mirror).145    public func subfolders(of id: String) async throws -> [DriveItem] {146        struct W: Decodable { let children: [ItemWire] }147        return try decode(W.self, await call("GET", "api/v1/folders/\(id)/children")).children.map(\.item)148    }149150    public func fileDetail(id: String) async throws -> FileDetail {151        struct W: Decodable { let file: ItemWire; let path: [PathCrumb]; let shares: Int; let versions: [FileVersion] }152        let w = try decode(W.self, await call("GET", "api/v1/files/\(id)"))153        return FileDetail(item: w.file.item, path: w.path, shareCount: w.shares, versions: w.versions)154    }155    /// Restoring a version creates a new one with the old content: nothing is lost.156    public func restoreVersion(fileID: String, versionID: String) async throws -> DriveItem {157        try decode(ItemWire.self, await call("POST", "api/v1/files/\(fileID)/versions/\(versionID)/restore")).item158    }159    public func deleteVersion(fileID: String, versionID: String) async throws { _ = try await call("DELETE", "api/v1/files/\(fileID)/versions/\(versionID)") }160}161
Files main
Menu

Theme