10 Commits
Author SHA1 Message Date
hauke 35e560020c chore #14740: release 0.2.2 2026-11-09 12:06:27 +01:00
haukeandClaude Opus 5.5 3a16c76257 feat #14740: track uploads per backend server
Schema v4 adds calls.crm_base_url; existing uploads are tagged with the
test backend. A call counts as uploaded (list/detail fields, the
"Hochgeladen am" line, the upload-once guard) only if it was uploaded to
this build's backend. Uploading to the other server replaces the single
upload record; nothing is deleted.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 10:52:16 +01:00
haukeandClaude Opus 5.5 d0ece263a2 feat #14740: release builds use the production backend
Release builds talk to https://backend.euvinopro.eu, debug builds keep
https://test.euvinopro.eu. A key bound to the test backend is discarded
in a release build (fresh login).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 10:51:09 +01:00
haukeandClaude Opus 5.5 a0f89454f9 fix #14740: linux update check and upload safety
- Linux: ask the feed for the windows-x86_64 entry only to learn the
  version; report it (the settings show the .deb hint) without storing a
  pending update or announcing it. install_update refuses off Windows.
- Background checks re-check is_due once the running lock is held.
- Check errors read "Update-Prüfung fehlgeschlagen: …".
- Settings: a failed follow-up getUpdate() never hides a found update; an
  unknown canSelfUpdate() shows it without an install button.
- An upload the CRM accepted but that could not be saved locally names
  the CRM id and is refused for re-upload until the app restarts.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 10:50:12 +01:00
hauke 083edf32a2 chore #14740: update feed 0.2.1 2026-11-06 15:48:53 +01:00
hauke 687d4bccfe chore #14740: release 0.2.1 2026-11-06 15:48:45 +01:00
haukeandClaude Sonnet 5 fa55dcb7bc fix #14740: upload a transcript only once
A call once uploaded can no longer be sent again: claim_upload refuses a
call that already carries a CRM transcript id ("Bereits hochgeladen"),
checked under the same lock that already serializes uploads per call, so a
concurrent second upload can never slip through between the check and the
one upload it allows. upload_transcript runs this check before any HTTP
request, so a rejected re-upload never reaches the backend.

The call detail view drops "Erneut hochladen" and its confirmation dialog:
once a call has uploaded_at/crm_transcript_id, only "Hochgeladen am …" is
shown, no button.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-06 15:40:31 +01:00
haukeandClaude Sonnet 5 dad98b4558 fix #14740: guard the backend url and the backend key
BACKEND_URL must never end with "/" (a stored key's base_url is compared
against it byte-for-byte): a unit test now asserts both RELEASE_BACKEND_URL
and DEV_BACKEND_URL have no trailing slash and start with "https://", and
AppState trims it defensively where it is stored (an earlier commit already
carries that trim).

