Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Drive pour iPhone et iPad9// File : Core/API/DriveAPI.swift10// Description : HTTP client of the SP Drive API on MacLustr (device11// session by bearer token). Transport, error mapping and the12// operations of `DriveRemote`; account, sharing and13// deposit-link calls are in DriveAPI+Account/+Sharing.14// Module : Core15// Repository : https://git.spboucher.ai/sp-drive-ios16// Created : 2026-11-1917// Last Modified : 2026-11-1918//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation9293public final class DriveAPI: DriveRemote, Sendable {94 public let baseURL: URL95 public let tokens: TokenStore96 let session: URLSession97 public static let userAgent: String = {98 let v = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "dev"99 return "SPDrive-iOS/\(v)"100 }()101102 /// `X-SPD-Client: <platform>/<app version> (<os version>)` — the 2.0 server shows it on the devices dashboard; a 1.0 server ignores it.103 public static let clientHeader: String = {104 let v = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "dev"105 let os = ProcessInfo.processInfo.operatingSystemVersion106 #if os(iOS)107 // the extensions cannot ask UIKit for the idiom: the device model says it108 var info = utsname(); uname(&info)109 let machine = withUnsafeBytes(of: &info.machine) { String(decoding: $0.prefix { $0 != 0 }, as: UTF8.self) }110 let simulated = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] ?? machine111 let platform = simulated.hasPrefix("iPad") ? "ipados" : "ios"112 #else113 let platform = "macos"114 #endif115 return "\(platform)/\(v) (\(os.majorVersion).\(os.minorVersion).\(os.patchVersion))"116 }()117118 public init(baseURL: URL = AppGroup.baseURL, tokens: TokenStore, configuration: URLSessionConfiguration? = nil) {119 self.baseURL = baseURL120 self.tokens = tokens121 let c = configuration ?? {122 let c = URLSessionConfiguration.ephemeral123 c.httpCookieStorage = nil124 c.httpShouldSetCookies = false125 c.urlCache = nil126 c.timeoutIntervalForRequest = 30127 c.timeoutIntervalForResource = 3600128 c.waitsForConnectivity = false129 c.httpAdditionalHeaders = ["User-Agent": DriveAPI.userAgent]130 return c131 }()132 session = URLSession(configuration: c)133 }134135 public var isSignedIn: Bool { tokens.token() != nil }136137 // MARK: Transport138139 /// Builds an authenticated request. Throws `.unauthenticated` when no session exists and one is needed.140 public func makeRequest(_ method: String, _ path: String, query: [String: String?] = [:], authenticated: Bool = true) throws -> URLRequest {141 var comps = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false)!142 let items = query.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }143 if !items.isEmpty { comps.queryItems = items }144 // `+` must not reach the server as a space145 comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")146 var r = URLRequest(url: comps.url!)147 r.httpMethod = method148 r.setValue(DriveAPI.userAgent, forHTTPHeaderField: "User-Agent")149 r.setValue(DriveAPI.clientHeader, forHTTPHeaderField: "X-SPD-Client")150 r.setValue("application/json", forHTTPHeaderField: "Accept")151 if authenticated {152 guard let t = tokens.token() else { throw RemoteError.unauthenticated }153 r.setValue("Bearer \(t)", forHTTPHeaderField: "Authorization")154 } else {155 // Unauthenticated state-changing calls (sign-in ceremonies) carry the header the server's CSRF guard asks of non-bearer requests.156 r.setValue("1", forHTTPHeaderField: "X-SPD-CSRF")157 }158 return r159 }160161 @discardableResult162 public func send(_ request: URLRequest, body: Data? = nil) async throws -> Data {163 var request = request164 if let body { request.httpBody = body; request.setValue("application/json", forHTTPHeaderField: "Content-Type") }165 let data: Data, response: URLResponse166 do { (data, response) = try await session.data(for: request) } catch { throw Self.transportError(error) }167 guard let http = response as? HTTPURLResponse else { throw RemoteError.offline }168 guard (200..<300).contains(http.statusCode) else { throw mapError(status: http.statusCode, body: data, authenticated: request.value(forHTTPHeaderField: "Authorization") != nil) }169 return data170 }171172 func call(_ method: String, _ path: String, query: [String: String?] = [:], json: [String: Any]? = nil, authenticated: Bool = true) async throws -> Data {173 let r = try makeRequest(method, path, query: query, authenticated: authenticated)174 let body = try json.map { try JSONSerialization.data(withJSONObject: $0) } ?? (method == "GET" || method == "DELETE" ? nil : Data("{}".utf8))175 return try await send(r, body: body)176 }177178 func decode<T: Decodable>(_ type: T.Type = T.self, _ data: Data) throws -> T {179 do { return try Self.decoder.decode(T.self, from: data) } catch { throw RemoteError.server(status: 200, code: "decode", message: "réponse inattendue du serveur") }180 }181182 static let decoder: JSONDecoder = {183 let d = JSONDecoder()184 d.dateDecodingStrategy = .custom { dec in185 let s = try dec.singleValueContainer().decode(String.self)186 if let date = DriveAPI.parseDate(s) { return date }187 throw DecodingError.dataCorrupted(.init(codingPath: dec.codingPath, debugDescription: "date"))188 }189 return d190 }()191192 static func parseDate(_ s: String) -> Date? {193 (try? Date.ISO8601FormatStyle(includingFractionalSeconds: true).parse(s)) ?? (try? Date.ISO8601FormatStyle().parse(s))194 }195 static func isoString(_ d: Date) -> String { d.formatted(Date.ISO8601FormatStyle(includingFractionalSeconds: true)) }196197 static func transportError(_ error: Error) -> Error {198 if error is CancellationError { return error }199 if let u = error as? URLError, u.code == .cancelled { return CancellationError() }200 return RemoteError.offline201 }202203 public func error(status: Int, body: Data) -> RemoteError { mapError(status: status, body: body, authenticated: true) }204205 func mapError(status: Int, body: Data, authenticated: Bool) -> RemoteError {206 let o = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]207 let code = o["error"] as? String ?? ""208 let message = o["message"] as? String ?? HTTPURLResponse.localizedString(forStatusCode: status)209 switch (status, code) {210 case (401, "unauthenticated"):211 // the server no longer knows this session: forget it so every process stops using it212 if authenticated { tokens.setToken(nil) }213 return .unauthenticated214 case (404, _): return .notFound215 case (409, "name_conflict"): return .nameConflict(name: o["name"] as? String ?? "")216 case (409, "version_conflict"): return .versionConflict217 case (409, "offset_mismatch"): return .offsetMismatch(received: (o["received"] as? NSNumber)?.int64Value ?? 0)218 case (409, "upload_closed"), (410, "upload_closed"): return .uploadClosed219 case (413, "quota_exceeded"): return .quotaExceeded220 case (413, "file_too_large"): return .fileTooLarge221 case (422, "chunk_corrupt"), (422, "checksum_mismatch"): return .checksumMismatch222 case (451, _): return .infected223 case (429, _): return .rateLimited(retryAfter: (o["retryAfterS"] as? NSNumber)?.intValue ?? 30)224 default: return .server(status: status, code: code, message: message)225 }226 }227228 // MARK: Change feed229230 struct ChangesWire: Decodable {231 struct Gone: Decodable { let id: String }232 let items: [ItemWire]; let deleted: [Gone]; let cursor: Int64; let more: Bool; let head: Int64; let rootId: String233 }234235 public func rootID() async throws -> String {236 struct W: Decodable { let rootId: String }237 return try decode(W.self, await call("GET", "api/v1/sync/cursor")).rootId238 }239240 /// Server head revision and root folder.241 public func cursor() async throws -> (head: Int64, rootID: String) {242 struct W: Decodable { let head: Int64; let rootId: String }243 let w = try decode(W.self, await call("GET", "api/v1/sync/cursor"))244 return (w.head, w.rootId)245 }246247 public func changes(since: Int64, limit: Int) async throws -> ChangePage {248 let w = try decode(ChangesWire.self, await call("GET", "api/v1/sync/changes", query: ["since": String(since), "limit": String(limit)]))249 // a cursor ahead of the server (server restored from a backup): the caller starts over250 if since > w.head { return ChangePage(items: [], deleted: [], cursor: -1, more: true) }251 return ChangePage(items: w.items.map(\.item), deleted: w.deleted.map(\.id), cursor: w.cursor, more: w.more)252 }253254 public func item(id: String, isFolder: Bool) async throws -> DriveItem {255 struct W: Decodable { let folders: [ItemWire]; let files: [ItemWire] }256 let w = try decode(W.self, await call("POST", "api/v1/sync/items", json: isFolder ? ["folderIds": [id]] : ["fileIds": [id]]))257 guard let i = (w.folders + w.files).first else { throw RemoteError.notFound }258 return i.item259 }260261 // MARK: Tree262263 public func createFolder(parentID: String, name: String, onConflict: NameConflictPolicy) async throws -> DriveItem {264 try decode(ItemWire.self, await call("POST", "api/v1/folders", json: ["parentId": parentID, "name": name, "onConflict": onConflict.rawValue])).item265 }266 public func rename(id: String, isFolder: Bool, name: String) async throws -> DriveItem {267 try decode(ItemWire.self, await call("PATCH", "api/v1/\(isFolder ? "folders" : "files")/\(id)", json: ["name": name])).item268 }269 public func setStarred(id: String, isFolder: Bool, starred: Bool) async throws -> DriveItem {270 try decode(ItemWire.self, await call("PATCH", "api/v1/\(isFolder ? "folders" : "files")/\(id)", json: ["starred": starred])).item271 }272 public func move(fileIDs: [String], folderIDs: [String], to destinationID: String, onConflict: NameConflictPolicy) async throws {273 _ = try await call("POST", "api/v1/move", json: ["fileIds": fileIDs, "folderIds": folderIDs, "destinationId": destinationID, "onConflict": onConflict.rawValue])274 }275 public func copy(fileIDs: [String], folderIDs: [String], to destinationID: String) async throws {276 _ = try await call("POST", "api/v1/copy", json: ["fileIds": fileIDs, "folderIds": folderIDs, "destinationId": destinationID])277 }278 public func trash(fileIDs: [String], folderIDs: [String]) async throws { _ = try await call("POST", "api/v1/trash", json: ["fileIds": fileIDs, "folderIds": folderIDs]) }279 public func restore(fileIDs: [String], folderIDs: [String]) async throws { _ = try await call("POST", "api/v1/restore", json: ["fileIds": fileIDs, "folderIds": folderIDs]) }280 public func purge(fileIDs: [String], folderIDs: [String]) async throws { _ = try await call("POST", "api/v1/purge", json: ["fileIds": fileIDs, "folderIds": folderIDs]) }281 public func emptyTrash() async throws { _ = try await call("POST", "api/v1/purge", json: ["all": true]) }282283 // MARK: Uploads284285 struct UploadWire: Decodable {286 let id: String; let size: Int64; let received: Int64; let status: String; let fileId: String?; let file: ItemWire?287 var upload: RemoteUpload { RemoteUpload(id: id, size: size, received: received, status: status, fileID: fileId) }288 }289290 public func createUpload(parentID: String, name: String, size: Int64, onConflict: NameConflictPolicy, fileID: String?, baseVersionID: String?) async throws -> RemoteUpload {291 var body: [String: Any] = ["folderId": parentID, "name": name, "size": size, "onConflict": onConflict.rawValue]292 if let fileID { body["fileId"] = fileID }293 if let baseVersionID, fileID != nil { body["baseVersionId"] = baseVersionID }294 return try decode(UploadWire.self, await call("POST", "api/v1/uploads", json: body)).upload295 }296 public func uploadStatus(id: String) async throws -> RemoteUpload { try decode(UploadWire.self, await call("GET", "api/v1/uploads/\(id)")).upload }297298 public func chunkRequest(uploadID: String, offset: Int64, sha256: String) async throws -> URLRequest {299 var r = try makeRequest("PATCH", "api/v1/uploads/\(uploadID)", query: ["offset": String(offset)])300 r.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")301 r.setValue(sha256, forHTTPHeaderField: "X-Chunk-SHA256")302 r.timeoutInterval = 300303 return r304 }305 public func sendChunk(uploadID: String, offset: Int64, sha256: String, fileURL: URL) async throws -> RemoteUpload {306 let r = try await chunkRequest(uploadID: uploadID, offset: offset, sha256: sha256)307 let data: Data, response: URLResponse308 do { (data, response) = try await session.upload(for: r, fromFile: fileURL) } catch { throw Self.transportError(error) }309 guard let http = response as? HTTPURLResponse else { throw RemoteError.offline }310 guard (200..<300).contains(http.statusCode) else { throw mapError(status: http.statusCode, body: data, authenticated: true) }311 return try decode(UploadWire.self, data).upload312 }313 public func decodeUpload(_ body: Data) throws -> RemoteUpload { try decode(UploadWire.self, body).upload }314315 public func completeUpload(id: String, sha256: String) async throws -> DriveItem {316 var r = try makeRequest("POST", "api/v1/uploads/\(id)/complete")317 r.timeoutInterval = 600 // the server re-hashes and seals the whole file318 let w = try decode(UploadWire.self, await send(r, body: JSONSerialization.data(withJSONObject: ["sha256": sha256])))319 guard let f = w.file else { throw RemoteError.server(status: 200, code: "decode", message: "réponse inattendue du serveur") }320 return f.item321 }322 public func abortUpload(id: String) async throws { _ = try await call("DELETE", "api/v1/uploads/\(id)") }323 /// Turns a refused new version into a separate file next to the original (conflict copy); the bytes already sent are kept.324 public func convertUploadToNewFile(id: String, name: String) async throws {325 _ = try await call("PATCH", "api/v1/uploads/\(id)/options", json: ["asNewFile": ["name": name]])326 }327328 // MARK: Downloads329330 public func contentRequest(fileID: String, versionID: String?, offset: Int64, etag: String?) async throws -> URLRequest {331 var r = try makeRequest("GET", "api/v1/files/\(fileID)/content", query: ["download": "1", "v": versionID])332 r.setValue("*/*", forHTTPHeaderField: "Accept")333 if offset > 0 {334 r.setValue("bytes=\(offset)-", forHTTPHeaderField: "Range")335 if let etag { r.setValue("\"\(etag)\"", forHTTPHeaderField: "If-Range") }336 }337 return r338 }339 public func thumbnailRequest(fileID: String) async throws -> URLRequest {340 var r = try makeRequest("GET", "api/v1/files/\(fileID)/preview/thumb")341 r.setValue("image/jpeg", forHTTPHeaderField: "Accept")342 return r343 }344345 /// Raw bytes of a small resource (thumbnails). 202 (not ready yet) and 404 return nil.346 public func fetchSmall(_ request: URLRequest) async throws -> Data? {347 let data: Data, response: URLResponse348 do { (data, response) = try await session.data(for: request) } catch { throw Self.transportError(error) }349 guard let http = response as? HTTPURLResponse else { throw RemoteError.offline }350 if http.statusCode == 200 { return data }351 if [202, 404, 422].contains(http.statusCode) { return nil }352 throw mapError(status: http.statusCode, body: data, authenticated: true)353 }354355 /// Downloads a response body into a file (foreground download, used by the File Provider and share extensions). When `append` is set and356 /// the server answered 206, the bytes are appended to what `destination` already holds; a 200 answer replaces the file. Returns the final size.357 public func download(_ request: URLRequest, to destination: URL, append: Bool, progress: (@Sendable (Int64) -> Void)? = nil) async throws -> Int64 {358 let tmp: URL, response: URLResponse359 do { (tmp, response) = try await session.download(for: request, delegate: progress.map(DownloadProgress.init)) } catch { throw Self.transportError(error) }360 defer { try? FileManager.default.removeItem(at: tmp) }361 guard let http = response as? HTTPURLResponse else { throw RemoteError.offline }362 guard http.statusCode == 200 || http.statusCode == 206 else {363 let body = (try? Data(contentsOf: tmp, options: .mappedIfSafe).prefix(8192)).map { Data($0) } ?? Data()364 throw mapError(status: http.statusCode, body: body, authenticated: true)365 }366 let fm = FileManager.default367 if append, http.statusCode == 206, fm.fileExists(atPath: destination.path) {368 let out = try FileHandle(forWritingTo: destination)369 defer { try? out.close() }370 try out.seekToEnd()371 let input = try FileHandle(forReadingFrom: tmp)372 defer { try? input.close() }373 while let chunk = try input.read(upToCount: 1 << 20), !chunk.isEmpty { try out.write(contentsOf: chunk) }374 } else {375 try? fm.removeItem(at: destination)376 try fm.moveItem(at: tmp, to: destination)377 }378 return (try fm.attributesOfItem(atPath: destination.path)[.size] as? NSNumber)?.int64Value ?? 0379 }380}381382private final class DownloadProgress: NSObject, URLSessionDownloadDelegate, Sendable {383 let report: @Sendable (Int64) -> Void384 init(_ report: @escaping @Sendable (Int64) -> Void) { self.report = report }385 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { report(totalBytesWritten) }386 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {}387}388389/// A file or folder as the API sends it.390struct ItemWire: Decodable {391 let id: String; let type: String; let name: String392 let parentId: String?; let folderId: String?393 let size: Int64?; let sha256: String?; let starred: Bool?394 let createdAt: Date; let updatedAt: Date; let trashedAt: Date?; let trashRoot: Bool?395 let rev: Int64?; let versionId: String?; let versionSeq: Int?; let versions: Int?; let scan: String?; let thumb: Bool?396397 var item: DriveItem {398 let folder = type == "folder"399 return DriveItem(id: id, isFolder: folder, parentID: folder ? parentId : folderId, name: name, size: size ?? 0, sha256: sha256 ?? "", versionID: versionId, versionSeq: versionSeq ?? 1,400 versionCount: versions ?? 1, rev: rev ?? 0, createdAt: createdAt, updatedAt: updatedAt, trashedAt: trashedAt, trashRoot: trashRoot ?? false, starred: starred ?? false,401 scan: folder ? "clean" : (scan ?? "pending"), hasThumbnail: thumb ?? false)402 }403}404