// Cotton Meetings' one door into the core. Every rule is the core's// (meetings-core, `apps/meetings/CORE.md`): the tables, the status a meeting// walks, where its audio is written, recovery after a kill, the windows a// long recording is heard in, merging them, naming a speaker, the files a// transcript is shared as. This file only names the methods and reads their// answers into what the screens draw.//// While a method answers `not_yet` (its shape without its body) or// `unknown_method` (absent from this build's core), the recording still// happens and the card still tells the truth: the row is written as a plain// record (`recording`, then `waiting`) under the take's own id and the audio// stays on the phone, as meetings-android does; reads fall back to// `records.list`; sharing words the transcript here.#if os(iOS)importCottonKitimportCottonValuesimportFoundationenumMeetingsMethod {staticlet recordStart = "meetings.record.start"staticlet recordTick = "meetings.record.tick"staticlet recordStop = "meetings.record.stop"staticlet recordRecover = "meetings.record.recover"staticlet transcribed = "meetings.transcribed"staticlet transcribe = "meetings.transcribe"staticlet next = "meetings.next"staticlet windows = "meetings.windows"staticlet merge = "meetings.merge"staticlet read = "meetings.read"staticlet nameSpeaker = "meetings.speaker.name"staticlet export = "meetings.export"staticlet summarise = "meetings.summarise"staticlet actionTodo = "meetings.action.todo"}enumMeetingsTable {staticlet meeting = "meetings_meeting"staticlet speaker = "meetings_speaker"staticlet line = "meetings_line"}/// True for an answer that means "this core has no body for that yet".func meetingsNotHere(_ error: Error) -> Bool {guardlet error = error as? CottonCallErrorelse { returnfalse }return error.code == "unknown_method" || error.code == "not_yet"}/// A meeting's status as the screen tells it.enumMeetingStatus: Equatable, Sendable {case recordingcase waitingcase transcribing(by: String?)case readycase failed(String?)init(raw: String?, why: String?, by: String?) {switch raw ?? "" {case"recording": self = .recordingcase"transcribing": self = .transcribing(by: by)case"ready": self = .readycase"failed": self = .failed(why)default: self = .waiting } }}/// One meeting, as the list and the transcript page draw it.structMeetingRow: Identifiable, Equatable, Sendable {let id: Stringlet title: String?let kind: MeetingKindlet startedAt: Date?let durationMs: Int?let status: MeetingStatuslet summary: String?/// `<where>:<engine>`, e.g. `mac:sherpa:whisper-large-v3`.let transcribedBy: String?let languages: [String]let marks: [Int]/// The audio's media key, where the row names one.let audioKey: String?/// Whether this phone holds the audio (`on_phone`, the device's answer).let onPhone: Boolinit(id: String, data: [String: RecordValue]) {self.id = id title = data["title"]?.text kind = MeetingKind(rawValue: data["kind"]?.text ?? "") ?? .meeting startedAt = (data["started_at"]?.text).flatMap { CottonDate.parse($0) } durationMs = data["duration_ms"]?.number.map { Int($0) } transcribedBy = data["transcribed_by"]?.textlet why = data["status_why"]?.text status = MeetingStatus(raw: data["status"]?.text, why: why, by: transcribedBy) summary = data["summary"]?.text languages = (data["languages"]?.text ?? "").split(separator: ",") .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }ifcase .list(let items) = data["marks"] ?? .null { marks = items.compactMap { $0.number.map { Int($0) } } } else { marks = [] } audioKey = Self.key(data["audio"]) onPhone = data["on_phone"]?.text == "kept" }/// Where it was transcribed: the part of `transcribed_by` before the engine.var transcribedWhere: String? { transcribedBy?.split(separator: ":").first.map(String.init) }/// A file column's key: a bare key, or `{key|ref|path}`.privatestaticfunc key(_ value: RecordValue?) -> String? {switch value ?? .null {case .text(let key): return key.isEmpty ? nil : keycase .object(let fields): return fields["key"]?.text ?? fields["ref"]?.text ?? fields["path"]?.textdefault: returnnil } }}/// One speaker of a meeting.structMeetingSpeaker: Identifiable, Equatable, Sendable {let id: Stringlet label: Stringlet name: String?}/// One thing a meeting said is to be done, as the core hands it (lane/// meetings-summaries): who and the day only where the meeting said them, and/// its one act, Add to todos, or the words saying it was added.structMeetingAction: Identifiable, Equatable, Sendable {let id: Stringlet words: Stringlet who: String?/// `YYYY-MM-DD`.let due: String?let dueSaid: String?let added: Bool/// The act's label while it is not added.let act: String?/// The words saying it was added.let said: String?init(_ flat: [String: RecordValue]) { id = flat["id"]?.text ?? "" words = flat["words"]?.text ?? "" who = flat["who"]?.text due = flat["due"]?.text dueSaid = flat["due_said"]?.text added = flat["added"] == .bool(true)ifcase .object(let act) = flat["act"] ?? .null { self.act = act["label"]?.text } else { act = nil } said = flat["said"]?.text }}/// A meeting's summary as the page draws it: the points, why there is none/// yet, and its actions.structMeetingNotes: Equatable, Sendable {var summary: String?var note: String?var actions: [MeetingAction] = []}/// One line of a transcript.structMeetingLine: Identifiable, Equatable, Sendable {let id: Stringlet speaker: Stringlet startMs: Intlet endMs: Intlet text: String}/// The transcript, as every transcription step hands it to the core.structMeetingTranscript: Codable, Equatable, Sendable {structSpeaker: Codable, Equatable, Sendable { let label: String }structLine: Codable, Equatable, Sendable {/// Nil from the phone (one microphone, one voice it cannot tell apart): the core's merge keeps such lines as/// one voice across windows (CONTRACT.md "Recordings"); a speaker only where the voices were told apart.let speaker: String?let start_ms: Intlet end_ms: Intlet text: Stringlet language: String? }let by: Stringlet languages: [String]let speakers: [Speaker]let lines: [Line]}/// One window of a long recording, as the core cuts it.structMeetingWindow: Codable, Equatable, Sendable {let index: Intlet start_ms: Intlet end_ms: Int}structMeetingsCore: Sendable {let core: any CottonCallingprivatestructListed: Decodable { let records: [CoreRecords.WireRecord] }// MARK: - RecordingstructStarted: Decodable, Sendable {let meeting: Stringlet audio_path: String }/// The meeting's row stands at `recording` from the first second; the/// core says which file to write. Nil while the core has no body for it./// `id` is this take's id, so a start sent twice is one recording.func recordStart(kind: MeetingKind, id: String, startedAt: Date) asyncthrows -> Started? {do {returntryawait core.call(MeetingsMethod.recordStart, ["kind": RecordValue.text(kind.rawValue), "id": .text(id), "started_at": .text(CottonDate.format(startedAt))],as: Started.self) } catchwhere meetingsNotHere(error) {returnnil } }/// Every ~10 s while recording, so a crash still knows the length.func recordTick(meeting: String, durationMs: Int) async { _ = try? await core.callJSON(MeetingsMethod.recordTick, ["meeting": RecordValue.text(meeting), "duration_ms": .number(Double(durationMs))]) }/// What `record.stop` and a named `record.recover` send.structFinish: Encodable, Sendable {let id: Stringlet path: Stringlet format: Stringlet duration_ms: Intlet marks: [Int]let ended_at: String }/// The take is over: the core takes the bytes at `path` (in `format`) into/// the store and the meeting waits.func recordStop(_ finish: Finish) asyncthrows { _ = tryawait core.callJSON(MeetingsMethod.recordStop, finish) }/// One take the app holds and the core has not finished (a killed/// process's, or one whose start never reached the core): the core makes/// it a meeting as Stop would.func recordRecover(_ finish: Finish) asyncthrows { _ = tryawait core.callJSON(MeetingsMethod.recordRecover, finish) }/// Once at launch: every `recording` row whose audio is here is finished/// as Stop would; answers the meetings recovered, or nil where the core/// has no body yet.func recordRecover() async -> [String]? {structRecovered: Decodable {structOne: Decodable { let meeting: String }let recovered: [One] }do {returntryawait core.call(MeetingsMethod.recordRecover, EmptyRequest(), as: Recovered.self) .recovered.map(\.meeting) } catch {if !meetingsNotHere(error) { Log.warn("meetings: record.recover refused: \(error)") }returnnil } }// MARK: - Transcribing/// The next recording this phone should transcribe; nil when there is/// none (or the core cannot say yet). `peek` claims nothing; `except`/// passes over recordings the object refused; `id` takes that one only.func next(charging: Bool, battery: Int? = nil, peek: Bool = false, except: [String] = [], id: String? = nil) async -> (meeting: String, audio: URL)? {structNext: Decodable { let meeting: String?; let audio_path: String? }var request: [String: RecordValue] = ["on": .text("phone"), "charging": .bool(charging)]// The core decides what a phone off power takes (CONTRACT.md "Recordings": a short one at 30% or more).iflet battery { request["battery"] = .number(Double(battery)) }if peek { request["peek"] = .bool(true) }if !except.isEmpty { request["except"] = .list(except.map(RecordValue.text)) }iflet id { request["id"] = .text(id) }guardlet answer = try? await core.call(MeetingsMethod.next, request, as: Next.self),let meeting = answer.meeting, let path = answer.audio_pathelse { returnnil }return (meeting, URL(fileURLWithPath: path)) }/// What the object said to this phone's claim.enumClaim: Equatable { case claimed, heldByAnother, alone }/// Claim a recording through the object (`meeting_claim { id, by: phone }`),/// so the phone and the Mac never both take one: `heldByAnother` on its/// 409 (`not_waiting`, `not_yours`), `alone` where this phone is not/// signed in or reaches no object (it is then the only transcriber it/// can know of).func claim(_ meeting: String) async -> Claim {do { _ = tryawait core.callJSON(CottonMethod.objectAct, ["act": RecordValue.text("meeting_claim"), "args": .object(["id": .text(meeting), "by": .text("phone")])])return .claimed } catchlet error asCottonCallErrorwhere error.code == "not_waiting" || error.code == "not_yours" {return .heldByAnother } catch {if (error as? CottonCallError)?.code != "sign_in_first" {Log.warn("meetings: the object did not answer this phone's claim on \(meeting): \(error)") }return .alone } }/// Give up a recording claimed through the object (`meeting_failed`).func giveUp(_ meeting: String, why: String) async { _ = try? await core.callJSON(CottonMethod.objectAct, ["act": RecordValue.text("meeting_failed"), "args": .object(["id": .text(meeting), "why": .text(why)])]) }/// The windows the core cuts a recording of this length into.func windows(durationMs: Int) async -> [MeetingWindow]? {structWindows: Decodable { let windows: [MeetingWindow] }returntry? await core.call(MeetingsMethod.windows, ["duration_ms": RecordValue.number(Double(durationMs))], as: Windows.self ).windows }structHeardWindow: Encodable, Sendable {let index: Intlet start_ms: Intlet end_ms: Intlet language: String?let lines: [MeetingTranscript.Line] }/// The windows' lines made one transcript: the core de-duplicates the/// overlaps and numbers the speakers.func merge(_ windows: [HeardWindow]) asyncthrows -> MeetingTranscript {structMerged: Decodable { let transcript: MeetingTranscript }structRequest: Encodable, Sendable { let windows: [HeardWindow] }returntryawait core.call(MeetingsMethod.merge, Request(windows: windows), as: Merged.self).transcript }/// Hand the core a finished transcript.func transcribed(meeting: String, _ transcript: MeetingTranscript) asyncthrows {structRequest: Encodable, Sendable { let meeting: String; let transcript: MeetingTranscript } _ = tryawait core.callJSON(MeetingsMethod.transcribed, Request(meeting: meeting, transcript: transcript)) }/// The step that claimed it could not finish: the meeting is `failed`/// with `why` (a word of the set's `why.*`), and Try again asks anew.func transcriptionFailed(_ meeting: String, why: String) asyncthrows { _ = tryawait core.callJSON(MeetingsMethod.transcribed, ["id": RecordValue.text(meeting), "failed": .text(why)]) }/// Ask for the meeting to be transcribed again.func transcribeAgain(_ meeting: String) asyncthrows { _ = tryawait core.callJSON(MeetingsMethod.transcribe, ["id": RecordValue.text(meeting)]) }// MARK: - Reading, naming, sharingfunc meetings() asyncthrows -> [MeetingRow] {let rows = tryawait list(MeetingsTable.meeting, where: [:], limit: 200)return rows.map { MeetingRow(id: $0.id, data: $0.data) } .sorted { ($0.startedAt ?? .distantPast) > ($1.startedAt ?? .distantPast) } }/// The meeting whole: its row, its speakers, its lines, its summary and actions.func read(_ id: String) asyncthrows -> (MeetingRow, [MeetingSpeaker], [MeetingLine], MeetingNotes) {// The core's rows come flat: `{id, …fields}`.structRead: Decodable {let meeting: [String: RecordValue]let speakers: [[String: RecordValue]]let lines: [[String: RecordValue]]let actions: [[String: RecordValue]]?let summary_note: String? }func wire(_ flat: [String: RecordValue]) -> (id: String, data: [String: RecordValue]) {var data = flatreturn (data.removeValue(forKey: "id")?.text ?? "", data) }do {let read = tryawait core.call(MeetingsMethod.read, ["id": RecordValue.text(id)], as: Read.self)let row = wire(read.meeting)let notes = MeetingNotes( summary: read.meeting["summary"]?.text, note: read.summary_note, actions: (read.actions ?? []).map(MeetingAction.init))return (MeetingRow(id: row.id, data: row.data), read.speakers.map { Self.speaker(wire($0)) }, read.lines.map { Self.line(wire($0)) }.sorted { $0.startMs < $1.startMs }, notes) } catchwhere meetingsNotHere(error) {let row = tryawait core.call(CottonMethod.recordsGet, ["table": RecordValue.text(MeetingsTable.meeting), "id": .text(id)],as: CoreRecords.WireRecord.self)let speakers = (try? await list(MeetingsTable.speaker, where: ["meeting": .text(id)], limit: 50)) ?? []let lines = (try? await list(MeetingsTable.line, where: ["meeting": .text(id)], limit: 5000)) ?? []return (MeetingRow(id: row.id, data: row.data), speakers.map { Self.speaker(($0.id, $0.data)) }, lines.map { Self.line(($0.id, $0.data)) }.sorted { $0.startMs < $1.startMs },MeetingNotes(summary: row.data["summary"]?.text)) } }privatestaticfunc speaker(_ row: (id: String, data: [String: RecordValue])) -> MeetingSpeaker {MeetingSpeaker(id: row.id, label: row.data["label"]?.text ?? row.id, name: row.data["name"]?.text) }privatestaticfunc line(_ row: (id: String, data: [String: RecordValue])) -> MeetingLine {MeetingLine( id: row.id, speaker: row.data["speaker"]?.text ?? "", startMs: Int(row.data["start_ms"]?.number ?? 0), endMs: Int(row.data["end_ms"]?.number ?? 0), text: row.data["text"]?.text ?? "") }/// Add to todos: the core makes the todo from the action and links it.func addToTodos(_ action: MeetingAction) asyncthrows { _ = tryawait core.callJSON(MeetingsMethod.actionTodo, ["id": RecordValue.text(action.id)]) }/// Ask the Mac for the summary again.func summariseAgain(_ meeting: String) asyncthrows { _ = tryawait core.callJSON(MeetingsMethod.summarise, ["id": RecordValue.text(meeting)]) }/// Name a speaker in place, for this meeting only.func name(speaker: MeetingSpeaker, as name: String) asyncthrows {do { _ = tryawait core.callJSON(MeetingsMethod.nameSpeaker, ["speaker": RecordValue.text(speaker.id), "name": .text(name)]) } catchwhere meetingsNotHere(error) { _ = tryawait core.callJSON("records.update", ["table": RecordValue.text(MeetingsTable.speaker), "id": .text(speaker.id),"patch": .object(["name": .text(name)]), ]) } }/// The open bundle a meeting is shared as: the audio, `transcript.txt`,/// `transcript.srt`, `transcript.json`. Nil while the core cannot make it.func export(_ id: String) async -> [(name: String, url: URL, type: String)]? {structExported: Decodable {structFile: Decodable { let name: String; let path: String; let type: String }let files: [File] }guardlet answer = try? await core.call(MeetingsMethod.export, ["id": RecordValue.text(id)], as: Exported.self)else { returnnil }return answer.files.map { ($0.name, URL(fileURLWithPath: $0.path), $0.type) } }/// A path on this phone to the meeting's audio, fetched first when it is/// not here; nil when there is none to have.func audio(of row: MeetingRow) async -> URL? {guardlet key = row.audioKey else { returnnil }structRead: Encodable, Sendable { let args: [String: String] }iflet here = try? await core.callJSON(CottonMethod.readMediaPath, Read(args: ["key": key])),let path = here.text("path"), FileManager.default.fileExists(atPath: path) {return URL(fileURLWithPath: path) }guardlet fetched = try? await core.callJSON(CottonMethod.mediaEnsure, Read(args: ["key": key])),let path = fetched.text("path")else { returnnil }return URL(fileURLWithPath: path) }privatefunc list(_ table: String, where filter: [String: RecordValue], limit: Int) asyncthrows -> [CoreRecords.WireRecord] {var request: [String: RecordValue] = ["table": .text(table), "limit": .number(Double(limit)), "page": .number(0)]if !filter.isEmpty { request["where"] = .object(filter) }returntryawait core.call(CottonMethod.recordsList, request, as: Listed.self).records }}#endif