//! Cotton Meetings: the phone core's methods over `meetings_meeting`, //! `meetings_speaker` and `meetings_line` (shapes: `apps/meetings/CORE.md`; //! the pure rules: `cotton_rules::meetings`). //! //! The Mac era's `cotton_meetings` rows and their one door, //! `meetings.create` (`phone::meetings`), are kept as they are; nothing here //! reads or writes them. //! //! ## A recording is a row from the first second //! //! `meetings.record.start` writes the row (status `recording`) before the //! microphone opens, and names the file the platform appends to. The platform //! may name its own (the Android recorder journals AAC frames beside it) and //! say so at stop with `path`. `meetings.record.stop` copies the bytes into //! the content-addressed store, writes the media ledger row the drain sends //! (sealed, as every person's file is: `media::sealed::SEALED_KINDS` holds //! `meetings`; large files in parts) and moves the row to `waiting`. A crash //! leaves a `recording` row and a file: `meetings.record.recover` finishes it //! as stop would, or fails it when no audio survived. //! //! ## Words land in one write //! //! `meetings.transcribed` replaces a meeting's speakers and lines in one //! write: a line a person corrected is kept over the new line it overlaps, //! and a name given to a speaker stays with the label the new transcript //! keeps. The person link is this meeting's alone: no voice print is kept. use std::path::{Path, PathBuf}; use serde_json::{json, Map, Value}; use cotton_client::media::store::put_media_file; use cotton_core::cotton_rules::meetings::{self as rules, HeldLine, Line, Transcript}; use cotton_core::media::keys::meeting_full_key_of; use cotton_core::media::meeting_audio::meeting_audio_mime_for_ext; use cotton_store::media_ledger::{enqueue_media, MediaEnqueueInput}; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::tables; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::phone::io_trouble::io_refusal; pub const METHODS: &[&str] = &[ "meetings.action.todo", "meetings.delete", "meetings.export", "meetings.import", "meetings.language", "meetings.line.correct", "meetings.merge", "meetings.next", "meetings.note", "meetings.read", "meetings.record.discard", "meetings.record.recover", "meetings.record.start", "meetings.record.stop", "meetings.record.tick", "meetings.search", "meetings.speaker.name", "meetings.summarise", "meetings.title", "meetings.transcribe", "meetings.transcribed", "meetings.windows", ]; pub(crate) const MEETING: &str = "meetings_meeting"; pub const SPEAKER: &str = "meetings_speaker"; pub const LINE: &str = "meetings_line"; pub const ACTION: &str = "meetings_action"; pub const TODO: &str = "todo"; /// The folder under the phone's root where a recording is written while it /// records; the store holds it once stopped. pub const RECORDINGS_DIR: &str = "recordings"; const KINDS: [&str; 2] = ["meeting", "memo"]; const SOURCES: [&str; 3] = ["room", "import", "call"]; pub const NOTE: &str = "note"; /// A phone hears a recording on any power when it is at most this long and /// the battery holds at least [`SHORT_BATTERY`] (DECISIONS "Recordings"). pub const SHORT_MS: i64 = 15 * 60 * 1000; pub const SHORT_BATTERY: i64 = 30; const ON: [&str; 4] = ["any", "mac", "phone", "service"]; pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { match method { "meetings.record.start" => { let root = handle.client().layout().root().to_path_buf(); with_write(handle, method, |ctx| start(ctx, &root, request)) } "meetings.record.tick" => with_write(handle, method, |ctx| tick(ctx, request)), "meetings.record.discard" => { let root = handle.client().layout().root().to_path_buf(); with_write(handle, method, |ctx| discard(ctx, &root, request)) } "meetings.record.stop" => stop_method(handle, method, request, false), "meetings.record.recover" => recover(handle, request), "meetings.transcribed" => with_write(handle, method, |ctx| transcribed(ctx, request)), "meetings.transcribe" => with_write(handle, method, |ctx| transcribe(ctx, request)), "meetings.next" => { let layout = handle.client().layout().clone(); with_write(handle, method, |ctx| next(ctx, &layout, request)) } "meetings.windows" => with_read(handle, method, |ctx| windows_of(ctx, request)), "meetings.merge" => merge_of(request), "meetings.read" => { let layout = handle.client().layout().clone(); with_read(handle, method, |ctx| read(ctx, &layout, request)) } "meetings.speaker.name" => with_write(handle, method, |ctx| name_speaker(ctx, request)), "meetings.line.correct" => with_write(handle, method, |ctx| correct_line(ctx, request)), "meetings.search" => with_read(handle, method, |ctx| search(ctx, request)), "meetings.export" => { let root = handle.client().layout().root().to_path_buf(); let layout = handle.client().layout().clone(); with_read(handle, method, |ctx| export(ctx, &layout, &root, request)) } "meetings.summarise" => with_write(handle, method, |ctx| summarise(ctx, request)), "meetings.action.todo" => action_todo(handle, request), "meetings.import" => import(handle, request), "meetings.language" => with_write(handle, method, |ctx| language(ctx, request)), "meetings.title" => with_write(handle, method, |ctx| retitle(ctx, request)), "meetings.delete" => { let layout = handle.client().layout().clone(); with_write(handle, method, |ctx| delete_meeting(ctx, &layout, request)) } "meetings.note" => { let zone = handle.client().time_zone().unwrap_or("Etc/UTC").to_string(); with_write(handle, method, |ctx| save_note(ctx, &zone, request)) } other => Err(MethodError::new("unknown_method", format!("`{other}` is not a meetings method"))), } } // ── plumbing (as `phone::story`'s) ────────────────────────────────────────── pub(crate) fn with_read(handle: &CottonHandle, label: &str, mut body: impl FnMut(&mut Ctx<'_>) -> Result) -> Result { let mut refusal: Option = None; let answer = handle.client().read_rows(label, &mut |ctx| { body(ctx).map_err(|refused| { let said = refused.message.clone(); refusal = Some(refused); said }) }); match (answer, refusal) { (Ok(answer), _) => Ok(answer), (Err(_), Some(refused)) => Err(refused), (Err(why), None) => Err(MethodError::new("unreadable", why)), } } pub(crate) fn with_write(handle: &CottonHandle, label: &str, mut body: impl FnMut(&mut Ctx<'_>) -> Result) -> Result { let mut refusal: Option = None; let answer = handle.client().write_rows(label, &mut |ctx| { body(ctx).map_err(|refused| { let said = refused.message.clone(); refusal = Some(refused); said }) }); match (answer, refusal) { (Ok(answer), _) => Ok(crate::authoring::own_answer(answer)), (Err(_), Some(refused)) => Err(refused), (Err(why), None) => Err(MethodError::new("write_refused", why)), } } fn tool(failure: cotton_tools::mcp::protocol::ToolFailure) -> MethodError { MethodError::new("write_refused", failure.to_string()) } pub(crate) fn object(value: Value) -> Map { value.as_object().cloned().unwrap_or_default() } pub(crate) fn bad(why: impl Into) -> MethodError { MethodError::new("bad_request", why.into()) } /// A line of the `meetings` set. pub(crate) fn line(name: &str) -> String { say(name, &[]) } /// A line of the `meetings` set with its blanks filled. pub(crate) fn say(name: &str, fill: &[(&str, &str)]) -> String { cotton_core::rules::shell_lines::LineSet::shipped("meetings").and_then(|lines| lines.say(name, fill)).unwrap_or_else(|| name.to_string()) } pub(crate) fn text<'a>(request: &'a Value, key: &str) -> Option<&'a str> { request.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) } /// The meeting a request names: `id`, else `meeting`. fn meeting_id(request: &Value) -> Result<&str, MethodError> { text(request, "id").or_else(|| text(request, "meeting")).ok_or_else(|| bad("this names the meeting: `id`")) } pub(crate) fn rows(ctx: &mut Ctx<'_>, table: &str, filter: Value) -> Result>, MethodError> { let mut out = Vec::new(); let mut page = 0u64; loop { let ask = object(json!({ "table": table, "where": filter, "limit": 500, "page": page })); let listed = tables::list_records(ctx, &ask).map_err(tool)?; let records = listed["records"].as_array().cloned().unwrap_or_default(); let got = records.len(); for record in records { let mut data = object(record["data"].clone()); if let Some(id) = record["id"].as_str() { data.insert("id".into(), json!(id)); } out.push(data); } match listed["next_page"].as_u64() { Some(next) if got > 0 && next > page => page = next, _ => break, } } Ok(out) } pub(crate) fn get(ctx: &mut Ctx<'_>, table: &str, id: &str) -> Option> { let got = tables::get_record_by_table(ctx, &object(json!({ "table": table, "id": id }))).ok()?; let record = if got.get("record").is_some() { &got["record"] } else { &got }; // A row in the bin is not here: a discarded recording, a replaced line. if !record["data"].is_object() || [&got, record].iter().any(|r| r.get("deleted_at").is_some_and(|d| !d.is_null())) { return None; } let mut data = object(record["data"].clone()); data.insert("id".into(), json!(id)); Some(data) } /// The columns the recordings gave Meetings' table (chat DECISIONS "Recordings", 23 Nov 2026). const LATE_COLUMNS: [&str; 6] = ["source", "call", "tracks", "languages_chosen", "note", "transcribing_on"]; /// What a write keeps of the recordings' columns: those the definition this copy's object serves holds. A server not /// yet deployed with them serves the table of before, and a recording is still kept, never refused over a column /// (seen on emulator-5608, 23 Nov 2026: Stop said `Meetings have no column "source"` against dev); it reads as a /// recording in the room until the server has them. fn fit(ctx: &mut Ctx<'_>, table: &str, data: &mut Map) { if table != MEETING || !LATE_COLUMNS.iter().any(|column| data.contains_key(*column)) { return; } let Ok(rows) = cotton_tools::definitions::definition_rows(ctx, Some(MEETING)) else { return }; let Some(row) = rows.first() else { return }; let definition: Value = serde_json::from_str(&row.definition).unwrap_or(Value::Null); let keys: Vec<&str> = definition["columns"].as_array().into_iter().flatten().filter_map(|c| c["key"].as_str()).collect(); if keys.is_empty() { return; } data.retain(|key, _| !LATE_COLUMNS.contains(&key.as_str()) || keys.contains(&key.as_str())); } pub(crate) fn create(ctx: &mut Ctx<'_>, table: &str, mut data: Value) -> Result { if let Some(map) = data.as_object_mut() { fit(ctx, table, map); } let made = tables::create_produced_record(ctx, &object(json!({ "table": table, "data": data }))).map_err(tool)?; made["record"]["id"].as_str().or_else(|| made["id"].as_str()).map(str::to_string).ok_or_else(|| MethodError::new("write_refused", format!("no id for the new {table}"))) } pub(crate) fn update(ctx: &mut Ctx<'_>, table: &str, id: &str, mut patch: Map) -> Result<(), MethodError> { fit(ctx, table, &mut patch); if let Some(held) = get(ctx, table, id) { patch.retain(|key, value| held.get(key).unwrap_or(&Value::Null) != value); } if patch.is_empty() { return Ok(()); } tables::update_produced_record(ctx, &object(json!({ "table": table, "id": id, "patch": Value::Object(patch) }))).map_err(tool)?; Ok(()) } fn delete(ctx: &mut Ctx<'_>, table: &str, id: &str) -> Result<(), MethodError> { tables::delete_record(ctx, &object(json!({ "table": table, "id": id }))).map_err(tool)?; Ok(()) } pub(crate) fn str_of<'a>(row: &'a Map, key: &str) -> &'a str { row.get(key).and_then(Value::as_str).unwrap_or_default() } pub(crate) fn int_of(row: &Map, key: &str) -> i64 { row.get(key).and_then(Value::as_f64).map_or(0, |n| n as i64) } fn now_iso(ctx: &Ctx<'_>) -> String { let ms = cotton_tools::mcp::handlers::common::now_ms(ctx); chrono::DateTime::from_timestamp_millis(ms).unwrap_or_default().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) } pub(crate) fn meeting_of(ctx: &mut Ctx<'_>, request: &Value) -> Result, MethodError> { let id = meeting_id(request)?.to_string(); get(ctx, MEETING, &id).ok_or_else(|| MethodError::new("not_found", line("refusal.no_meeting"))) } fn duration_arg(request: &Value) -> Option { request.get("duration_ms").and_then(Value::as_f64).filter(|n| n.is_finite() && *n >= 0.0).map(|n| n.round() as i64) } // ── recording ─────────────────────────────────────────────────────────────── /// The file a recording is written to while it records. pub fn recording_path(root: &Path, meeting: &str, ext: &str) -> PathBuf { root.join(RECORDINGS_DIR).join(format!("{meeting}.{ext}")) } pub(crate) fn start(ctx: &mut Ctx<'_>, root: &Path, request: &Value) -> Result { let kind = text(request, "kind").unwrap_or("meeting"); if !KINDS.contains(&kind) { return Err(bad("`kind` is meeting or memo")); } let take = text(request, "id").or_else(|| text(request, "take")).map(str::to_string).unwrap_or_else(|| ctx.new_uuid()); if let Some(held) = get(ctx, MEETING, &take) { // The same take started again (a double tap, a retry): the same row. let path = recording_path(root, &take, "wav"); return Ok(json!({ "meeting": take, "audio_path": path.to_string_lossy(), "started_at": held.get("started_at").cloned().unwrap_or(Value::Null) })); } let started_at = text(request, "started_at").map(str::to_string).unwrap_or_else(|| now_iso(ctx)); let mut data = json!({ "take": take, "kind": kind, "status": "recording", "started_at": started_at, "duration_ms": 0, "transcribe_on": "any", "attempts": 0, }); if let Some(title) = text(request, "title") { data["title"] = json!(title); } if let Some(device) = text(request, "recorded_on").or_else(|| text(request, "device")) { data["recorded_on"] = json!(device); } let source = text(request, "source").unwrap_or("room"); if !SOURCES.contains(&source) { return Err(bad("`source` is room, import or call")); } data["source"] = json!(source); if let Some(call) = text(request, "call") { data["call"] = json!(call); } let id = create(ctx, MEETING, data)?; let path = recording_path(root, &id, "wav"); if let Some(dir) = path.parent() { std::fs::create_dir_all(dir).map_err(|e| io_refusal("the recordings folder could not be made", dir, &e)).map_err(|why| MethodError::new("io", why))?; } Ok(json!({ "meeting": id, "audio_path": path.to_string_lossy(), "started_at": started_at })) } fn tick(ctx: &mut Ctx<'_>, request: &Value) -> Result { let meeting = meeting_of(ctx, request)?; if str_of(&meeting, "status") != "recording" { return Ok(json!({})); } if let Some(ms) = duration_arg(request) { update(ctx, MEETING, str_of(&meeting, "id"), object(json!({ "duration_ms": ms })))?; } Ok(json!({})) } /// Discard, on the person's word: a recording still being made (`recording`) /// goes, its row to the bin and its working file deleted, and nothing is made /// from it. A /// recording already stopped is never discarded here (it is the person's /// meeting; the bin takes it), and one already gone answers as discarded, so /// a platform that discards before the core heard the start is not refused. fn discard(ctx: &mut Ctx<'_>, root: &Path, request: &Value) -> Result { let id = text(request, "id").or_else(|| text(request, "meeting")).ok_or_else(|| bad("this names the meeting: `id`"))?.to_string(); let Some(meeting) = get(ctx, MEETING, &id) else { return Ok(json!({ "meeting": id, "discarded": true })); }; if str_of(&meeting, "status") != "recording" { return Err(MethodError::new("refused", line("refusal.not_recording"))); } delete(ctx, MEETING, &id)?; for ext in ["wav", "m4a", "aac"] { // not a copy: recordings. let _ = std::fs::remove_file(recording_path(root, &id, ext)); } Ok(json!({ "meeting": id, "discarded": true })) } /// What stop and recovery do to one recording: the file, the ledger, the row. struct Finish { meeting: String, path: PathBuf, ext: String, duration_ms: Option, ended_at: Option, marks: Option, /// Stretches a call took the microphone, `[[from_ms, to_ms]…]` (Android's journal). silenced: Option, recovered: bool, /// A call's notes (Take notes): each person's own file, `me` first, beside `path` (which is `me`'s). tracks: Vec<(String, PathBuf, String)>, } fn finish_of(root: &Path, request: &Value, recovered: bool) -> Result { let meeting = meeting_id(request)?.to_string(); let mut tracks: Vec<(String, PathBuf, String)> = Vec::new(); for track in request.get("tracks").and_then(Value::as_array).into_iter().flatten() { let (Some(id), Some(path)) = (track["track"].as_str(), track["path"].as_str()) else { return Err(bad("each of `tracks` is { track, path }")) }; let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_else(|| "aac".into()); tracks.push((id.to_string(), PathBuf::from(path), ext)); } tracks.sort_by_key(|(id, ..)| id != "me"); let given = text(request, "path").map(PathBuf::from).or_else(|| tracks.first().map(|(_, path, _)| path.clone())); let path = given.unwrap_or_else(|| { ["wav", "m4a", "aac"].iter().map(|ext| recording_path(root, &meeting, ext)).find(|p| p.exists()).unwrap_or_else(|| recording_path(root, &meeting, "wav")) }); let ext = text(request, "format") .map(str::to_ascii_lowercase) .or_else(|| path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase)) .unwrap_or_else(|| "wav".into()); let ext = if ext == "adts" { "aac".to_string() } else { ext }; if meeting_audio_mime_for_ext(&ext).is_none() { return Err(bad(format!("a .{ext} recording is not one Meetings keeps"))); } Ok(Finish { meeting, path, ext, duration_ms: duration_arg(request), ended_at: text(request, "ended_at").map(str::to_string), marks: request.get("marks").filter(|m| m.is_array()).cloned(), silenced: request.get("silenced").filter(|s| s.as_array().is_some_and(|spans| spans.iter().all(|span| span.as_array().is_some_and(|ends| ends.len() == 2)))).cloned(), recovered: recovered || request.get("recovered").and_then(Value::as_bool).unwrap_or(false), tracks, }) } fn stop_method(handle: &CottonHandle, method: &str, request: &Value, recovered: bool) -> Result { let layout = handle.client().layout().clone(); let finish = finish_of(layout.root(), request, recovered)?; if finish.ext == "wav" { // A WAV written as it records has a header that still says empty; // the bytes are the truth. let _ = fix_wav_header(&finish.path); } with_write(handle, method, |ctx| finish_one(ctx, &layout, &finish)) } fn finish_one(ctx: &mut Ctx<'_>, layout: &cotton_client::layout::Layout, finish: &Finish) -> Result { let meeting = get(ctx, MEETING, &finish.meeting).ok_or_else(|| MethodError::new("not_found", line("refusal.no_meeting")))?; let status = str_of(&meeting, "status").to_string(); if status != "recording" { // Stopped already (a second Stop, a recovery after a stop that landed). return Ok(json!({ "meeting": finish.meeting, "status": status, "audio_bytes": int_of(&meeting, "audio_bytes") })); } let now = now_iso(ctx); let bytes = std::fs::metadata(&finish.path).map(|m| m.len()).unwrap_or(0); let header_only = finish.ext == "wav" && bytes <= 44; if bytes == 0 || header_only { let mut patch = object(json!({ "status": "failed", "status_why": "no_audio", "ended_at": finish.ended_at.clone().unwrap_or_else(|| now.clone()) })); if let Some(ms) = finish.duration_ms { patch.insert("duration_ms".into(), json!(ms)); } update(ctx, MEETING, &finish.meeting, patch)?; return Ok(json!({ "meeting": finish.meeting, "status": "failed", "audio_bytes": 0 })); } let workspace_id = ctx.workspace_id.to_string(); let stored = put_media_file(layout, &workspace_id, &finish.path, &finish.ext) .map_err(|error| MethodError::new("io", io_refusal("the recording could not be copied into this device's store", &finish.path, &error)))?; let key = meeting_full_key_of(ctx.file.id(), &finish.meeting, &finish.ext); let content_type = meeting_audio_mime_for_ext(&finish.ext).unwrap_or("application/octet-stream"); enqueue_media( ctx.db(), &MediaEnqueueInput { key: key.clone(), workspace_id, sha256: stored.sha256.clone(), content_type: content_type.to_string(), size_bytes: i64::try_from(stored.size_bytes).unwrap_or(i64::MAX), local_path: Some(stored.path.to_string_lossy().to_string()), state: None, after: None, after_row_id: None, tier: None, captured_here: true, now: now.clone(), }, ) .map_err(|error| MethodError::new("write_refused", error.to_string()))?; let duration_ms = finish.duration_ms.or_else(|| wav_duration_ms(&stored.path)).unwrap_or_else(|| int_of(&meeting, "duration_ms")); let mut patch = object(json!({ "status": "waiting", "status_why": if finish.recovered { json!("recovered") } else { Value::Null }, "audio": key, "audio_bytes": stored.size_bytes, "duration_ms": duration_ms, "ended_at": finish.ended_at.clone().unwrap_or_else(|| now.clone()), "asked_at": now, })); if let Some(marks) = &finish.marks { patch.insert("marks".into(), json!(marks.to_string())); } if let Some(silenced) = &finish.silenced { patch.insert("silenced".into(), json!(silenced.to_string())); } if !finish.tracks.is_empty() { patch.insert("tracks".into(), json!(keep_tracks(ctx, layout, &meeting, finish, &key, &now)?.to_string())); } update(ctx, MEETING, &finish.meeting, patch)?; // The working file is the store's now. if finish.path.starts_with(layout.root().join(RECORDINGS_DIR)) { // not a copy: recordings. let _ = std::fs::remove_file(&finish.path); } Ok(json!({ "meeting": finish.meeting, "status": "waiting", "audio_bytes": stored.size_bytes, "duration_ms": duration_ms })) } /// A call's notes: every person's file kept in the store as the recording's own (sealed like its audio, the first /// being `me`'s, which is the recording's `audio`), and the tracks the call named at the start given their keys. fn keep_tracks(ctx: &mut Ctx<'_>, layout: &cotton_client::layout::Layout, meeting: &Map, finish: &Finish, me_key: &str, now: &str) -> Result { let named: Vec = serde_json::from_str(str_of(meeting, "tracks")).unwrap_or_default(); let mut kept = Vec::new(); for (index, (track, path, ext)) in finish.tracks.iter().enumerate() { let bytes = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0); let mut said = named.iter().find(|t| t["track"] == json!(track)).cloned().unwrap_or_else(|| json!({ "track": track })); said.as_object_mut().map(|t| t.remove("path")); if bytes == 0 { continue; } let key = if index == 0 && track == "me" { me_key.to_string() } else { let workspace_id = ctx.workspace_id.to_string(); let stored = put_media_file(layout, &workspace_id, path, ext).map_err(|error| MethodError::new("io", io_refusal("a track could not be copied into this device's store", path, &error)))?; let key = cotton_core::media::keys::meeting_track_key_of(ctx.file.id(), &finish.meeting, track, ext); enqueue_media( ctx.db(), &MediaEnqueueInput { key: key.clone(), workspace_id, sha256: stored.sha256.clone(), content_type: meeting_audio_mime_for_ext(ext).unwrap_or("application/octet-stream").to_string(), size_bytes: i64::try_from(stored.size_bytes).unwrap_or(i64::MAX), local_path: Some(stored.path.to_string_lossy().to_string()), state: None, after: None, after_row_id: None, tier: None, captured_here: true, now: now.to_string(), }, ) .map_err(|error| MethodError::new("write_refused", error.to_string()))?; if path.starts_with(layout.root().join(RECORDINGS_DIR)) { // not a copy: recordings. let _ = std::fs::remove_file(path); } key }; said["key"] = json!(key); kept.push(said); } Ok(json!(kept)) } /// Recovery at launch: one take the platform names (Android's), or every /// `recording` row this phone left behind. fn recover(handle: &CottonHandle, request: &Value) -> Result { if meeting_id(request).is_ok() { let answer = stop_method(handle, "meetings.record.recover", request, true)?; return Ok(json!({ "recovered": [answer] })); } let layout = handle.client().layout().clone(); let left = with_read(handle, "meetings.record.recover", |ctx| Ok(json!(rows(ctx, MEETING, json!({ "status": "recording" }))?)))?; let mut recovered = Vec::new(); let only = text(request, "source"); for row in left.as_array().cloned().unwrap_or_default() { let id = row["id"].as_str().unwrap_or_default().to_string(); // `source: call`: only a call's notes (Android's own takes recover through their journal, by id). if only.is_some_and(|only| row["source"].as_str() != Some(only)) { continue; } // A call's notes the app was killed in: each person's file kept so far, as the stop would have handed it. let tracks: Vec = serde_json::from_str::>(row["tracks"].as_str().unwrap_or_default()) .unwrap_or_default() .iter() .filter_map(|t| { let track = t["track"].as_str()?; let safe: String = track.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect(); let path = recording_path(layout.root(), &format!("{id}.{safe}"), "aac"); path.exists().then(|| json!({ "track": track, "path": path.to_string_lossy() })) }) .collect(); if !tracks.is_empty() { recovered.push(stop_method(handle, "meetings.record.recover", &json!({ "id": id, "tracks": tracks, "format": "aac" }), true)?); continue; } if only.is_some() { continue; } let held = ["wav", "m4a", "aac"].iter().map(|ext| recording_path(layout.root(), &id, ext)).any(|p| p.exists()); let device = text(request, "device"); let recorded_on = row["recorded_on"].as_str(); // Another phone's recording in progress is not this phone's to end. if !held && device.is_some() && recorded_on.is_some() && device != recorded_on { continue; } if !held && device.is_none() && recorded_on.is_some() { continue; } let answer = stop_method(handle, "meetings.record.recover", &json!({ "id": id }), true)?; recovered.push(answer); } Ok(json!({ "recovered": recovered })) } /// A RIFF/WAVE file's sizes rewritten from its length. pub fn fix_wav_header(path: &Path) -> std::io::Result<()> { use std::io::{Read, Seek, SeekFrom, Write}; let mut file = std::fs::OpenOptions::new().read(true).write(true).open(path)?; let len = file.metadata()?.len(); if len < 44 { return Ok(()); } let mut head = [0u8; 12]; file.read_exact(&mut head)?; if &head[0..4] != b"RIFF" || &head[8..12] != b"WAVE" { return Ok(()); } let riff = u32::try_from(len - 8).unwrap_or(u32::MAX); file.seek(SeekFrom::Start(4))?; file.write_all(&riff.to_le_bytes())?; // Walk the chunks to the data chunk. let mut at = 12u64; while at + 8 <= len { file.seek(SeekFrom::Start(at))?; let mut chunk = [0u8; 8]; file.read_exact(&mut chunk)?; let size = u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]]) as u64; if &chunk[0..4] == b"data" { let data = u32::try_from(len - at - 8).unwrap_or(u32::MAX); file.seek(SeekFrom::Start(at + 4))?; file.write_all(&data.to_le_bytes())?; break; } at += 8 + size + (size & 1); } Ok(()) } /// A PCM WAV's length in milliseconds, from its header. pub fn wav_duration_ms(path: &Path) -> Option { let bytes = std::fs::read(path).ok()?; if bytes.len() < 44 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WAVE" { return None; } let mut at = 12usize; let mut byte_rate = 0u32; while at + 8 <= bytes.len() { let size = u32::from_le_bytes(bytes[at + 4..at + 8].try_into().ok()?) as usize; if &bytes[at..at + 4] == b"fmt " && at + 20 <= bytes.len() { byte_rate = u32::from_le_bytes(bytes[at + 16..at + 20].try_into().ok()?); } if &bytes[at..at + 4] == b"data" { let data = (bytes.len() - at - 8) as i64; return (byte_rate > 0).then(|| data * 1000 / byte_rate as i64); } at += 8 + size + (size & 1); } None } // ── transcription ─────────────────────────────────────────────────────────── fn transcribe(ctx: &mut Ctx<'_>, request: &Value) -> Result { let meeting = meeting_of(ctx, request)?; let id = str_of(&meeting, "id").to_string(); // A phone that took it and cannot hear it yet (its model still coming down) gives it back: waiting again, saying // why, so the Mac or the next pass may take it; never left `transcribing` with no one at it. if request.get("release").and_then(Value::as_bool) == Some(true) { if str_of(&meeting, "status") == "transcribing" { let why = text(request, "why").filter(|w| *w == "model").map(|_| json!("model")).unwrap_or(Value::Null); update(ctx, MEETING, &id, object(json!({ "status": "waiting", "status_why": why, "transcribing_on": null })))?; return Ok(json!({ "meeting": id, "status": "waiting" })); } return Ok(json!({ "meeting": id, "status": str_of(&meeting, "status") })); } match str_of(&meeting, "status") { "recording" => return Err(MethodError::new("still_recording", line("refusal.still_recording"))), "waiting" | "transcribing" => return Ok(json!({ "meeting": id, "status": str_of(&meeting, "status") })), _ => {} } if str_of(&meeting, "audio").is_empty() { return Err(MethodError::new("no_audio", line("why.no_audio"))); } let mut patch = object(json!({ "status": "waiting", "status_why": Value::Null, "asked_at": now_iso(ctx) })); if let Some(on) = text(request, "on") { if !ON.contains(&on) { return Err(bad("`on` is any, mac, phone or service")); } patch.insert("transcribe_on".into(), json!(on)); } update(ctx, MEETING, &id, patch)?; Ok(json!({ "meeting": id, "status": "waiting" })) } /// The next recording this phone should turn into text: its own audio here, /// waiting, asked of any transcriber or of the phone, and only on charge. /// Signed in, the phone claims through the object first (`meeting_claim`, /// refused 409 when the Mac holds it): `peek` names the candidate and claims /// nothing, `except` passes over the ones the object refused, and `id` takes /// that one recording only — so a 409 is never this phone's own claim come /// back by sync. fn next(ctx: &mut Ctx<'_>, layout: &cotton_client::layout::Layout, request: &Value) -> Result { // On charge a phone takes any; off it, a short one while the battery holds // (`battery` given), and nothing at all from a shell that says no more. let charging = request.get("charging").and_then(Value::as_bool); let battery = request.get("battery").and_then(Value::as_i64); let short_only = match (charging, battery) { (Some(false), Some(level)) if level >= SHORT_BATTERY => true, (Some(false), _) => return Ok(json!({ "meeting": Value::Null, "why": "not_charging" })), _ => false, }; // The languages this phone holds a model for (absent: the shell did not say, so any). let held: Option> = request.get("languages").and_then(Value::as_array).map(|l| l.iter().filter_map(Value::as_str).map(str::to_string).collect()); let mut waiting = rows(ctx, MEETING, json!({ "status": "waiting" }))?; waiting.retain(|m| matches!(str_of(m, "transcribe_on"), "any" | "phone" | "")); // Two languages or more are heard on the Mac, line by line: a phone would force them into one. waiting.retain(|m| chosen_languages(m).len() < 2); if short_only { waiting.retain(|m| int_of(m, "duration_ms") <= SHORT_MS); } if let Some(held) = &held { waiting.retain(|m| chosen_languages(m).first().is_none_or(|l| held.contains(l))); } let except: Vec<&str> = request.get("except").and_then(Value::as_array).map(|ids| ids.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); waiting.retain(|m| !except.contains(&str_of(m, "id"))); if let Some(only) = text(request, "id") { waiting.retain(|m| str_of(m, "id") == only); } let peek = request.get("peek").and_then(Value::as_bool).unwrap_or(false); waiting.sort_by(|a, b| str_of(a, "asked_at").cmp(str_of(b, "asked_at")).then(str_of(a, "started_at").cmp(str_of(b, "started_at")))); for meeting in waiting { let key = str_of(&meeting, "audio").to_string(); let Some(path) = local_audio(ctx, layout, &key) else { continue }; let id = str_of(&meeting, "id").to_string(); if !peek { let attempts = int_of(&meeting, "attempts") + 1; update(ctx, MEETING, &id, object(json!({ "status": "transcribing", "attempts": attempts, "status_why": Value::Null, "transcribing_on": "phone" })))?; } let duration_ms = int_of(&meeting, "duration_ms"); let mut answer = json!({ "meeting": id, "audio_path": path.to_string_lossy(), "language": chosen_languages(&meeting).first(), "duration_ms": duration_ms, "windows": rules::windows(duration_ms, &[], rules::WINDOW_MS, rules::OVERLAP_MS), }); // A call's notes: each person's file, heard alone (`meetings.transcribed { tracks }`). let tracks: Vec = serde_json::from_str(str_of(&meeting, "tracks")).unwrap_or_default(); let held: Vec = tracks .iter() .filter_map(|t| { let path = local_audio(ctx, layout, t["key"].as_str().unwrap_or_default())?; Some(json!({ "track": t["track"], "audio_path": path.to_string_lossy() })) }) .collect(); if !held.is_empty() { answer["tracks"] = json!(held); } return Ok(answer); } Ok(json!({ "meeting": Value::Null })) } /// Where this phone holds `key`'s bytes, when it does. fn local_audio(ctx: &mut Ctx<'_>, layout: &cotton_client::layout::Layout, key: &str) -> Option { if key.is_empty() { return None; } let row = cotton_store::media_ledger::media_by_key(ctx.db(), key).ok().flatten()?; let path = row.local_path.map(PathBuf::from).or_else(|| { let ext = key.rsplit('.').next().unwrap_or_default(); Some(cotton_client::media::store::media_file_path(layout, ctx.workspace_id, &row.sha256, ext)) })?; path.exists().then_some(path) } fn windows_of(ctx: &mut Ctx<'_>, request: &Value) -> Result { let duration_ms = match duration_arg(request) { Some(ms) => ms, None => int_of(&meeting_of(ctx, request)?, "duration_ms"), }; let speech: Vec = request.get("speech").cloned().map(serde_json::from_value).transpose().map_err(|e| bad(format!("`speech` is a list of {{start_ms, end_ms}}: {e}")))?.unwrap_or_default(); let window_ms = request.get("window_ms").and_then(Value::as_i64).unwrap_or(rules::WINDOW_MS); let overlap_ms = request.get("overlap_ms").and_then(Value::as_i64).unwrap_or(rules::OVERLAP_MS); Ok(json!({ "windows": rules::windows(duration_ms, &speech, window_ms, overlap_ms) })) } fn merge_of(request: &Value) -> Result { let heard: Vec = request.get("windows").cloned().map(serde_json::from_value).transpose().map_err(|e| bad(format!("`windows` is a list of heard windows: {e}")))?.ok_or_else(|| bad("this names `windows`"))?; let by = text(request, "by").unwrap_or_default(); Ok(json!({ "transcript": rules::merge(by, &heard) })) } fn transcribed(ctx: &mut Ctx<'_>, request: &Value) -> Result { let meeting = meeting_of(ctx, request)?; let id = str_of(&meeting, "id").to_string(); if let Some(why) = text(request, "failed") { update(ctx, MEETING, &id, object(json!({ "status": "failed", "status_why": why })))?; return Ok(json!({ "meeting": id, "status": "failed" })); } let transcript: Transcript = match request.get("transcript") { Some(t) => serde_json::from_value(t.clone()).map_err(|e| bad(format!("`transcript` is {{ by, languages, speakers, lines }}: {e}")))?, // A call's notes: each track's windows, one person each. None if request.get("tracks").is_some() => { let tracks: Vec = serde_json::from_value(request["tracks"].clone()).map_err(|e| bad(format!("`tracks` is a list of {{ track, windows }}: {e}")))?; rules::merge_tracks(text(request, "by").unwrap_or_default(), &tracks) } // A phone may hand its heard windows and let the core merge them. None => { let heard: Vec = request.get("windows").cloned().map(serde_json::from_value).transpose().map_err(|e| bad(e.to_string()))?.ok_or_else(|| bad("this names `transcript` or `windows`"))?; rules::merge(text(request, "by").unwrap_or_default(), &heard) } }; let landed = land(ctx, &id, &transcript)?; name_tracks(ctx, &meeting, &id)?; Ok(json!({ "meeting": id, "status": "ready", "lines": landed.0, "speakers": landed.1 })) } /// A call's voices named as the call named them: each speaker whose label is a track takes that track's person /// (his people row) and name, unless he has named it himself. fn name_tracks(ctx: &mut Ctx<'_>, meeting: &Map, id: &str) -> Result<(), MethodError> { let tracks: Vec = serde_json::from_str(str_of(meeting, "tracks")).unwrap_or_default(); if tracks.is_empty() { return Ok(()); } for speaker in rows(ctx, SPEAKER, json!({ "meeting": id }))? { let Some(track) = tracks.iter().find(|t| t["track"].as_str() == Some(str_of(&speaker, "label"))) else { continue }; if !str_of(&speaker, "name").is_empty() || !str_of(&speaker, "person").is_empty() { continue; } let mut patch = Map::new(); if let Some(person) = track["person"].as_str().filter(|p| get(ctx, "person", p).is_some()) { patch.insert("person".into(), json!(person)); } // His own voice is "You", as the call names him; another's, as the call named them, else their number. let you = (track["member"] == "me").then(|| chat_line("app.call.group.you")); if let Some(name) = you.as_deref().or_else(|| track["name"].as_str()).or_else(|| track["number"].as_str()) { patch.insert("name".into(), json!(name)); } update(ctx, SPEAKER, str_of(&speaker, "id"), patch)?; } Ok(()) } /// Speakers and lines replaced in this one write; corrections and names kept. pub(crate) fn land(ctx: &mut Ctx<'_>, meeting: &str, fresh: &Transcript) -> Result<(usize, usize), MethodError> { let old_speakers = rows(ctx, SPEAKER, json!({ "meeting": meeting }))?; let old_lines = rows(ctx, LINE, json!({ "meeting": meeting }))?; let label_of = |speaker: &str| old_speakers.iter().find(|s| str_of(s, "id") == speaker).map(|s| str_of(s, "label").to_string()).unwrap_or_default(); let held: Vec = old_lines .iter() .filter(|l| l.get("edited").and_then(Value::as_bool) == Some(true)) .map(|l| HeldLine { start_ms: int_of(l, "start_ms"), end_ms: int_of(l, "end_ms"), text: str_of(l, "text").to_string(), speaker: label_of(str_of(l, "speaker")), language: l.get("language").and_then(Value::as_str).map(str::to_string), }) .collect(); let transcript = rules::keep_corrections(&rules::as_written(fresh), &held); for old in &old_lines { delete(ctx, LINE, str_of(old, "id"))?; } let figures = rules::speaker_figures(&transcript); let mut ids: Vec<(String, String)> = Vec::new(); for figure in &figures { let kept = old_speakers.iter().find(|s| str_of(s, "label") == figure.label); let patch = json!({ "lines": figure.lines, "talk_ms": figure.talk_ms, "first_ms": figure.first_ms }); let id = match kept { Some(s) => { let id = str_of(s, "id").to_string(); update(ctx, SPEAKER, &id, object(patch))?; id } None => { let mut data = patch; data["meeting"] = json!(meeting); data["label"] = json!(figure.label); create(ctx, SPEAKER, data)? } }; ids.push((figure.label.clone(), id)); } for gone in old_speakers.iter().filter(|s| !figures.iter().any(|f| f.label == str_of(s, "label"))) { delete(ctx, SPEAKER, str_of(gone, "id"))?; } for (position, l) in transcript.lines.iter().enumerate() { let speaker = ids.iter().find(|(label, _)| label == &l.speaker).map(|(_, id)| id.clone()); let was_held = held.iter().any(|h| h.start_ms == l.start_ms && h.end_ms == l.end_ms && h.text == l.text); create( ctx, LINE, json!({ "meeting": meeting, "speaker": speaker, "position": position as i64 + 1, "start_ms": l.start_ms, "end_ms": l.end_ms, "text": l.text, "language": l.language, "edited": was_held, }), )?; } let now = now_iso(ctx); update( ctx, MEETING, meeting, object(json!({ "status": "ready", "status_why": Value::Null, "languages": transcript.languages.join(","), "speakers": figures.len(), "lines": transcript.lines.len(), "transcribed_by": if transcript.by.is_empty() { Value::Null } else { json!(transcript.by) }, "transcribed_at": now, })), )?; Ok((transcript.lines.len(), figures.len())) } // ── reading, naming, finding ──────────────────────────────────────────────── pub(crate) fn lines_of(ctx: &mut Ctx<'_>, meeting: &str) -> Result>, MethodError> { let mut lines = rows(ctx, LINE, json!({ "meeting": meeting }))?; lines.sort_by_key(|l| (int_of(l, "start_ms"), int_of(l, "position"))); Ok(lines) } pub(crate) fn speakers_of(ctx: &mut Ctx<'_>, meeting: &str) -> Result>, MethodError> { let mut speakers = rows(ctx, SPEAKER, json!({ "meeting": meeting }))?; speakers.sort_by_key(|s| (int_of(s, "first_ms"), str_of(s, "label").to_string())); Ok(speakers) } /// The meeting whole for its transcript page, the same on both phones: /// `{meeting, speakers, lines, marks, silenced, audio?, audio_path?, actions, summary_note}`. /// `marks` is the moments the person marked, in ms from the start, as a list /// (the row keeps them as JSON text); `silenced` the stretches a call took the /// microphone, `[[from_ms, to_ms]…]`; `audio` is `{key, path?}`, `path` (and /// `audio_path`, the same) only where this phone holds the bytes (otherwise /// the phone asks `media.ensure {key}` for them). fn read(ctx: &mut Ctx<'_>, layout: &cotton_client::layout::Layout, request: &Value) -> Result { let meeting = meeting_of(ctx, request)?; let id = str_of(&meeting, "id").to_string(); let speakers = speakers_of(ctx, &id)?; let lines = lines_of(ctx, &id)?; let mut marks: Vec = match meeting.get("marks") { Some(Value::String(text)) => serde_json::from_str::>(text).unwrap_or_default(), Some(Value::Array(list)) => list.clone(), _ => Vec::new(), } .iter() .filter_map(|m| m.as_i64().or_else(|| m.as_f64().map(|f| f as i64)).or_else(|| m.get("at_ms").and_then(Value::as_i64))) .collect(); marks.sort_unstable(); let silenced: Vec = match meeting.get("silenced") { Some(Value::String(text)) => serde_json::from_str(text).unwrap_or_default(), _ => Vec::new(), }; let key = str_of(&meeting, "audio").to_string(); let held = if key.is_empty() { None } else { local_audio(ctx, layout, &key) }; let audio = match (&held, key.is_empty()) { (_, true) => Value::Null, (Some(path), false) => json!({ "key": key, "path": path.to_string_lossy() }), (None, false) => json!({ "key": key }), }; let audio_path = held.map(|path| json!(path.to_string_lossy())).unwrap_or(Value::Null); let actions = actions_of(ctx, &id, &speakers)?; let summary_note = summary_note(&meeting); let charging = request.get("charging").and_then(Value::as_bool).unwrap_or(false); let status_words = status_words(&meeting, charging); let transcribed_by = transcribed_by_words(&meeting); Ok(json!({ "meeting": meeting, "speakers": speakers, "lines": lines, "marks": marks, "silenced": silenced, "audio": audio, "audio_path": audio_path, "actions": actions, "summary_note": summary_note, "status_words": status_words, "transcribed_by": transcribed_by })) } /// What a meeting's state says, the same on both phones (`status.*`, a /// failure's why from `why.*`): waiting says whether this phone, on charge, /// may turn it into text too. pub(crate) fn status_words(meeting: &Map, charging: bool) -> String { match str_of(meeting, "status") { "recording" => line("status.recording"), "waiting" => line(if charging { "status.waiting" } else { "status.waiting_charge" }), "transcribing" => line("status.transcribing"), "ready" => line("status.ready"), "failed" => match str_of(meeting, "status_why") { "" => line("status.failed_plain"), why => { let said = cotton_core::rules::shell_lines::LineSet::shipped("meetings").and_then(|lines| lines.say(&format!("why.{why}"), &[])).unwrap_or_else(|| why.to_string()); say("status.failed", &[("why", &said)]) } }, other => other.to_string(), } } /// Where a ready meeting was turned into text ("Turned into text by this /// phone / your Mac"), from its `transcribed_by` (`phone:…`, `mac:…`); null /// when it does not say. fn transcribed_by_words(meeting: &Map) -> Value { if str_of(meeting, "status") != "ready" { return Value::Null; } match str_of(meeting, "transcribed_by").split(':').next().unwrap_or_default() { "phone" => json!(say("transcript.transcribed_by", &[("who", &line("phone.me"))])), "mac" => json!(say("transcript.transcribed_by", &[("who", &line("phone.mac"))])), _ => Value::Null, } } // ── the summary and its actions ─────────────────── // // A meeting's summary and actions are written on the person's Mac by a local // model (`cotton-mac` `summarise`), or by the person's own assistant over // MCP; the phone reads them. Each action is a `meetings_action` row; the one // act on it is Add to todos, which makes a todo and links it from the action, // so the action says it was added from then on. /// The meeting's actions as the shells draw them, in order: each with who /// (a speaker's name where the person gave one), the day, and its act, or the /// words saying it was already added. pub(crate) fn actions_of(ctx: &mut Ctx<'_>, meeting: &str, speakers: &[Map]) -> Result, MethodError> { let mut actions = rows(ctx, ACTION, json!({ "meeting": meeting }))?; actions.sort_by_key(|a| (int_of(a, "position"), str_of(a, "words").to_string())); Ok(actions .into_iter() .map(|a| { let speaker = speakers.iter().find(|s| !str_of(&a, "speaker").is_empty() && str_of(s, "id") == str_of(&a, "speaker")).or_else(|| speakers.iter().find(|s| !str_of(&a, "who").is_empty() && str_of(s, "label") == str_of(&a, "who"))); let who_said = match speaker { Some(s) if !str_of(s, "name").trim().is_empty() => Some(str_of(s, "name").trim().to_string()), Some(s) => Some(say("transcript.speaker", &[("number", str_of(s, "label").trim_start_matches('S'))])), None => Some(str_of(&a, "who").trim().to_string()).filter(|w| !w.is_empty()), }; let added = !str_of(&a, "todo").is_empty(); json!({ "id": str_of(&a, "id"), "words": str_of(&a, "words"), "who": who_said, "due": a.get("due").cloned().unwrap_or(Value::Null), "due_said": a.get("due_said").cloned().unwrap_or(Value::Null), "at_ms": a.get("at_ms").cloned().unwrap_or(Value::Null), "todo": a.get("todo").cloned().unwrap_or(Value::Null), "added": added, "act": if added { Value::Null } else { json!({ "label": line("summary.add"), "method": "meetings.action.todo" }) }, "said": if added { json!(line("summary.added")) } else { Value::Null }, }) }) .collect()) } /// Why a ready meeting has no summary yet, in the person's words; none once /// it has one or while it is not ready. pub(crate) fn summary_note(meeting: &Map) -> Value { if str_of(meeting, "status") != "ready" || !str_of(meeting, "summary").trim().is_empty() { return Value::Null; } let why = match (str_of(meeting, "summarise_on"), str_of(meeting, "summary_why")) { ("off", _) => "off", (_, "") => "no_mac", (_, why) => why, }; json!(line(&format!("summary_why.{why}"))) } /// Summarise (again): the Mac is asked, by `summary_asked_at`, and the /// meeting is put back on (`summarise_on: mac`); nothing leaves the person's /// devices. fn summarise(ctx: &mut Ctx<'_>, request: &Value) -> Result { let meeting = meeting_of(ctx, request)?; let id = str_of(&meeting, "id").to_string(); if str_of(&meeting, "status") == "recording" { return Err(MethodError::new("still_recording", line("refusal.still_recording"))); } let now = now_iso(ctx); update(ctx, MEETING, &id, object(json!({ "summary_asked_at": now, "summarise_on": "mac", "summary_why": null })))?; Ok(json!({ "meeting": id, "status": "asked", "said": line("summary.asked") })) } /// Add to todos: a todo made from the action (its words, its day, where it /// came from in its notes) and linked from the action, in one write. An /// action already added answers the todo it made and makes no other. fn action_todo(handle: &CottonHandle, request: &Value) -> Result { let id = text(request, "action").or_else(|| text(request, "id")).ok_or_else(|| bad("this names the `action`"))?.to_string(); // A day is placed in the phone's own zone, never UTC. let zone = handle.client().time_zone().map(str::to_string); with_write(handle, "meetings.action.todo", |ctx| { let action = get(ctx, ACTION, &id).ok_or_else(|| MethodError::new("not_found", line("refusal.no_action")))?; if !str_of(&action, "todo").is_empty() { return Ok(json!({ "action": id, "todo": str_of(&action, "todo"), "added": true, "already": true, "said": line("summary.added") })); } let meeting = get(ctx, MEETING, str_of(&action, "meeting")).unwrap_or_default(); let title = Some(str_of(&meeting, "title").trim()).filter(|t| !t.is_empty()).map(str::to_string).unwrap_or_else(|| line("summary.untitled")); let mut todo = object(json!({ "title": str_of(&action, "words"), "notes": say("summary.from_meeting", &[("title", &title)]) })); if let Some(due) = action.get("due").and_then(Value::as_str).filter(|d| !d.is_empty()) { todo.insert("dueDate".into(), json!(&due[..due.len().min(10)])); if let Some(zone) = &zone { todo.insert("timezone".into(), json!(zone)); } } let made = cotton_tools::mcp::handlers::records_1::todos::create_todo(ctx, &todo).map_err(tool)?; let todo_id = made["id"] .as_str() .or_else(|| made["todo"]["id"].as_str()) .or_else(|| made["record"]["id"].as_str()) .map(str::to_string) .ok_or_else(|| MethodError::new("write_refused", format!("no id for the new todo: {made}")))?; update(ctx, ACTION, &id, object(json!({ "todo": todo_id })))?; Ok(json!({ "action": id, "todo": todo_id, "added": true, "already": false, "said": line("summary.added") })) }) } fn name_speaker(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = text(request, "speaker").or_else(|| text(request, "id")).ok_or_else(|| bad("this names the `speaker`"))?.to_string(); get(ctx, SPEAKER, &id).ok_or_else(|| MethodError::new("not_found", line("refusal.no_speaker")))?; let mut patch = Map::new(); if let Some(name) = request.get("name") { patch.insert("name".into(), match name.as_str().map(str::trim) { Some("") | None => Value::Null, Some(name) => json!(name), }); } if let Some(person) = request.get("person") { patch.insert("person".into(), if person.as_str().is_some_and(|p| !p.trim().is_empty()) { person.clone() } else { Value::Null }); } if patch.is_empty() { return Err(bad("this names a `name` or a `person`")); } update(ctx, SPEAKER, &id, patch)?; Ok(json!({ "speaker": get(ctx, SPEAKER, &id) })) } /// A person's correction of what a line says: kept over every later /// transcription of the same moment. fn correct_line(ctx: &mut Ctx<'_>, request: &Value) -> Result { let id = text(request, "line").or_else(|| text(request, "id")).ok_or_else(|| bad("this names the `line`"))?.to_string(); let said = request.get("text").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| bad("this names the corrected `text`"))?; get(ctx, LINE, &id).ok_or_else(|| MethodError::new("not_found", line("refusal.no_line")))?; update(ctx, LINE, &id, object(json!({ "text": said, "edited": true })))?; Ok(json!({ "line": get(ctx, LINE, &id) })) } /// Folded for finding: lower case. fn folded(text: &str) -> String { text.chars().flat_map(char::to_lowercase).collect() } fn search(ctx: &mut Ctx<'_>, request: &Value) -> Result { let q = text(request, "q").ok_or_else(|| bad("this names the words to find: `q`"))?; let words: Vec = folded(q).split_whitespace().map(str::to_string).collect(); let limit = request.get("limit").and_then(Value::as_u64).unwrap_or(100) as usize; let filter = match text(request, "id").or_else(|| text(request, "meeting")) { Some(meeting) => json!({ "meeting": meeting }), None => json!({}), }; let mut lines = rows(ctx, LINE, filter)?; lines.retain(|l| { let said = folded(str_of(l, "text")); words.iter().all(|w| said.contains(w.as_str())) }); lines.sort_by(|a, b| str_of(a, "meeting").cmp(str_of(b, "meeting")).then(int_of(a, "start_ms").cmp(&int_of(b, "start_ms")))); let total = lines.len(); let hits: Vec = lines .into_iter() .take(limit) .map(|l| json!({ "meeting": l.get("meeting"), "line": l.get("id"), "start_ms": int_of(&l, "start_ms"), "end_ms": int_of(&l, "end_ms"), "text": l.get("text"), "speaker": l.get("speaker") })) .collect(); Ok(json!({ "hits": hits, "total": total })) } // ── the open bundle ───────────────────────────────────────────────────────── /// A meeting's rows as the rules' transcript, with the names given. fn transcript_of(ctx: &mut Ctx<'_>, meeting: &Map) -> Result<(Transcript, Vec<(String, String)>), MethodError> { let id = str_of(meeting, "id").to_string(); let speakers = speakers_of(ctx, &id)?; let lines = lines_of(ctx, &id)?; let label = |speaker: &str| speakers.iter().find(|s| str_of(s, "id") == speaker).map(|s| str_of(s, "label").to_string()).unwrap_or_default(); let transcript = Transcript { by: str_of(meeting, "transcribed_by").to_string(), languages: str_of(meeting, "languages").split(',').filter(|l| !l.is_empty()).map(str::to_string).collect(), speakers: speakers.iter().map(|s| rules::Speaker { label: str_of(s, "label").to_string() }).collect(), lines: lines .iter() .map(|l| Line { speaker: label(str_of(l, "speaker")), start_ms: int_of(l, "start_ms"), end_ms: int_of(l, "end_ms"), text: str_of(l, "text").to_string(), language: l.get("language").and_then(Value::as_str).map(str::to_string), }) .collect(), }; let names = speakers.iter().map(|s| (str_of(s, "label").to_string(), str_of(s, "name").to_string())).collect(); Ok((transcript, names)) } fn export(ctx: &mut Ctx<'_>, layout: &cotton_client::layout::Layout, root: &Path, request: &Value) -> Result { let meeting = meeting_of(ctx, request)?; let id = str_of(&meeting, "id").to_string(); let (transcript, names) = transcript_of(ctx, &meeting)?; let title = str_of(&meeting, "title").to_string(); let dir = text(request, "dir").map(PathBuf::from).unwrap_or_else(|| root.join("exports").join("meetings").join(&id)); std::fs::create_dir_all(&dir).map_err(|e| MethodError::new("io", io_refusal("the export folder could not be made", &dir, &e)))?; let only = text(request, "format"); let mut files = Vec::new(); let mut write = |name: &str, kind: &str, body: String| -> Result<(), MethodError> { let path = dir.join(name); // not a copy: recordings. std::fs::write(&path, body).map_err(|e| MethodError::new("io", io_refusal("the export could not be written", &path, &e)))?; files.push(json!({ "name": name, "path": path.to_string_lossy(), "type": kind })); Ok(()) }; let want = |f: &str| only.map_or(true, |o| o == f || (o == "text" && f == "txt")); if want("txt") { write("transcript.txt", "text/plain", rules::to_text(&title, &transcript, &names))?; } if want("srt") { write("transcript.srt", "application/x-subrip", rules::to_srt(&transcript, &names))?; } if want("json") { let body = serde_json::to_string_pretty(&rules::to_json(&title, &transcript, &names)).unwrap_or_default(); write("transcript.json", "application/json", body + "\n")?; } if want("audio") { let key = str_of(&meeting, "audio").to_string(); if let Some(path) = local_audio(ctx, layout, &key) { let ext = key.rsplit('.').next().unwrap_or("wav"); let name = format!("recording.{ext}"); let to = dir.join(&name); // not a copy: recordings. std::fs::copy(&path, &to).map_err(|e| MethodError::new("io", io_refusal("the recording could not be copied out", &to, &e)))?; files.push(json!({ "name": name, "path": to.to_string_lossy(), "type": meeting_audio_mime_for_ext(ext).unwrap_or("application/octet-stream") })); } } Ok(json!({ "files": files, "dir": dir.to_string_lossy() })) } // ── on this phone ─────────────────────────────────────────────────────────── const ON_PHONE: &str = "on_phone"; const KEPT: &str = "kept"; const ABSENT: &str = "absent"; /// A key no recording names: a list of what this phone keeps, when it keeps none. const NOTHING_KEPT: &str = "-"; /// The recordings' audio keys this phone holds the bytes of. fn kept_here(client: &crate::shell::client::ClientController) -> Result, MethodError> { let layout = client.layout().clone(); let answer = client .read_rows("meetings.on_phone", &mut |ctx| { let rows = ctx .db() .all("SELECT key, sha256, local_path FROM _media WHERE key LIKE ?", &[rusqlite::types::Value::Text("%/meetings/%".into())]) .map_err(|e| e.to_string())?; let mut keys = Vec::new(); for row in rows { let Some(key) = row.text("key") else { continue }; let ext = key.rsplit('.').next().unwrap_or_default(); let path = row.text("local_path").map(PathBuf::from).unwrap_or_else(|| cotton_client::media::store::media_file_path(&layout, ctx.workspace_id, row.text("sha256").unwrap_or_default(), ext)); if path.exists() { keys.push(Value::from(key)); } } Ok(Value::Array(keys)) }) .map_err(|why| MethodError::new("unreadable", why))?; Ok(answer.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()) } /// Fill `on_phone` on every recording of a records answer: `kept` while its /// audio is here (or it is still recording here), else `absent`. pub(crate) fn answer_on_phone(client: &crate::shell::client::ClientController, answer: &mut Value) -> Result<(), MethodError> { let records: Vec<&mut Value> = match answer.get_mut("records").and_then(Value::as_array_mut) { Some(records) => records.iter_mut().collect(), None => vec![answer], }; let mut kept: Option> = None; for record in records { let data = match record.get_mut("data").and_then(Value::as_object_mut) { Some(data) => data, None => match record.as_object_mut() { Some(data) if data.contains_key("status") => data, _ => continue, }, }; data.remove(ON_PHONE); let recording = data.get("status").and_then(Value::as_str) == Some("recording"); let audio = data.get("audio").and_then(Value::as_str).unwrap_or_default().to_string(); if kept.is_none() && !audio.is_empty() { kept = Some(kept_here(client)?); } let here = recording || kept.as_ref().is_some_and(|k| k.contains(&audio)); data.insert(ON_PHONE.to_string(), Value::from(if here { KEPT } else { ABSENT })); } Ok(()) } /// A list of recordings read by `where.on_phone` (On this phone): the column /// is this device's answer, never stored, so it is read as the audio keys /// this phone holds. Other tables pass unchanged. pub(crate) fn narrow_where(client: &crate::shell::client::ClientController, args: &mut Map) -> Result<(), MethodError> { if args.get("table").and_then(Value::as_str) != Some(MEETING) { return Ok(()); } let Some(conditions) = args.get_mut("where").and_then(Value::as_object_mut) else { return Ok(()) }; let Some(wanted) = conditions.remove(ON_PHONE) else { return Ok(()) }; let states: Vec = match &wanted { Value::String(state) => vec![state.clone()], Value::Array(states) => states.iter().filter_map(Value::as_str).map(str::to_string).collect(), Value::Object(shape) => shape.get("values").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(), _ => Vec::new(), }; let kept: Vec = kept_here(client)?.into_iter().map(Value::from).collect(); let condition = match states.iter().map(String::as_str).collect::>().as_slice() { [KEPT] => Value::Array(if kept.is_empty() { vec![Value::from(NOTHING_KEPT)] } else { kept }), [ABSENT] if kept.is_empty() => json!({ "present": true }), [ABSENT] => json!({ "not": kept }), _ => return Err(bad("on_phone reads kept or absent")), }; conditions.insert("audio".to_string(), condition); Ok(()) } #[cfg(test)] #[path = "meetings_app_tests.rs"] mod tests; // ── recordings in Comms (DECISIONS "Recordings") ────── /// The languages the person chose for a recording, in order (empty: Cotton picks). pub(crate) fn chosen_languages(meeting: &Map) -> Vec { str_of(meeting, "languages_chosen").split(',').map(str::trim).filter(|l| !l.is_empty()).map(str::to_string).collect() } /// The ending a file is kept under, from its name, else from what the shell says it is. fn import_ext(name: Option<&str>, mime: Option<&str>) -> Option { let by_name = name.and_then(|n| Path::new(n).extension()).and_then(|e| e.to_str()).map(str::to_ascii_lowercase); // 3GPP is the MPEG-4 file family: kept as one. let by_name = by_name.map(|e| if e == "3gp" || e == "3gpp" { "mp4".to_string() } else { e }); if let Some(ext) = by_name.filter(|e| meeting_audio_mime_for_ext(e).is_some()) { return Some(ext); } let mime = mime?.split(';').next()?.trim().to_ascii_lowercase(); let ext = match mime.as_str() { "audio/mp4" | "audio/m4a" | "audio/x-m4a" | "audio/3gpp" | "video/3gpp" => "m4a", "audio/aac" | "audio/x-aac" | "audio/aac-adts" => "aac", "audio/mpeg" | "audio/mp3" => "mp3", "audio/wav" | "audio/x-wav" | "audio/wave" | "audio/vnd.wave" => "wav", "audio/ogg" | "audio/opus" | "application/ogg" => "ogg", "audio/flac" | "audio/x-flac" => "flac", "audio/amr" | "audio/amr-wb" => "amr", "audio/x-caf" => "caf", _ => return None, }; Some(ext.to_string()) } /// An audio file shared or opened into the app becomes a recording /// (`source: import`), copied into the sealed store and heard as any other. fn import(handle: &CottonHandle, request: &Value) -> Result { let path = PathBuf::from(text(request, "path").ok_or_else(|| bad("this names the file's `path`"))?); let name = text(request, "name").map(str::to_string).or_else(|| path.file_name().and_then(|n| n.to_str()).map(str::to_string)); let Some(ext) = import_ext(name.as_deref(), text(request, "mime")) else { return Err(MethodError::new("not_audio", chat_line("app.recording.import.not_audio"))); }; if std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0) == 0 { return Err(MethodError::new("not_audio", chat_line("app.recording.import.not_audio"))); } let title = name.as_deref().map(|n| Path::new(n).file_stem().and_then(|s| s.to_str()).unwrap_or(n).trim().to_string()).filter(|t| !t.is_empty()); let duration_ms = duration_arg(request); let layout = handle.client().layout().clone(); let root = layout.root().to_path_buf(); let zone = handle.client().time_zone().unwrap_or("Etc/UTC").to_string(); with_write(handle, "meetings.import", |ctx| { // When it was made: the file's own time, its name's, its last change, else now (`recording_time::taken_at`). let started_at = match text(request, "taken_at") { Some(at) => at.to_string(), None => { let now = chrono::DateTime::from_timestamp_millis(cotton_tools::mcp::handlers::common::now_ms(ctx)).unwrap_or_default(); let facts = cotton_core::messages::app::recording_time::Facts { name: name.as_deref(), recorded: text(request, "recorded"), modified_ms: request.get("modified_ms").and_then(Value::as_f64).filter(|n| n.is_finite()).map(|n| n as i64), }; cotton_core::messages::app::recording_time::taken_at(&facts, &zone, now).to_rfc3339_opts(chrono::SecondsFormat::Millis, true) } }; let started = start(ctx, &root, &json!({ "kind": "memo", "source": "import", "title": title, "started_at": started_at }))?; let meeting = started["meeting"].as_str().unwrap_or_default().to_string(); let ended_at = duration_ms.and_then(|ms| chrono::DateTime::parse_from_rfc3339(&started_at).ok().map(|at| (at + chrono::Duration::milliseconds(ms)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true))); let finish = Finish { meeting: meeting.clone(), path: path.clone(), ext: ext.clone(), duration_ms, ended_at, marks: None, silenced: None, recovered: false, tracks: Vec::new() }; let done = finish_one(ctx, &layout, &finish)?; Ok(json!({ "meeting": meeting, "status": done["status"], "said": chat_line("app.recording.import.said") })) }) } /// His correction of a recording's languages: kept, and the recording heard /// again (on the Mac when he named two or more). fn language(ctx: &mut Ctx<'_>, request: &Value) -> Result { let meeting = meeting_of(ctx, request)?; let id = str_of(&meeting, "id").to_string(); let languages: Vec = request.get("languages").and_then(Value::as_array).map(|l| l.iter().filter_map(Value::as_str).map(|c| c.trim().to_ascii_lowercase()).filter(|c| !c.is_empty()).collect()).unwrap_or_default(); let mut seen = Vec::new(); for code in languages { if !seen.contains(&code) { seen.push(code); } } update(ctx, MEETING, &id, object(json!({ "languages_chosen": if seen.is_empty() { Value::Null } else { json!(seen.join(",")) } })))?; let on = if seen.len() >= 2 { "mac" } else { "any" }; match str_of(&meeting, "status") { "recording" => {} _ if str_of(&meeting, "audio").is_empty() => {} _ => { update(ctx, MEETING, &id, object(json!({ "status": "waiting", "status_why": null, "asked_at": now_iso(ctx), "transcribe_on": on })))?; } } Ok(json!({ "meeting": id, "languages": seen, "on": on })) } /// A recording's date and time, his to set: `at` (RFC 3339, any offset), or `date` `YYYY-MM-DD` and `time` `HH:MM` on /// his wall clock. Its end moves with it, so its length stays. Never after now. pub(crate) fn redate(ctx: &mut Ctx<'_>, zone: &str, request: &Value) -> Result { use cotton_core::messages::app::recording_time::{set_by_hand, Refused}; let meeting = meeting_of(ctx, request)?; let id = str_of(&meeting, "id").to_string(); let now = chrono::DateTime::from_timestamp_millis(cotton_tools::mcp::handlers::common::now_ms(ctx)).unwrap_or_default(); let asked = match text(request, "at") { Some(at) => chrono::DateTime::parse_from_rfc3339(at.trim()).map(|at| at.with_timezone(&chrono::Utc)).map_err(|_| Refused::Unreadable).and_then(|at| if at > now { Err(Refused::Later) } else { Ok(at) }), None => set_by_hand(text(request, "date").unwrap_or_default(), text(request, "time").unwrap_or_default(), zone, now), }; let at = asked.map_err(|why| match why { Refused::Later => MethodError::new("future", chat_line("app.recording.date.future")), Refused::Unreadable => bad("this names the recording's `at` (RFC 3339), or its `date` (YYYY-MM-DD) and `time` (HH:MM)"), })?; let iso = |t: chrono::DateTime| t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let was = chrono::DateTime::parse_from_rfc3339(str_of(&meeting, "started_at")).ok(); let ended = chrono::DateTime::parse_from_rfc3339(str_of(&meeting, "ended_at")).ok(); let ended_at = match (was, ended) { (Some(was), Some(ended)) => Some(iso(at + (ended - was))), _ => None, }; let mut patch = json!({ "started_at": iso(at) }); if let Some(ended_at) = ended_at { patch["ended_at"] = json!(ended_at); } update(ctx, MEETING, &id, object(patch))?; Ok(json!({ "meeting": id, "started_at": iso(at) })) } /// A recording's title, his to change (empty: the core's untitled words again). fn retitle(ctx: &mut Ctx<'_>, request: &Value) -> Result { let meeting = meeting_of(ctx, request)?; let id = str_of(&meeting, "id").to_string(); let title = request.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()); update(ctx, MEETING, &id, object(json!({ "title": title })))?; Ok(json!({ "meeting": id, "title": title })) } /// A recording to the bin with its lines, speakers and actions; a to-do made /// from it stays, and so does its note. fn delete_meeting(ctx: &mut Ctx<'_>, layout: &cotton_client::layout::Layout, request: &Value) -> Result { let meeting = meeting_of(ctx, request)?; let id = str_of(&meeting, "id").to_string(); for table in [LINE, SPEAKER, ACTION] { for row in rows(ctx, table, json!({ "meeting": id }))? { delete(ctx, table, str_of(&row, "id"))?; } } if str_of(&meeting, "status") == "recording" { for ext in ["wav", "m4a", "aac"] { // not a copy: recordings. let _ = std::fs::remove_file(recording_path(layout.root(), &id, ext)); } } delete(ctx, MEETING, &id)?; Ok(json!({ "meeting": id, "deleted": true, "said": chat_line("app.recording.delete.said") })) } /// A line of Comms' set (`chat`). pub(crate) fn chat_line(name: &str) -> String { chat_say(name, &[]) } pub(crate) fn chat_say(name: &str, fill: &[(&str, &str)]) -> String { cotton_core::rules::shell_lines::LineSet::shipped("chat").and_then(|lines| lines.say(name, fill)).unwrap_or_else(|| name.to_string()) } /// A recording's title as a person reads it: his own, else the core's words for its kind. pub(crate) fn title_of(meeting: &Map, call_with: Option<&str>) -> String { if let Some(title) = Some(str_of(meeting, "title").trim()).filter(|t| !t.is_empty()) { return title.to_string(); } match (str_of(meeting, "source"), call_with) { ("call", Some(name)) => chat_say("app.recording.untitled.call", &[("name", name)]), ("import", _) => chat_line("app.recording.untitled.import"), _ if str_of(meeting, "kind") == "memo" => chat_line("app.recording.untitled.memo"), _ => chat_line("app.recording.untitled.meeting"), } } /// "12:04" in a transcript, from ms. fn clock(ms: i64) -> String { let s = ms.max(0) / 1000; if s >= 3600 { format!("{}:{:02}:{:02}", s / 3600, (s / 60) % 60, s % 60) } else { format!("{}:{:02}", s / 60, s % 60) } } /// What a recording says as text: its title and day, the summary's points, /// the actions, then what was said with who and when. The note and a share /// are both made from it (`with_transcript` false for a share). pub(crate) fn as_text(ctx: &mut Ctx<'_>, meeting: &Map, zone: &str, with_transcript: bool) -> Result<(String, String), MethodError> { let id = str_of(meeting, "id").to_string(); let title = title_of(meeting, None); let when = chrono::DateTime::parse_from_rfc3339(str_of(meeting, "started_at")) .ok() .map(|at| { let zone: chrono_tz::Tz = zone.parse().unwrap_or(chrono_tz::UTC); at.with_timezone(&zone).format("%-d %B %Y, %H:%M").to_string() }) .unwrap_or_default(); let mut body = String::new(); let points: Vec = str_of(meeting, "summary").lines().map(|l| l.trim().trim_start_matches(['-', '*', '•']).trim().to_string()).filter(|l| !l.is_empty()).collect(); if !points.is_empty() { body.push_str(&format!("## {}\n\n", chat_line("app.recording.text.summary"))); for p in &points { body.push_str(&format!("- {p}\n")); } body.push('\n'); } let speakers = speakers_of(ctx, &id)?; let actions = actions_of(ctx, &id, &speakers)?; if !actions.is_empty() { body.push_str(&format!("## {}\n\n", chat_line("app.recording.text.actions"))); for a in &actions { let who = a["who"].as_str().map(|w| format!(" ({w})")).unwrap_or_default(); let due = a["due_said"].as_str().map(|d| format!(", {d}")).unwrap_or_default(); body.push_str(&format!("- [ ] {}{who}{due}\n", a["words"].as_str().unwrap_or_default())); } body.push('\n'); } if with_transcript { let lines = lines_of(ctx, &id)?; if !lines.is_empty() { body.push_str(&format!("## {}\n\n", chat_line("app.recording.text.transcript"))); for l in &lines { let speaker = speakers.iter().find(|s| str_of(s, "id") == str_of(l, "speaker")); let who = speaker.map(|s| person_named(ctx, s)).unwrap_or_default(); body.push_str(&format!("**{who}** {} \n{}\n\n", clock(int_of(l, "start_ms")), str_of(l, "text").trim())); } } } let heading = if when.is_empty() { title.clone() } else { chat_say("app.recording.text.title", &[("title", &title), ("when", &when)]) }; Ok((heading, body.trim_end().to_string())) } /// A speaker as the page and the note name them: the name he gave, else "Speaker 2". pub(crate) fn speaker_name(speaker: &Map) -> String { match str_of(speaker, "name").trim() { "" => chat_say("app.recording.speaker", &[("number", str_of(speaker, "label").trim_start_matches('S'))]), name => name.to_string(), } } /// A speaker by the name he gave, else the person he tied them to, else "Speaker 2". pub(crate) fn person_named(ctx: &mut Ctx<'_>, speaker: &Map) -> String { if str_of(speaker, "name").trim().is_empty() && !str_of(speaker, "person").is_empty() { if let Some(person) = get(ctx, "person", str_of(speaker, "person")) { if let Some(name) = ["full_name", "name"].iter().map(|k| str_of(&person, k).trim().to_string()).find(|n| !n.is_empty()) { return name; } } } speaker_name(speaker) } /// Save as note: one `note` in his copy made from the recording, written the /// first time and brought up to date after; Words shows it wherever it is. fn save_note(ctx: &mut Ctx<'_>, zone: &str, request: &Value) -> Result { let meeting = meeting_of(ctx, request)?; let id = str_of(&meeting, "id").to_string(); let (title, body) = as_text(ctx, &meeting, zone, true)?; let held = Some(str_of(&meeting, "note").to_string()).filter(|n| !n.is_empty()).filter(|n| get(ctx, NOTE, n).is_some()); let note = match held { Some(note) => { update(ctx, NOTE, ¬e, object(json!({ "title": title, "body": body })))?; note } None => { let note = create(ctx, NOTE, json!({ "kind": "note", "title": title, "body": body }))?; update(ctx, MEETING, &id, object(json!({ "note": note })))?; note } }; Ok(json!({ "meeting": id, "note": note, "said": chat_line("app.recording.note.saved") })) }