set_api_key/has_api_key now refuse Service::Backend ("Dieser Schlüssel wird
über die Backend-Anmeldung verwaltet"): its key is only ever set by the
backend login, which holds backend_key_lock and binds it to this build's
backend.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-06 15:40:15 +01:00
haukeandClaude Sonnet 5 96eec22971 feat #14740: check for updates from the settings
Adds a "Nach Updates suchen" button to the settings' new Updates section,
next to the app's own version. It runs check_for_update_now, the very same
feed check the background loop uses (one implementation, shared via
UpdateSchedule), so a manual check counts as an attempt for the same
scheduler: success resets the 6 h interval and the failure count, a failure
advances the backoff by one step, and a manual and a background check never
run at the same time (serialized).

An available update leaves the same state the background check does, so the
main window's banner still shows it; the settings also show it inline with
the existing "Installieren & neu starten" button and busy guard/hint. "None"
and "error" results are shown inline (unlike the background check, which
never surfaces its errors). On Linux (can_self_update) the button still asks
the feed but offers no install, since Debian builds never self-update.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-06 15:38:35 +01:00
hauke 1735f431dd chore #14740: update feed 0.2.0 2026-11-06 15:20:29 +01:00
18 changed files with 973 additions and 129 deletions
Generated
+1 -1
View File
@@ -445,7 +445,7 @@ dependencies = [
[[package]]
name = "call-recorder"
version = "0.2.0"
version = "0.2.2"
dependencies = [
"async-trait",
"chrono",
+90 -10
View File
@@ -28,7 +28,13 @@ pub struct CallListItem {
}
impl CallListItem {
pub fn of(call: &Call) -> Self {
/// `backend_url` is this build's backend (`crate::backend::BACKEND_URL`
/// in the app): an upload recorded for a different one is shown as not
/// uploaded at all ([`uploaded_here`]) — e.g. a transcript sent to the
/// test backend must not look done to a release build reading the same
/// row. Nothing is deleted; the fields are just not shown as set.
pub fn of(call: &Call, backend_url: &str) -> Self {
let uploaded = uploaded_here(call, backend_url);
Self {
id: call.id,
app: call.app.clone(),
@@ -37,8 +43,12 @@ impl CallListItem {
status: call.status,
interrupted: call.interrupted,
title: call.title.clone(),
crm_transcript_id: call.crm_transcript_id.clone(),
uploaded_at: call.uploaded_at,
crm_transcript_id: if uploaded {
call.crm_transcript_id.clone()
} else {
None
},
uploaded_at: if uploaded { call.uploaded_at } else { None },
}
}
}
@@ -50,6 +60,16 @@ pub fn duration_secs(call: &Call) -> i64 {
.map_or(0, |end| (end - call.started_at).num_seconds().max(0))
}
/// Whether `call`'s upload belongs to `backend_url`: its
/// `crm_transcript_id` is set *and* `crm_base_url` is exactly this
/// backend. An upload recorded for a different one (e.g. the test backend,
/// read by a release build) counts as not uploaded: the CRM this
/// `backend_url` talks to has never seen the transcript, so the UI offers
/// the normal upload control again instead of claiming it is done.
pub fn uploaded_here(call: &Call, backend_url: &str) -> bool {
call.crm_transcript_id.is_some() && call.crm_base_url.as_deref() == Some(backend_url)
}
/// 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).
@@ -104,12 +124,14 @@ pub struct CallDetail {
impl CallDetail {
/// `segments` are the stored ones; `merges` the stored speaker merges
/// (source key → target key).
/// (source key → target key); `backend_url` is this build's backend
/// (see [`CallListItem::of`]).
pub fn of(
call: &Call,
segments: &[Segment],
speaker_names: BTreeMap<String, String>,
merges: &BTreeMap<String, String>,
backend_url: &str,
) -> Self {
let segments = merge::apply_merges(segments, merges)
.iter()
@@ -123,7 +145,7 @@ impl CallDetail {
.collect();
Self {
call: CallHeader {
item: CallListItem::of(call),
item: CallListItem::of(call, backend_url),
error: call.error.clone(),
transcribed_at: call.transcribed_at,
},
@@ -234,6 +256,11 @@ mod tests {
use super::*;
use crate::model::Speaker;
/// This build's backend, for `CallListItem::of`/`CallDetail::of`.
const BACKEND: &str = "https://backend.example";
/// A different backend, for the "uploaded elsewhere" cases.
const OTHER_BACKEND: &str = "https://other.example";
fn at(h: u32, m: u32, s: u32) -> DateTime<Local> {
Local.with_ymd_and_hms(2026, 11, 5, h, m, s).unwrap()
}
@@ -253,6 +280,7 @@ mod tests {
audio_deleted: false,
title: None,
crm_transcript_id: None,
crm_base_url: None,
uploaded_at: None,
}
}
@@ -283,7 +311,7 @@ mod tests {
c.status = CallStatus::AwaitingDecision;
c.interrupted = true;
assert_eq!(
CallListItem::of(&c),
CallListItem::of(&c, BACKEND),
CallListItem {
id: 7,
app: "Microsoft Teams".into(),
@@ -299,13 +327,51 @@ mod tests {
c.title = Some("Angebot Rioja".into());
c.crm_transcript_id = Some("4711".into());
c.crm_base_url = Some(BACKEND.into());
c.uploaded_at = Some(at(11, 0, 0));
let item = CallListItem::of(&c);
let item = CallListItem::of(&c, BACKEND);
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 uploaded_here_needs_a_transcript_id_and_a_matching_backend() {
let mut c = call(Some(at(10, 15, 0)));
assert!(!uploaded_here(&c, BACKEND), "never uploaded");
c.crm_transcript_id = Some("4711".into());
c.crm_base_url = Some(OTHER_BACKEND.into());
assert!(
!uploaded_here(&c, BACKEND),
"uploaded, but to a different backend"
);
c.crm_base_url = Some(BACKEND.into());
assert!(uploaded_here(&c, BACKEND));
}
#[test]
fn an_upload_to_another_backend_is_hidden_from_the_list_item() {
// Uploaded to OTHER_BACKEND; this build's backend is BACKEND: the
// row still has crm_transcript_id/uploaded_at, but the view must
// not show them, so the UI offers the normal upload control again.
let mut c = call(Some(at(10, 15, 0)));
c.crm_transcript_id = Some("4711".into());
c.crm_base_url = Some(OTHER_BACKEND.into());
c.uploaded_at = Some(at(11, 0, 0));
let item = CallListItem::of(&c, BACKEND);
assert_eq!(item.crm_transcript_id, None);
assert_eq!(item.uploaded_at, None);
// The same row, read by a build whose backend actually matches:
// shown normally.
let item = CallListItem::of(&c, OTHER_BACKEND);
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 = [
@@ -322,6 +388,7 @@ mod tests {
&segments,
names.clone(),
&BTreeMap::new(),
BACKEND,
);
let lines: Vec<_> = detail
@@ -366,7 +433,13 @@ mod tests {
("remote:10", "remote:4"),
]);
let detail = CallDetail::of(&call(Some(at(10, 15, 0))), &segments, names, &merges);
let detail = CallDetail::of(
&call(Some(at(10, 15, 0))),
&segments,
names,
&merges,
BACKEND,
);
let lines: Vec<_> = detail
.segments
@@ -418,7 +491,8 @@ mod tests {
let merges = keys(&[("remote:2", "remote:1")]);
let value =
serde_json::to_value(CallDetail::of(&c, &[], BTreeMap::new(), &merges)).unwrap();
serde_json::to_value(CallDetail::of(&c, &[], BTreeMap::new(), &merges, BACKEND))
.unwrap();
assert_eq!(
value,
@@ -450,7 +524,13 @@ mod tests {
}
fn detail_with(c: &Call, segments: &[Segment], names: &[(&str, &str)]) -> CallDetail {
CallDetail::of(c, segments, keys(names), &keys(&[("remote:2", "remote:1")]))
CallDetail::of(
c,
segments,
keys(names),
&keys(&[("remote:2", "remote:1")]),
BACKEND,
)
}
#[test]
+5
View File
@@ -41,6 +41,11 @@ pub struct Call {
pub title: Option<String>,
/// The id the CRM gave the transcript at its last upload.
pub crm_transcript_id: Option<String>,
/// The backend ([`crate::backend`]'s base URL) `crm_transcript_id` was
/// uploaded to; `None` if never uploaded. A build whose own backend
/// differs (e.g. release reading a row a test build uploaded) does not
/// count this as uploaded — see `call_view::uploaded_here`.
pub crm_base_url: Option<String>,
/// When the transcript was last uploaded.
pub uploaded_at: Option<DateTime<Local>>,
}
+1
View File
@@ -90,6 +90,7 @@ mod tests {
audio_deleted: false,
title: None,
crm_transcript_id: None,
crm_base_url: None,
uploaded_at: None,
}
}
+121 -22
View File
@@ -120,9 +120,19 @@ ALTER TABLE calls ADD COLUMN crm_transcript_id TEXT;
ALTER TABLE calls ADD COLUMN uploaded_at TEXT;
";
/// Version 4: which backend an upload belongs to, so a build whose own
/// backend differs (see `crate::backend`) does not show someone else's
/// upload as done (`call_view::uploaded_here`). Every upload before this
/// version only ever went to the test backend (production never had the
/// API yet): backfilled here, so existing rows keep meaning what they did.
const SCHEMA_V4_SQL: &str = "
ALTER TABLE calls ADD COLUMN crm_base_url TEXT;
UPDATE calls SET crm_base_url = 'https://test.euvinopro.eu' WHERE crm_transcript_id IS NOT NULL;
";
/// Schema steps by `PRAGMA user_version`: entry `i` takes a database from
/// version `i` to `i + 1`. A new database runs all of them.
const MIGRATIONS: &[&str] = &[SCHEMA_V1_SQL, SCHEMA_V2_SQL, SCHEMA_V3_SQL];
const MIGRATIONS: &[&str] = &[SCHEMA_V1_SQL, SCHEMA_V2_SQL, SCHEMA_V3_SQL, SCHEMA_V4_SQL];
/// SQLite-backed store for calls and everything derived from them.
pub struct Store {
@@ -361,18 +371,21 @@ impl Store {
Ok(())
}
/// Records that the transcript was uploaded to the CRM at `at`, which
/// gave it `crm_transcript_id`; replaces an earlier upload's record.
/// Records that the transcript was uploaded to `crm_base_url` at `at`,
/// which gave it `crm_transcript_id`; replaces an earlier upload's
/// record (even one of another backend — one upload slot per call, see
/// `call_view::uploaded_here`).
pub fn set_uploaded(
&self,
id: CallId,
crm_transcript_id: &str,
crm_base_url: &str,
at: DateTime<Local>,
) -> Result<()> {
let conn = self.conn.lock().unwrap();
conn.execute(
"UPDATE calls SET crm_transcript_id = ?1, uploaded_at = ?2 WHERE id = ?3",
params![crm_transcript_id, dt_to_str(at), id],
"UPDATE calls SET crm_transcript_id = ?1, crm_base_url = ?2, uploaded_at = ?3 WHERE id = ?4",
params![crm_transcript_id, crm_base_url, dt_to_str(at), id],
)?;
Ok(())
}
@@ -536,9 +549,9 @@ fn ids_with_status(conn: &rusqlite::Connection, status: CallStatus) -> Result<Ve
Ok(ids)
}
const SELECT_ALL_CALLS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, title, crm_transcript_id, uploaded_at FROM calls";
const SELECT_ALL_CALLS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, title, crm_transcript_id, uploaded_at, crm_base_url 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, title, crm_transcript_id, uploaded_at FROM calls WHERE id = ?1";
const SELECT_CALL_COLUMNS_SQL: &str = "SELECT id, app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, title, crm_transcript_id, uploaded_at, crm_base_url FROM calls WHERE id = ?1";
fn row_to_call(row: &Row) -> Result<Call> {
let id: CallId = row.get(0)?;
@@ -555,6 +568,7 @@ fn row_to_call(row: &Row) -> Result<Call> {
let title: Option<String> = row.get(11)?;
let crm_transcript_id: Option<String> = row.get(12)?;
let uploaded_at: Option<String> = row.get(13)?;
let crm_base_url: Option<String> = row.get(14)?;
Ok(Call {
id,
@@ -570,6 +584,7 @@ fn row_to_call(row: &Row) -> Result<Call> {
audio_deleted,
title,
crm_transcript_id,
crm_base_url,
uploaded_at: opt_dt_from_str(uploaded_at)?,
})
}
@@ -692,6 +707,14 @@ CREATE TABLE speaker_merges (
into_key TEXT NOT NULL,
PRIMARY KEY (call_id, from_key)
);
";
/// The schema of user_version 3, exactly as release 0.2.0 created it
/// (copied from `SCHEMA_V3_SQL` at `HEAD`): version 2 plus these
/// statements.
const RELEASED_V3_STEP_SQL: &str = "
ALTER TABLE calls ADD COLUMN crm_transcript_id TEXT;
ALTER TABLE calls ADD COLUMN uploaded_at TEXT;
";
fn user_version(path: &Path) -> i64 {
@@ -715,17 +738,19 @@ CREATE TABLE speaker_merges (
}
#[test]
fn a_new_database_starts_at_version_3() {
fn a_new_database_starts_at_version_4() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("calls.sqlite");
let store = Store::open(&path).unwrap();
let id = new_call(&store);
store.set_title(id, Some("Angebot")).unwrap();
store.set_speaker_merge(id, "remote:2", "remote:1").unwrap();
store.set_uploaded(id, "4711", Local::now()).unwrap();
store
.set_uploaded(id, "4711", "https://backend.example", Local::now())
.unwrap();
drop(store);
assert_eq!(user_version(&path), 3);
assert_eq!(user_version(&path), 4);
}
#[test]
@@ -782,7 +807,7 @@ CREATE TABLE speaker_merges (
store.set_title(1, Some("Lieferung März")).unwrap();
store.set_speaker_merge(1, "remote:2", "remote:1").unwrap();
drop(store);
assert_eq!(user_version(&path), 3);
assert_eq!(user_version(&path), 4);
let store = Store::open(&path).unwrap();
let call = store.get_call(1).unwrap().unwrap();
assert_eq!(call.title.as_deref(), Some("Lieferung März"));
@@ -832,41 +857,115 @@ CREATE TABLE speaker_merges (
// The new columns work, and opening again changes nothing.
let uploaded = Local::now();
store.set_uploaded(1, "crm-1", uploaded).unwrap();
store
.set_uploaded(1, "crm-1", "https://backend.example", uploaded)
.unwrap();
drop(store);
assert_eq!(user_version(&path), 3);
assert_eq!(user_version(&path), 4);
let store = Store::open(&path).unwrap();
let call = store.get_call(1).unwrap().unwrap();
assert_eq!(call.crm_transcript_id.as_deref(), Some("crm-1"));
assert_eq!(
call.crm_base_url.as_deref(),
Some("https://backend.example")
);
assert_eq!(call.uploaded_at, Some(uploaded));
}
#[test]
fn an_upload_is_recorded_and_replaced_by_the_next() {
fn a_version_3_database_is_upgraded_backfilling_the_test_backend_for_uploads() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("calls.sqlite");
let started = "2026-11-05T10:14:00+01:00";
{
let conn = rusqlite::Connection::open(&path).unwrap();
conn.execute_batch(RELEASED_V1_SCHEMA_SQL).unwrap();
conn.execute_batch(RELEASED_V2_STEP_SQL).unwrap();
conn.execute_batch(RELEASED_V3_STEP_SQL).unwrap();
conn.execute_batch("PRAGMA user_version = 3;").unwrap();
// An already-uploaded call (every pre-v4 upload went to the
// test backend; production never had the API).
conn.execute(
"INSERT INTO calls \
(app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id, title, crm_transcript_id, uploaded_at) \
VALUES ('Microsoft Teams', ?1, ?1, 'done', 0, NULL, '/rec/1-mic.wav', '/rec/1-out.wav', ?1, 0, NULL, NULL, 'crm-1', ?1)",
rusqlite::params![started],
)
.unwrap();
// A call that was never uploaded.
conn.execute(
"INSERT INTO calls \
(app, started_at, ended_at, status, interrupted, error, mic_path, out_path, transcribed_at, audio_deleted, account_id, title, crm_transcript_id, uploaded_at) \
VALUES ('MicroSIP', ?1, NULL, 'awaiting_decision', 0, NULL, '/rec/2-mic.wav', '/rec/2-out.wav', NULL, 0, NULL, NULL, NULL, NULL)",
rusqlite::params![started],
)
.unwrap();
}
let store = Store::open(&path).unwrap();
let uploaded = store.get_call(1).unwrap().expect("call kept");
assert_eq!(uploaded.crm_transcript_id.as_deref(), Some("crm-1"));
assert_eq!(
uploaded.crm_base_url.as_deref(),
Some("https://test.euvinopro.eu")
);
let not_uploaded = store.get_call(2).unwrap().expect("call kept");
assert_eq!(not_uploaded.crm_transcript_id, None);
assert_eq!(not_uploaded.crm_base_url, None);
assert_eq!(user_version(&path), 4);
}
#[test]
fn an_upload_is_recorded_and_replaced_by_the_next_even_for_another_backend() {
let store = Store::open_in_memory().unwrap();
let id = new_call(&store);
let other = new_call(&store);
let first = Local::now();
let second = first + chrono::Duration::minutes(5);
store.set_uploaded(id, "4711", first).unwrap();
store
.set_uploaded(id, "4711", "https://test.euvinopro.eu", first)
.unwrap();
let call = store.get_call(id).unwrap().unwrap();
assert_eq!(
(call.crm_transcript_id.as_deref(), call.uploaded_at),
(Some("4711"), Some(first))
(
call.crm_transcript_id.as_deref(),
call.crm_base_url.as_deref(),
call.uploaded_at
),
(Some("4711"), Some("https://test.euvinopro.eu"), Some(first))
);
store.set_uploaded(id, "4712", second).unwrap();
// One upload slot per call: a later upload, even to a different
// backend, replaces it rather than keeping both.
store
.set_uploaded(id, "4712", "https://backend.euvinopro.eu", second)
.unwrap();
let listed = store.list_calls().unwrap();
let call = listed.iter().find(|c| c.id == id).unwrap();
assert_eq!(
(call.crm_transcript_id.as_deref(), call.uploaded_at),
(Some("4712"), Some(second))
(
call.crm_transcript_id.as_deref(),
call.crm_base_url.as_deref(),
call.uploaded_at
),
(
Some("4712"),
Some("https://backend.euvinopro.eu"),
Some(second)
)
);
let untouched = store.get_call(other).unwrap().unwrap();
assert_eq!(
(untouched.crm_transcript_id, untouched.uploaded_at),
(None, None)
(
untouched.crm_transcript_id,
untouched.crm_base_url,
untouched.uploaded_at
),
(None, None, None)
);
}
+4 -8
View File
@@ -1,14 +1,10 @@
{
"version": "0.1.1",
"pub_date": "2026-11-06T11:12:59Z",
"version": "0.2.1",
"pub_date": "2026-11-06T14:48:27Z",
"platforms": {
"windows-x86_64": {
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUdGpRa1ZvalU2SUU5ME1DVkRlaXdwYXdpT0tvRk0rUFcvZXR4ditldzI5QWkyUVU2d0dqemN4UXhaMVA4bU8yQnJzU2ZJLzN1NnJFc3lWSmtqaDM2ZkFWeHBTdEtWQXdBPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzOTYzNDE1CWZpbGU6R2VzcHLDpGNoc3Jla29yZGVyXzAuMS4xX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjEuMQpPdVllUzFVSm13UTFKL3BTRVpjeEVOTzh4Z2pnN1J4OW15TWpIM1B3V1YzNlFLam9DaEc4Q21PUTZKSjlRZXRlZUx1U1ROcytGemtTK0hOTXdsNmhCUT09Cg==",
"url": "https://gitea.euvino.eu/public/call-recorder/releases/download/v0.1.1/Gespraechsrekorder_0.1.1_x64-setup.exe"
},
"linux-x86_64": {
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUdGpRa1ZvalU2SUtVMWk1Yzhjcy9CeTBzeTV3ck1YNXhpQTEzMm9ES1l4YVM2OGI1Z1Vnbm9EMXFmZlNtcjBNMWJOd0l1ei9vVVg4VkZwR2JicllHNkQreE5ZRWYxSndJPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzOTYzNTc5CWZpbGU6R2VzcHLDpGNoc3Jla29yZGVyXzAuMS4xX2FtZDY0LkFwcEltYWdlCXZlcnNpb246MC4xLjEKTUJnbWdKN0JWZytvcXl4UVAyRnlOaUhZempseXpEbE8yTGk0RldoZEZWVzQvWUF5V0pvb0Q2eG1mRjM3cnhnWWtTQjdzTS9pSkR0N0VBN245VnovQ2c9PQo=",
"url": "https://gitea.euvino.eu/public/call-recorder/releases/download/v0.1.1/Gespraechsrekorder_0.1.1_amd64.AppImage"
"signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVUdGpRa1ZvalU2SU9ZeUN6RUpYcjNFQ0VFTTZrZFpEa255SkRib0JtMVE4aEdVOG9ack5valRJdVAwZy9wcHZ2a1JFUHREZmJGT21Yd2hNOTh2TmMwSTVYRlRhQ1NqREFZPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzOTc2NDgwCWZpbGU6R2VzcHLDpGNoc3Jla29yZGVyXzAuMi4xX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjIuMQplYUZLR25PZVk0dm4xZUczMElNYlpYeEZ5Um9VbTgwbEJKUmQwU2l1QkZPUE9Bdy9sd1FIUHAyb0MyeEZlemkxaktwM0VBd05PZDBRV3NYWTVOSmlBQT09Cg==",
"url": "https://gitea.euvino.eu/public/call-recorder/releases/download/v0.2.1/Gespraechsrekorder_0.2.1_x64-setup.exe"
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "call-recorder"
version = "0.2.0"
version = "0.2.2"
description = "Gesprächsrekorder desktop app"
edition = "2021"
+42 -6
View File
@@ -31,11 +31,13 @@ use crate::state::AppState;
// The backend this build talks to: the one place to change it. It is not a
// setting; a key created on one backend is never sent to another.
/// Release builds. Switch to "https://backend.euvinopro.eu" here, then
/// release, once that backend is live.
const RELEASE_BACKEND_URL: &str = "https://test.euvinopro.eu";
/// Debug builds (`cargo tauri dev`) always use the test backend.
const DEV_BACKEND_URL: &str = "https://test.euvinopro.eu";
/// Release builds: the production euvino admin backend.
pub(crate) const RELEASE_BACKEND_URL: &str = "https://backend.euvinopro.eu";
/// Debug builds (`cargo tauri dev`) always use the test backend, never the
/// production one. `pub(crate)`: `state.rs` tests the exact test-backend →
/// release-backend transition against this value (a key bound to one must
/// never work for the other).
pub(crate) const DEV_BACKEND_URL: &str = "https://test.euvinopro.eu";
/// The backend of this build (no trailing slash).
pub const BACKEND_URL: &str = if cfg!(debug_assertions) {
DEV_BACKEND_URL
@@ -235,7 +237,22 @@ async fn upload(app: &AppHandle, state: &AppState, id: CallId) -> CmdResult<()>
.await
.inspect_err(|e| log::warn!("call {id}: upload failed: {e}"))?;
log::info!("call {id}: transcript uploaded (CRM id {crm_id})");
state.mark_uploaded(id, &crm_id)
if let Err(e) = state.mark_uploaded(id, &crm_id) {
// The CRM already has it: a retry must never send it again, even
// though the row itself still shows no crm_transcript_id.
state.note_upload_confirmed_but_unsaved(id);
log::error!("call {id}: uploaded (CRM id {crm_id}) but could not save locally: {e}");
return Err(unsaved_upload_message(&crm_id, &e));
}
Ok(())
}
/// Message for an upload that reached the CRM (`crm_id`) but whose local
/// record (`mark_uploaded`) failed with `e`: names the CRM id so the user
/// can find it there, and says plainly not to upload the call again (the
/// app also refuses on its own, see `AppState::note_upload_confirmed_but_unsaved`).
fn unsaved_upload_message(crm_id: &str, e: &str) -> String {
format!("Hochgeladen (ID {crm_id}), aber lokal nicht gespeichert: {e} – nicht erneut hochladen")
}
/// [`Login`] through the login window, for the upload.
@@ -440,6 +457,25 @@ fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mod tests {
use super::*;
#[test]
fn backend_urls_have_no_trailing_slash_and_use_https() {
for url in [RELEASE_BACKEND_URL, DEV_BACKEND_URL] {
assert!(!url.ends_with('/'), "{url}");
assert!(url.starts_with("https://"), "{url}");
}
// Release and dev talk to different backends: a key from one must
// never be usable on the other (see AppState::backend_key).
assert_ne!(RELEASE_BACKEND_URL, DEV_BACKEND_URL);
}
#[test]
fn the_unsaved_upload_message_names_the_crm_id_and_warns_against_retrying() {
assert_eq!(
unsaved_upload_message("4711", "disk full"),
"Hochgeladen (ID 4711), aber lokal nicht gespeichert: disk full – nicht erneut hochladen"
);
}
#[test]
fn everyone_waiting_gets_the_one_login_result() {
let waiters = LoginWaiters::default();
+39 -2
View File
@@ -23,6 +23,10 @@ use crate::state::{
};
const LEVELS_INTERVAL: Duration = Duration::from_millis(100);
/// `set_api_key`/`has_api_key` refuse this service: its key is managed only
/// by the backend login (`backend::login`), which holds `backend_key_lock`
/// and binds the key to this build's backend.
const BACKEND_KEY_MANAGED: &str = "Dieser Schlüssel wird über die Backend-Anmeldung verwaltet";
type CmdResult<T> = Result<T, String>;
@@ -32,6 +36,12 @@ struct CallEnded {
id: CallId,
}
/// This build's own version, for the settings' "Updates" section.
#[tauri::command]
pub fn get_app_version(app: AppHandle) -> String {
app.package_info().version.to_string()
}
#[tauri::command]
pub fn get_settings(state: State<'_, AppState>) -> Settings {
state.settings()
@@ -49,9 +59,11 @@ pub fn save_settings(
Ok(())
}
/// Stores `key` in the keyring; an empty key deletes the entry.
/// Stores `key` in the keyring; an empty key deletes the entry. Refuses
/// `Service::Backend` (see [`BACKEND_KEY_MANAGED`]).
#[tauri::command]
pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdResult<()> {
reject_backend_service(service)?;
blocking(app, move |app| {
let secrets = &app.state::<AppState>().secrets;
let key = key.trim();
@@ -65,9 +77,11 @@ pub async fn set_api_key(app: AppHandle, service: Service, key: String) -> CmdRe
.await
}
/// Whether a key is stored. Never returns the key itself.
/// Whether a key is stored. Never returns the key itself. Refuses
/// `Service::Backend` (see [`BACKEND_KEY_MANAGED`]).
#[tauri::command]
pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
reject_backend_service(service)?;
blocking(app, move |app| {
let key = app.state::<AppState>().secrets.get(service);
Ok(key.is_some_and(|key| !key.is_empty()))
@@ -75,6 +89,15 @@ pub async fn has_api_key(app: AppHandle, service: Service) -> CmdResult<bool> {
.await
}
/// Refuses direct keyring access to `Service::Backend`: its key is only
/// ever set by the backend login flow.
fn reject_backend_service(service: Service) -> CmdResult<()> {
if service == Service::Backend {
return Err(BACKEND_KEY_MANAGED.to_string());
}
Ok(())
}
#[tauri::command]
pub async fn list_devices() -> CmdResult<Devices> {
tauri::async_runtime::spawn_blocking(recorder_audio::list_devices)
@@ -412,3 +435,17 @@ where
.await
.map_err(|e| e.to_string())?
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_backend_key_is_managed_only_by_the_login() {
assert_eq!(
reject_backend_service(Service::Backend),
Err(BACKEND_KEY_MANAGED.to_string())
);
assert_eq!(reject_backend_service(Service::DeepScript), Ok(()));
}
}
+5 -1
View File
@@ -14,7 +14,7 @@ use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_log::{RotationStrategy, Target, TargetKind, TimezoneStrategy};
use crate::state::AppState;
use crate::updater::PendingUpdate;
use crate::updater::{PendingUpdate, UpdateSchedule};
/// Command-line flag the login item starts the app with; the main window
/// then stays hidden in the tray.
@@ -98,6 +98,7 @@ pub fn run() {
processing::clear_upload_dir(app.handle());
app.manage(state);
app.manage(PendingUpdate::default());
app.manage(UpdateSchedule::default());
app.manage(backend::LoginWaiters::default());
// Windows are created here (`create: false` in tauri.conf.json)
// instead of by Tauri before `setup` runs: their webviews load
@@ -130,6 +131,7 @@ pub fn run() {
}
})
.invoke_handler(tauri::generate_handler![
commands::get_app_version,
commands::get_settings,
commands::save_settings,
commands::set_api_key,
@@ -160,6 +162,8 @@ pub fn run() {
backend::upload_transcript,
updater::get_update,
updater::install_update,
updater::check_for_update_now,
updater::can_self_update,
])
.run(tauri::generate_context!())
.expect("error while building tauri application");
+161 -9
View File
@@ -164,6 +164,12 @@ pub struct AppState {
backend_key_lock: Mutex<()>,
/// Calls whose transcript is being uploaded; one upload per call.
uploading: Mutex<HashSet<CallId>>,
/// Calls whose transcript reached the CRM but could not be recorded
/// locally (`mark_uploaded` failed after a successful upload):
/// `claim_upload` refuses these for the rest of this run, so a retry
/// never creates a second copy at the CRM. In-memory only; a restart
/// forgets it (the row's `crm_transcript_id` is still empty then).
upload_confirmed_unsaved: Mutex<HashSet<CallId>>,
}
/// An upload reserved with [`AppState::claim_upload`]; released when
@@ -209,9 +215,15 @@ impl AppState {
pending_prompts: Mutex::new(VecDeque::new()),
processing: Mutex::new(HashSet::new()),
devices_busy: AtomicBool::new(false),
backend_url: crate::backend::BACKEND_URL.to_string(),
// Defensive: BACKEND_URL itself must never have a trailing
// slash (see backend::tests::backend_urls_have_no_trailing…),
// but a stored key's base_url is compared against this field.
backend_url: crate::backend::BACKEND_URL
.trim_end_matches('/')
.to_string(),
backend_key_lock: Mutex::new(()),
uploading: Mutex::new(HashSet::new()),
upload_confirmed_unsaved: Mutex::new(HashSet::new()),
}
}
@@ -337,11 +349,31 @@ impl AppState {
}
/// Reserves call `id` for one upload; released when the claim is
/// dropped. A second upload of the same call is refused meanwhile.
/// dropped. A second upload of the same call is refused meanwhile, and
/// so is a call already uploaded to *this build's* backend
/// ([`call_view::uploaded_here`]) — or one the CRM confirmed but whose
/// id could not be saved locally, see
/// [`AppState::note_upload_confirmed_but_unsaved`]: the CRM this build
/// talks to must never get a duplicate. An upload recorded for another
/// backend (e.g. the test backend, read by a release build) is not
/// "uploaded" here and is claimed like any other call. All three checks
/// happen while `uploading` is locked, so a second upload can never
/// slip in between this check and the one upload it allows.
pub fn claim_upload(&self, id: CallId) -> Result<UploadClaim<'_>, String> {
if !lock(&self.uploading).insert(id) {
let mut uploading = lock(&self.uploading);
if uploading.contains(&id) {
return Err("Wird bereits hochgeladen".to_string());
}
if lock(&self.upload_confirmed_unsaved).contains(&id) {
return Err("Bereits hochgeladen".to_string());
}
// An upload recorded for another backend (e.g. the test backend,
// read by a release build) does not count: the CRM this build
// talks to has never seen this transcript.
if call_view::uploaded_here(&self.find_call(id)?, &self.backend_url) {
return Err("Bereits hochgeladen".to_string());
}
uploading.insert(id);
Ok(UploadClaim { state: self, id })
}
@@ -350,6 +382,14 @@ impl AppState {
lock(&self.uploading).contains(&id)
}
/// Records that call `id`'s transcript reached the CRM, but saving that
/// locally (`mark_uploaded`) failed: [`AppState::claim_upload`] refuses
/// this call for the rest of the run, so a retry can never send the CRM
/// a second copy. In-memory only; see the field's doc comment.
pub fn note_upload_confirmed_but_unsaved(&self, id: CallId) {
lock(&self.upload_confirmed_unsaved).insert(id);
}
/// Changes and saves settings the app manages itself; saves only if
/// something changed.
fn update_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), String> {
@@ -593,7 +633,10 @@ impl AppState {
/// All calls for the main window's list, newest first.
pub fn call_list(&self) -> Result<Vec<CallListItem>, String> {
let calls = self.store.list_calls().map_err(|e| e.to_string())?;
Ok(calls.iter().map(CallListItem::of).collect())
Ok(calls
.iter()
.map(|call| CallListItem::of(call, &self.backend_url))
.collect())
}
/// The selected call with its transcript (speaker merges applied),
@@ -603,7 +646,7 @@ impl AppState {
let segments = self.store.segments(id).map_err(|e| e.to_string())?;
let names = self.store.speaker_names(id).map_err(|e| e.to_string())?;
let merges = self.store.speaker_merges(id).map_err(|e| e.to_string())?;
let mut detail = CallDetail::of(&call, &segments, names, &merges);
let mut detail = CallDetail::of(&call, &segments, names, &merges, &self.backend_url);
detail.uploading = self.is_uploading(id);
Ok(detail)
}
@@ -658,7 +701,7 @@ impl AppState {
pub fn mark_uploaded(&self, id: CallId, crm_transcript_id: &str) -> Result<(), String> {
self.find_call(id)?;
self.store
.set_uploaded(id, crm_transcript_id, Local::now())
.set_uploaded(id, crm_transcript_id, &self.backend_url, Local::now())
.map_err(|e| format!("Upload konnte nicht vermerkt werden: {e}"))
}
@@ -1504,6 +1547,42 @@ mod tests {
}
}
/// The real transition the review asked to lock in: a key created while
/// this install talked to the test backend must not work once the same
/// install is a release build talking to the production backend — it is
/// discarded and a fresh login is required, exactly like any other
/// backend mismatch above, but with the two real build-time constants
/// instead of a placeholder domain.
#[test]
fn a_key_from_the_test_backend_does_not_work_for_a_release_build() {
let mut f = fixture();
// A build on the test backend (what `cargo tauri dev` is), whatever
// profile this test itself runs in.
f.state.backend_url = crate::backend::DEV_BACKEND_URL.to_string();
f.state
.store_backend_key(
&new_key("euv_test"),
crate::backend::DEV_BACKEND_URL,
Some("hinrichs".into()),
)
.unwrap();
assert!(f.state.backend_key().is_some());
// Same keyring entry and settings file; now read as a release build
// would (a different `backend_url`, nothing else changed).
f.state.backend_url = crate::backend::RELEASE_BACKEND_URL.to_string();
assert_eq!(
f.state.backend_key(),
None,
"a test-backend key must not work for the release backend"
);
assert_eq!(f.state.secrets.get(Service::Backend), None);
let settings = f.state.settings();
assert_eq!(settings.backend_username, None);
assert_eq!(settings.backend_key_base_url, None);
}
#[test]
fn the_backend_login_is_refreshed_from_the_key_info() {
let f = fixture();
@@ -1588,10 +1667,17 @@ mod tests {
#[test]
fn the_backend_is_fixed_per_build() {
let f = fixture();
assert_eq!(f.state.backend_url(), "https://test.euvinopro.eu");
// Debug builds (`cargo tauri dev`, `cargo test`) use the test
// backend, release builds the production one.
let expected = if cfg!(debug_assertions) {
"https://test.euvinopro.eu"
} else {
"https://backend.euvinopro.eu"
};
assert_eq!(f.state.backend_url(), expected);
assert_eq!(
f.state.backend_client().login_url(),
"https://test.euvinopro.eu/euvadm"
format!("{expected}/euvadm")
);
}
@@ -1599,6 +1685,7 @@ mod tests {
fn a_call_is_uploaded_once_at_a_time() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
let (other, _, _) = finished_call(&f, "b");
assert!(!f.state.call_detail(id).unwrap().uploading);
let claim = f.state.claim_upload(id).unwrap();
@@ -1608,13 +1695,77 @@ mod tests {
f.state.claim_upload(id).err(),
Some("Wird bereits hochgeladen".to_string())
);
assert!(f.state.claim_upload(id + 1).is_ok(), "other calls are free");
assert!(f.state.claim_upload(other).is_ok(), "other calls are free");
drop(claim);
assert!(!f.state.is_uploading(id));
assert!(f.state.claim_upload(id).is_ok());
}
#[test]
fn a_call_already_uploaded_is_not_claimed_again() {
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state.mark_uploaded(id, "4711").unwrap();
assert_eq!(
f.state.claim_upload(id).err(),
Some("Bereits hochgeladen".to_string())
);
assert!(!f.state.is_uploading(id));
}
/// The real case the review asked to lock in: a call uploaded to the
/// test backend is refused for upload by a build whose own backend is
/// the test backend (the normal case, above), but uploadable again by a
/// build whose backend is the production one — the CRM at that backend
/// has never seen this transcript.
#[test]
fn an_upload_to_another_backend_is_not_counted_as_uploaded_here() {
let mut f = fixture();
let (id, _, _) = finished_call(&f, "a");
// A build on the test backend (what `cargo tauri dev` is), whatever
// profile this test itself runs in: mark_uploaded records it.
f.state.backend_url = crate::backend::DEV_BACKEND_URL.to_string();
f.state.mark_uploaded(id, "4711").unwrap();
assert_eq!(
f.state.find_call(id).unwrap().crm_base_url.as_deref(),
Some(crate::backend::DEV_BACKEND_URL)
);
assert_eq!(
f.state.claim_upload(id).err(),
Some("Bereits hochgeladen".to_string())
);
// The same row, now read as a release build would be: a different
// backend, nothing else changed.
f.state.backend_url = crate::backend::RELEASE_BACKEND_URL.to_string();
assert!(f.state.claim_upload(id).is_ok());
}
#[test]
fn an_upload_confirmed_but_unsaved_is_never_retried() {
// The CRM has the transcript, but mark_uploaded failed: the row
// itself still shows no crm_transcript_id.
let f = fixture();
let (id, _, _) = finished_call(&f, "a");
f.state.note_upload_confirmed_but_unsaved(id);
assert!(f
.state
.call_detail(id)
.unwrap()
.call
.item
.crm_transcript_id
.is_none());
assert_eq!(
f.state.claim_upload(id).err(),
Some("Bereits hochgeladen".to_string())
);
assert!(!f.state.is_uploading(id));
}
#[test]
fn an_upload_is_recorded_on_the_call() {
let f = fixture();
@@ -1624,6 +1775,7 @@ mod tests {
let call = f.state.store.get_call(id).unwrap().unwrap();
assert_eq!(call.crm_transcript_id.as_deref(), Some("4711"));
assert_eq!(call.crm_base_url.as_deref(), Some(BASE));
assert!(call.uploaded_at.is_some());
assert_eq!(
f.state.mark_uploaded(id + 1, "1"),
+303 -28
View File
@@ -2,12 +2,18 @@
//! in `tauri.conf.json`) at startup and every 6 h (sooner after a failed
//! check), tells the main window about a newer version and installs it when
//! the user asks, but never while a recording runs or a call is being
//! processed.
//! processed. The settings' "Nach Updates suchen" button
//! ([`check_for_update_now`]) runs the very same check immediately, counts
//! as an attempt for the same scheduler ([`UpdateSchedule`]) and never runs
//! at the same time as the background loop.
//!
//! On Windows the NSIS installer runs in passive mode for the current user
//! (no admin rights) and restarts the app; installing ends this process.
//! Debian builds never self-update; a manual check still asks the feed
//! there (see [`can_self_update`]).
use std::fs;
use std::future::Future;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
@@ -42,6 +48,17 @@ const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const MIB: u64 = 1024 * 1024;
/// Why the banner cannot install yet; the banner shows the same hint.
const BUSY: &str = "Nach der laufenden Aufnahme/Verarbeitung möglich";
/// The feed's key for the one installable release this app ever builds for
/// itself (see `UpdaterBuilder::target`). Asked explicitly on platforms
/// that cannot self-update, since the feed has no entry of their own and
/// the updater's automatic target lookup would otherwise fail with
/// `TargetsNotFound` even when a newer version exists.
const WINDOWS_TARGET: &str = "windows-x86_64";
/// Why installing is refused outright on this platform (`install_update`'s
/// own guard, in case a future feed ever gets a non-Windows entry and
/// `check` started finding updates there too).
const LINUX_CANNOT_INSTALL: &str =
"Updates werden unter Linux nicht automatisch installiert – bitte das .deb neu installieren.";
/// The newest update found, and whether one is being installed.
#[derive(Default)]
@@ -58,6 +75,99 @@ pub struct UpdateInfo {
pub can_install: bool,
}
/// Answer of `check_for_update_now`: what a check (background or manual)
/// found. On Windows, `Available` also leaves the same state `get_update`
/// reads and fires the same `update-available` event as the background
/// loop, so the main window's banner shows it too; elsewhere it only
/// reports the version (see `check_outcome`).
#[derive(Serialize, Clone, Debug, PartialEq)]
#[serde(tag = "status", rename_all = "lowercase")]
pub enum UpdateCheckResult {
/// No newer version on the feed.
None,
Available {
version: String,
},
/// The feed could not be asked; safe to show (never a secret).
Error {
message: String,
},
}
/// When the last check attempt (background or manual) started and how many
/// failed in a row, shared so a manual check feeds the same scheduler the
/// background loop uses: success resets the 6 h interval and the failure
/// count, a failure advances the backoff by one step. `running` also
/// serializes checks, so a manual and a background check never run at once.
#[derive(Default)]
pub struct UpdateSchedule {
state: Mutex<Schedule>,
running: tokio::sync::Mutex<()>,
}
#[derive(Default, Clone, Copy)]
struct Schedule {
last_attempt: Option<SystemTime>,
failures: u32,
}
impl UpdateSchedule {
/// Whether a check is due at `now`, per the last recorded attempt.
fn is_due(&self, now: SystemTime) -> bool {
let s = lock(&self.state);
check_due(s.last_attempt, s.failures, now)
}
/// Records the outcome of a check attempt that started at `now`.
fn record(&self, now: SystemTime, success: bool) {
let mut s = lock(&self.state);
s.last_attempt = Some(now);
s.failures = if success {
0
} else {
s.failures.saturating_add(1)
};
}
/// Runs one check attempt right now, unconditionally: for a manual
/// check, which the user asked for regardless of whether one is due.
/// Serialized against any other check (background or manual) via
/// `running`, and recorded for the scheduler exactly like a background
/// attempt.
async fn run(&self, app: &AppHandle) -> UpdateCheckResult {
self.attempt(false, || check(app))
.await
.expect("an unconditional attempt always runs")
}
/// For the background loop: like [`UpdateSchedule::run`], but only if a
/// check is still due once `running` is held (see `attempt`).
async fn run_if_due(&self, app: &AppHandle) {
self.attempt(true, || check(app)).await;
}
/// One serialized, recorded check attempt: takes `running`, then (if
/// `only_if_due`) re-checks `is_due` before calling `check`. Without
/// that re-check, a background tick that found a check due but then
/// had to wait behind a manual check (or another tick) would run its
/// own check right after, although the one it waited for just made the
/// next one not due any more. `None`: skipped, nothing recorded.
async fn attempt<F, Fut>(&self, only_if_due: bool, check: F) -> Option<UpdateCheckResult>
where
F: FnOnce() -> Fut,
Fut: Future<Output = UpdateCheckResult>,
{
let _serialize = self.running.lock().await;
let now = SystemTime::now();
if only_if_due && !self.is_due(now) {
return None;
}
let result = check().await;
self.record(now, !matches!(result, UpdateCheckResult::Error { .. }));
Some(result)
}
}
/// Payload of `update-progress`.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Progress {
@@ -67,27 +177,22 @@ pub struct Progress {
}
/// Starts the periodic update check. Only on Windows: Debian builds do not
/// update themselves.
/// update themselves (a manual check from the settings still asks the feed
/// on Linux, see `check_for_update_now`).
pub fn spawn(app: AppHandle) {
if !cfg!(windows) {
log::info!("update check disabled on this platform");
return;
}
thread::spawn(move || {
let mut last_attempt = None;
let mut failures = 0;
loop {
thread::spawn(move || loop {
let now = SystemTime::now();
if check_due(last_attempt, failures, now) {
last_attempt = Some(now);
if tauri::async_runtime::block_on(check(&app)) {
failures = 0;
} else {
failures = failures.saturating_add(1);
}
// Cheap early exit so most wake-ups never touch `running`; the due
// check that decides whether a check actually runs happens again
// inside `run_if_due`, once `running` is held (see its doc comment).
if app.state::<UpdateSchedule>().is_due(now) {
tauri::async_runtime::block_on(app.state::<UpdateSchedule>().run_if_due(&app));
}
thread::sleep(WAKE_INTERVAL);
}
});
}
@@ -110,31 +215,65 @@ fn check_due(last_attempt: Option<SystemTime>, failures: u32, now: SystemTime) -
.map_or(true, |elapsed| elapsed >= wait)
}
/// Asks the release feed for a newer version; `false` if the check failed.
/// Failures (offline, no release yet) are expected and only logged.
async fn check(app: &AppHandle) -> bool {
let result = match app.updater_builder().timeout(CHECK_TIMEOUT).build() {
/// Asks the release feed for a newer version: the one implementation the
/// background loop and a manual check (`check_for_update_now`) both run.
/// A failed check (offline, no release yet) is expected; only logged here,
/// and shown to the user only by a manual check (via the returned message).
///
/// The feed only ever has a `windows-x86_64` entry (Debian builds never
/// self-update, see `RELEASING.md`). On Windows the automatic target lookup
/// finds it on its own; on any other platform it is asked for explicitly
/// ([`WINDOWS_TARGET`]), only to learn the version number — see
/// [`check_outcome`] for why nothing is stored or announced there.
async fn check(app: &AppHandle) -> UpdateCheckResult {
let is_windows = cfg!(windows);
let mut builder = app.updater_builder().timeout(CHECK_TIMEOUT);
if !is_windows {
builder = builder.target(WINDOWS_TARGET);
}
let result = match builder.build() {
Ok(updater) => updater.check().await,
Err(e) => Err(e),
};
match result {
Ok(Some(update)) => {
log::info!("update available: {}", update.version);
let version = update.version.clone();
*lock(&app.state::<PendingUpdate>().update) = Some(update);
let _ = app.emit("update-available", info(app, version));
true
Ok(found) => {
let version = found.as_ref().map(|update| update.version.clone());
match &version {
Some(v) => log::info!("update available: {v}"),
None => log::info!("no update available"),
}
Ok(None) => {
log::info!("no update available");
true
let (outcome, offer_install) = check_outcome(is_windows, version.clone());
if let (Some(update), true) = (found, offer_install) {
*lock(&app.state::<PendingUpdate>().update) = Some(update);
let _ = app.emit(
"update-available",
info(app, version.expect("offer_install implies a version")),
);
}
outcome
}
Err(e) => {
log::info!("update check failed: {e}");
false
UpdateCheckResult::Error {
message: format!("Update-Prüfung fehlgeschlagen: {e}"),
}
}
}
}
/// What a feed answer (`version`, if any) means on this platform: the
/// result to return either way, and whether to remember the update for
/// `install_update` and announce it to the main window's banner. Only
/// Windows self-updates, so only there is a found update ever stored or
/// announced; elsewhere a manual check still reports the version (the
/// settings show it with a "not on this platform" hint instead of an
/// install button), but nothing is kept to install.
fn check_outcome(is_windows: bool, version: Option<String>) -> (UpdateCheckResult, bool) {
match version {
Some(version) => (UpdateCheckResult::Available { version }, is_windows),
None => (UpdateCheckResult::None, false),
}
}
/// Whether this is the first start of `version` (e.g. right after an
/// update), going by the version remembered in `path`; remembers `version`
@@ -161,6 +300,24 @@ fn info(app: &AppHandle, version: String) -> UpdateInfo {
}
}
/// "Nach Updates suchen" in the settings: runs the same check as the
/// background loop, immediately, reusing its scheduling (a success resets
/// the 6 h interval and the failure count, same as a background success)
/// and never running at the same time as a background check. Works on
/// every platform; see `can_self_update` for whether this build can then
/// install what it finds.
#[tauri::command]
pub async fn check_for_update_now(app: AppHandle) -> UpdateCheckResult {
app.state::<UpdateSchedule>().run(&app).await
}
/// Whether this build can install an update itself (Windows only: Debian
/// builds ship a `.deb` and never self-update, see `spawn`).
#[tauri::command]
pub fn can_self_update() -> bool {
cfg!(windows)
}
/// The update found by the last check, if any.
#[tauri::command]
pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
@@ -174,6 +331,11 @@ pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
/// app. Returns only on failure.
#[tauri::command]
pub async fn install_update(app: AppHandle) -> Result<(), String> {
// Defense in depth: `check` only ever stores a pending update on
// Windows, but this guard holds even if that ever changes.
if !cfg!(windows) {
return Err(LINUX_CANNOT_INSTALL.to_string());
}
let pending = app.state::<PendingUpdate>();
if pending.installing.swap(true, Ordering::SeqCst) {
return Err("Das Update wird bereits installiert".to_string());
@@ -350,4 +512,117 @@ mod tests {
let reports = reported(&mut meter, &[half, half, half, half, half], None);
assert_eq!(reports, [MIB / 2, MIB, 2 * MIB]);
}
#[test]
fn update_check_result_maps_to_a_tagged_status() {
assert_eq!(
serde_json::to_value(UpdateCheckResult::None).unwrap(),
serde_json::json!({"status": "none"})
);
assert_eq!(
serde_json::to_value(UpdateCheckResult::Available {
version: "0.3.0".into()
})
.unwrap(),
serde_json::json!({"status": "available", "version": "0.3.0"})
);
assert_eq!(
serde_json::to_value(UpdateCheckResult::Error {
message: "Update-Prüfung fehlgeschlagen: x".into()
})
.unwrap(),
serde_json::json!({"status": "error", "message": "Update-Prüfung fehlgeschlagen: x"})
);
}
/// Only Windows self-updates: elsewhere a found update is still
/// reported (so the settings can show the version), but never stored
/// for `install_update` or announced to the banner.
#[test]
fn only_windows_offers_to_install_a_found_update() {
assert_eq!(
check_outcome(true, Some("0.3.0".into())),
(
UpdateCheckResult::Available {
version: "0.3.0".into()
},
true
)
);
assert_eq!(
check_outcome(false, Some("0.3.0".into())),
(
UpdateCheckResult::Available {
version: "0.3.0".into()
},
false
)
);
assert_eq!(check_outcome(true, None), (UpdateCheckResult::None, false));
assert_eq!(check_outcome(false, None), (UpdateCheckResult::None, false));
}
/// A manual check feeds the very scheduler the background loop reads
/// (`record` is the one function either kind of attempt calls): a
/// failure advances the backoff by exactly the one step a single
/// failure always does (never more just for being a manual attempt),
/// and a success resets the interval to 6 h and the failure count.
#[test]
fn a_manual_checks_result_feeds_the_background_scheduler() {
let schedule = UpdateSchedule::default();
assert!(schedule.is_due(t0()), "nothing attempted yet");
// One failed manual check: due again after the 1st retry delay,
// exactly as check_due(_, 1, _) says, not sooner and not later.
schedule.record(t0(), false);
assert!(!schedule.is_due(t0() + MIN - Duration::from_secs(1)));
assert!(schedule.is_due(t0() + MIN));
// A second failed attempt (background or manual, the scheduler does
// not distinguish) advances to the 2nd retry delay, not further.
schedule.record(t0() + MIN, false);
assert!(!schedule.is_due(t0() + MIN + 5 * MIN - Duration::from_secs(1)));
assert!(schedule.is_due(t0() + MIN + 5 * MIN));
// A manual check that then succeeds resets the interval to 6 h and
// the failure count, exactly like a background success.
schedule.record(t0() + MIN, true);
assert!(!schedule.is_due(t0() + MIN + 6 * HOUR - MIN));
assert!(schedule.is_due(t0() + MIN + 6 * HOUR));
}
/// A background tick that found a check due, but only got `running`
/// after a manual check finished, must not check again: `is_due` is
/// re-checked once the lock is held. Sequential here (the tick's own
/// early `is_due` happened before the manual check, so only the
/// re-check inside `attempt` can stop it).
#[test]
fn a_background_attempt_rechecks_due_once_it_holds_the_lock() {
let schedule = UpdateSchedule::default();
assert!(
schedule.is_due(SystemTime::now()),
"the tick saw a due check"
);
let manual = tauri::async_runtime::block_on(
schedule.attempt(false, || async { UpdateCheckResult::None }),
);
assert_eq!(manual, Some(UpdateCheckResult::None));
let mut checked = false;
let background = tauri::async_runtime::block_on(schedule.attempt(true, || {
checked = true;
async { UpdateCheckResult::None }
}));
assert_eq!(background, None);
assert!(!checked, "no second check right after the manual one");
// A manual check always runs, due or not.
let again = tauri::async_runtime::block_on(schedule.attempt(false, || async {
UpdateCheckResult::Error {
message: "x".into(),
}
}));
assert!(matches!(again, Some(UpdateCheckResult::Error { .. })));
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Gesprächsrekorder",
"version": "0.2.0",
"version": "0.2.2",
"identifier": "eu.euvino.callrecorder",
"build": {
"frontendDist": "../ui/dist",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "ui",
"private": true,
"version": "0.2.0",
"version": "0.2.2",
"type": "module",
"scripts": {
"dev": "vite",
+4 -11
View File
@@ -8,6 +8,8 @@
onRecordingState,
onUpdateAvailable,
onUpdateProgress,
updateProgressText,
UPDATE_BUSY_HINT,
type UpdateInfo,
type UpdateProgress,
} from './api'
@@ -62,16 +64,7 @@
}
}
function megabytes(bytes: number): string {
return (bytes / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' MB'
}
let progressText = $derived.by(() => {
if (!progress) return 'Update wird heruntergeladen…'
if (progress.total === null) return `Update wird heruntergeladen… ${megabytes(progress.downloaded)}`
if (progress.downloaded >= progress.total) return 'Update wird installiert…'
return `Update wird heruntergeladen… ${Math.floor((progress.downloaded * 100) / progress.total)} %`
})
let progressText = $derived(updateProgressText(progress))
</script>
{#if update}
@@ -84,7 +77,7 @@
Installieren &amp; neu starten
</button>
{#if !update.can_install}
<span class="hint">Nach der laufenden Aufnahme/Verarbeitung möglich</span>
<span class="hint">{UPDATE_BUSY_HINT}</span>
{/if}
{/if}
{#if error}
+30
View File
@@ -137,6 +137,15 @@ export interface UpdateProgress {
total: number | null
}
/** Why the install button is disabled, shown next to it as a hint. */
export const UPDATE_BUSY_HINT = 'Nach der laufenden Aufnahme/Verarbeitung möglich'
/** What a check (background or manual) found. */
export type UpdateCheckResult =
| { status: 'none' }
| { status: 'available'; version: string }
| { status: 'error'; message: string }
export interface Levels {
mic: number
out: number
@@ -185,6 +194,14 @@ export const uploadTranscript = (id: CallId) => invoke<void>('upload_transcript'
export const getUpdate = () => invoke<UpdateInfo | null>('get_update')
/** Resolves only on failure: on success the app restarts. */
export const installUpdate = () => invoke<void>('install_update')
/** This build's own version, for the settings' "Updates" section. */
export const getAppVersion = () => invoke<string>('get_app_version')
/** Whether this build can install an update itself (Windows only). */
export const canSelfUpdate = () => invoke<boolean>('can_self_update')
/** "Nach Updates suchen": runs the same check as the background loop,
* immediately. An `available` result leaves the same state `getUpdate`
* reads, so the main window's banner shows it too. */
export const checkForUpdateNow = () => invoke<UpdateCheckResult>('check_for_update_now')
export const onRecordingState = (handler: (state: RecordingState) => void): Promise<UnlistenFn> =>
listen<RecordingState>('recording-state', (event) => handler(event.payload))
@@ -218,6 +235,19 @@ export function meterFill(level: number): number {
return Math.min(1, Math.max(0, (db + 60) / 60))
}
function megabytes(bytes: number): string {
return (bytes / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 }) + ' MB'
}
/** Text shown while an update installs (the banner and the settings'
* Updates section share this). */
export function updateProgressText(progress: UpdateProgress | null): string {
if (!progress) return 'Update wird heruntergeladen…'
if (progress.total === null) return `Update wird heruntergeladen… ${megabytes(progress.downloaded)}`
if (progress.downloaded >= progress.total) return 'Update wird installiert…'
return `Update wird heruntergeladen… ${Math.floor((progress.downloaded * 100) / progress.total)} %`
}
/** Error text of a rejected command. */
export function errorText(err: unknown): string {
return typeof err === 'string' ? err : err instanceof Error ? err.message : String(err)
+7 -25
View File
@@ -49,7 +49,6 @@
// take a while); their errors are kept per call too.
let uploading = $state<CallId[]>([])
let uploadErrors = $state<Record<CallId, string>>({})
let confirmingUpload = $state(false)
let editingTitle = $state(false)
let titleDraft = $state('')
@@ -106,7 +105,6 @@
actionError = ''
editingTitle = false
titleError = ''
confirmingUpload = false
refreshDetail()
}
@@ -117,7 +115,6 @@
actionError = ''
editingTitle = false
titleError = ''
confirmingUpload = false
}
onMount(() => {
@@ -192,18 +189,12 @@
refreshList()
})
/** "Transkript hochladen"; an upload done before asks first. */
function uploadClick() {
if (!detail) return
if (detail.call.uploaded_at) confirmingUpload = true
else upload()
}
/** Uploads the shown call's transcript (logging in first if needed). */
/** Uploads the shown call's transcript (logging in first if needed). A
* call already uploaded has no button any more: the CRM never gets a
* duplicate. */
async function upload() {
if (!detail) return
const id = detail.call.id
confirmingUpload = false
if (uploading.includes(id)) return
uploading = [...uploading, id]
delete uploadErrors[id]
@@ -360,22 +351,14 @@
{:else if call.status === 'failed'}
<button class="btn primary" disabled={busy} onclick={retry}>Erneut versuchen</button>
<button class="btn danger" disabled={busy} onclick={discard}>Verwerfen</button>
{:else if call.status === 'done' && confirmingUpload}
<span class="confirm">Dieses Transkript wurde bereits hochgeladen. Nochmal hochladen?</span>
<button class="btn primary" onclick={upload}>Hochladen</button>
<button class="btn" onclick={() => (confirmingUpload = false)}>Abbrechen</button>
{:else if call.status === 'done'}
{:else if call.status === 'done' && !call.uploaded_at}
<button
class="btn primary"
disabled={!call.transcribed_at || isUploading}
title={call.transcribed_at ? 'Transkript ins CRM hochladen' : 'Noch kein Transkript'}
onclick={uploadClick}
onclick={upload}
>
{isUploading
? 'wird hochgeladen…'
: call.uploaded_at
? 'Erneut hochladen'
: 'Transkript hochladen'}
{isUploading ? 'wird hochgeladen…' : 'Transkript hochladen'}
</button>
{/if}
</span>
@@ -568,8 +551,7 @@
margin-left: auto;
}
.uploaded,
.confirm {
.uploaded {
font-size: 12px;
}
+154
View File
@@ -6,17 +6,26 @@
backendLogout,
backendServer,
backendStatus,
canSelfUpdate,
checkForUpdateNow,
errorText,
getAppVersion,
getSettings,
getUpdate,
hasApiKey,
installUpdate,
listDevices,
meterFill,
onBackendChanged,
onBackendLoginError,
onUpdateAvailable,
onUpdateProgress,
openBackendKeysPage,
saveSettings,
setApiKey,
testDevices,
updateProgressText,
UPDATE_BUSY_HINT,
type BackendServer,
type BackendStatus,
type DeviceInfo,
@@ -24,6 +33,9 @@
type Devices,
type Service,
type Settings,
type UpdateCheckResult,
type UpdateInfo,
type UpdateProgress,
} from '../lib/api'
const services: { id: Service; name: string }[] = [
@@ -48,19 +60,104 @@
// Status answers can arrive out of order; only the newest is applied.
let statusRequest = 0
let appVersion = $state('')
/** `null` until known: whether this build can install an update itself
* (Windows only); avoids guessing wrong for an instant. */
let selfUpdateCapable = $state<boolean | null>(null)
let checking = $state(false)
let checkResult = $state<UpdateCheckResult | null>(null)
let pendingUpdate = $state<UpdateInfo | null>(null)
let installing = $state(false)
let installProgress = $state<UpdateProgress | null>(null)
let installError = $state('')
/** The version to show as "available", if any. On Windows this comes
* from `pendingUpdate` (kept in sync with the banner by `get_update`/
* `update-available`, so it is current even without a manual check).
* Everywhere else the backend never stores `pendingUpdate` for a found
* update (see `updater::check_outcome`), so a manual check's own result
* is the only source. It is also the fallback whenever `pendingUpdate`
* is not known (e.g. the follow-up `getUpdate()` failed, or
* `canSelfUpdate()` failed): a found update is never hidden. */
let availableVersion = $derived(
(selfUpdateCapable === true ? pendingUpdate?.version : undefined) ??
(checkResult?.status === 'available' ? checkResult.version : undefined),
)
/** Whether the install button/progress can be offered for
* `availableVersion`: only once this build is confirmed able to
* self-update AND `pendingUpdate` (with its `can_install` guard) is
* actually known. */
let canOfferInstall = $derived(selfUpdateCapable === true && pendingUpdate !== null)
onMount(() => {
load()
backendServer()
.then((s) => (server = s))
.catch((err) => (backendError = errorText(err)))
refreshBackend()
getAppVersion()
.then((v) => (appVersion = v))
.catch(() => {})
canSelfUpdate()
.then((v) => (selfUpdateCapable = v))
.catch(() => {})
getUpdate()
.then((u) => (pendingUpdate = u))
.catch(() => {})
const unlisten = [
onBackendChanged(refreshBackend),
onBackendLoginError((msg) => (backendError = msg)),
onUpdateAvailable((info) => (pendingUpdate = info)),
onUpdateProgress((progress) => (installProgress = progress)),
]
return () => unlisten.forEach((u) => u.then((off) => off()))
})
/** "Nach Updates suchen": runs the same check as the background loop,
* immediately. An available update also arrives via `update-available`
* (so the main window's banner shows it too, on Windows), but is applied
* here as well in case that event is missed. That follow-up fetch is
* best-effort: if it fails, the "available" result just found still
* stands — it must never be replaced by that unrelated failure. */
async function checkUpdateNow() {
checking = true
checkResult = null
try {
checkResult = await checkForUpdateNow()
} catch (err) {
checkResult = { status: 'error', message: errorText(err) }
checking = false
return
}
if (checkResult.status === 'available') await refreshPendingUpdate()
checking = false
}
async function refreshPendingUpdate() {
try {
pendingUpdate = await getUpdate()
} catch {
// Optional refresh; the next event or check tries again.
}
}
/** "Installieren & neu starten" for the update found above; reuses the
* install command and guard the main window's banner uses. */
async function installUpdateNow() {
installing = true
installProgress = null
installError = ''
try {
// Returns only on failure: on success the app restarts.
await installUpdate()
} catch (err) {
installError = errorText(err)
refreshPendingUpdate()
} finally {
installing = false
}
}
/** Checks the stored key with the backend. */
async function refreshBackend() {
const request = ++statusRequest
@@ -377,6 +474,54 @@
</div>
</section>
<section class="card">
<h2>Updates</h2>
<div class="grid">
<span>Version</span>
<span>{appVersion || '…'}</span>
</div>
<div class="update-check">
<button class="btn" disabled={checking} onclick={checkUpdateNow}>
{checking ? 'Suche…' : 'Nach Updates suchen'}
</button>
{#if checkResult?.status === 'none'}
<span class="muted">Keine neue Version verfügbar (aktuell: {appVersion})</span>
{:else if checkResult?.status === 'error'}
<span class="error">{checkResult.message}</span>
{/if}
</div>
{#if availableVersion !== undefined}
<div class="update-available">
<span>Update verfügbar (v{availableVersion})</span>
{#if canOfferInstall}
{#if installing}
<span>{updateProgressText(installProgress)}</span>
{:else}
<button
class="btn primary small"
disabled={!pendingUpdate?.can_install}
onclick={installUpdateNow}
>
Installieren &amp; neu starten
</button>
{#if !pendingUpdate?.can_install}
<span class="muted">{UPDATE_BUSY_HINT}</span>
{/if}
{/if}
{#if installError}
<span class="error">{installError}</span>
{/if}
{:else if selfUpdateCapable !== true}
<!-- Not able to self-update, or unknown (`canSelfUpdate()`
failed): never an install button, just the hint. -->
<span class="muted">
Updates gibt es unter Windows automatisch; unter Linux bitte das .deb neu installieren.
</span>
{/if}
</div>
{/if}
</section>
<div class="footer">
<button class="btn primary" onclick={() => run(persist, 'Einstellungen gespeichert ✓')}>
Speichern
@@ -503,6 +648,15 @@
overflow-wrap: anywhere;
}
.update-check,
.update-available {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px 10px;
margin-top: 12px;
}
.footer {
display: flex;
align-items: center;