Files
call-recorder/crates/core/src/call_view.rs
T
haukeandClaude Opus 5.5 3358de7888 fix #14740: fixed backend url per build, key bound to its server
- the backend URL is no longer a setting: one constant per build
  (release/dev) in src-tauri/src/backend.rs; Settings shows the server
  read-only; an old backend_url in settings.json is ignored
- the stored key records the backend it was created for; a key of
  another backend is discarded before any use and never stored
- a refused key is discarded only if it still is the stored one
- the keyring is never called while the settings are locked
- one upload per call at a time, also visible after a view switch
- opener plugin without its link-click script (it also ran in the
  remote login page); a login error says to reload the login page

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-06 15:18:05 +01:00

515 lines
17 KiB
Rust

//! What the main window shows about calls: the rows of the call list and
//! the detail of the selected call, shaped from the stored data.
use std::collections::BTreeMap;
use chrono::{DateTime, Local};
use serde::Serialize;
use crate::merge;
use crate::model::{Call, CallId, CallStatus, Segment, Speaker};
/// A row of the call list.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct CallListItem {
pub id: CallId,
pub app: String,
pub started_at: DateTime<Local>,
/// Whole seconds from start to end; 0 while recording.
pub duration_secs: i64,
pub status: CallStatus,
pub interrupted: bool,
/// The name the user gave the call, if any.
pub title: Option<String>,
/// The id the CRM gave the transcript at its last upload.
pub crm_transcript_id: Option<String>,
/// When the transcript was last uploaded.
pub uploaded_at: Option<DateTime<Local>>,
}
impl CallListItem {
pub fn of(call: &Call) -> Self {
Self {
id: call.id,
app: call.app.clone(),
started_at: call.started_at,
duration_secs: duration_secs(call),
status: call.status,
interrupted: call.interrupted,
title: call.title.clone(),
crm_transcript_id: call.crm_transcript_id.clone(),
uploaded_at: call.uploaded_at,
}
}
}
/// Whole seconds from `started_at` to `ended_at`; 0 while the call has not
/// ended (and never negative).
pub fn duration_secs(call: &Call) -> i64 {
call.ended_at
.map_or(0, |end| (end - call.started_at).num_seconds().max(0))
}
/// The selected call's header data: its list row plus the error of a
/// failed run and when it was transcribed (only a transcribed call can be
/// uploaded).
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct CallHeader {
#[serde(flatten)]
pub item: CallListItem,
pub error: Option<String>,
pub transcribed_at: Option<DateTime<Local>>,
}
/// A transcript line with the speaker's display label.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct SegmentView {
/// [`crate::model::Speaker::key`], stable across renames.
pub speaker_key: String,
pub label: String,
pub start: f64,
pub end: f64,
pub text: String,
}
/// A merged speaker: "Sprecher 2 → Frau Beispiel zusammengeführt".
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct MergeView {
pub from_key: String,
/// The source's default label: its own rename is not in effect while
/// it is merged.
pub from_label: String,
/// The speaker the source's lines now belong to (the end of a chain of
/// merges).
pub into_key: String,
pub into_label: String,
}
/// Everything the detail pane shows about one call.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct CallDetail {
pub call: CallHeader,
/// The transcript with speaker merges applied
/// ([`merge::apply_merges`]).
pub segments: Vec<SegmentView>,
/// Renamed speakers by key; speakers not in here keep their default
/// label.
pub speaker_names: BTreeMap<String, String>,
/// The call's speaker merges, by source speaker number.
pub merges: Vec<MergeView>,
/// Whether the transcript is being uploaded right now. Set by the app,
/// which tracks its uploads; `false` from [`CallDetail::of`].
pub uploading: bool,
}
impl CallDetail {
/// `segments` are the stored ones; `merges` the stored speaker merges
/// (source key → target key).
pub fn of(
call: &Call,
segments: &[Segment],
speaker_names: BTreeMap<String, String>,
merges: &BTreeMap<String, String>,
) -> Self {
let segments = merge::apply_merges(segments, merges)
.iter()
.map(|segment| SegmentView {
speaker_key: segment.speaker.key(),
label: merge::label(&segment.speaker, &speaker_names),
start: segment.start,
end: segment.end,
text: segment.text.clone(),
})
.collect();
Self {
call: CallHeader {
item: CallListItem::of(call),
error: call.error.clone(),
transcribed_at: call.transcribed_at,
},
segments,
merges: merge_views(merges, &speaker_names),
uploading: false,
speaker_names,
}
}
}
impl CallDetail {
/// The transcript as plain text for the CRM, as the user sees it
/// (speaker merges and renames applied): a header with title, date,
/// call app and duration, a blank line, then one `[mm:ss] Name: text`
/// line per segment (`h:mm:ss` from one hour on). Blank segments are
/// left out; with none left, the error is [`NO_TRANSCRIPT`].
pub fn upload_text(&self) -> Result<String, String> {
let lines: Vec<String> = self
.segments
.iter()
.filter(|segment| !segment.text.trim().is_empty())
.map(|segment| {
format!(
"[{}] {}: {}",
offset(segment.start),
segment.label,
segment.text.trim()
)
})
.collect();
if lines.is_empty() {
return Err(NO_TRANSCRIPT.to_string());
}
let item = &self.call.item;
let date = item.started_at.format("%d.%m.%Y %H:%M").to_string();
let title = match &item.title {
Some(title) => title.clone(),
None => format!("{} · {date}", item.app),
};
let minutes = ((item.duration_secs as f64 / 60.0).round() as i64).max(1);
let header = [
format!("Titel: {title}"),
format!("Datum: {date}"),
format!("Kanal: {}", item.app),
format!("Dauer: {minutes} min"),
String::new(),
];
Ok(header
.into_iter()
.chain(lines)
.collect::<Vec<_>>()
.join("\n"))
}
}
/// Why [`CallDetail::upload_text`] has nothing to upload.
pub const NO_TRANSCRIPT: &str = "Kein Transkript zum Hochladen";
/// Position in the recording: "04:07", or "1:02:07" from one hour on (like
/// the transcript view).
fn offset(secs: f64) -> String {
let total = if secs.is_finite() && secs > 0.0 {
secs as u64
} else {
0
};
let (h, m, s) = (total / 3600, total % 3600 / 60, total % 60);
if h > 0 {
format!("{h}:{m:02}:{s:02}")
} else {
format!("{m:02}:{s:02}")
}
}
fn merge_views(
merges: &BTreeMap<String, String>,
speaker_names: &BTreeMap<String, String>,
) -> Vec<MergeView> {
let mut views: Vec<(u32, MergeView)> = merge::resolve_merges(merges)
.into_iter()
.filter_map(|(from_key, into_key)| {
let (Some(Speaker::Remote(n)), Some(into)) =
(Speaker::from_key(&from_key), Speaker::from_key(&into_key))
else {
return None;
};
let view = MergeView {
from_label: Speaker::Remote(n).default_label(),
into_label: merge::label(&into, speaker_names),
from_key,
into_key,
};
Some((n, view))
})
.collect();
views.sort_by_key(|(n, _)| *n);
views.into_iter().map(|(_, view)| view).collect()
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use chrono::TimeZone;
use serde_json::json;
use super::*;
use crate::model::Speaker;
fn at(h: u32, m: u32, s: u32) -> DateTime<Local> {
Local.with_ymd_and_hms(2026, 11, 5, h, m, s).unwrap()
}
fn call(ended_at: Option<DateTime<Local>>) -> Call {
Call {
id: 7,
app: "Microsoft Teams".into(),
started_at: at(10, 14, 0),
ended_at,
status: CallStatus::Done,
interrupted: false,
error: None,
mic_path: PathBuf::from("7-mic.wav"),
out_path: PathBuf::from("7-out.wav"),
transcribed_at: None,
audio_deleted: false,
title: None,
crm_transcript_id: None,
uploaded_at: None,
}
}
fn segment(speaker: Speaker, start: f64, text: &str) -> Segment {
Segment {
speaker,
start,
end: start + 2.0,
text: text.into(),
}
}
#[test]
fn duration_runs_from_start_to_end() {
assert_eq!(duration_secs(&call(Some(at(10, 46, 30)))), 32 * 60 + 30);
}
#[test]
fn duration_is_zero_while_recording_and_never_negative() {
assert_eq!(duration_secs(&call(None)), 0);
assert_eq!(duration_secs(&call(Some(at(10, 13, 0)))), 0);
}
#[test]
fn list_item_carries_the_row_fields() {
let mut c = call(Some(at(10, 15, 0)));
c.status = CallStatus::AwaitingDecision;
c.interrupted = true;
assert_eq!(
CallListItem::of(&c),
CallListItem {
id: 7,
app: "Microsoft Teams".into(),
started_at: at(10, 14, 0),
duration_secs: 60,
status: CallStatus::AwaitingDecision,
interrupted: true,
title: None,
crm_transcript_id: None,
uploaded_at: None,
}
);
c.title = Some("Angebot Rioja".into());
c.crm_transcript_id = Some("4711".into());
c.uploaded_at = Some(at(11, 0, 0));
let item = CallListItem::of(&c);
assert_eq!(item.title.as_deref(), Some("Angebot Rioja"));
assert_eq!(item.crm_transcript_id.as_deref(), Some("4711"));
assert_eq!(item.uploaded_at, Some(at(11, 0, 0)));
}
#[test]
fn detail_labels_segments_with_renames_and_defaults() {
let segments = [
segment(Speaker::Me, 0.0, "Guten Tag."),
segment(Speaker::Remote(1), 2.5, "Hallo."),
segment(Speaker::Remote(2), 5.0, "Moin."),
];
let mut names = BTreeMap::new();
names.insert("remote:1".to_string(), "Frau Beispiel".to_string());
names.insert("remote:2".to_string(), " ".to_string());
let detail = CallDetail::of(
&call(Some(at(10, 15, 0))),
&segments,
names.clone(),
&BTreeMap::new(),
);
let lines: Vec<_> = detail
.segments
.iter()
.map(|s| (s.speaker_key.as_str(), s.label.as_str(), s.text.as_str()))
.collect();
assert_eq!(
lines,
[
("me", "Ich", "Guten Tag."),
("remote:1", "Frau Beispiel", "Hallo."),
("remote:2", "Sprecher 2", "Moin."),
]
);
assert_eq!(detail.segments[1].start, 2.5);
assert_eq!(detail.segments[1].end, 4.5);
assert_eq!(detail.speaker_names, names);
assert_eq!(detail.merges, []);
}
fn keys(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
pairs
.iter()
.map(|(a, b)| (a.to_string(), b.to_string()))
.collect()
}
#[test]
fn detail_shows_merged_speakers_under_their_target() {
let segments = [
segment(Speaker::Remote(1), 0.0, "Guten Tag,"),
segment(Speaker::Remote(2), 2.5, "hier Weingut Beispiel."),
segment(Speaker::Me, 5.0, "Hallo."),
segment(Speaker::Remote(3), 7.5, "Zur Lieferung:"),
segment(Speaker::Remote(4), 10.0, "Moin."),
];
let names = keys(&[("remote:1", "Frau Beispiel"), ("remote:2", "Herr Probe")]);
let merges = keys(&[
("remote:3", "remote:2"),
("remote:2", "remote:1"),
("remote:10", "remote:4"),
]);
let detail = CallDetail::of(&call(Some(at(10, 15, 0))), &segments, names, &merges);
let lines: Vec<_> = detail
.segments
.iter()
.map(|s| (s.speaker_key.as_str(), s.label.as_str(), s.text.as_str()))
.collect();
assert_eq!(
lines,
[
(
"remote:1",
"Frau Beispiel",
"Guten Tag, hier Weingut Beispiel."
),
("me", "Ich", "Hallo."),
("remote:1", "Frau Beispiel", "Zur Lieferung:"),
("remote:4", "Sprecher 4", "Moin."),
]
);
let merge_lines: Vec<_> = detail
.merges
.iter()
.map(|m| {
(
m.from_key.as_str(),
m.from_label.as_str(),
m.into_key.as_str(),
m.into_label.as_str(),
)
})
.collect();
assert_eq!(
merge_lines,
[
("remote:2", "Sprecher 2", "remote:1", "Frau Beispiel"),
("remote:3", "Sprecher 3", "remote:1", "Frau Beispiel"),
("remote:10", "Sprecher 10", "remote:4", "Sprecher 4"),
]
);
}
#[test]
fn detail_serializes_the_call_header_flat() {
let mut c = call(Some(at(10, 15, 0)));
c.status = CallStatus::Failed;
c.error = Some("Netzwerkfehler".into());
c.title = Some("Reklamation".into());
c.transcribed_at = Some(at(10, 20, 0));
let merges = keys(&[("remote:2", "remote:1")]);
let value =
serde_json::to_value(CallDetail::of(&c, &[], BTreeMap::new(), &merges)).unwrap();
assert_eq!(
value,
json!({
"call": {
"id": 7,
"app": "Microsoft Teams",
"started_at": serde_json::to_value(at(10, 14, 0)).unwrap(),
"duration_secs": 60,
"status": "failed",
"interrupted": false,
"title": "Reklamation",
"crm_transcript_id": null,
"uploaded_at": null,
"error": "Netzwerkfehler",
"transcribed_at": serde_json::to_value(at(10, 20, 0)).unwrap(),
},
"segments": [],
"speaker_names": {},
"merges": [{
"from_key": "remote:2",
"from_label": "Sprecher 2",
"into_key": "remote:1",
"into_label": "Sprecher 1",
}],
"uploading": false,
})
);
}
fn detail_with(c: &Call, segments: &[Segment], names: &[(&str, &str)]) -> CallDetail {
CallDetail::of(c, segments, keys(names), &keys(&[("remote:2", "remote:1")]))
}
#[test]
fn the_upload_text_has_a_header_and_the_lines_the_user_sees() {
let segments = [
segment(Speaker::Remote(1), 0.0, "Guten Tag,"),
segment(Speaker::Remote(2), 2.5, "hier Weingut Beispiel."),
segment(Speaker::Me, 65.9, "Hallo."),
segment(Speaker::Remote(3), 600.0, " "),
segment(Speaker::Remote(1), 3725.0, "Zur Lieferung."),
];
let c = call(Some(at(10, 46, 0)));
let text = detail_with(&c, &segments, &[("remote:1", "Frau Beispiel")]).upload_text();
assert_eq!(
text.as_deref(),
Ok("Titel: Microsoft Teams · 05.11.2026 10:14\n\
Datum: 05.11.2026 10:14\n\
Kanal: Microsoft Teams\n\
Dauer: 32 min\n\
\n\
[00:00] Frau Beispiel: Guten Tag, hier Weingut Beispiel.\n\
[01:05] Ich: Hallo.\n\
[1:02:05] Frau Beispiel: Zur Lieferung.")
);
}
#[test]
fn the_upload_text_uses_the_title_and_at_least_one_minute() {
let mut c = call(Some(at(10, 14, 10)));
c.title = Some("Angebot Rioja".into());
let text = detail_with(&c, &[segment(Speaker::Me, 0.0, "Hallo.")], &[])
.upload_text()
.unwrap();
let header: Vec<_> = text.lines().take(4).collect();
assert_eq!(
header,
[
"Titel: Angebot Rioja",
"Datum: 05.11.2026 10:14",
"Kanal: Microsoft Teams",
"Dauer: 1 min",
]
);
}
#[test]
fn an_empty_transcript_is_not_uploaded() {
let c = call(Some(at(10, 46, 0)));
for segments in [vec![], vec![segment(Speaker::Me, 0.0, " ")]] {
assert_eq!(
detail_with(&c, &segments, &[]).upload_text(),
Err(NO_TRANSCRIPT.to_string())
);
}
assert_eq!(NO_TRANSCRIPT, "Kein Transkript zum Hochladen");
}
}