// COTTON DATA'S CALLS (assets/design/data/CONTRACT.md "The core calls each screen needs"; // crates/cotton-ffi/src/phone/data_app.rs): every `data.*` answer, decoded exactly as the core shapes it, its // snake_case keys read as Swift's names. Every word arrives said; nothing here makes a sentence, a number or a date. // Read only: every call is a read, but for this device's own Keep everything choice (`data.keep.set`). #if os(iOS) import CottonKit import Foundation /// A labelled choice the core answers (Tables' chips, Search's, Lately's). struct DataChipAnswer: Decodable, Equatable, Sendable, Identifiable { var id: String var title: String var on: Bool? } /// `data.welcome`: what the app is, once. struct DataWelcome: Decodable, Equatable, Sendable { struct Keep: Decodable, Equatable, Sendable { var on: Bool var title: String var costLine: String? var offLine: String } var title: String var lead: String var onlyLooks: String var keep: Keep var start: String } /// One table on the Tables list. struct DataTableLine: Decodable, Equatable, Sendable, Identifiable { var table: String var rowsLine: String var line: String var roomLine: String? /// `server_reads`: the open lock, still read by the server. var mark: String? var onPhone: Bool? var openable: Bool? var id: String { table } } /// The core's first-sync state (FIRST SYNC STATES, f80d9c3312): while this phone's copy is in its first sync, Tables, /// a table's rows and Lately carry it. `line` is the standing's words ("Loading your data…"); `seen` is what Account /// says of sync ("Syncing 1,200 of 3,108", with its percent while a pass counts). struct DataFirstSync: Decodable, Equatable, Sendable { struct Seen: Decodable, Equatable, Sendable { var state: String?; var line: String?; var percent: Double? } var state: String var line: String var seen: Seen? /// The words drawn: the count while a pass counts it, else the standing's line. var said: String { seen?.state == "catching_up" ? (seen?.line ?? line) : line } } /// `data.tables`. struct DataTables: Decodable, Equatable, Sendable { struct Room: Decodable, Equatable, Sendable { var usedLine: String; var line: String; var share: Double; var go: String } struct Group: Decodable, Equatable, Sendable { var title: String?; var countLine: String?; var tables: [DataTableLine] } struct Leftovers: Decodable, Equatable, Sendable { var title: String; var line: String; var count: Int } var title: String var count: Int var search: String var room: Room? var chips: [DataChipAnswer] var groups: [Group] var leftovers: Leftovers? var foot: String? var firstSync: DataFirstSync? } /// `data.room`: Where room goes. struct DataRoom: Decodable, Equatable, Sendable { struct Part: Decodable, Equatable, Sendable, Identifiable { var id: String var name: String var sizeLine: String var line: String var share: Double var staysOnServer: Bool } struct Big: Decodable, Equatable, Sendable { var table: String; var sizeLine: String; var share: Double } var title: String var lead: String var parts: [Part] var biggestTitle: String? var biggestNote: String? var biggest: [Big] var deletedLine: String? var measuredLine: String? } /// One row as a short sentence: its title, the fields that tell rows apart, its date. struct DataRowLine: Decodable, Equatable, Sendable { var id: String var table: String? var title: String var line: String? var when: String? } /// `data.rows`: a table's rows by month, or (`sealed_view`) the locked list as the server holds it. struct DataRows: Decodable, Equatable, Sendable { struct Group: Decodable, Equatable, Sendable { var title: String; var count: Int; var rows: [DataRowLine] } struct Empty: Decodable, Equatable, Sendable { var title: String; var body: String; var act: String? } struct Act: Decodable, Equatable, Sendable, Identifiable { var id: String; var title: String } struct Locked: Decodable, Equatable, Sendable { var title: String var line: String var sizes: String? var unlock: String? var noKeyLine: String? var acts: [Act]? } struct LockedRow: Decodable, Equatable, Sendable { var id: String? var madeLine: String var clearLine: String? var pointsLine: String? var sizeLine: String? } var table: String var lead: String var q: String? /// The table's own search field's words ("Search 1,204 rows"). var search: String? var sortLine: String? var dateLine: String? var groups: [Group] var more: Bool? /// The next page's place, handed back as `after`. var after: JSONValue? var foot: String? var empty: Empty? var firstSync: DataFirstSync? var sealedView: Bool? var locked: Locked? var rows: [LockedRow]? } /// A step of the trail: the rows followed to reach this one. The phone keeps it; the core names each step. struct DataStep: Codable, Equatable, Hashable, Sendable { var table: String var id: String var name: String } /// One field of a row, drawn as its kind asks. struct DataField: Decodable, Equatable, Sendable { struct Link: Decodable, Equatable, Sendable { var table: String; var id: String?; var ids: [String]? } struct Folded: Decodable, Equatable, Sendable { var lines: Int; var allLine: String } var column: String var typeLine: String /// `text long link amount date time choice bool several url place photo file number bytes account`. var kind: String var valueLine: String var sub: String? var items: [String]? var link: Link? var url: String? var media: String? var folded: Folded? var clear: Bool var empty: Bool } /// `data.row`: one row, opened; or (`sealed_view`) the server's facts about it on a phone without the key. struct DataRow: Decodable, Equatable, Sendable { struct Points: Decodable, Equatable, Sendable { struct Row: Decodable, Equatable, Sendable { var table: String; var id: String; var title: String } var table: String var column: String var throughLine: String var count: Int var rows: [Row] } struct Band: Decodable, Equatable, Sendable { var title: String; var line: String } struct Fact: Decodable, Equatable, Sendable { var label: String; var value: String } var table: String? var id: String? var title: String var lead: String? var trail: [DataStep]? var fields: [DataField]? var pointsHere: [Points]? var pointsTitle: String? var severalNote: String? /// As stored's word. var stored: String? var foot: String? var sealedView: Bool? var band: Band? var facts: [Fact]? var acts: [DataRows.Act]? } /// `data.stored`: each value exactly as it sits in the row. struct DataStored: Decodable, Equatable, Sendable { struct Field: Decodable, Equatable, Sendable { var column: String; var stored: String } var fields: [Field] var plain: String } /// `data.link`: a url field opened. struct DataLinkSheet: Decodable, Equatable, Sendable { var title: String var fromLine: String var address: String var site: String var open: String var copy: String var copied: String var note: String } /// `data.media`: a photo or file field, its bytes fetched by `key` (`media.ensure`). struct DataMedia: Decodable, Equatable, Sendable { var name: String var key: String var kind: String var sizeTitle: String? var fromTitle: String var fromLine: String var note: String var offline: String var close: String } /// `data.about`: what a table is, in sentences. struct DataAbout: Decodable, Equatable, Sendable { struct Fact: Decodable, Equatable, Sendable { var icon: String; var title: String; var line: String?; var act: String? } struct Row: Decodable, Equatable, Sendable, Identifiable { var id: String; var title: String; var valueLine: String? } var table: String var title: String var lead: String var facts: [Fact] var rows: [Row] var foot: String } /// `data.columns`. struct DataColumns: Decodable, Equatable, Sendable { struct Column: Decodable, Equatable, Sendable { var name: String; var typeLine: String; var clear: Bool; var link: String? } var title: String var lead: String var clearWord: String var columns: [Column] } /// `data.links`: one table in the middle, what it points at above, what points at it below. struct DataLinks: Decodable, Equatable, Sendable { struct Neighbour: Decodable, Equatable, Sendable { var table: String var column: String var throughLine: String var counted: Bool var countLine: String? } var table: String var title: String var lead: String var outTitle: String var inTitle: String var out: [Neighbour] var `in`: [Neighbour] var twoStepsLine: String? var none: String? } /// `data.search`: rows by table, table names, column names, and what was searched. struct DataSearch: Decodable, Equatable, Sendable { struct Group: Decodable, Equatable, Sendable { var table: String; var title: String?; var rows: [DataRowLine] } struct Named: Decodable, Equatable, Sendable { var table: String; var line: String? } struct Column: Decodable, Equatable, Sendable { var table: String; var column: String } struct Nothing: Decodable, Equatable, Sendable { var title: String; var names: String? } var title: String var placeholder: String? var chips: [DataChipAnswer]? var groups: [Group] var foundLine: String? var tables: [Named] var columns: [Column] var searchedLine: String? var nothing: Nothing? } /// `data.lately`: every write, by day. struct DataLately: Decodable, Equatable, Sendable { struct Item: Decodable, Equatable, Sendable { var line: String; var table: String?; var when: String?; var count: Int? } struct Day: Decodable, Equatable, Sendable { var title: String; var countLine: String; var items: [Item] } var title: String var lead: String var chips: [DataChipAnswer] var days: [Day] var more: Bool /// The next page's place, handed back as `before`. var before: JSONValue? var foot: String var firstSync: DataFirstSync? } /// `data.assistants`. struct DataAssistants: Decodable, Equatable, Sendable { struct Item: Decodable, Equatable, Sendable { var table: String; var line: String; var when: String? } struct Band: Decodable, Equatable, Sendable { var name: String var openLine: String? var todayLine: String? var items: [Item] var moreLine: String? } var title: String var lead: String var assistants: [Band] var none: String? var neverTitle: String var neverLine: String var gapLine: String } /// `data.leftovers`. struct DataLeftovers: Decodable, Equatable, Sendable { struct Table: Decodable, Equatable, Sendable { var table: String; var line: String; var roomLine: String? } struct Tables: Decodable, Equatable, Sendable { var title: String; var line: String; var tables: [Table] } struct Dangling: Decodable, Equatable, Sendable { struct Item: Decodable, Equatable, Sendable { var line: String; var throughLine: String; var table: String; var column: String? } var title: String var items: [Item] } var title: String var lead: String var unused: Tables? var retired: Tables? var dangling: Dangling? var foot: String var none: String? } /// `data.keep`, and `data.keep.set`'s answer. struct DataKeep: Decodable, Equatable, Sendable { struct Cost: Decodable, Equatable, Sendable { var name: String; var valueLine: String } struct Progress: Decodable, Equatable, Sendable { var percent: Int; var leftLine: String?; var line: String? } var title: String var `switch`: String var on: Bool var wifiOnly: Bool var costsTitle: String var cost: [Cost] var whyLine: String? var privacyLine: String var howTitle: String var wifi: String var wifiLine: String var shortTitle: String var shortLine: String var allMailLine: String? /// `off`, `waiting`, `filling`, `keeping`, `paused`. var state: String var stateLine: String? var progress: Progress? var tooSmallLine: String? } /// `data.you`: the card's line and Data's own places. struct DataYou: Decodable, Equatable, Sendable { struct Card: Decodable, Equatable, Sendable { var line: String? } struct Row: Decodable, Equatable, Sendable, Identifiable { var id: String; var title: String; var valueLine: String? } var title: String var card: Card var rows: [Row] var privacyLine: String? } /// The core's refusal, already in words (`{ code, message }` with `message` the line). struct DataRefusal: Error, Equatable { let words: String } /// A field of a call, as JSON. enum DataValue: Encodable, Sendable { case text(String), flag(Bool), number(Int64), steps([DataStep]), value(JSONValue) func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer() switch self { case .text(let s): try c.encode(s) case .flag(let b): try c.encode(b) case .number(let n): try c.encode(n) case .steps(let s): try c.encode(s) case .value(let v): try c.encode(v) } } } /// Every call Data makes. All reads but `keep(set:)`, which writes this device's own choice beside its copies. struct DataCalls: Sendable { let core: any CottonCalling /// Answers are read with snake_case keys as Swift's names. static func decode(_ data: Data, as: A.Type) throws -> A { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase return try decoder.decode(A.self, from: data) } /// The envelope, `{"ok":true,"data":…}` / `{"ok":false,"error":{…}}`. private struct Envelope: Decodable { var data: A? var error: CottonCallError? } private func call(_ method: String, _ fields: [String: DataValue] = [:], as: A.Type) async throws -> A { let body = String(decoding: try JSONEncoder().encode(fields), as: UTF8.self) let answer: String do { answer = try await core.callRaw(method, requestJSON: body) } catch { throw Self.words(error) } let envelope = try Self.decode(Data(answer.utf8), as: Envelope.self) if let error = envelope.error { throw Self.words(error) } guard let data = envelope.data else { throw CottonClientError.malformedAnswer(answer) } return data } /// A refusal's words (the core's `message`, already said), else the error as it came. static func words(_ error: Error) -> Error { if let refused = error as? DataRefusal { return refused } if let message = (error as? CottonCallError)?.message, !message.isEmpty { return DataRefusal(words: message) } return error } /// The phone's free room as the system enforces it: Keep everything weighs its cost against it. static var free: Int64 { let home = URL(fileURLWithPath: NSHomeDirectory()) let values = try? home.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]) return values?.volumeAvailableCapacityForImportantUsage ?? 0 } /// A paging place as the core reads it back: numbers as their digits (`before` and `after.at` are read as text). static func place(_ value: JSONValue?) -> JSONValue? { switch value { case .number(let n)?: .string(String(Int64(n))) case .object(let o)?: .object(o.mapValues { place($0) ?? .null }) case let other: other } } func welcome() async throws -> DataWelcome { try await call("data.welcome", ["free": .number(Self.free)], as: DataWelcome.self) } func tables(by: String, q: String) async throws -> DataTables { var fields: [String: DataValue] = ["by": .text(by)] if !q.isEmpty { fields["q"] = .text(q) } return try await call("data.tables", fields, as: DataTables.self) } func room() async throws -> DataRoom { try await call("data.room", as: DataRoom.self) } func rows(_ table: String, q: String?, after: JSONValue?) async throws -> DataRows { var fields: [String: DataValue] = ["table": .text(table)] if let q { fields["q"] = .text(q) } if let after = Self.place(after) { fields["after"] = .value(after) } return try await call("data.rows", fields, as: DataRows.self) } func row(_ table: String, id: String, trail: [DataStep]) async throws -> DataRow { try await call("data.row", ["table": .text(table), "id": .text(id), "trail": .steps(trail)], as: DataRow.self) } func stored(_ table: String, id: String) async throws -> DataStored { try await call("data.stored", ["table": .text(table), "id": .text(id)], as: DataStored.self) } func link(_ table: String, id: String, column: String) async throws -> DataLinkSheet { try await call("data.link", ["table": .text(table), "id": .text(id), "column": .text(column)], as: DataLinkSheet.self) } func media(_ table: String, id: String, column: String) async throws -> DataMedia { try await call("data.media", ["table": .text(table), "id": .text(id), "column": .text(column)], as: DataMedia.self) } /// The file's bytes on this phone, fetched into its cache (`media.ensure`): its path. func ensure(_ key: String) async throws -> String? { struct Landed: Decodable, Sendable { var path: String? } do { return try await core.call(CottonMethod.mediaEnsure, ["args": ["key": key]], as: Landed.self).path } catch { throw Self.words(error) } } func about(_ table: String) async throws -> DataAbout { try await call("data.about", ["table": .text(table)], as: DataAbout.self) } func columns(_ table: String) async throws -> DataColumns { try await call("data.columns", ["table": .text(table)], as: DataColumns.self) } func links(_ table: String) async throws -> DataLinks { try await call("data.links", ["table": .text(table)], as: DataLinks.self) } func search(_ q: String, in within: String) async throws -> DataSearch { try await call("data.search", ["q": .text(q), "in": .text(within)], as: DataSearch.self) } func lately(who: String, before: JSONValue?) async throws -> DataLately { var fields: [String: DataValue] = [:] if who != "all" { fields["who"] = .text(who) } if let before = Self.place(before), before != .null { fields["before"] = .value(before) } return try await call("data.lately", fields, as: DataLately.self) } func assistants() async throws -> DataAssistants { try await call("data.assistants", as: DataAssistants.self) } func leftovers() async throws -> DataLeftovers { try await call("data.leftovers", as: DataLeftovers.self) } func keep() async throws -> DataKeep { try await call("data.keep", ["free": .number(Self.free)], as: DataKeep.self) } /// This device's choice only, never a write to the database. func keepSet(on: Bool? = nil, wifiOnly: Bool? = nil) async throws -> DataKeep { var fields: [String: DataValue] = ["free": .number(Self.free)] if let on { fields["on"] = .flag(on) } if let wifiOnly { fields["wifi_only"] = .flag(wifiOnly) } return try await call("data.keep.set", fields, as: DataKeep.self) } func you() async throws -> DataYou { try await call("data.you", as: DataYou.self) } } #endif