feat #14740: call model and sqlite store

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-05 13:57:54 +01:00
co-authored by Claude Opus 5.5
parent 5a381b8f56
commit 7cfe2963c0
5 changed files with 901 additions and 0 deletions
Generated
+102
View File
@@ -8,6 +8,18 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "ahash"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]] [[package]]
name = "aho-corasick" name = "aho-corasick"
version = "1.1.5" version = "1.1.5"
@@ -346,8 +358,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
dependencies = [ dependencies = [
"iana-time-zone", "iana-time-zone",
"js-sys",
"num-traits", "num-traits",
"serde", "serde",
"wasm-bindgen",
"windows-link", "windows-link",
] ]
@@ -764,6 +778,18 @@ dependencies = [
"typeid", "typeid",
] ]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]] [[package]]
name = "fastrand" name = "fastrand"
version = "2.5.0" version = "2.5.0"
@@ -1220,12 +1246,30 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
]
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.17.1" version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "hashlink"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
dependencies = [
"hashbrown 0.14.5",
]
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.4.1" version = "0.4.1"
@@ -1746,6 +1790,17 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "libsqlite3-sys"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c10584274047cb335c23d3e61bcef8e323adae7c5c8c760540f73610177fc3f"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]] [[package]]
name = "litemap" name = "litemap"
version = "0.8.3" version = "0.8.3"
@@ -2430,6 +2485,13 @@ dependencies = [
[[package]] [[package]]
name = "recorder-core" name = "recorder-core"
version = "0.1.0" version = "0.1.0"
dependencies = [
"chrono",
"rusqlite",
"serde",
"serde_json",
"thiserror 1.0.69",
]
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
@@ -2533,6 +2595,20 @@ dependencies = [
"web-sys", "web-sys",
] ]
[[package]]
name = "rusqlite"
version = "0.31.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b838eba278d213a8beaf485bd313fd580ca4505a00d5871caeb1457c55322cae"
dependencies = [
"bitflags 2.13.2",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink",
"libsqlite3-sys",
"smallvec",
]
[[package]] [[package]]
name = "rustc-hash" name = "rustc-hash"
version = "2.1.3" version = "2.1.3"
@@ -3721,6 +3797,12 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]] [[package]]
name = "version-compare" name = "version-compare"
version = "0.2.1" version = "0.2.1"
@@ -4333,6 +4415,26 @@ dependencies = [
"synstructure", "synstructure",
] ]
[[package]]
name = "zerocopy"
version = "0.8.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]] [[package]]
name = "zerofrom" name = "zerofrom"
version = "0.1.8" version = "0.1.8"
+5
View File
@@ -8,3 +8,8 @@ name = "recorder_core"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
rusqlite = { version = "0.31", features = ["bundled"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
chrono = { version = "0.4", features = ["serde"] }
thiserror = "1.0"
+3
View File
@@ -4,6 +4,9 @@
//! transcription and summarization logic, kept independent of the Tauri //! transcription and summarization logic, kept independent of the Tauri
//! application shell so it can be unit-tested without a GUI or network. //! application shell so it can be unit-tested without a GUI or network.
pub mod model;
pub mod store;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#[test] #[test]
+132
View File
@@ -0,0 +1,132 @@
//! Domain types shared by the recording pipeline, the SQLite store and the
//! Tauri command layer.
use std::path::PathBuf;
use chrono::{DateTime, Local, NaiveDate};
use serde::{Deserialize, Serialize};
/// Primary key of a `calls` row (SQLite `rowid`).
pub type CallId = i64;
/// Lifecycle state of a recorded call.
///
/// Serializes (and is persisted) as its lowercase snake_case name, e.g.
/// `CallStatus::AwaitingDecision` -> `"awaiting_decision"`.
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CallStatus {
Recording,
AwaitingDecision,
Processing,
Done,
Failed,
}
/// A single recorded call and everything tracked about its lifecycle.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Call {
pub id: CallId,
pub app: String,
pub started_at: DateTime<Local>,
pub ended_at: Option<DateTime<Local>>,
pub status: CallStatus,
pub interrupted: bool,
pub error: Option<String>,
pub mic_path: PathBuf,
pub out_path: PathBuf,
pub transcribed_at: Option<DateTime<Local>>,
pub audio_deleted: bool,
pub account_id: Option<String>,
}
/// A single transcribed word with its timing and speaker attribution.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Word {
pub text: String,
pub start: f64,
pub end: f64,
pub speaker: Option<String>,
}
/// Who is speaking in a segment: the local user, or one of the remote
/// participants detected via diarization.
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
pub enum Speaker {
Me,
Remote(u32),
}
impl Speaker {
/// Stable identifier used as a storage/lookup key, e.g. for
/// `Store::set_speaker_name` / `Store::speaker_names`.
pub fn key(&self) -> String {
match self {
Speaker::Me => "me".to_string(),
Speaker::Remote(n) => format!("remote:{n}"),
}
}
/// Default German display label before the user renames a speaker.
pub fn default_label(&self) -> String {
match self {
Speaker::Me => "Ich".to_string(),
Speaker::Remote(n) => format!("Sprecher {n}"),
}
}
/// Parses a key produced by [`Speaker::key`] back into a `Speaker`.
pub fn from_key(key: &str) -> Option<Self> {
if key == "me" {
Some(Speaker::Me)
} else {
key.strip_prefix("remote:")
.and_then(|n| n.parse::<u32>().ok())
.map(Speaker::Remote)
}
}
}
/// A merged, diarized stretch of transcript attributed to one speaker.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Segment {
pub speaker: Speaker,
pub start: f64,
pub end: f64,
pub text: String,
}
/// Who owns a to-do coming out of the call summary.
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Owner {
Ich,
Kunde,
Sonstige,
}
/// A single action item extracted from the call summary.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Todo {
pub text: String,
pub owner: Owner,
pub faellig: Option<NaiveDate>,
#[serde(default)]
pub erledigt: bool,
}
/// The next agreed point of contact, if any.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub struct NaechsterKontakt {
pub datum: Option<NaiveDate>,
pub notiz: Option<String>,
}
/// Structured summary produced by Claude for a finished call.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Summary {
pub kernpunkte: Vec<String>,
pub vereinbarungen: Vec<String>,
pub todos: Vec<Todo>,
pub naechster_kontakt: NaechsterKontakt,
}
+659
View File
@@ -0,0 +1,659 @@
//! SQLite-backed persistence for calls, their transcripts, summaries,
//! speaker renames and outstanding remote transcription/summary jobs.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use chrono::{DateTime, Local};
use rusqlite::{params, Connection, Row};
use thiserror::Error;
use crate::model::{Call, CallId, CallStatus, Segment, Speaker, Summary};
/// Errors a [`Store`] operation can fail with.
#[derive(Debug, Error)]
pub enum StoreError {
#[error(transparent)]
Sqlite(#[from] rusqlite::Error),
/// A value read back from SQLite could not be interpreted, e.g. an
/// unknown `status` string, invalid RFC 3339 timestamp, unparsable
/// speaker key or malformed summary JSON.
#[error("corrupt stored value: {0}")]
Corrupt(String),
}
pub type Result<T> = std::result::Result<T, StoreError>;
const SCHEMA_SQL: &str = "
CREATE TABLE IF NOT EXISTS calls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
app TEXT NOT NULL,
started_at TEXT NOT NULL,
ended_at TEXT,
status TEXT NOT NULL,
interrupted INTEGER NOT NULL,
error TEXT,
mic_path TEXT NOT NULL,
out_path TEXT NOT NULL,
transcribed_at TEXT,
audio_deleted INTEGER NOT NULL,
account_id TEXT
);
CREATE TABLE IF NOT EXISTS segments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
call_id INTEGER NOT NULL REFERENCES calls(id) ON DELETE CASCADE,
seq INTEGER NOT NULL,
speaker TEXT NOT NULL,
start_ts REAL NOT NULL,
end_ts REAL NOT NULL,
text TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS segments_call_id_idx ON segments(call_id);
CREATE TABLE IF NOT EXISTS summaries (
call_id INTEGER PRIMARY KEY REFERENCES calls(id) ON DELETE CASCADE,
json TEXT NOT NULL,
edited INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS speaker_names (
call_id INTEGER NOT NULL REFERENCES calls(id) ON DELETE CASCADE,
speaker_key TEXT NOT NULL,
name TEXT NOT NULL,
PRIMARY KEY (call_id, speaker_key)
);
CREATE TABLE IF NOT EXISTS remote_jobs (
call_id INTEGER NOT NULL REFERENCES calls(id) ON DELETE CASCADE,
track TEXT NOT NULL,
remote_id TEXT NOT NULL,
PRIMARY KEY (call_id, track, remote_id)
);
";
/// SQLite-backed store for calls and everything derived from them.
pub struct Store {
conn: Mutex<Connection>,
}
impl Store {
/// Opens (creating if necessary) a database file on disk.
pub fn open(path: &Path) -> Result<Store> {
let conn = Connection::open(path)?;
Self::init(conn)
}
/// Opens a throwaway in-memory database, used by tests.
pub fn open_in_memory() -> Result<Store> {
let conn = Connection::open_in_memory()?;
Self::init(conn)
}
fn init(conn: Connection) -> Result<Store> {
conn.execute_batch("PRAGMA foreign_keys = ON;")?;
let user_version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
if user_version < 1 {
conn.execute_batch(SCHEMA_SQL)?;
conn.execute_batch("PRAGMA user_version = 1;")?;
}
Ok(Store {
conn: Mutex::new(conn),
})
}
pub fn create_call(
&self,
app: &str,
started_at: DateTime<Local>,
mic_path: &Path,
out_path: &Path,
) -> Result<CallId> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO calls \
(app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id) \
VALUES (?1, ?2, NULL, ?3, 0, NULL, ?4, ?5, NULL, 0, NULL)",
params![
app,
dt_to_str(started_at),
status_to_str(CallStatus::Recording),
path_to_str(mic_path)?,
path_to_str(out_path)?,
],
)?;
Ok(conn.last_insert_rowid())
}
pub fn finish_recording(
&self,
id: CallId,
ended_at: DateTime<Local>,
interrupted: bool,
) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE calls SET ended_at = ?1, interrupted = ?2, status = ?3 WHERE id = ?4",
params![
dt_to_str(ended_at),
interrupted,
status_to_str(CallStatus::AwaitingDecision),
id
],
)?;
Ok(())
}
pub fn set_status(&self, id: CallId, status: CallStatus, error: Option<&str>) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE calls SET status = ?1, error = ?2 WHERE id = ?3",
params![status_to_str(status), error, id],
)?;
Ok(())
}
/// Corrects the end time of an interrupted recording.
pub fn set_ended_at(&self, id: CallId, at: DateTime<Local>) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE calls SET ended_at = ?1 WHERE id = ?2",
params![dt_to_str(at), id],
)?;
Ok(())
}
pub fn get_call(&self, id: CallId) -> Result<Option<Call>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(SELECT_CALL_COLUMNS_SQL)?;
let mut rows = stmt.query(params![id])?;
match rows.next()? {
Some(row) => Ok(Some(row_to_call(row)?)),
None => Ok(None),
}
}
/// Lists all calls, newest (by `started_at`) first.
pub fn list_calls(&self) -> Result<Vec<Call>> {
let conn = self.conn.lock().unwrap();
let sql = format!("{} ORDER BY started_at DESC, id DESC", SELECT_ALL_CALLS_SQL);
let mut stmt = conn.prepare(&sql)?;
let mut rows = stmt.query([])?;
let mut calls = Vec::new();
while let Some(row) = rows.next()? {
calls.push(row_to_call(row)?);
}
Ok(calls)
}
/// Replaces all stored segments for a call with `segments`.
pub fn save_segments(&self, id: CallId, segments: &[Segment]) -> Result<()> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
tx.execute("DELETE FROM segments WHERE call_id = ?1", params![id])?;
for (seq, segment) in segments.iter().enumerate() {
tx.execute(
"INSERT INTO segments (call_id, seq, speaker, start_ts, end_ts, text) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![id, seq as i64, segment.speaker.key(), segment.start, segment.end, segment.text],
)?;
}
tx.commit()?;
Ok(())
}
pub fn segments(&self, id: CallId) -> Result<Vec<Segment>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT speaker, start_ts, end_ts, text FROM segments WHERE call_id = ?1 ORDER BY seq ASC",
)?;
let mut rows = stmt.query(params![id])?;
let mut segments = Vec::new();
while let Some(row) = rows.next()? {
let speaker_key: String = row.get(0)?;
segments.push(Segment {
speaker: speaker_from_key(&speaker_key)?,
start: row.get(1)?,
end: row.get(2)?,
text: row.get(3)?,
});
}
Ok(segments)
}
pub fn save_summary(&self, id: CallId, summary: &Summary, edited: bool) -> Result<()> {
let conn = self.conn.lock().unwrap();
let json = serde_json::to_string(summary)
.map_err(|e| StoreError::Corrupt(format!("failed to serialize summary: {e}")))?;
conn.execute(
"INSERT INTO summaries (call_id, json, edited) VALUES (?1, ?2, ?3) \
ON CONFLICT(call_id) DO UPDATE SET json = excluded.json, edited = excluded.edited",
params![id, json, edited],
)?;
Ok(())
}
pub fn summary(&self, id: CallId) -> Result<Option<Summary>> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn.prepare("SELECT json FROM summaries WHERE call_id = ?1")?;
let mut rows = stmt.query(params![id])?;
match rows.next()? {
Some(row) => {
let json: String = row.get(0)?;
let summary = serde_json::from_str(&json)
.map_err(|e| StoreError::Corrupt(format!("invalid summary json: {e}")))?;
Ok(Some(summary))
}
None => Ok(None),
}
}
pub fn set_speaker_name(&self, id: CallId, speaker_key: &str, name: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT INTO speaker_names (call_id, speaker_key, name) VALUES (?1, ?2, ?3) \
ON CONFLICT(call_id, speaker_key) DO UPDATE SET name = excluded.name",
params![id, speaker_key, name],
)?;
Ok(())
}
pub fn speaker_names(&self, id: CallId) -> Result<BTreeMap<String, String>> {
let conn = self.conn.lock().unwrap();
let mut stmt =
conn.prepare("SELECT speaker_key, name FROM speaker_names WHERE call_id = ?1")?;
let mut rows = stmt.query(params![id])?;
let mut names = BTreeMap::new();
while let Some(row) = rows.next()? {
names.insert(row.get(0)?, row.get(1)?);
}
Ok(names)
}
pub fn mark_transcribed(&self, id: CallId, at: DateTime<Local>) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE calls SET transcribed_at = ?1 WHERE id = ?2",
params![dt_to_str(at), id],
)?;
Ok(())
}
pub fn mark_audio_deleted(&self, id: CallId) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE calls SET audio_deleted = 1 WHERE id = ?1",
params![id],
)?;
Ok(())
}
/// Deletes a call and every row derived from it (segments, summary,
/// speaker names, remote jobs).
pub fn delete_call(&self, id: CallId) -> Result<()> {
let mut conn = self.conn.lock().unwrap();
let tx = conn.transaction()?;
tx.execute("DELETE FROM segments WHERE call_id = ?1", params![id])?;
tx.execute("DELETE FROM summaries WHERE call_id = ?1", params![id])?;
tx.execute("DELETE FROM speaker_names WHERE call_id = ?1", params![id])?;
tx.execute("DELETE FROM remote_jobs WHERE call_id = ?1", params![id])?;
tx.execute("DELETE FROM calls WHERE id = ?1", params![id])?;
tx.commit()?;
Ok(())
}
pub fn set_account(&self, id: CallId, account_id: Option<&str>) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE calls SET account_id = ?1 WHERE id = ?2",
params![account_id, id],
)?;
Ok(())
}
pub fn record_remote_job(&self, id: CallId, track: &str, remote_id: &str) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT OR REPLACE INTO remote_jobs (call_id, track, remote_id) VALUES (?1, ?2, ?3)",
params![id, track, remote_id],
)?;
Ok(())
}
pub fn remote_jobs(&self, id: CallId) -> Result<Vec<(String, String)>> {
let conn = self.conn.lock().unwrap();
let mut stmt =
conn.prepare("SELECT track, remote_id FROM remote_jobs WHERE call_id = ?1")?;
let mut rows = stmt.query(params![id])?;
let mut jobs = Vec::new();
while let Some(row) = rows.next()? {
jobs.push((row.get(0)?, row.get(1)?));
}
Ok(jobs)
}
pub fn clear_remote_jobs(&self, id: CallId) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute("DELETE FROM remote_jobs WHERE call_id = ?1", params![id])?;
Ok(())
}
}
const SELECT_ALL_CALLS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id FROM calls";
const SELECT_CALL_COLUMNS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id FROM calls WHERE id = ?1";
fn row_to_call(row: &Row) -> Result<Call> {
let id: CallId = row.get(0)?;
let app: String = row.get(1)?;
let started_at: String = row.get(2)?;
let ended_at: Option<String> = row.get(3)?;
let status: String = row.get(4)?;
let interrupted: bool = row.get(5)?;
let error: Option<String> = row.get(6)?;
let mic_path: String = row.get(7)?;
let out_path: String = row.get(8)?;
let transcribed_at: Option<String> = row.get(9)?;
let audio_deleted: bool = row.get(10)?;
let account_id: Option<String> = row.get(11)?;
Ok(Call {
id,
app,
started_at: dt_from_str(&started_at)?,
ended_at: opt_dt_from_str(ended_at)?,
status: status_from_str(&status)?,
interrupted,
error,
mic_path: PathBuf::from(mic_path),
out_path: PathBuf::from(out_path),
transcribed_at: opt_dt_from_str(transcribed_at)?,
audio_deleted,
account_id,
})
}
fn path_to_str(path: &Path) -> Result<&str> {
path.to_str()
.ok_or_else(|| StoreError::Corrupt(format!("non-utf8 path: {}", path.display())))
}
fn dt_to_str(dt: DateTime<Local>) -> String {
dt.to_rfc3339()
}
fn dt_from_str(s: &str) -> Result<DateTime<Local>> {
DateTime::parse_from_rfc3339(s)
.map(|dt| dt.with_timezone(&Local))
.map_err(|e| StoreError::Corrupt(format!("invalid timestamp {s:?}: {e}")))
}
fn opt_dt_from_str(s: Option<String>) -> Result<Option<DateTime<Local>>> {
s.map(|s| dt_from_str(&s)).transpose()
}
fn status_to_str(status: CallStatus) -> &'static str {
match status {
CallStatus::Recording => "recording",
CallStatus::AwaitingDecision => "awaiting_decision",
CallStatus::Processing => "processing",
CallStatus::Done => "done",
CallStatus::Failed => "failed",
}
}
fn status_from_str(s: &str) -> Result<CallStatus> {
match s {
"recording" => Ok(CallStatus::Recording),
"awaiting_decision" => Ok(CallStatus::AwaitingDecision),
"processing" => Ok(CallStatus::Processing),
"done" => Ok(CallStatus::Done),
"failed" => Ok(CallStatus::Failed),
other => Err(StoreError::Corrupt(format!(
"unknown call status: {other:?}"
))),
}
}
fn speaker_from_key(key: &str) -> Result<Speaker> {
Speaker::from_key(key)
.ok_or_else(|| StoreError::Corrupt(format!("invalid speaker key: {key:?}")))
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::path::Path;
use chrono::Local;
use crate::model::{
CallId, CallStatus, NaechsterKontakt, Owner, Segment, Speaker, Summary, Todo,
};
use crate::store::Store;
#[test]
fn create_and_finish_call() {
let store = Store::open_in_memory().unwrap();
let started = Local::now();
let id = store
.create_call(
"teams.exe",
started,
Path::new("/tmp/mic.wav"),
Path::new("/tmp/out.wav"),
)
.unwrap();
let call = store.get_call(id).unwrap().expect("call exists");
assert_eq!(call.app, "teams.exe");
assert_eq!(call.status, CallStatus::Recording);
assert_eq!(call.started_at, started);
assert!(call.ended_at.is_none());
assert!(!call.interrupted);
assert!(call.error.is_none());
let ended = started + chrono::Duration::seconds(30);
store.finish_recording(id, ended, true).unwrap();
let call = store.get_call(id).unwrap().expect("call exists");
assert_eq!(call.status, CallStatus::AwaitingDecision);
assert!(call.interrupted);
assert_eq!(call.ended_at, Some(ended));
}
#[test]
fn segments_roundtrip_replaces() {
let store = Store::open_in_memory().unwrap();
let id = store
.create_call(
"teams.exe",
Local::now(),
Path::new("/tmp/mic.wav"),
Path::new("/tmp/out.wav"),
)
.unwrap();
let first = vec![
Segment {
speaker: Speaker::Me,
start: 0.0,
end: 1.5,
text: "Hallo".to_string(),
},
Segment {
speaker: Speaker::Remote(1),
start: 1.5,
end: 3.0,
text: "Hi".to_string(),
},
];
store.save_segments(id, &first).unwrap();
assert_eq!(store.segments(id).unwrap(), first);
let second = vec![Segment {
speaker: Speaker::Remote(2),
start: 0.0,
end: 2.0,
text: "Neuer Inhalt".to_string(),
}];
store.save_segments(id, &second).unwrap();
assert_eq!(store.segments(id).unwrap(), second);
}
#[test]
fn summary_roundtrip_with_null_dates() {
let store = Store::open_in_memory().unwrap();
let id = store
.create_call(
"teams.exe",
Local::now(),
Path::new("/tmp/mic.wav"),
Path::new("/tmp/out.wav"),
)
.unwrap();
assert_eq!(store.summary(id).unwrap(), None);
let summary = Summary {
kernpunkte: vec!["Punkt 1".to_string()],
vereinbarungen: vec!["Angebot folgt".to_string()],
todos: vec![Todo {
text: "Angebot schicken".to_string(),
owner: Owner::Ich,
faellig: None,
erledigt: false,
}],
naechster_kontakt: NaechsterKontakt {
datum: None,
notiz: None,
},
};
store.save_summary(id, &summary, false).unwrap();
assert_eq!(store.summary(id).unwrap(), Some(summary));
}
#[test]
fn speaker_names_upsert() {
let store = Store::open_in_memory().unwrap();
let id = store
.create_call(
"teams.exe",
Local::now(),
Path::new("/tmp/mic.wav"),
Path::new("/tmp/out.wav"),
)
.unwrap();
store
.set_speaker_name(id, "remote:1", "Herr Mueller")
.unwrap();
store.set_speaker_name(id, "me", "Ich").unwrap();
let names = store.speaker_names(id).unwrap();
let mut expected = BTreeMap::new();
expected.insert("remote:1".to_string(), "Herr Mueller".to_string());
expected.insert("me".to_string(), "Ich".to_string());
assert_eq!(names, expected);
store
.set_speaker_name(id, "remote:1", "Frau Mueller")
.unwrap();
let names = store.speaker_names(id).unwrap();
assert_eq!(names.len(), 2);
assert_eq!(names.get("remote:1").unwrap(), "Frau Mueller");
}
#[test]
fn list_newest_first() {
let store = Store::open_in_memory().unwrap();
let t0 = Local::now();
let id1 = store
.create_call(
"teams.exe",
t0,
Path::new("/tmp/mic1.wav"),
Path::new("/tmp/out1.wav"),
)
.unwrap();
let id2 = store
.create_call(
"chrome.exe",
t0 + chrono::Duration::seconds(10),
Path::new("/tmp/mic2.wav"),
Path::new("/tmp/out2.wav"),
)
.unwrap();
let id3 = store
.create_call(
"msedge.exe",
t0 + chrono::Duration::seconds(20),
Path::new("/tmp/mic3.wav"),
Path::new("/tmp/out3.wav"),
)
.unwrap();
let ids: Vec<CallId> = store
.list_calls()
.unwrap()
.into_iter()
.map(|c| c.id)
.collect();
assert_eq!(ids, vec![id3, id2, id1]);
}
#[test]
fn delete_call_cascades() {
let store = Store::open_in_memory().unwrap();
let id = store
.create_call(
"teams.exe",
Local::now(),
Path::new("/tmp/mic.wav"),
Path::new("/tmp/out.wav"),
)
.unwrap();
store
.save_segments(
id,
&[Segment {
speaker: Speaker::Me,
start: 0.0,
end: 1.0,
text: "Hi".to_string(),
}],
)
.unwrap();
store
.save_summary(
id,
&Summary {
kernpunkte: vec![],
vereinbarungen: vec![],
todos: vec![],
naechster_kontakt: NaechsterKontakt {
datum: None,
notiz: None,
},
},
false,
)
.unwrap();
store.set_speaker_name(id, "me", "Ich").unwrap();
store
.record_remote_job(id, "deepscript", "job-123")
.unwrap();
store.delete_call(id).unwrap();
assert_eq!(store.get_call(id).unwrap(), None);
assert_eq!(store.segments(id).unwrap(), Vec::new());
assert_eq!(store.summary(id).unwrap(), None);
assert_eq!(store.speaker_names(id).unwrap(), BTreeMap::new());
assert_eq!(store.remote_jobs(id).unwrap(), Vec::new());
}
}