mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* meetings: discard recordings with no speech * meetings: discard empty recordings without a finished event * meetings: share the keep-or-discard decision
1432 lines
52 KiB
Rust
1432 lines
52 KiB
Rust
use std::fs::{self, File, OpenOptions};
|
||
use std::io::{BufWriter, Write};
|
||
use std::path::{Path, PathBuf};
|
||
use std::sync::Arc;
|
||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||
use std::sync::mpsc::{self, Receiver, SyncSender};
|
||
use std::thread;
|
||
use std::time::{Duration, Instant};
|
||
|
||
use color_eyre::eyre::{Result, WrapErr, eyre};
|
||
use hound::{SampleFormat, WavSpec, WavWriter};
|
||
use serde::{Deserialize, Serialize};
|
||
|
||
use crate::desktop::events::now_ms;
|
||
use crate::durable::{lock_contended, sync_directory, sync_file};
|
||
|
||
const SAMPLE_RATE: u32 = 16_000;
|
||
/// Beside the manifest of a meeting Hex quit while recording or during its
|
||
/// final transcription: its audio is
|
||
/// saved and its final transcript runs at the next launch.
|
||
const FINAL_PENDING_FILE: &str = "final.pending";
|
||
/// While an audio import runs, until final.pending exists: marks the folder
|
||
/// as an import the launch sweep may remove once its lock is free.
|
||
const IMPORT_PENDING_FILE: &str = "import.pending";
|
||
|
||
mod capture;
|
||
mod chapters;
|
||
mod chunk_level;
|
||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||
pub(crate) mod detection;
|
||
#[cfg(target_os = "linux")]
|
||
#[path = "meeting/linux.rs"]
|
||
mod os;
|
||
#[cfg(target_os = "macos")]
|
||
#[path = "meeting/macos.rs"]
|
||
mod os;
|
||
#[cfg(target_os = "windows")]
|
||
#[path = "meeting/windows.rs"]
|
||
mod os;
|
||
pub(crate) mod window_title;
|
||
/// Linux's Trash, for capture retention too: distros ship no `trash` command.
|
||
#[cfg(target_os = "linux")]
|
||
pub(crate) use os::move_to_trash;
|
||
#[cfg(target_os = "macos")]
|
||
pub(crate) use os::{
|
||
SystemAudioAuthorization, create_tap_aggregate, request_screen_recording,
|
||
request_system_audio_access, reset_system_audio_request, screen_recording_permitted,
|
||
system_audio_authorization, system_audio_ready,
|
||
};
|
||
pub(crate) use os::{open_folder, reveal};
|
||
mod delete;
|
||
mod delta;
|
||
mod echo;
|
||
mod export_name;
|
||
mod finish;
|
||
pub(crate) mod finished_events;
|
||
pub(crate) mod generator;
|
||
#[cfg(target_os = "macos")]
|
||
pub(crate) mod import;
|
||
#[cfg(any(target_os = "windows", test))]
|
||
mod loopback_route;
|
||
mod markdown;
|
||
pub(crate) mod mcp;
|
||
mod notes;
|
||
mod notes_file;
|
||
pub mod query;
|
||
mod recording;
|
||
mod recovery;
|
||
mod retention;
|
||
#[cfg(any(target_os = "linux", target_os = "windows"))]
|
||
pub(crate) mod runtime;
|
||
pub(crate) mod seen_calls;
|
||
pub(crate) mod sweep;
|
||
mod transcript;
|
||
mod turn;
|
||
mod warning;
|
||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||
pub(crate) mod watcher;
|
||
pub use capture::track_levels;
|
||
#[cfg(all(debug_assertions, target_os = "macos"))]
|
||
pub use chapters::chapters_file;
|
||
#[cfg(target_os = "macos")]
|
||
pub use chapters::section_for_id;
|
||
pub use chapters::{Chapter, chapter_entries, section_markdown};
|
||
#[cfg(test)]
|
||
pub use delete::DeleteRefusal;
|
||
pub use delete::{DeleteError, TrashedMeeting, delete, trash};
|
||
pub use delta::*;
|
||
pub(crate) use finish::keep_or_discard;
|
||
pub use markdown::{
|
||
live_transcript_markdown, render_turns_markdown, speaker_label, transcript_markdown,
|
||
transcript_markdown_with,
|
||
};
|
||
pub use notes::{MeetingNotes, display_title, notes_in_progress, notes_wanted, spawn_summary};
|
||
#[cfg(all(debug_assertions, target_os = "macos"))]
|
||
pub use notes::{summarize, summarize_file};
|
||
pub use recording::recording;
|
||
#[cfg(test)]
|
||
pub use retention::audio_expired;
|
||
pub use retention::{expire, expire_audio, list, retention_for};
|
||
pub use transcript::TranscriptReader;
|
||
pub use turn::coalesce_transcript;
|
||
pub use warning::TrackWarning;
|
||
|
||
/// What the recorder knows about a meeting when it starts.
|
||
#[derive(Clone, Debug, Default)]
|
||
pub struct MeetingStart {
|
||
/// An explicit title; otherwise one is derived from the app and time.
|
||
pub title: Option<String>,
|
||
/// The detected call application, such as `Zoom`.
|
||
pub app: Option<String>,
|
||
/// The call app's canonical bundle identifier, whose input the
|
||
/// microphone follows where the OS reports it.
|
||
pub application: Option<String>,
|
||
/// The calendar event the recording was started for.
|
||
pub calendar: Option<MeetingCalendar>,
|
||
/// Where `title` came from; ignored without a title.
|
||
pub title_source: TitleSource,
|
||
}
|
||
|
||
/// Where a meeting's title came from. Only a title the user typed is never
|
||
/// extended or replaced by generated ones.
|
||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(rename_all = "snake_case")]
|
||
pub enum TitleSource {
|
||
/// The app-and-time title Hex made up.
|
||
#[default]
|
||
Default,
|
||
/// The detected call's own name, such as a browser tab's.
|
||
Call,
|
||
/// The calendar event the recording was started for.
|
||
Calendar,
|
||
/// Typed by the user when recording started or in a rename.
|
||
User,
|
||
}
|
||
|
||
/// The calendar event behind a meeting: its title and the other attendees,
|
||
/// kept as context for the transcript and its notes.
|
||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||
pub struct MeetingCalendar {
|
||
pub title: String,
|
||
#[serde(default)]
|
||
pub attendees: Vec<String>,
|
||
}
|
||
|
||
/// What the recorder reports to its owner while it runs.
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
pub enum RecordingUpdate {
|
||
/// Capture started; `id` identifies the meeting folder and `title` is the one it shows.
|
||
Started { id: String, title: String },
|
||
/// A provisional title from the transcript so far.
|
||
Retitled { title: String },
|
||
/// The live chapters so far (Labs).
|
||
Chapters(Vec<Chapter>),
|
||
/// The microphone's captured audio became digitally silent, or its
|
||
/// audio returned.
|
||
SourceWarning { warning: Option<TrackWarning> },
|
||
/// Capture stopped; final transcription is running.
|
||
Transcribing,
|
||
}
|
||
|
||
pub fn default_title(app: Option<&str>, created_at_ms: u64) -> String {
|
||
titled(app, &transcript::LocalTime::from_ms(created_at_ms).clock())
|
||
}
|
||
|
||
/// The default title naming a meeting at `clock`, `2:30 PM` or `14:30`.
|
||
fn titled(app: Option<&str>, clock: &str) -> String {
|
||
match app {
|
||
Some(app) => format!("{app} call — {clock}"),
|
||
None => format!("Meeting — {clock}"),
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||
pub enum MeetingRequest {
|
||
/// Record a meeting now; `title` names it instead of the default.
|
||
Start {
|
||
title: Option<String>,
|
||
},
|
||
Stop,
|
||
/// Regenerate Apple Intelligence notes for a completed meeting.
|
||
Summarize(String),
|
||
/// Import a local audio file as a meeting (macOS; Labs › Import audio).
|
||
Import(PathBuf),
|
||
}
|
||
|
||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||
pub struct MeetingManifest {
|
||
pub schema_version: u8,
|
||
pub id: String,
|
||
pub title: String,
|
||
pub status: MeetingStatus,
|
||
pub created_at_ms: u64,
|
||
pub ended_at_ms: Option<u64>,
|
||
pub duration_ms: Option<u64>,
|
||
pub system: TrackManifest,
|
||
pub microphone: TrackManifest,
|
||
/// Why the in-call transcript stopped, read from beside the manifest.
|
||
#[serde(default)]
|
||
pub live_transcription_error: Option<String>,
|
||
pub error: Option<String>,
|
||
/// The detected call application, such as `Zoom`.
|
||
#[serde(default)]
|
||
pub app: Option<String>,
|
||
/// The published Markdown copy in the user's meeting folder.
|
||
#[serde(default)]
|
||
pub export_path: Option<PathBuf>,
|
||
#[serde(default)]
|
||
pub export_error: Option<String>,
|
||
#[serde(default)]
|
||
pub echo_suppressed_utterances: u64,
|
||
/// A title generated from the transcript while recording; shown only
|
||
/// while `title` is the default and no notes title exists.
|
||
#[serde(default)]
|
||
pub provisional_title: Option<String>,
|
||
/// Apple Intelligence notes generated after final publication.
|
||
#[serde(default)]
|
||
pub notes: Option<MeetingNotes>,
|
||
#[serde(default)]
|
||
pub notes_error: Option<String>,
|
||
/// The calendar event the recording was started for, if any.
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub calendar: Option<MeetingCalendar>,
|
||
/// Where `title` came from. Older manifests have none: a title other
|
||
/// than the default one counts as the user's.
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub title_source: Option<TitleSource>,
|
||
/// Topic chapters in time order (Labs).
|
||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||
pub chapters: Vec<Chapter>,
|
||
/// The chapter boundaries were corrected over the whole transcript.
|
||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||
pub chapters_refined: bool,
|
||
/// Recorded since retention began: until the user chooses one, it is
|
||
/// kept 24 hours by default. Older meetings stay until then.
|
||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||
pub retention_applies: bool,
|
||
/// SHA-256 of the exported Markdown as Hex last wrote it. Expiry moves
|
||
/// that file to the Trash only while it still matches, so a copy the
|
||
/// user edited stays.
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub export_sha256: Option<String>,
|
||
/// The notes file beside the transcript while Separate notes file
|
||
/// wrote one, tracked so renames, Trash, and retention follow it.
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub notes_export_path: Option<PathBuf>,
|
||
/// SHA-256 of the notes file as Hex last wrote it. A later notes
|
||
/// regeneration rewrites it only while it still matches, and expiry moves
|
||
/// it only then, so a copy the user edited stays.
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub notes_export_sha256: Option<String>,
|
||
/// The tracked notes file was deleted outside Hex. Hex forgets its path
|
||
/// and never writes another notes file for this meeting.
|
||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||
pub notes_export_removed: bool,
|
||
/// When the meeting's WAV tracks moved to the Trash (Meetings ›
|
||
/// Settings › Keep audio); the transcript, notes, and Markdown stay.
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub audio_removed_at_ms: Option<u64>,
|
||
/// Imported from an audio file rather than recorded: one speaker track,
|
||
/// labelled Speaker.
|
||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||
pub imported: bool,
|
||
}
|
||
|
||
impl MeetingManifest {
|
||
/// What a transcript line's source is called in the user's Markdown: an
|
||
/// imported meeting has one track, so every turn is just Speaker.
|
||
pub fn speaker_label(&self, source: MeetingSource) -> &'static str {
|
||
markdown::speaker_label(source, self.imported)
|
||
}
|
||
|
||
/// Where `title` came from, inferred for manifests that predate the field.
|
||
pub fn title_source(&self) -> TitleSource {
|
||
self.title_source.unwrap_or_else(|| {
|
||
let app = self.app.as_deref();
|
||
let time = transcript::LocalTime::from_ms(self.created_at_ms);
|
||
// A default from before meeting times followed the language was
|
||
// named with English's 12-hour clock.
|
||
if self.title == titled(app, &time.clock())
|
||
|| self.title == titled(app, &time.twelve_hour_clock())
|
||
{
|
||
TitleSource::Default
|
||
} else {
|
||
TitleSource::User
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(rename_all = "snake_case")]
|
||
pub enum MeetingStatus {
|
||
Starting,
|
||
Recording,
|
||
Transcribing,
|
||
Complete,
|
||
Interrupted,
|
||
Failed,
|
||
}
|
||
|
||
impl MeetingStatus {
|
||
pub fn is_active(self) -> bool {
|
||
matches!(self, Self::Starting | Self::Recording | Self::Transcribing)
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||
pub struct TrackManifest {
|
||
pub file: String,
|
||
pub sample_rate: Option<u32>,
|
||
pub first_pts_us: Option<i64>,
|
||
pub last_pts_us: Option<i64>,
|
||
pub first_arrival_us: Option<u64>,
|
||
pub samples: u64,
|
||
pub dropped_packets: u64,
|
||
/// Stretches where this source captured nothing while the meeting kept
|
||
/// recording, filled with silence so the track stays on the timeline.
|
||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||
pub gaps: Vec<TrackGap>,
|
||
/// A problem with this track that the user should know about. For the
|
||
/// microphone, `digital_silence` means the stream was digitally silent
|
||
/// at some point during the recording, even if its audio returned later.
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub warning: Option<TrackWarning>,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||
pub struct TrackGap {
|
||
/// Where the silence starts, in milliseconds of this track.
|
||
pub start_ms: u64,
|
||
pub duration_ms: u64,
|
||
}
|
||
|
||
/// A source that resumes after at least this much silence is padded back
|
||
/// onto the timeline. Ordinary callback jitter and clock drift stay below it.
|
||
const GAP_PAD_THRESHOLD_MS: u64 = 1_000;
|
||
|
||
/// Samples missing before `packet`, judged from its arrival on the shared
|
||
/// capture clock against the samples this track already holds. Packets are
|
||
/// stamped as they finish, so the packet's own length is subtracted; the
|
||
/// estimate errs toward padding slightly too little rather than too much.
|
||
fn missing_samples(track: &TrackManifest, packet: &AudioPacket) -> u64 {
|
||
let Some(first_arrival_us) = track.first_arrival_us else {
|
||
return 0;
|
||
};
|
||
let elapsed_us = packet.arrival_us.saturating_sub(first_arrival_us);
|
||
let expected_start = (u128::from(elapsed_us) * u128::from(packet.sample_rate) / 1_000_000)
|
||
.saturating_sub(packet.samples.len() as u128) as u64;
|
||
let missing = expected_start.saturating_sub(track.samples);
|
||
if missing * 1_000 >= GAP_PAD_THRESHOLD_MS * u64::from(packet.sample_rate) {
|
||
missing
|
||
} else {
|
||
0
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
|
||
pub struct TranscriptEntry {
|
||
pub source: MeetingSource,
|
||
pub start_ms: u64,
|
||
pub end_ms: u64,
|
||
pub text: String,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
|
||
#[serde(rename_all = "snake_case")]
|
||
pub enum MeetingSource {
|
||
System,
|
||
Microphone,
|
||
}
|
||
|
||
impl MeetingSource {
|
||
pub fn label(self) -> &'static str {
|
||
match self {
|
||
Self::System => "Them",
|
||
Self::Microphone => "You",
|
||
}
|
||
}
|
||
}
|
||
|
||
struct AudioPacket {
|
||
source: MeetingSource,
|
||
pts_us: Option<i64>,
|
||
arrival_us: u64,
|
||
/// Samples of this source recorded before the packet: its place in the
|
||
/// WAV, set by the writer. Consumers that drop packets use it to keep
|
||
/// later audio on the recording's timeline.
|
||
position: u64,
|
||
sample_rate: u32,
|
||
samples: Vec<f32>,
|
||
}
|
||
|
||
#[derive(Default)]
|
||
struct CaptureStats {
|
||
system: TrackManifest,
|
||
microphone: TrackManifest,
|
||
}
|
||
|
||
struct ActiveMeeting {
|
||
_file: File,
|
||
}
|
||
|
||
impl ActiveMeeting {
|
||
/// `None` while another process holds the meeting.
|
||
fn try_acquire(directory: &Path) -> Result<Option<Self>> {
|
||
let file = OpenOptions::new()
|
||
.create(true)
|
||
.truncate(false)
|
||
.read(true)
|
||
.write(true)
|
||
.open(directory.join("active.lock"))?;
|
||
match fs2::FileExt::try_lock_exclusive(&file) {
|
||
Ok(()) => Ok(Some(Self { _file: file })),
|
||
Err(error) if lock_contended(&error) => Ok(None),
|
||
Err(error) => Err(error.into()),
|
||
}
|
||
}
|
||
|
||
fn acquire(directory: &Path) -> Result<Self> {
|
||
let path = directory.join("active.lock");
|
||
let file = OpenOptions::new()
|
||
.create(true)
|
||
.truncate(false)
|
||
.read(true)
|
||
.write(true)
|
||
.open(&path)?;
|
||
set_owner_only(&path, false)?;
|
||
fs2::FileExt::lock_exclusive(&file)?;
|
||
Ok(Self { _file: file })
|
||
}
|
||
}
|
||
|
||
pub fn root() -> Result<PathBuf> {
|
||
Ok(crate::app_paths::support_dir()?.join("meetings"))
|
||
}
|
||
|
||
pub fn record(
|
||
start: MeetingStart,
|
||
shutdown: &AtomicBool,
|
||
updates: Option<SyncSender<RecordingUpdate>>,
|
||
) -> Result<MeetingManifest> {
|
||
if crate::desktop::process_exit::quitting() {
|
||
return Err(eyre!("Hex is quitting"));
|
||
}
|
||
let (_, transcription_selection) = crate::app_settings::transcription_selection();
|
||
let transcription_model = crate::transcription::models::validate(&transcription_selection)?;
|
||
if !crate::transcription::models::is_installed(
|
||
&transcription_model,
|
||
&transcription_selection.language,
|
||
) {
|
||
return Err(eyre!("{} is not installed", transcription_model.name));
|
||
}
|
||
os::ensure_system_audio()?;
|
||
let created_at_ms = now_ms();
|
||
let id = format!("{created_at_ms}-{}", std::process::id());
|
||
let meeting_dir = root()?.join(&id);
|
||
fs::create_dir_all(&meeting_dir).wrap_err("could not create meeting directory")?;
|
||
set_owner_only(&meeting_dir, true)?;
|
||
let _active = ActiveMeeting::acquire(&meeting_dir)?;
|
||
// A quit may have begun while this recording was being set up: refuse
|
||
// rather than start audio the drain will cut off.
|
||
if crate::desktop::process_exit::quitting() {
|
||
drop(_active);
|
||
recovery::discard_refused_start(&meeting_dir);
|
||
return Err(eyre!("Hex is quitting"));
|
||
}
|
||
// Held until this recording returns: a quit or a restart to update can
|
||
// see it and wait for the audio to be finalised.
|
||
let _recording = recording::Recording::start();
|
||
|
||
let given_title = start.title.filter(|title| !title.trim().is_empty());
|
||
let title_source = match (&given_title, start.title_source) {
|
||
(None, _) => TitleSource::Default,
|
||
// A title without a known source is treated as the user's.
|
||
(Some(_), TitleSource::Default) => TitleSource::User,
|
||
(Some(_), source) => source,
|
||
};
|
||
let mut manifest = MeetingManifest {
|
||
schema_version: 1,
|
||
id,
|
||
title: given_title.unwrap_or_else(|| default_title(start.app.as_deref(), created_at_ms)),
|
||
status: MeetingStatus::Starting,
|
||
created_at_ms,
|
||
ended_at_ms: None,
|
||
duration_ms: None,
|
||
system: TrackManifest {
|
||
file: "system.wav".into(),
|
||
..TrackManifest::default()
|
||
},
|
||
microphone: TrackManifest {
|
||
file: "microphone.wav".into(),
|
||
..TrackManifest::default()
|
||
},
|
||
live_transcription_error: None,
|
||
error: None,
|
||
app: start.app,
|
||
export_path: None,
|
||
export_error: None,
|
||
echo_suppressed_utterances: 0,
|
||
provisional_title: None,
|
||
notes: None,
|
||
notes_error: None,
|
||
calendar: start.calendar,
|
||
title_source: None,
|
||
chapters: Vec::new(),
|
||
chapters_refined: false,
|
||
retention_applies: true,
|
||
export_sha256: None,
|
||
notes_export_path: None,
|
||
notes_export_sha256: None,
|
||
notes_export_removed: false,
|
||
audio_removed_at_ms: None,
|
||
imported: false,
|
||
};
|
||
set_title_source(&mut manifest, title_source);
|
||
write_manifest(&meeting_dir, &manifest)?;
|
||
|
||
let result = (|| -> Result<MeetingManifest> {
|
||
if shutdown.load(Ordering::Relaxed) {
|
||
return Err(eyre!("meeting recording stopped before capture started"));
|
||
}
|
||
let (sender, receiver) = mpsc::sync_channel::<AudioPacket>(128);
|
||
let system_drops = Arc::new(AtomicU64::new(0));
|
||
let microphone_drops = Arc::new(AtomicU64::new(0));
|
||
let mut rolling =
|
||
transcript::Rolling::start(meeting_dir.clone(), transcription_selection.clone());
|
||
let rolling_feed = rolling.feed();
|
||
let writer_dir = meeting_dir.clone();
|
||
let writer = thread::spawn(move || write_tracks(&writer_dir, receiver, rolling_feed));
|
||
let cleanup_failed_setup =
|
||
|sender: SyncSender<AudioPacket>, writer: thread::JoinHandle<Result<CaptureStats>>| {
|
||
drop(sender);
|
||
if let Err(cleanup_error) = join_audio_writer(writer) {
|
||
tracing::error!(%cleanup_error, "could not finalize failed meeting setup");
|
||
}
|
||
};
|
||
let capture_clock = Instant::now();
|
||
let sleep_prevention = crate::audio::idle_sleep::prevent_sleep();
|
||
let sink = |source, drops: &Arc<AtomicU64>| capture::PacketSink {
|
||
source,
|
||
sender: sender.clone(),
|
||
drops: drops.clone(),
|
||
clock: capture_clock,
|
||
};
|
||
// Each source recovers on its own: losing system audio (for example
|
||
// when ScreenCaptureKit loses its display) never stops the microphone.
|
||
let microphone_warnings = warning::TrackWarnings::new(updates.clone());
|
||
let microphone_capture = capture::SourceSupervisor::microphone(
|
||
sink(MeetingSource::Microphone, µphone_drops),
|
||
start.application.clone(),
|
||
microphone_warnings.clone(),
|
||
);
|
||
let system_capture = capture::SourceSupervisor::system(
|
||
sink(MeetingSource::System, &system_drops),
|
||
start.application.clone(),
|
||
);
|
||
manifest.status = MeetingStatus::Recording;
|
||
if let Err(error) = write_manifest(&meeting_dir, &manifest) {
|
||
drop(system_capture);
|
||
drop(microphone_capture);
|
||
cleanup_failed_setup(sender, writer);
|
||
return Err(error);
|
||
}
|
||
if let Some(updates) = &updates {
|
||
let _ = updates.send(RecordingUpdate::Started {
|
||
id: manifest.id.clone(),
|
||
title: display_title(&manifest),
|
||
});
|
||
}
|
||
|
||
let started = Instant::now();
|
||
let titles = notes::ProvisionalTitles::start(manifest.id.clone());
|
||
let live_chapters = crate::labs::live_chapters()
|
||
.then(|| chapters::LiveChapters::start(manifest.id.clone()));
|
||
println!("Recording '{}' (Ctrl-C to stop)", manifest.title);
|
||
let take_updates = |manifest: &mut MeetingManifest| {
|
||
if let Some(title) = titles.take() {
|
||
record_provisional_title(&meeting_dir, manifest, title, updates.as_ref());
|
||
}
|
||
if let Some(chapters) = live_chapters.as_ref().and_then(|live| live.take()) {
|
||
record_chapters(&meeting_dir, manifest, chapters, updates.as_ref());
|
||
}
|
||
// Written as soon as the microphone is warned about, so a crash
|
||
// while recording still says it was digitally silent.
|
||
warning::persist_warning(&meeting_dir, manifest, µphone_warnings);
|
||
};
|
||
while !shutdown.load(Ordering::Relaxed) && !writer.is_finished() {
|
||
take_updates(&mut manifest);
|
||
thread::sleep(Duration::from_millis(100));
|
||
}
|
||
take_updates(&mut manifest);
|
||
if let Some(chapters) = live_chapters.as_ref().and_then(|live| live.finish()) {
|
||
record_chapters(&meeting_dir, &mut manifest, chapters, updates.as_ref());
|
||
}
|
||
drop(titles);
|
||
drop(live_chapters);
|
||
keep_rename(&meeting_dir, &mut manifest);
|
||
drop(system_capture);
|
||
drop(microphone_capture);
|
||
drop(sender);
|
||
drop(sleep_prevention);
|
||
|
||
manifest.ended_at_ms = Some(now_ms());
|
||
manifest.duration_ms = Some(started.elapsed().as_millis() as u64);
|
||
let mut stats = join_audio_writer(writer)?;
|
||
stats.system.dropped_packets = system_drops.load(Ordering::Relaxed);
|
||
stats.microphone.dropped_packets = microphone_drops.load(Ordering::Relaxed);
|
||
manifest.system = stats.system;
|
||
manifest.microphone = stats.microphone;
|
||
manifest.microphone.warning = microphone_warnings.persisted();
|
||
if crate::desktop::process_exit::quitting() && has_recorded_audio(&manifest) {
|
||
// Final transcription would outlast quitting's drain.
|
||
drop(rolling.finish());
|
||
fs::write(meeting_dir.join(FINAL_PENDING_FILE), b"")?;
|
||
manifest.status = MeetingStatus::Interrupted;
|
||
write_manifest(&meeting_dir, &manifest)?;
|
||
tracing::info!(
|
||
meeting = manifest.id,
|
||
"Hex quit while recording; the transcript finishes at the next launch"
|
||
);
|
||
return Ok(manifest);
|
||
}
|
||
let capture_error =
|
||
(!has_recorded_audio(&manifest)).then(|| "no meeting audio was captured".to_string());
|
||
prepare_for_transcription(
|
||
&meeting_dir,
|
||
&mut manifest,
|
||
capture_error,
|
||
Ok(()),
|
||
updates.as_ref(),
|
||
)?;
|
||
|
||
let rolling = rolling.finish();
|
||
match transcribe(
|
||
&meeting_dir,
|
||
&mut manifest,
|
||
&transcription_selection,
|
||
rolling,
|
||
) {
|
||
Ok(()) => manifest.status = MeetingStatus::Complete,
|
||
Err(error) if crate::desktop::process_exit::quitting() => {
|
||
// Quitting cut the final pass short: like quitting while
|
||
// recording, the transcript finishes at the next launch.
|
||
keep_rename(&meeting_dir, &mut manifest);
|
||
fs::write(meeting_dir.join(FINAL_PENDING_FILE), b"")?;
|
||
manifest.status = MeetingStatus::Interrupted;
|
||
manifest.error = None;
|
||
write_manifest(&meeting_dir, &manifest)?;
|
||
tracing::info!(
|
||
meeting = manifest.id,
|
||
%error,
|
||
"Hex quit during final transcription; the transcript finishes at the next launch"
|
||
);
|
||
return Ok(manifest);
|
||
}
|
||
Err(error) => {
|
||
keep_rename(&meeting_dir, &mut manifest);
|
||
manifest.status = MeetingStatus::Failed;
|
||
manifest.error = Some(error.to_string());
|
||
write_manifest(&meeting_dir, &manifest)?;
|
||
return Err(error);
|
||
}
|
||
}
|
||
keep_rename(&meeting_dir, &mut manifest);
|
||
write_manifest(&meeting_dir, &manifest)?;
|
||
println!("Saved meeting {}", meeting_dir.display());
|
||
Ok(manifest)
|
||
})();
|
||
if let Err(error) = &result {
|
||
persist_meeting_failure(&meeting_dir, error);
|
||
}
|
||
result
|
||
}
|
||
|
||
fn record_provisional_title(
|
||
directory: &Path,
|
||
manifest: &mut MeetingManifest,
|
||
title: String,
|
||
updates: Option<&SyncSender<RecordingUpdate>>,
|
||
) {
|
||
keep_rename(directory, manifest);
|
||
manifest.provisional_title = Some(title);
|
||
if let Err(error) = write_manifest(directory, manifest) {
|
||
tracing::warn!(%error, meeting = manifest.id, "could not record provisional meeting title");
|
||
return;
|
||
}
|
||
if let Some(updates) = updates {
|
||
let _ = updates.try_send(RecordingUpdate::Retitled {
|
||
title: display_title(manifest),
|
||
});
|
||
}
|
||
}
|
||
|
||
fn record_chapters(
|
||
directory: &Path,
|
||
manifest: &mut MeetingManifest,
|
||
chapters: Vec<Chapter>,
|
||
updates: Option<&SyncSender<RecordingUpdate>>,
|
||
) {
|
||
keep_rename(directory, manifest);
|
||
let previous_title = display_title(manifest);
|
||
manifest.chapters = chapters;
|
||
if let Err(error) = write_manifest(directory, manifest) {
|
||
tracing::warn!(%error, meeting = manifest.id, "could not record meeting chapters");
|
||
return;
|
||
}
|
||
if let Some(updates) = updates {
|
||
let _ = updates.try_send(RecordingUpdate::Chapters(manifest.chapters.clone()));
|
||
let title = display_title(manifest);
|
||
if title != previous_title {
|
||
let _ = updates.try_send(RecordingUpdate::Retitled { title });
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Records where the title came from, which only live chapters read; with
|
||
/// the experiment off, a manifest that has neither stays as it was.
|
||
fn set_title_source(manifest: &mut MeetingManifest, source: TitleSource) {
|
||
if manifest.title_source.is_some()
|
||
|| !manifest.chapters.is_empty()
|
||
|| crate::labs::live_chapters()
|
||
{
|
||
manifest.title_source = Some(source);
|
||
}
|
||
}
|
||
|
||
/// Keeps a rename made while recording (Labs).
|
||
fn keep_rename(directory: &Path, manifest: &mut MeetingManifest) {
|
||
if crate::labs::live_chapters() {
|
||
adopt_rename(directory, manifest);
|
||
}
|
||
}
|
||
|
||
/// The recorder rewrites the manifest from memory, so it adopts a user
|
||
/// title written meanwhile.
|
||
fn adopt_rename(directory: &Path, manifest: &mut MeetingManifest) {
|
||
if let Ok(stored) = read_manifest(directory)
|
||
&& stored.title_source() == TitleSource::User
|
||
&& (stored.title != manifest.title || manifest.title_source() != TitleSource::User)
|
||
{
|
||
manifest.title = stored.title;
|
||
manifest.title_source = Some(TitleSource::User);
|
||
}
|
||
}
|
||
|
||
fn join_audio_writer(writer: thread::JoinHandle<Result<CaptureStats>>) -> Result<CaptureStats> {
|
||
writer
|
||
.join()
|
||
.map_err(|_| eyre!("meeting audio writer panicked"))
|
||
.and_then(|result| result)
|
||
}
|
||
|
||
fn stamp_ended(manifest: &mut MeetingManifest, ended_at_ms: u64) {
|
||
manifest.ended_at_ms.get_or_insert(ended_at_ms);
|
||
manifest
|
||
.duration_ms
|
||
.get_or_insert(ended_at_ms.saturating_sub(manifest.created_at_ms));
|
||
}
|
||
|
||
fn persist_meeting_failure(directory: &Path, error: &color_eyre::Report) {
|
||
let result = (|| -> Result<()> {
|
||
let mut manifest = read_manifest(directory)?;
|
||
if manifest.status != MeetingStatus::Complete {
|
||
manifest.status = MeetingStatus::Failed;
|
||
stamp_ended(&mut manifest, now_ms());
|
||
manifest.error = Some(error.to_string());
|
||
write_manifest(directory, &manifest)?;
|
||
}
|
||
Ok(())
|
||
})();
|
||
if let Err(persist_error) = result {
|
||
tracing::error!(%persist_error, %error, "could not persist meeting failure");
|
||
}
|
||
}
|
||
|
||
fn has_recorded_audio(manifest: &MeetingManifest) -> bool {
|
||
manifest.system.samples > 0 || manifest.microphone.samples > 0
|
||
}
|
||
|
||
fn prepare_for_transcription(
|
||
directory: &Path,
|
||
manifest: &mut MeetingManifest,
|
||
capture_error: Option<String>,
|
||
stop_result: Result<()>,
|
||
updates: Option<&SyncSender<RecordingUpdate>>,
|
||
) -> Result<()> {
|
||
if !has_recorded_audio(manifest) {
|
||
if let Some(error) = capture_error {
|
||
write_manifest(directory, manifest)?;
|
||
return Err(eyre!("meeting capture stopped unexpectedly: {error}"));
|
||
}
|
||
if let Err(error) = stop_result {
|
||
write_manifest(directory, manifest)?;
|
||
return Err(error);
|
||
}
|
||
} else {
|
||
if let Some(error) = capture_error {
|
||
tracing::warn!(
|
||
%error,
|
||
meeting = manifest.id,
|
||
"meeting capture stopped early; transcribing recorded audio"
|
||
);
|
||
}
|
||
if let Err(error) = stop_result {
|
||
tracing::warn!(
|
||
%error,
|
||
meeting = manifest.id,
|
||
"meeting capture stop reported an error; transcribing recorded audio"
|
||
);
|
||
}
|
||
}
|
||
if let Some(updates) = updates {
|
||
// Never dropped: the controller drains until the recorder finishes.
|
||
let _ = updates.send(RecordingUpdate::Transcribing);
|
||
}
|
||
manifest.status = MeetingStatus::Transcribing;
|
||
manifest.error = None;
|
||
write_manifest(directory, manifest)
|
||
}
|
||
|
||
fn write_tracks(
|
||
directory: &Path,
|
||
receiver: Receiver<AudioPacket>,
|
||
mut rolling: Option<transcript::RollingFeed>,
|
||
) -> Result<CaptureStats> {
|
||
let mut system = None;
|
||
let mut microphone = None;
|
||
let mut stats = CaptureStats::default();
|
||
stats.system.file = "system.wav".into();
|
||
stats.microphone.file = "microphone.wav".into();
|
||
while let Ok(mut packet) = receiver.recv() {
|
||
let (writer, track, file_name) = match packet.source {
|
||
MeetingSource::System => (&mut system, &mut stats.system, "system.wav"),
|
||
MeetingSource::Microphone => (&mut microphone, &mut stats.microphone, "microphone.wav"),
|
||
};
|
||
if let Some(rate) = track.sample_rate
|
||
&& rate != packet.sample_rate
|
||
{
|
||
return Err(eyre!(
|
||
"{file_name} sample rate changed from {rate} to {}",
|
||
packet.sample_rate
|
||
));
|
||
}
|
||
track.sample_rate = Some(packet.sample_rate);
|
||
if writer.is_none() {
|
||
let path = directory.join(file_name);
|
||
let created = WavWriter::create(
|
||
&path,
|
||
WavSpec {
|
||
channels: 1,
|
||
sample_rate: packet.sample_rate,
|
||
bits_per_sample: 32,
|
||
sample_format: SampleFormat::Float,
|
||
},
|
||
)?;
|
||
set_owner_only(&path, false)?;
|
||
*writer = Some(created);
|
||
}
|
||
let writer = writer
|
||
.as_mut()
|
||
.ok_or_else(|| eyre!("could not initialize {file_name}"))?;
|
||
if let Some(pts_us) = packet.pts_us {
|
||
track.first_pts_us.get_or_insert(pts_us);
|
||
track.last_pts_us = Some(pts_us);
|
||
}
|
||
let missing = missing_samples(track, &packet);
|
||
if missing > 0 {
|
||
let rate = u64::from(packet.sample_rate);
|
||
track.gaps.push(TrackGap {
|
||
start_ms: track.samples * 1_000 / rate,
|
||
duration_ms: missing * 1_000 / rate,
|
||
});
|
||
tracing::warn!(
|
||
source = ?packet.source,
|
||
gap_ms = missing * 1_000 / rate,
|
||
"meeting source resumed after a gap; padding silence"
|
||
);
|
||
for _ in 0..missing {
|
||
writer.write_sample(0.0)?;
|
||
}
|
||
track.samples += missing;
|
||
}
|
||
track.first_arrival_us.get_or_insert(packet.arrival_us);
|
||
packet.position = track.samples;
|
||
track.samples += packet.samples.len() as u64;
|
||
for &sample in &packet.samples {
|
||
writer.write_sample(sample)?;
|
||
}
|
||
if let Some(rolling) = &mut rolling {
|
||
rolling.offer(&packet);
|
||
}
|
||
}
|
||
if let Some(rolling) = &mut rolling {
|
||
rolling.flush();
|
||
}
|
||
finalize_track(directory.join("system.wav"), system)?;
|
||
finalize_track(directory.join("microphone.wav"), microphone)?;
|
||
Ok(stats)
|
||
}
|
||
|
||
fn finalize_track(path: PathBuf, writer: Option<WavWriter<BufWriter<File>>>) -> Result<()> {
|
||
if let Some(writer) = writer {
|
||
writer.finalize()?;
|
||
Ok(sync_file(&path)?)
|
||
} else {
|
||
create_empty_track(path)
|
||
}
|
||
}
|
||
|
||
fn create_empty_track(path: PathBuf) -> Result<()> {
|
||
WavWriter::create(
|
||
&path,
|
||
WavSpec {
|
||
channels: 1,
|
||
sample_rate: SAMPLE_RATE,
|
||
bits_per_sample: 32,
|
||
sample_format: SampleFormat::Float,
|
||
},
|
||
)?
|
||
.finalize()?;
|
||
set_owner_only(&path, false)?;
|
||
Ok(sync_file(&path)?)
|
||
}
|
||
|
||
fn transcribe(
|
||
directory: &Path,
|
||
manifest: &mut MeetingManifest,
|
||
selection: &crate::transcription::models::TranscriptionSelection,
|
||
rolling: Option<transcript::RollingOutcome>,
|
||
) -> Result<()> {
|
||
let (transcript, echo_suppressed) =
|
||
transcript::transcribe(directory, manifest, selection, rolling)?;
|
||
manifest.echo_suppressed_utterances = echo_suppressed;
|
||
// Transcription takes a while; the headings use a rename made meanwhile.
|
||
keep_rename(directory, manifest);
|
||
|
||
let ndjson_temporary = directory.join("transcript.ndjson.tmp");
|
||
let markdown_temporary = directory.join("transcript.md.tmp");
|
||
let mut ndjson = BufWriter::new(File::create(&ndjson_temporary)?);
|
||
let mut markdown = BufWriter::new(File::create(&markdown_temporary)?);
|
||
set_owner_only(&ndjson_temporary, false)?;
|
||
set_owner_only(&markdown_temporary, false)?;
|
||
writeln!(markdown, "# {}\n", display_title(manifest))?;
|
||
for entry in &transcript {
|
||
serde_json::to_writer(&mut ndjson, entry)?;
|
||
ndjson.write_all(b"\n")?;
|
||
writeln!(markdown, "{}", markdown_line(entry))?;
|
||
}
|
||
ndjson.flush()?;
|
||
markdown.flush()?;
|
||
ndjson.get_ref().sync_all()?;
|
||
markdown.get_ref().sync_all()?;
|
||
sync_directory(directory)?;
|
||
fs::rename(&ndjson_temporary, directory.join("transcript.ndjson"))?;
|
||
fs::rename(&markdown_temporary, directory.join("transcript.md"))?;
|
||
sync_directory(directory)?;
|
||
|
||
match transcript::export_markdown(
|
||
&crate::app_settings::meeting_output_folder(),
|
||
manifest,
|
||
&transcript,
|
||
crate::app_settings::meeting_notes_file(),
|
||
) {
|
||
Ok(path) => {
|
||
tracing::info!(path = %path.display(), "published meeting transcript");
|
||
manifest.export_sha256 = file_sha256(&path);
|
||
manifest.export_path = Some(path);
|
||
}
|
||
Err(error) => {
|
||
tracing::warn!(%error, "could not publish meeting Markdown");
|
||
manifest.export_error = Some(error.to_string());
|
||
}
|
||
}
|
||
let _ = fs::remove_file(directory.join(FINAL_PENDING_FILE));
|
||
Ok(())
|
||
}
|
||
|
||
/// Meetings Hex left with `final.pending` (quit while recording or
|
||
/// importing), oldest first.
|
||
pub fn pending_final_transcripts() -> Vec<String> {
|
||
let Ok(entries) = root().and_then(|root| Ok(fs::read_dir(root)?)) else {
|
||
return Vec::new();
|
||
};
|
||
let mut ids = entries
|
||
.flatten()
|
||
.filter(|entry| entry.path().join(FINAL_PENDING_FILE).exists())
|
||
.filter_map(|entry| entry.file_name().into_string().ok())
|
||
.collect::<Vec<_>>();
|
||
ids.sort();
|
||
ids
|
||
}
|
||
|
||
/// Maintenance must still see expired folders, including failed Trash attempts.
|
||
fn list_all() -> Result<Vec<MeetingManifest>> {
|
||
let root = root()?;
|
||
let mut meetings = Vec::new();
|
||
for entry in match fs::read_dir(root) {
|
||
Ok(entries) => entries,
|
||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(meetings),
|
||
Err(error) => return Err(error.into()),
|
||
} {
|
||
let directory = entry?.path();
|
||
let path = directory.join("manifest.json");
|
||
if let Ok(data) = fs::read(&path)
|
||
&& let Ok(mut manifest) = serde_json::from_slice::<MeetingManifest>(&data)
|
||
{
|
||
manifest.live_transcription_error =
|
||
fs::read_to_string(directory.join(transcript::ERROR_FILE))
|
||
.ok()
|
||
.map(|error| error.trim().to_string());
|
||
let process_is_active = meeting_is_active(&directory);
|
||
if process_is_active == Some(false) {
|
||
if let Err(error) = recover_final_publication(&directory) {
|
||
tracing::warn!(%error, meeting = manifest.id, "could not recover final transcript publication");
|
||
}
|
||
let recovered =
|
||
recovered_status(manifest.status, false, final_transcript_exists(&directory));
|
||
if recovered != manifest.status {
|
||
manifest.status = recovered;
|
||
match recovered {
|
||
MeetingStatus::Complete => manifest.error = None,
|
||
MeetingStatus::Interrupted => stamp_ended(&mut manifest, now_ms()),
|
||
MeetingStatus::Starting
|
||
| MeetingStatus::Recording
|
||
| MeetingStatus::Transcribing
|
||
| MeetingStatus::Failed => {}
|
||
}
|
||
if let Err(error) = write_manifest(&directory, &manifest) {
|
||
tracing::warn!(%error, meeting = manifest.id, "could not persist recovered meeting status");
|
||
}
|
||
}
|
||
}
|
||
meetings.push(manifest);
|
||
}
|
||
}
|
||
meetings.sort_by_key(|meeting| std::cmp::Reverse(meeting.created_at_ms));
|
||
Ok(meetings)
|
||
}
|
||
|
||
fn meeting_is_active(directory: &Path) -> Option<bool> {
|
||
let file = match OpenOptions::new()
|
||
.read(true)
|
||
.write(true)
|
||
.open(directory.join("active.lock"))
|
||
{
|
||
Ok(file) => file,
|
||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Some(false),
|
||
Err(error) => {
|
||
tracing::warn!(%error, directory = %directory.display(), "could not open meeting lock");
|
||
return None;
|
||
}
|
||
};
|
||
match fs2::FileExt::try_lock_exclusive(&file) {
|
||
Ok(()) => {
|
||
let _ = fs2::FileExt::unlock(&file);
|
||
Some(false)
|
||
}
|
||
Err(error) if lock_contended(&error) => Some(true),
|
||
Err(error) => {
|
||
tracing::warn!(%error, directory = %directory.display(), "could not inspect meeting lock");
|
||
None
|
||
}
|
||
}
|
||
}
|
||
|
||
fn recovered_status(
|
||
status: MeetingStatus,
|
||
process_is_active: bool,
|
||
final_transcript_exists: bool,
|
||
) -> MeetingStatus {
|
||
match (status, process_is_active, final_transcript_exists) {
|
||
(
|
||
MeetingStatus::Transcribing | MeetingStatus::Interrupted | MeetingStatus::Failed,
|
||
false,
|
||
true,
|
||
) => MeetingStatus::Complete,
|
||
(MeetingStatus::Complete, false, false) => MeetingStatus::Interrupted,
|
||
(
|
||
MeetingStatus::Starting | MeetingStatus::Recording | MeetingStatus::Transcribing,
|
||
false,
|
||
_,
|
||
) => MeetingStatus::Interrupted,
|
||
_ => status,
|
||
}
|
||
}
|
||
|
||
/// The local clock time of a timestamp: `2:30 PM` in English, `14:30` in
|
||
/// every other language.
|
||
pub fn clock(milliseconds: u64) -> String {
|
||
transcript::LocalTime::from_ms(milliseconds).clock()
|
||
}
|
||
|
||
/// `Today`, `Yesterday`, or a date such as `Thursday, October 15, 2026`.
|
||
pub fn day_label(milliseconds: u64, now_ms: u64) -> String {
|
||
let day = transcript::LocalTime::from_ms(milliseconds);
|
||
if day.day() == transcript::LocalTime::from_ms(now_ms).day() {
|
||
"Today".into()
|
||
} else if day.day() == transcript::LocalTime::from_ms(now_ms.saturating_sub(86_400_000)).day() {
|
||
"Yesterday".into()
|
||
} else {
|
||
day.date()
|
||
}
|
||
}
|
||
|
||
/// The notes as Markdown, for copying.
|
||
pub fn notes_markdown(notes: &MeetingNotes) -> String {
|
||
notes::render_notes_block(notes)
|
||
.lines()
|
||
.filter(|line| !line.starts_with("<!--") && !line.starts_with("_Written on this Mac"))
|
||
.collect::<Vec<_>>()
|
||
.join("\n")
|
||
.trim()
|
||
.to_string()
|
||
}
|
||
|
||
/// The exported Markdown while it is still on disk: the file the pane's
|
||
/// `Reveal Markdown` selects, and the one Trash takes with the recording.
|
||
fn exported_markdown(manifest: &MeetingManifest) -> Option<PathBuf> {
|
||
manifest.export_path.clone().filter(|path| path.exists())
|
||
}
|
||
|
||
/// What the Meetings pane's reveal action shows: the exported Markdown while
|
||
/// it still exists, else the meeting's recording folder.
|
||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||
pub enum RevealTarget {
|
||
Markdown(PathBuf),
|
||
Folder(PathBuf),
|
||
}
|
||
|
||
impl RevealTarget {
|
||
/// The target for one meeting: [`exported_markdown`] while it finds the
|
||
/// file, else its `directory`. The pane labels the menu with it and the
|
||
/// host reveals it, so the two can't disagree.
|
||
pub fn for_meeting(manifest: &MeetingManifest, directory: &Path) -> Self {
|
||
match exported_markdown(manifest) {
|
||
Some(path) => Self::Markdown(path),
|
||
None => Self::Folder(directory.to_path_buf()),
|
||
}
|
||
}
|
||
|
||
/// The file or folder the desktop's file manager shows.
|
||
pub fn path(&self) -> &Path {
|
||
match self {
|
||
Self::Markdown(path) | Self::Folder(path) => path,
|
||
}
|
||
}
|
||
|
||
/// Whether the pane labels this target `Reveal Markdown`.
|
||
pub fn is_markdown(&self) -> bool {
|
||
matches!(self, Self::Markdown(_))
|
||
}
|
||
}
|
||
|
||
/// Explorer's argument that selects `path`: `/select,"C:\…\file.md"`.
|
||
///
|
||
/// The path is quoted on its own because Explorer reads the switch only while
|
||
/// the comma is outside the quotes. `Command` would quote the whole argument
|
||
/// once a folder name has a space, which Explorer ignores. Its bytes are kept
|
||
/// as they are: the path is already absolute by the time the Windows caller
|
||
/// passes it, so `GetFullPathNameW` has normalized any forward slashes.
|
||
#[cfg(any(windows, test))]
|
||
fn explorer_select(path: &Path) -> std::ffi::OsString {
|
||
let mut select = std::ffi::OsString::from("/select,\"");
|
||
select.push(path.as_os_str());
|
||
select.push("\"");
|
||
select
|
||
}
|
||
|
||
/// Explorer's argument that opens `path` itself: the quoted path alone, with
|
||
/// no select switch, so a folder opens rather than its parent selecting it.
|
||
///
|
||
/// The path is quoted on its own because Explorer splits its command line on
|
||
/// commas, and `Command` quotes only the paths that contain a space.
|
||
#[cfg(any(windows, test))]
|
||
fn explorer_open(path: &Path) -> std::ffi::OsString {
|
||
let mut open = std::ffi::OsString::from("\"");
|
||
open.push(path.as_os_str());
|
||
open.push("\"");
|
||
open
|
||
}
|
||
|
||
/// The lowercase hex SHA-256 of a file, `None` when it can't be read.
|
||
fn file_sha256(path: &Path) -> Option<String> {
|
||
fs::read(path).ok().map(|bytes| text_sha256(&bytes))
|
||
}
|
||
|
||
fn text_sha256(bytes: &[u8]) -> String {
|
||
use sha2::{Digest, Sha256};
|
||
Sha256::digest(bytes)
|
||
.iter()
|
||
.map(|byte| format!("{byte:02x}"))
|
||
.collect()
|
||
}
|
||
|
||
/// Renames a meeting. The Markdown heading follows only while it still reads
|
||
/// the previous title. The file keeps its name unless Descriptive meeting file
|
||
/// names is on, which renames it to the new title.
|
||
pub fn rename(id: &str, title: &str) -> Result<MeetingManifest> {
|
||
rename_meeting(&root()?.join(id), title)
|
||
}
|
||
|
||
fn rename_meeting(directory: &Path, title: &str) -> Result<MeetingManifest> {
|
||
rename_meeting_with(
|
||
directory,
|
||
title,
|
||
crate::app_settings::meeting_descriptive_filenames(),
|
||
)
|
||
}
|
||
|
||
fn rename_meeting_with(
|
||
directory: &Path,
|
||
title: &str,
|
||
descriptive_filenames: bool,
|
||
) -> Result<MeetingManifest> {
|
||
let title = title.split_whitespace().collect::<Vec<_>>().join(" ");
|
||
if title.is_empty() {
|
||
return Err(eyre!("The title is empty"));
|
||
}
|
||
let id = directory
|
||
.file_name()
|
||
.map(|name| name.to_string_lossy().into_owned())
|
||
.unwrap_or_default();
|
||
let mut manifest = read_manifest(directory)?;
|
||
let previous = display_title(&manifest);
|
||
manifest.title = title;
|
||
set_title_source(&mut manifest, TitleSource::User);
|
||
let next = display_title(&manifest);
|
||
let mut markdown_error = None;
|
||
let title_changed = previous != next;
|
||
let mut heading_updated = title_changed;
|
||
if heading_updated
|
||
&& let Some(path) = manifest.export_path.clone().filter(|path| path.exists())
|
||
&& let Err(error) =
|
||
notes::retitle_markdown_file(&path, &mut manifest.export_sha256, &previous, &next)
|
||
{
|
||
tracing::warn!(%error, meeting = id, "could not retitle meeting Markdown");
|
||
markdown_error = Some(error);
|
||
heading_updated = false;
|
||
}
|
||
// The notes writer applies its own title and renames the file; leaving
|
||
// the name alone here keeps it from racing that in-place rewrite. A
|
||
// failed heading update keeps the old name too, as notes do. The notes
|
||
// file follows the title independently, since it is Hex's own copy.
|
||
if heading_updated && !notes_in_progress(&manifest.id) {
|
||
export_name::rename_to_title(&mut manifest, &next, descriptive_filenames);
|
||
}
|
||
if title_changed && !notes_in_progress(&manifest.id) {
|
||
notes_file::refresh(&mut manifest);
|
||
}
|
||
write_manifest(directory, &manifest)?;
|
||
match markdown_error {
|
||
Some(error) => Err(error.wrap_err("Renamed, but the Markdown heading was not updated")),
|
||
None => Ok(manifest),
|
||
}
|
||
}
|
||
|
||
/// Debug CLI: transcribes a finished or interrupted meeting's WAV tracks
|
||
/// and publishes its final transcript and Markdown copy.
|
||
#[cfg(debug_assertions)]
|
||
pub fn transcribe_meeting(id: &str) -> Result<MeetingManifest> {
|
||
let (_, selection) = crate::app_settings::transcription_selection();
|
||
let model = crate::transcription::models::validate(&selection)?;
|
||
if !crate::transcription::models::is_installed(&model, &selection.language) {
|
||
return Err(eyre!("{} is not installed", model.name));
|
||
}
|
||
let directory = root()?.join(id);
|
||
if meeting_is_active(&directory) != Some(false) {
|
||
return Err(eyre!("Stop the recording before transcribing it"));
|
||
}
|
||
let mut manifest = read_manifest(&directory)?;
|
||
if manifest.audio_removed_at_ms.is_some() {
|
||
return Err(eyre!("this meeting's audio was deleted"));
|
||
}
|
||
if !has_recorded_audio(&manifest) {
|
||
return Err(eyre!("meeting has no recorded audio"));
|
||
}
|
||
manifest.status = MeetingStatus::Transcribing;
|
||
manifest.error = None;
|
||
manifest.export_error = None;
|
||
write_manifest(&directory, &manifest)?;
|
||
match transcribe(&directory, &mut manifest, &selection, None) {
|
||
Ok(()) => {
|
||
manifest.status = MeetingStatus::Complete;
|
||
manifest.error = None;
|
||
write_manifest(&directory, &manifest)?;
|
||
Ok(manifest)
|
||
}
|
||
Err(error) => {
|
||
manifest.status = MeetingStatus::Failed;
|
||
manifest.error = Some(error.to_string());
|
||
write_manifest(&directory, &manifest)?;
|
||
Err(error)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Debug CLI: replays a recording's tracks through echo suppression.
|
||
#[cfg(debug_assertions)]
|
||
pub fn echo_report(
|
||
directory: &Path,
|
||
microphone_offset_ms: Option<u64>,
|
||
transcribe: bool,
|
||
) -> Result<String> {
|
||
transcript::echo_report(directory, microphone_offset_ms, transcribe)
|
||
}
|
||
|
||
#[cfg(debug_assertions)]
|
||
pub fn show(id: &str) -> Result<String> {
|
||
let directory = root()?.join(id);
|
||
let path = directory.join("transcript.md");
|
||
recover_final_publication(&directory)?;
|
||
if final_transcript_exists(&directory) {
|
||
return fs::read_to_string(&path)
|
||
.wrap_err_with(|| format!("could not read {}", path.display()));
|
||
}
|
||
let manifest = read_manifest(&directory)?;
|
||
let mut markdown = format!("# {}\n\n", manifest.title);
|
||
for entry in transcript_entries_in(&directory)? {
|
||
markdown.push_str(&markdown_line(&entry));
|
||
markdown.push('\n');
|
||
}
|
||
Ok(markdown)
|
||
}
|
||
|
||
fn markdown_line(entry: &TranscriptEntry) -> String {
|
||
format!(
|
||
"**{} {}** {}",
|
||
format_duration(entry.start_ms),
|
||
entry.source.label(),
|
||
entry.text
|
||
)
|
||
}
|
||
|
||
/// Callers recover the final publication first; `show` does so before its
|
||
/// `final_transcript_exists` check.
|
||
#[cfg(any(debug_assertions, test))]
|
||
fn transcript_entries_in(directory: &Path) -> Result<Vec<TranscriptEntry>> {
|
||
let final_path = directory.join("transcript.ndjson");
|
||
if final_transcript_exists(directory) {
|
||
return read_ndjson(&final_path);
|
||
}
|
||
let rolling_path = directory.join(transcript::ROLLING_FILE);
|
||
if !rolling_path.exists() {
|
||
return Ok(Vec::new());
|
||
}
|
||
Ok(read_ndjson::<transcript::RollingLine>(&rolling_path)?
|
||
.into_iter()
|
||
.collect::<transcript::RollingView>()
|
||
.entries)
|
||
}
|
||
|
||
fn read_ndjson<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<Vec<T>> {
|
||
let contents = fs::read(path).wrap_err_with(|| format!("could not read {}", path.display()))?;
|
||
let complete = contents
|
||
.iter()
|
||
.rposition(|byte| *byte == b'\n')
|
||
.map_or(&[][..], |newline| &contents[..newline]);
|
||
complete
|
||
.split(|byte| *byte == b'\n')
|
||
.filter(|line| !line.is_empty())
|
||
.map(|line| serde_json::from_slice(line).map_err(Into::into))
|
||
.collect()
|
||
}
|
||
|
||
fn final_transcript_exists(directory: &Path) -> bool {
|
||
directory.join("transcript.ndjson").exists() && directory.join("transcript.md").exists()
|
||
}
|
||
|
||
fn recover_final_publication(directory: &Path) -> Result<()> {
|
||
if meeting_is_active(directory) != Some(false) {
|
||
return Ok(());
|
||
}
|
||
let ndjson = directory.join("transcript.ndjson");
|
||
let markdown = directory.join("transcript.md");
|
||
let markdown_temporary = directory.join("transcript.md.tmp");
|
||
if ndjson.exists() && !markdown.exists() && markdown_temporary.exists() {
|
||
fs::rename(markdown_temporary, markdown)?;
|
||
sync_directory(directory)?;
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
fn read_manifest(directory: &Path) -> Result<MeetingManifest> {
|
||
let path = directory.join("manifest.json");
|
||
let data = fs::read(&path).wrap_err_with(|| format!("could not read {}", path.display()))?;
|
||
serde_json::from_slice(&data).wrap_err("could not decode meeting manifest")
|
||
}
|
||
|
||
fn write_manifest(directory: &Path, manifest: &MeetingManifest) -> Result<()> {
|
||
let temporary = directory.join("manifest.json.tmp");
|
||
let final_path = directory.join("manifest.json");
|
||
let mut file = BufWriter::new(File::create(&temporary)?);
|
||
set_owner_only(&temporary, false)?;
|
||
serde_json::to_writer_pretty(&mut file, manifest)?;
|
||
file.write_all(b"\n")?;
|
||
file.flush()?;
|
||
file.get_ref().sync_all()?;
|
||
fs::rename(&temporary, &final_path)?;
|
||
Ok(sync_directory(directory)?)
|
||
}
|
||
|
||
pub fn format_duration(milliseconds: u64) -> String {
|
||
let total_seconds = milliseconds / 1_000;
|
||
format!("{:02}:{:02}", total_seconds / 60, total_seconds % 60)
|
||
}
|
||
|
||
#[cfg(unix)]
|
||
fn set_owner_only(path: &Path, directory: bool) -> Result<()> {
|
||
use std::os::unix::fs::PermissionsExt;
|
||
fs::set_permissions(
|
||
path,
|
||
fs::Permissions::from_mode(if directory { 0o700 } else { 0o600 }),
|
||
)?;
|
||
Ok(())
|
||
}
|
||
|
||
/// The meetings folder is inside the user's own profile, which Windows
|
||
/// already keeps from other users.
|
||
#[cfg(windows)]
|
||
fn set_owner_only(_path: &Path, _directory: bool) -> Result<()> {
|
||
Ok(())
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests;
|
||
|
||
#[cfg(all(test, target_os = "macos"))]
|
||
mod echo_replay_tests;
|
||
|
||
#[cfg(all(test, target_os = "macos"))]
|
||
mod live_replay_tests;
|