Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Next/Models.swift3// Description: SPDriveNext — value types of the SP Drive 2.0 API, as the server sends them (API-NEXT.md §2–§8). Decoding is tolerant: a field the server omits in one context (shared files, uploader answers) is optional here.4import Foundation56// MARK: Files and folders (the 1.0 objects, plus what 2.0 adds around them)7public struct SearchMatch: Codable, Sendable, Hashable {8 /// name | content | both9 public var `where`: String10 /// Plain text; matched words are wrapped in ⟦ ⟧ (U+27E6 / U+27E7). Present for content and both.11 public var snippet: String?12 public var page: Int?13 /// The snippet cut at its markers: (text, isMatch) runs, for display with highlights.14 public var snippetRuns: [(text: String, matched: Bool)] {15 guard let snippet else { return [] }16 var runs: [(String, Bool)] = [], current = "", inside = false17 for ch in snippet {18 if ch == "⟦" { if !current.isEmpty { runs.append((current, inside)) }; current = ""; inside = true }19 else if ch == "⟧" { if !current.isEmpty { runs.append((current, inside)) }; current = ""; inside = false }20 else { current.append(ch) }21 }22 if !current.isEmpty { runs.append((current, inside)) }23 return runs24 }25}26public struct NextFile: Codable, Sendable, Identifiable, Hashable {27 public var id: String28 public var name: String29 public var folderId: String?30 public var size: Int6431 public var sha256: String?32 /// How the server previews it: image, pdf, video, audio, text, office, heic, archive, sheet, none…33 public var kind: String?34 public var starred: Bool35 public var createdAt: Date?36 public var updatedAt: Date?37 public var contentAt: Date?38 public var trashedAt: Date?39 public var scan: String?40 public var thumb: Bool41 public var tagIds: [String]42 public var versions: Int?43 public var rev: Int64?44 public var versionId: String?45 public var versionSeq: Int?46 /// Search results only.47 public var match: SearchMatch?48 /// `duplicates?mode=similar-images` only: 64-bit difference hash, hexadecimal.49 public var dhash: String?50 public var modified: Date? { contentAt ?? updatedAt }51 public var fileExtension: String { let e = (name as NSString).pathExtension; return e.lowercased() }52 enum K: String, CodingKey { case id, name, folderId, size, sha256, kind, starred, createdAt, updatedAt, contentAt, trashedAt, scan, thumb, tagIds, versions, rev, versionId, versionSeq, match, dhash }53 public init(from decoder: Decoder) throws {54 let c = try decoder.container(keyedBy: K.self)55 id = try c.decode(String.self, forKey: .id); name = try c.decode(String.self, forKey: .name)56 folderId = try c.decodeIfPresent(String.self, forKey: .folderId); size = try c.decodeIfPresent(Int64.self, forKey: .size) ?? 057 sha256 = try c.decodeIfPresent(String.self, forKey: .sha256); kind = try c.decodeIfPresent(String.self, forKey: .kind)58 starred = try c.decodeIfPresent(Bool.self, forKey: .starred) ?? false59 createdAt = try c.decodeIfPresent(Date.self, forKey: .createdAt); updatedAt = try c.decodeIfPresent(Date.self, forKey: .updatedAt)60 contentAt = try c.decodeIfPresent(Date.self, forKey: .contentAt); trashedAt = try c.decodeIfPresent(Date.self, forKey: .trashedAt)61 scan = try c.decodeIfPresent(String.self, forKey: .scan); thumb = try c.decodeIfPresent(Bool.self, forKey: .thumb) ?? false62 tagIds = try c.decodeIfPresent([String].self, forKey: .tagIds) ?? []; versions = try c.decodeIfPresent(Int.self, forKey: .versions)63 rev = try c.decodeIfPresent(Int64.self, forKey: .rev); versionId = try c.decodeIfPresent(String.self, forKey: .versionId)64 versionSeq = try c.decodeIfPresent(Int.self, forKey: .versionSeq); match = try c.decodeIfPresent(SearchMatch.self, forKey: .match)65 dhash = try c.decodeIfPresent(String.self, forKey: .dhash)66 }67}68public struct NextFolder: Codable, Sendable, Identifiable, Hashable {69 public var id: String70 public var name: String71 /// nil for the account's root, and for the granted folder seen through a grant.72 public var parentId: String?73 public var starred: Bool74 public var createdAt: Date?75 public var updatedAt: Date?76 public var trashedAt: Date?77 public var rev: Int64?78 /// A shared folder with a name of its own ("workspace").79 public var workspaceName: String?80 /// Grant routes only: true for the folder the grant was given on.81 public var isGrantRoot: Bool?82 public var match: SearchMatch?83 public var displayName: String { workspaceName?.isEmpty == false ? workspaceName! : name }84 enum K: String, CodingKey { case id, name, parentId, starred, createdAt, updatedAt, trashedAt, rev, workspaceName, isGrantRoot, match }85 public init(from decoder: Decoder) throws {86 let c = try decoder.container(keyedBy: K.self)87 id = try c.decode(String.self, forKey: .id); name = try c.decodeIfPresent(String.self, forKey: .name) ?? ""88 parentId = try c.decodeIfPresent(String.self, forKey: .parentId); starred = try c.decodeIfPresent(Bool.self, forKey: .starred) ?? false89 createdAt = try c.decodeIfPresent(Date.self, forKey: .createdAt); updatedAt = try c.decodeIfPresent(Date.self, forKey: .updatedAt)90 trashedAt = try c.decodeIfPresent(Date.self, forKey: .trashedAt); rev = try c.decodeIfPresent(Int64.self, forKey: .rev)91 workspaceName = try c.decodeIfPresent(String.self, forKey: .workspaceName); isGrantRoot = try c.decodeIfPresent(Bool.self, forKey: .isGrantRoot)92 match = try c.decodeIfPresent(SearchMatch.self, forKey: .match)93 }94}95public struct NextCrumb: Codable, Sendable, Hashable, Identifiable { public var id: String; public var name: String; public init(id: String, name: String) { self.id = id; self.name = name } }9697// MARK: §2 Capabilities, sessions98public struct ServerMeta: Codable, Sendable, Equatable {99 public var api: Int100 public var version: String101 public var features: [String]102 public init(api: Int, version: String, features: [String]) { self.api = api; self.version = version; self.features = features }103 /// What a 1.0 server (404 on /meta) amounts to.104 public static let v1 = ServerMeta(api: 1, version: "1", features: [])105 public func has(_ feature: Feature) -> Bool { features.contains(feature.rawValue) }106 public enum Feature: String, Sendable, CaseIterable {107 case events, contentSearch = "content-search", ocr, semantic, ai, collab, collections, activity, storage, similarImages = "similar-images", uploadHistory = "upload-history"108 }109}110public struct ClientInfo: Codable, Sendable, Hashable { public var platform: String; public var version: String; public var os: String? }111public struct NextSession: Codable, Sendable, Identifiable, Hashable {112 public var id: String; public var createdAt: Date; public var lastSeenAt: Date; public var ip: String; public var userAgent: String; public var method: String113 public var kind: String?; public var deviceName: String?; public var current: Bool114 /// nil for web sessions and for devices that never sent `X-SPD-Client`.115 public var client: ClientInfo?116}117public struct AccountPatch: Encodable, Sendable {118 public var displayName: String?; public var locale: String?; public var aiExternal: Bool?119 public init(displayName: String? = nil, locale: String? = nil, aiExternal: Bool? = nil) { self.displayName = displayName; self.locale = locale; self.aiExternal = aiExternal }120}121122// MARK: §3 Sync events123public enum SyncEvent: Sendable, Equatable {124 case hello(head: Int64)125 case change(head: Int64)126 case notify(kind: String)127}128129// MARK: §4 Search130public enum SearchScope: String, Sendable { case name, content, all }131public struct SearchParameters: Sendable {132 public var q: String133 public var scope = SearchScope.all134 /// any, image, pdf, document, sheet, video, audio, archive, text, folder135 public var kind: String?136 public var starred: Bool?137 public var from: Date?; public var to: Date?138 public var minSize: Int64?; public var maxSize: Int64?139 public var sort: String?; public var dir: String?140 public init(q: String, scope: SearchScope = .all) { self.q = q; self.scope = scope }141}142public struct SearchResults: Codable, Sendable { public var folders: [NextFolder]; public var files: [NextFile] }143public struct SemanticHit: Codable, Sendable, Identifiable {144 public struct Passage: Codable, Sendable, Hashable { public var text: String; public var page: Int? }145 public var file: NextFile146 /// Cosine in [-1, 1]. Only the ORDER of hits means something: never show it, never threshold on it (API-NEXT §4.4).147 public var score: Double148 public var passage: Passage149 public var id: String { file.id }150}151public struct SemanticResults: Codable, Sendable { public var available: Bool; public var hits: [SemanticHit] }152public struct FileTextStatus: Codable, Sendable, Equatable {153 /// pending | ready | empty | unsupported | failed154 public var status: String155 public var source: String?156 public var pages: Int?; public var chars: Int?157 public var excerpt: String?158 public var error: String?159}160public struct IndexStatus: Codable, Sendable, Equatable {161 public struct Content: Codable, Sendable, Equatable { public var enabled: Bool?; public var ready: Int; public var pending: Int; public var failed: Int; public var unsupported: Int; public var empty: Int? }162 public struct Semantic: Codable, Sendable, Equatable { public var available: Bool; public var model: String?; public var embedded: Int? }163 public var content: Content; public var semantic: Semantic164}165166// MARK: §5 Document intelligence167public struct AIModel: Codable, Sendable, Hashable, Identifiable {168 public var id: String; public var label: String169 /// Who made the model — distinct from the provider, which is the route to it.170 public var creator: String?171}172public struct AIProvider: Codable, Sendable, Hashable, Identifiable {173 public var id: String; public var label: String174 public var local: Bool; public var configured: Bool175 /// configured and (local, or external providers allowed by both the server and the account).176 public var usable: Bool?177 public var models: [AIModel]178}179public struct AIProviders: Codable, Sendable, Equatable {180 public struct Choice: Codable, Sendable, Hashable { public var provider: String; public var model: String; public init(provider: String, model: String) { self.provider = provider; self.model = model } }181 public struct External: Codable, Sendable, Hashable { public var server: Bool; public var account: Bool }182 /// At least one provider is usable by this account.183 public var enabled: Bool184 public var externalAllowed: Bool185 public var external: External?186 public var `default`: Choice?187 public var providers: [AIProvider]188}189public enum AIScope: Sendable, Equatable { case files([String]), folder(String), all }190public struct AITurn: Codable, Sendable, Hashable { public var role: String; public var content: String; public init(role: String, content: String) { self.role = role; self.content = content } }191public struct AIAskRequest: Encodable, Sendable {192 public var scope: AIScope; public var question: String; public var provider: String?; public var model: String?; public var history: [AITurn]?193 public init(scope: AIScope, question: String, provider: String? = nil, model: String? = nil, history: [AITurn]? = nil) { self.scope = scope; self.question = question; self.provider = provider; self.model = model; self.history = history }194 enum K: String, CodingKey { case scope, question, provider, model, history }195 enum S: String, CodingKey { case fileIds, folderId, all }196 public func encode(to encoder: Encoder) throws {197 var c = encoder.container(keyedBy: K.self)198 var s = c.nestedContainer(keyedBy: S.self, forKey: .scope)199 switch scope { case .files(let ids): try s.encode(ids, forKey: .fileIds); case .folder(let id): try s.encode(id, forKey: .folderId); case .all: try s.encode(true, forKey: .all) }200 try c.encode(question, forKey: .question); try c.encodeIfPresent(provider, forKey: .provider); try c.encodeIfPresent(model, forKey: .model)201 if let history, !history.isEmpty { try c.encode(history, forKey: .history) }202 }203}204public struct AISource: Codable, Sendable, Hashable, Identifiable {205 /// What `[n]` in the answer refers to; starts at 1.206 public var n: Int; public var fileId: String; public var name: String; public var page: Int?; public var text: String207 public var id: Int { n }208}209public struct AIUnindexed: Codable, Sendable, Hashable { public var fileId: String; public var name: String; public var status: String }210public struct AIDone: Codable, Sendable, Equatable {211 public struct Usage: Codable, Sendable, Equatable { public var inputTokens: Int?; public var outputTokens: Int? }212 /// true: nothing in the scope matched the question; no model was called.213 public var empty: Bool?214 public var provider: String?; public var model: String?; public var usage: Usage?; public var stopReason: String?215 public init(empty: Bool? = nil, provider: String? = nil, model: String? = nil, usage: Usage? = nil, stopReason: String? = nil) { self.empty = empty; self.provider = provider; self.model = model; self.usage = usage; self.stopReason = stopReason }216}217/// The events of one streamed answer, in order: optional notice, sources (once), deltas, then done or error.218public enum AIEvent: Sendable, Equatable {219 case notice(unindexed: [AIUnindexed])220 case sources([AISource])221 case delta(String)222 case done(AIDone)223 /// provider_auth, provider_unreachable, provider_unavailable, provider_rate_limited, provider_refused, model_unknown, provider_error224 case error(code: String, message: String)225}226public struct AISuggestion: Codable, Sendable, Hashable, Identifiable {227 public struct Folder: Codable, Sendable, Hashable { public var id: String; public var path: String }228 public var fileId: String; public var name: String?; public var tags: [String]?; public var folder: Folder?; public var category: String?; public var reason: String?229 public var id: String { fileId }230}231public struct AISuggestions: Codable, Sendable { public var provider: String?; public var model: String?; public var suggestions: [AISuggestion] }232233// MARK: §6 Private sharing234public enum GrantRole: String, Codable, Sendable, CaseIterable, Identifiable {235 case viewer, editor, uploader236 public var id: String { rawValue }237 public var canList: Bool { self != .uploader }238 public var canWrite: Bool { self == .editor }239 public var canUpload: Bool { self != .viewer }240}241public struct ResolvedUser: Codable, Sendable, Hashable { public var userId: String; public var displayName: String }242public struct FolderMember: Codable, Sendable, Hashable, Identifiable {243 public var grantId: String; public var userId: String; public var displayName: String; public var email: String?; public var role: GrantRole; public var createdAt: Date?244 public var id: String { userId }245}246public struct FolderMembers: Codable, Sendable { public var folder: NextFolder; public var members: [FolderMember] }247public struct OutgoingShare: Codable, Sendable, Identifiable { public var folder: NextFolder; public var members: Int; public var id: String { folder.id } }248public struct SharedGrant: Codable, Sendable, Hashable, Identifiable {249 public struct Owner: Codable, Sendable, Hashable { public var displayName: String }250 public struct Folder: Codable, Sendable, Hashable { public var id: String; public var name: String; public var workspaceName: String?; public var updatedAt: Date? }251 public var grantId: String; public var role: GrantRole; public var owner: Owner; public var folder: Folder; public var createdAt: Date?252 public var id: String { grantId }253 public var displayName: String { folder.workspaceName?.isEmpty == false ? folder.workspaceName! : folder.name }254}255public struct SharedListing: Codable, Sendable {256 public var grantId: String; public var role: GrantRole; public var folder: NextFolder; public var breadcrumbs: [NextCrumb]; public var folders: [NextFolder]; public var files: [NextFile]257}258public struct SharedFileDetails: Codable, Sendable { public var grantId: String; public var role: GrantRole; public var file: NextFile; public var path: [NextCrumb]? }259public enum SharedItem: Sendable { case file(NextFile), folder(NextFolder) }260public struct NextUpload: Codable, Sendable, Identifiable, Hashable {261 public var id: String; public var name: String; public var size: Int64; public var received: Int64262 /// active | completing | done | aborted263 public var status: String264 public var fileId: String?265 // history only266 public var fileExists: Bool?; public var folderId: String?; public var grantId: String?; public var createdAt: Date?; public var updatedAt: Date?267}268public struct NextUploadResult: Codable, Sendable { public var id: String; public var status: String; public var file: NextFile; public var created: Bool? }269public struct UploadHistory: Codable, Sendable { public var uploads: [NextUpload] }270271// MARK: §7.1 Collections272public enum RuleValue: Codable, Sendable, Hashable {273 case string(String), number(Double), bool(Bool)274 public init(from decoder: Decoder) throws {275 let c = try decoder.singleValueContainer()276 if let b = try? c.decode(Bool.self) { self = .bool(b) } else if let n = try? c.decode(Double.self) { self = .number(n) } else { self = .string(try c.decode(String.self)) }277 }278 public func encode(to encoder: Encoder) throws {279 var c = encoder.singleValueContainer()280 switch self { case .string(let s): try c.encode(s); case .bool(let b): try c.encode(b)281 case .number(let n): if n == n.rounded(), abs(n) < 9e15 { try c.encode(Int64(n)) } else { try c.encode(n) } }282 }283}284public struct RuleCondition: Codable, Sendable, Hashable {285 /// kind, ext, name, tag, untagged, size, modified, created, starred, shared, folder, text286 public var field: String287 /// is, isNot, contains, gt, lt, within288 public var op: String289 public var value: RuleValue290 public init(field: String, op: String, value: RuleValue) { self.field = field; self.op = op; self.value = value }291}292public struct CollectionRule: Codable, Sendable, Hashable {293 public struct Sort: Codable, Sendable, Hashable { public var by: String; public var dir: String; public init(by: String, dir: String) { self.by = by; self.dir = dir } }294 /// all | any295 public var match: String296 public var conditions: [RuleCondition]297 public var sort: Sort?298 public init(match: String = "all", conditions: [RuleCondition], sort: Sort? = nil) { self.match = match; self.conditions = conditions; self.sort = sort }299 /// Fields, their operators and the kind of value each takes (API-NEXT §7.1), for rule builders.300 public static let fields: [(field: String, ops: [String], value: String)] = [301 ("kind", ["is", "isNot"], "kind"), ("ext", ["is", "isNot"], "string"), ("name", ["contains", "is", "isNot"], "string"), ("text", ["contains"], "string"),302 ("size", ["gt", "lt"], "bytes"), ("modified", ["within", "gt", "lt"], "date"), ("created", ["within", "gt", "lt"], "date"),303 ("starred", ["is"], "bool"), ("shared", ["is"], "bool"), ("untagged", ["is"], "bool"), ("folder", ["is", "isNot"], "folder"), ("tag", ["is", "isNot"], "tag")]304 public static let kinds = ["image", "pdf", "document", "sheet", "video", "audio", "archive", "text"]305 public static let colors = ["slate", "red", "orange", "amber", "green", "teal", "blue", "violet", "pink"]306}307public struct SmartCollection: Codable, Sendable, Identifiable, Hashable {308 public var id: String; public var name: String; public var icon: String?; public var color: String?; public var rule: CollectionRule309 public var createdAt: Date?; public var updatedAt: Date?310 /// Present in the list only.311 public var count: Int?312}313public struct CollectionDraft: Encodable, Sendable {314 public var name: String?; public var icon: String?; public var color: String?; public var rule: CollectionRule?315 public init(name: String? = nil, icon: String? = nil, color: String? = nil, rule: CollectionRule? = nil) { self.name = name; self.icon = icon; self.color = color; self.rule = rule }316}317public struct CollectionItems: Codable, Sendable { public var collection: SmartCollection?; public var files: [NextFile]; public var total: Int; public var limit: Int?; public var offset: Int? }318319// MARK: §7.2 Activity320public struct ActivityEvent: Codable, Sendable, Identifiable, Hashable {321 public struct Actor: Codable, Sendable, Hashable { public var kind: String; public var userId: String?; public var displayName: String?; public var me: Bool? }322 /// `name`: the present name of a file or folder that still exists (nil once purged, for the root, and for other target types).323 public struct Target: Codable, Sendable, Hashable { public var type: String; public var id: String?; public var name: String? }324 public var id: String; public var at: Date; public var action: String; public var actor: Actor; public var target: Target?; public var meta: [String: NextJSON]?325 /// Done by a member through a grant.326 public var viaGrant: Bool { meta?["via"]?.string == "grant" }327}328public struct ActivityPage: Codable, Sendable { public var events: [ActivityEvent]; public var more: Bool }329330// MARK: §7.3 Storage331public struct StorageOverview: Codable, Sendable {332 public struct Quota: Codable, Sendable, Hashable { public var limit: Int64; public var used: Int64; public var uploading: Int64? }333 public struct Counts: Codable, Sendable, Hashable { public var files: Int; public var folders: Int; public var versions: Int; public var trashedFiles: Int }334 public struct Kind: Codable, Sendable, Hashable, Identifiable { public var kind: String; public var files: Int; public var bytes: Int64; public var id: String { kind } }335 public struct FolderShare: Codable, Sendable, Identifiable { public var folder: NextFolder; public var files: Int; public var bytes: Int64; public var direct: Bool?; public var id: String { folder.id + (direct == true ? "-direct" : "") } }336 public struct Day: Codable, Sendable, Hashable, Identifiable { public var date: String; public var bytes: Int64; public var versions: Int; public var id: String { date } }337 /// `reclaimableBytes` is always 0 (identical content is stored once): deleting a duplicate frees a name, not bytes. `duplicateBytes` is the logical size of the redundant copies.338 public struct Duplicates: Codable, Sendable, Hashable { public var groups: Int; public var duplicateBytes: Int64?; public var reclaimableBytes: Int64 }339 public var quota: Quota; public var liveBytes: Int64; public var trashBytes: Int64; public var oldVersionBytes: Int64340 public var counts: Counts; public var byKind: [Kind]; public var byFolder: [FolderShare]; public var largest: [NextFile]; public var growth: [Day]; public var duplicates: Duplicates341}342public struct StorageFolder: Codable, Sendable {343 public struct Sum: Codable, Sendable, Hashable { public var files: Int; public var bytes: Int64 }344 public struct Child: Codable, Sendable, Identifiable { public var folder: NextFolder; public var files: Int; public var bytes: Int64; public var id: String { folder.id } }345 public var folder: NextFolder; public var breadcrumbs: [NextCrumb]; public var total: Sum; public var direct: Sum; public var children: [Child]; public var files: [NextFile]346}347348// MARK: §7.4 Duplicates349public enum DuplicateMode: String, Sendable { case exact, similarImages = "similar-images" }350public struct DuplicateGroup: Codable, Sendable, Identifiable {351 public var sha256: String?; public var size: Int64?352 /// exact mode: same content under different names.353 public var distinctNames: Bool?354 /// similar-images mode: largest number of differing bits inside the group.355 public var maxDistance: Int?356 public var files: [NextFile]357 public var id: String { sha256 ?? files.map(\.id).joined(separator: "+") }358}359public struct Duplicates: Codable, Sendable { public var mode: String?; public var distance: Int?; public var groups: [DuplicateGroup] }360361// MARK: §7.5 Versions362public struct VersionInfo: Codable, Sendable, Identifiable, Hashable {363 public struct Author: Codable, Sendable, Hashable { public var userId: String?; public var displayName: String?; public var me: Bool? }364 public var id: String; public var seq: Int; public var size: Int64; public var sha256: String; public var createdAt: Date; public var note: String?365 public var current: Bool; public var scan: String?366 /// nil for a file that came through a deposit portal.367 public var createdBy: Author?368}369public struct VersionList: Codable, Sendable { public var fileId: String; public var currentVersionId: String?; public var versions: [VersionInfo] }370371// MARK: §8 Administration372public struct AdminSystem: Sendable {373 public struct Worker: Codable, Sendable, Hashable { public var alive: Bool?; public var heartbeatAgeS: Double?; public var pid: Int? }374 public struct Job: Codable, Sendable, Hashable, Identifiable { public var kind: String; public var status: String; public var count: Int; public var oldestAgeS: Double?; public var id: String { kind + "/" + status } }375 public struct PreviewFailure: Codable, Sendable, Hashable, Identifiable { public var kind: String; public var count: Int; public var lastError: String?; public var id: String { kind } }376 public var version: String?377 public var features: [String]378 public var worker: Worker?379 public var jobs: [Job]380 public var previewFailures: [PreviewFailure]381 /// Everything the server answered (1.0 fields included), for what has no typed accessor: converter, textkit, antivirusSignatures, index, events, backup…382 public var raw: [String: NextJSON]383}384