1use crate::error::{DomainError, ErrorCode};
2use crate::{
3 USER_AGENT,
4 config::{Config, validate_url},
5 model::{Recording, Station},
6 process,
7 store::Store,
8};
9use anyhow::{Context, Result, bail};
10use serde_json::Value;
11use std::{
12 fs::{self, OpenOptions},
13 io::{BufRead, BufReader},
14 path::{Path, PathBuf},
15 process::{Child, Command, Stdio},
16 sync::{
17 Arc,
18 atomic::{AtomicBool, AtomicU64, Ordering},
19 },
20 thread,
21 time::{Duration, Instant},
22};
23
24pub struct Recorder {
25 pub space_estimated: bool,
26 child: Child,
27 pub record: Recording,
28 partial: PathBuf,
29 deadline: Option<Instant>,
30 target_duration: Option<Duration>,
31 ended_without_stop: bool,
32 timed_out: bool,
33 progress: Arc<AtomicU64>,
34 duration_ms: u64,
35 readers: Vec<thread::JoinHandle<()>>,
36 errors: Arc<std::sync::Mutex<String>>,
37 reconnects: Arc<AtomicU64>,
38 finished: bool,
39 stop_requested: bool,
40}
41
42pub struct RecordingMetadata<'a> {
43 pub station: &'a Station,
44 pub track: Option<&'a str>,
45}
46
47fn filename_component(text: &str, max_chars: usize, max_bytes: usize) -> String {
48 let mut result = String::new();
49 for c in text
50 .chars()
51 .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
52 .take(max_chars)
53 {
54 if result.len() + c.len_utf8() > max_bytes {
55 break;
56 }
57 result.push(c);
58 }
59 result
60}
61
62fn track_filename_component(text: &str, max_bytes: usize) -> String {
63 let words: Vec<_> = text
64 .split_whitespace()
65 .map(|word| filename_component(word, 40, max_bytes))
66 .filter(|word| !word.is_empty())
67 .collect();
68 filename_component(&words.join("_"), 40, max_bytes)
69}
70
71const ERROR_TAIL_BYTES: usize = 8192;
72
73fn recording_progress(line: &str) -> bool {
74 line.split_once('=').is_some_and(|(key, _)| {
75 matches!(
76 key,
77 "frame"
78 | "fps"
79 | "bitrate"
80 | "total_size"
81 | "out_time_us"
82 | "out_time_ms"
83 | "out_time"
84 | "dup_frames"
85 | "drop_frames"
86 | "speed"
87 | "progress"
88 )
89 })
90}
91
92fn append_error_tail(text: &mut String, line: &str) {
93 text.extend(
95 line.chars()
96 .filter(|c| !c.is_control() || *c == '\n' || *c == '\t'),
97 );
98 let mut start = text.len().saturating_sub(ERROR_TAIL_BYTES);
99 while !text.is_char_boundary(start) {
100 start += 1;
101 }
102 if start > 0 {
103 text.drain(..start);
104 }
105}
106
107pub fn probe(config: &Config, url: &str, stop: &Arc<AtomicBool>) -> Result<Value> {
108 probe_with_timeout(
109 config,
110 url,
111 stop,
112 Duration::from_secs(config.settings.probe_timeout_secs),
113 )
114}
115
116fn probe_with_timeout(
117 config: &Config,
118 url: &str,
119 stop: &Arc<AtomicBool>,
120 timeout: Duration,
121) -> Result<Value> {
122 let data = process::output(
123 Command::new(&config.settings.ffprobe).args([
124 "-v",
125 "error",
126 "-rw_timeout",
127 "5000000",
128 "-analyzeduration",
129 "1000000",
130 "-probesize",
131 "262144",
132 "-user_agent",
133 USER_AGENT,
134 "-select_streams",
135 "a:0",
136 "-show_entries",
137 "stream=codec_name,bit_rate:format=duration,bit_rate",
138 "-of",
139 "json",
140 "-i",
141 url,
142 ]),
143 timeout,
144 stop,
145 )?;
146 Ok(serde_json::from_slice(&data)?)
147}
148
149pub fn format_for_codec(codec: &str) -> Result<(&'static str, &'static str)> {
150 match codec {
151 "mp3" => Ok(("mp3", "mp3")),
152 "aac" => Ok(("aac", "adts")),
153 "vorbis" => Ok(("ogg", "ogg")),
154 "opus" => Ok(("opus", "opus")),
155 _ => bail!(DomainError::new(ErrorCode::UnsupportedCodec).with("codec", codec)),
156 }
157}
158
159pub fn sidecar(record: &Recording) -> Result<()> {
160 let path = PathBuf::from(format!("{}.json", record.path));
161 let temp = PathBuf::from(format!("{}.tmp", path.display()));
162 fs::write(&temp, serde_json::to_vec_pretty(record)?)?;
163 fs::rename(temp, path)?;
164 Ok(())
165}
166
167fn complete_finalization(store: &Store, record: &mut Recording) -> Result<()> {
168 let partial = PathBuf::from(&record.path);
169 let final_path = PathBuf::from(
170 record
171 .final_path
172 .as_ref()
173 .context(DomainError::new(ErrorCode::FinalPathMissing))?,
174 );
175 if partial.exists() {
176 crate::files::publish_noclobber(&partial, &final_path).with_context(|| {
177 DomainError::new(ErrorCode::RecordingPublish)
178 .with("id", &record.id)
179 .with("path", partial.display())
180 .with("final_path", final_path.display())
181 })?;
182 }
183 let size = fs::metadata(&final_path)?.len();
184 if size != record.size_bytes || size == 0 {
185 bail!(DomainError::new(ErrorCode::RecordingSizeMismatch));
186 }
187 let mut complete = record.clone();
188 complete.path = final_path.to_string_lossy().into();
189 complete.status = "complete".into();
190 complete.error = None;
191 complete.recovery_pending = false;
192 sidecar(&complete)?;
194 store.save_recording(&complete)?;
195 let _ = fs::remove_file(format!("{}.json", partial.display()));
196 *record = complete;
197 Ok(())
198}
199
200pub fn recover(store: &Store) -> Result<Vec<String>> {
201 let mut warnings = Vec::new();
202 for mut r in store.unfinished_recordings()? {
203 let result = (|| -> Result<()> {
204 if r.status == "finalizing" {
205 return complete_finalization(store, &mut r);
206 }
207 if r.status == "recording" {
208 r.status = "interrupted".into();
209 r.stopped_at = Some(crate::timestamp::now());
210 r.error = Some("上一个会话未正常结束;保留临时文件供恢复".into());
211 r.size_bytes = fs::metadata(&r.path).map(|m| m.len()).unwrap_or(0);
212 r.recovery_pending = true;
213 store.save_recording(&r)?;
214 }
215 let retry = r.recovery_pending;
216 if retry {
217 r.error = Some(
218 if Path::new(&r.path).exists() {
219 "上一个会话未正常结束;临时文件保留,元数据已恢复"
220 } else {
221 "上一个会话未正常结束;音频文件缺失,元数据已恢复"
222 }
223 .into(),
224 );
225 }
226 r.recovery_pending = false;
227 sidecar(&r)?;
228 if retry {
229 store.save_recording(&r)?;
230 }
231 Ok(())
232 })();
233 if let Err(error) = result {
234 let message = format!(
235 "恢复失败: 录音 {} ({}):{error:#};使用 recordings recover 重试",
236 r.id, r.path
237 );
238 r.error = Some(message.clone());
239 r.recovery_pending = true;
240 if let Err(db_error) = store.save_recording(&r) {
241 warnings.push(format!("{message};数据库: {db_error:#}"));
242 } else {
243 warnings.push(message);
244 }
245 }
246 }
247 Ok(warnings)
248}
249
250fn required_space(
253 reserve_mb: u64,
254 station_kbps: u32,
255 info: &Value,
256 duration: Option<Duration>,
257) -> (u64, bool) {
258 let positive = |v: &Value| {
259 v.as_str()
260 .and_then(|v| v.parse::<u64>().ok())
261 .or_else(|| v.as_u64())
262 .filter(|v| *v > 0)
263 };
264 let bitrate = positive(&info["streams"][0]["bit_rate"])
265 .or_else(|| positive(&info["format"]["bit_rate"]))
266 .or_else(|| (station_kbps > 0).then_some(u64::from(station_kbps) * 1000));
267 let reserve = reserve_mb.saturating_mul(1024 * 1024);
268 match (duration, bitrate) {
269 (Some(duration), Some(bitrate)) => {
270 let bytes = u128::from(bitrate).saturating_mul(duration.as_nanos());
271 let bytes = bytes.div_ceil(8_000_000_000).min(u128::from(u64::MAX)) as u64;
272 (reserve.saturating_add(bytes), true)
273 }
274 (None, _) | (_, None) => (reserve, false),
275 }
276}
277
278impl Recorder {
279 pub fn start(
280 config: &Config,
281 store: &Store,
282 station: &Station,
283 url: &str,
284 dir: &Path,
285 duration: Option<Duration>,
286 stop: &Arc<AtomicBool>,
287 ) -> Result<Self> {
288 validate_url(url)?;
289 let info = probe(config, url, stop)?;
290 Self::start_with_info(config, store, station, url, dir, duration, info)
291 }
292
293 pub fn start_with_info(
294 config: &Config,
295 store: &Store,
296 station: &Station,
297 url: &str,
298 dir: &Path,
299 duration: Option<Duration>,
300 info: Value,
301 ) -> Result<Self> {
302 Self::start_with_metadata(
303 config,
304 store,
305 RecordingMetadata {
306 station,
307 track: None,
308 },
309 url,
310 dir,
311 duration,
312 info,
313 )
314 }
315
316 pub fn start_with_metadata(
317 config: &Config,
318 store: &Store,
319 metadata: RecordingMetadata<'_>,
320 url: &str,
321 dir: &Path,
322 duration: Option<Duration>,
323 info: Value,
324 ) -> Result<Self> {
325 let station = metadata.station;
326 let track = metadata
327 .track
328 .map(crate::clean_text)
329 .map(|title| title.trim().to_owned())
330 .filter(|title| !title.is_empty());
331 validate_url(url)?;
332 let codec = info["streams"][0]["codec_name"]
333 .as_str()
334 .context(DomainError::new(ErrorCode::NoAudio))?
335 .to_owned();
336 let (extension, muxer) = format_for_codec(&codec)?;
337 let dir = std::path::absolute(dir)?;
338 let (required, space_estimated) = required_space(
339 config.settings.recording_min_free_mb,
340 station.bitrate,
341 &info,
342 duration,
343 );
344 let mut ancestor = dir.as_path();
347 loop {
348 match fs::metadata(ancestor) {
349 Ok(_) => break,
350 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
351 ancestor = ancestor
352 .parent()
353 .context(DomainError::new(ErrorCode::FinalPathMissing))?;
354 }
355 Err(error) => return Err(error.into()),
356 }
357 }
358 let available = fs2::available_space(ancestor)?;
359 if available < required {
360 bail!(
361 DomainError::new(ErrorCode::InsufficientSpace)
362 .with("available", available)
363 .with("required", required)
364 );
365 }
366 fs::create_dir_all(&dir)?;
367 let dir = fs::canonicalize(dir)?;
368 let id = uuid::Uuid::new_v4().to_string();
369 let name = filename_component(&station.name, 60, 180);
372 let track_name = track_filename_component(track.as_deref().unwrap_or(""), 200 - name.len());
373 let label = if track_name.is_empty() {
374 name
375 } else {
376 format!("{name}-{track_name}")
377 };
378 let base = format!(
379 "{}-{}-{}",
380 jiff::ZonedDateTime::now().strftime("%Y%m%d-%H%M%S"),
381 label,
382 &id[..8]
383 );
384 let final_path = dir.join(format!("{base}.{extension}"));
385 let partial = dir.join(format!("{base}.{extension}.part"));
386 let file = OpenOptions::new()
387 .write(true)
388 .create_new(true)
389 .open(&partial)?;
390 let mut command = Command::new(&config.settings.ffmpeg);
391 command.args([
392 "-hide_banner",
393 "-loglevel",
394 "warning",
395 "-nostats",
396 "-rw_timeout",
397 "12000000",
398 "-reconnect",
403 "1",
404 "-reconnect_streamed",
405 "1",
406 "-reconnect_delay_max",
407 "2",
408 "-analyzeduration",
409 "1000000",
410 "-probesize",
411 "262144",
412 "-user_agent",
413 USER_AGENT,
414 "-i",
415 url,
416 "-map",
417 "0:a:0",
418 "-c:a",
419 "copy",
420 ]);
421 if let Some(duration) = duration {
422 command.arg("-t").arg(duration.as_secs_f64().to_string());
423 }
424 command.args(["-progress", "pipe:2", "-f", muxer, "pipe:1"]);
425 command
427 .stdin(Stdio::piped())
428 .stdout(Stdio::from(file))
429 .stderr(Stdio::piped());
430 let child_result = process::spawn_owned(command);
431 let mut child = match child_result {
432 Ok(child) => child,
433 Err(e) => {
434 let _ = fs::remove_file(&partial);
435 return Err(e).context(
436 DomainError::new(ErrorCode::MissingDependency).with("program", "ffmpeg"),
437 );
438 }
439 };
440 let progress = Arc::new(AtomicU64::new(0));
441 let latest = progress.clone();
442 let errors = Arc::new(std::sync::Mutex::new(String::new()));
443 let target = errors.clone();
444 let reconnects = Arc::new(AtomicU64::new(0));
445 let retry_count = reconnects.clone();
446 let stderr = child.stderr.take().unwrap();
447 let reader = thread::spawn(move || {
448 let mut input = BufReader::new(stderr);
449 let mut line = String::new();
450 loop {
451 line.clear();
452 match input.read_line(&mut line) {
453 Ok(0) | Err(_) => break,
454 _ => {}
455 }
456 if let Some(value) = line.trim().strip_prefix("out_time_us=") {
457 if let Ok(value) = value.parse::<u64>() {
458 latest.fetch_max(value / 1000, Ordering::Relaxed);
459 }
460 } else if !recording_progress(line.trim()) {
461 if line.contains("Will reconnect at") || line.contains("Failed to open segment")
467 {
468 retry_count.fetch_add(1, Ordering::Relaxed);
469 }
470 let mut text = target.lock().unwrap();
471 append_error_tail(&mut text, &line);
472 }
473 }
474 });
475 let record = Recording {
476 id,
477 stationuuid: station.stationuuid.clone(),
478 station_name: station.name.clone(),
479 track,
480 source_url_resolved: url.into(),
481 started_at: crate::timestamp::now(),
482 stopped_at: None,
483 media_duration_ms: None,
484 codec,
485 container: muxer.into(),
486 path: partial.to_string_lossy().into(),
487 final_path: Some(final_path.to_string_lossy().into()),
488 size_bytes: 0,
489 status: "recording".into(),
490 error: None,
491 reconnects: 0,
492 recovery_pending: false,
493 };
494 let recorder = Self {
495 space_estimated,
496 child,
497 record,
498 partial,
499 deadline: duration.map(|d| {
500 Instant::now() + d + Duration::from_secs(config.settings.playback_timeout_secs)
501 }),
502 target_duration: duration,
503 ended_without_stop: false,
504 timed_out: false,
505 progress,
506 duration_ms: 0,
507 readers: vec![reader],
508 errors,
509 reconnects,
510 finished: false,
511 stop_requested: false,
512 };
513 store.save_recording(&recorder.record)?;
514 sidecar(&recorder.record)?;
515 Ok(recorder)
516 }
517
518 pub fn poll(&mut self) -> Result<bool> {
519 self.duration_ms = self.progress.load(Ordering::Relaxed);
520 self.ended_without_stop = self.child.try_wait()?.is_some();
521 self.timed_out =
522 !self.ended_without_stop && self.deadline.is_some_and(|d| Instant::now() >= d);
523 Ok(self.ended_without_stop || self.timed_out)
524 }
525
526 pub fn elapsed_ms(&self) -> u64 {
527 self.duration_ms
528 }
529
530 fn stop_child(&mut self) -> Result<std::process::ExitStatus> {
531 if let Some(status) = self.child.try_wait()? {
532 return Ok(status);
533 }
534 self.stop_requested = true;
537 unsafe { libc::kill(self.child.id() as libc::pid_t, libc::SIGINT) };
538 let deadline = Instant::now() + Duration::from_secs(3);
539 loop {
540 if let Some(status) = self.child.try_wait()? {
541 return Ok(status);
542 }
543 if Instant::now() >= deadline {
544 self.child.kill()?;
545 return Ok(self.child.wait()?);
546 }
547 thread::sleep(Duration::from_millis(30));
548 }
549 }
550
551 pub fn finish(self, config: &Config, store: &Store, reason: Option<&str>) -> Result<Recording> {
552 self.finish_cancellable(config, store, reason, &Arc::new(AtomicBool::new(false)))
553 }
554
555 pub fn finish_cancellable(
556 mut self,
557 config: &Config,
558 store: &Store,
559 reason: Option<&str>,
560 stop: &Arc<AtomicBool>,
561 ) -> Result<Recording> {
562 let status = self.stop_child()?;
563 for handle in self.readers.drain(..) {
564 let _ = handle.join();
565 }
566 self.duration_ms = self.progress.load(Ordering::Relaxed);
567 self.record.stopped_at = Some(crate::timestamp::now());
568 self.record.reconnects = self.reconnects.load(Ordering::Relaxed);
569 self.record.size_bytes = fs::metadata(&self.partial)?.len();
570 let verification = probe_with_timeout(
571 config,
572 &self.partial.to_string_lossy(),
573 stop,
574 Duration::from_secs(2),
575 );
576 if let Ok(info) = &verification {
577 self.record.media_duration_ms = info["format"]["duration"]
578 .as_str()
579 .and_then(|s| s.parse::<f64>().ok())
580 .filter(|d| d.is_finite() && *d >= 0.)
581 .map(|d| (d * 1000.) as u64);
582 }
583 let premature = self.ended_without_stop
584 && self.target_duration.is_none_or(|d| {
585 self.record
586 .media_duration_ms
587 .unwrap_or(self.duration_ms)
588 .saturating_add(100)
589 < d.as_millis() as u64
590 });
591 let reason = reason.or(if self.timed_out {
592 Some("录音未在时限内完成")
593 } else if premature && status.success() {
594 Some("直播源提前结束")
595 } else {
596 None
597 });
598 let graceful = status.success() || self.stop_requested;
601 self.record.status = if graceful && reason.is_none() && self.record.size_bytes > 0 {
602 "complete"
603 } else if reason.is_some() {
604 "interrupted"
605 } else {
606 "failed"
607 }
608 .into();
609 if self.record.status == "complete"
610 && verification
611 .as_ref()
612 .ok()
613 .and_then(|info| info["streams"][0]["codec_name"].as_str())
614 != Some(self.record.codec.as_str())
615 {
616 self.record.status = "failed".into();
617 self.record.error = Some("录音文件未通过音频轨道验证;保留临时文件".into());
618 }
619 if self.record.media_duration_ms.is_none() && self.duration_ms > 0 {
621 self.record.media_duration_ms = Some(self.duration_ms);
622 }
623 if self.record.status == "complete" {
624 self.record.status = "finalizing".into();
627 store.save_recording(&self.record)?;
628 sidecar(&self.record)?;
629 if let Err(error) = complete_finalization(store, &mut self.record) {
630 self.record.recovery_pending = true;
631 self.record.error = Some(format!(
632 "录音 {} ({}) 收尾待重试: {error:#}",
633 self.record.id, self.record.path
634 ));
635 let _ = store.save_recording(&self.record);
636 let _ = sidecar(&self.record);
637 return Err(error).context(self.record.error.clone().unwrap());
638 }
639 } else {
640 let errors = self.errors.lock().unwrap();
641 let summary = self
642 .record
643 .error
644 .as_deref()
645 .or(reason)
646 .map(str::to_owned)
647 .unwrap_or_else(|| format!("FFmpeg: {status}"));
648 self.record.error = Some(if errors.trim().is_empty() {
649 summary
650 } else {
651 format!("{summary}\n{}", errors.trim())
652 });
653 }
654 if self.record.status != "complete" {
655 store.save_recording(&self.record)?;
656 sidecar(&self.record)?;
657 }
658 self.finished = true;
659 Ok(self.record.clone())
660 }
661}
662
663impl Drop for Recorder {
664 fn drop(&mut self) {
665 if !self.finished {
666 let _ = self.stop_child();
667 }
668 for handle in self.readers.drain(..) {
669 let _ = handle.join();
670 }
671 }
672}
673
674pub fn parse_duration(value: &str) -> Result<Duration> {
675 let split = value
676 .find(|c: char| !c.is_ascii_digit())
677 .unwrap_or(value.len());
678 let n = value[..split]
679 .parse::<u64>()
680 .context(DomainError::new(ErrorCode::InvalidDuration))?;
681 let factor = match &value[split..] {
682 "" | "s" => 1,
683 "m" => 60,
684 "h" => 3600,
685 _ => bail!(DomainError::new(ErrorCode::DurationUnit)),
686 };
687 let secs = n
688 .checked_mul(factor)
689 .context(DomainError::new(ErrorCode::DurationOverflow))?;
690 if secs == 0 || secs > 365 * 24 * 3600 {
691 bail!(DomainError::new(ErrorCode::DurationRange));
692 }
693 Ok(Duration::from_secs(secs))
694}
695
696#[cfg(test)]
697mod tests {
698 use super::*;
699
700 #[test]
701 fn recording_track_is_optional_for_older_metadata() {
702 let dir = tempfile::tempdir().unwrap();
703 let old = pending(dir.path());
704 let value = serde_json::to_value(&old).unwrap();
705 assert!(value.get("track").is_none());
706 let decoded: Recording = serde_json::from_value(value).unwrap();
707 assert!(decoded.track.is_none());
708 }
709
710 fn pending(dir: &Path) -> Recording {
711 let partial = dir.join("test.mp3.part");
712 fs::write(&partial, b"verified audio").unwrap();
713 Recording {
714 id: uuid::Uuid::new_v4().to_string(),
715 stationuuid: uuid::Uuid::new_v4().to_string(),
716 station_name: "test".into(),
717 track: None,
718 source_url_resolved: "https://example.com/audio".into(),
719 started_at: "2026-01-01T00:00:00Z".into(),
720 stopped_at: Some("2026-01-01T00:00:01Z".into()),
721 media_duration_ms: Some(1000),
722 codec: "mp3".into(),
723 container: "mp3".into(),
724 path: partial.to_string_lossy().into(),
725 final_path: Some(dir.join("test.mp3").to_string_lossy().into()),
726 size_bytes: 14,
727 status: "finalizing".into(),
728 error: None,
729 reconnects: 0,
730 recovery_pending: false,
731 }
732 }
733
734 #[test]
735 fn space_estimate_prefers_audio_bitrate_and_reports_unknown_totals() {
736 let reserve = 16 * 1024 * 1024;
737 let mut info =
738 serde_json::json!({"streams":[{"bit_rate":"128000"}], "format":{"bit_rate":"256000"}});
739 assert_eq!(
740 required_space(16, 320, &info, Some(Duration::from_millis(1500))),
741 (reserve + 24000, true)
742 );
743 assert_eq!(required_space(16, 320, &info, None), (reserve, false));
744 info["streams"][0]["bit_rate"] = "0".into();
745 assert_eq!(
746 required_space(16, 320, &info, Some(Duration::from_secs(1))),
747 (reserve + 32000, true)
748 );
749 assert_eq!(
750 required_space(16, 0, &Value::Null, Some(Duration::from_secs(1))),
751 (reserve, false)
752 );
753 assert_eq!(
754 required_space(16, 128, &Value::Null, Some(Duration::from_secs(1))),
755 (reserve + 16000, true)
756 );
757 let extreme = serde_json::json!({"streams":[{"bit_rate":u64::MAX.to_string()}]});
758 assert_eq!(
759 required_space(16, 0, &extreme, Some(Duration::from_secs(u64::MAX))),
760 (u64::MAX, true)
761 );
762 }
763
764 #[test]
765 fn recovery_repairs_each_publication_boundary_idempotently() {
766 for phase in 0..5 {
767 let dir = tempfile::tempdir().unwrap();
768 let store = Store::open(&dir.path().join("radio.db")).unwrap();
769 let mut r = pending(dir.path());
770 r.reconnects = 2;
771 store.save_recording(&r).unwrap();
772 sidecar(&r).unwrap();
773 if phase >= 1 {
774 fs::hard_link(&r.path, r.final_path.as_ref().unwrap()).unwrap();
775 }
776 if phase >= 2 {
777 crate::files::publish_noclobber(
778 Path::new(&r.path),
779 Path::new(r.final_path.as_ref().unwrap()),
780 )
781 .unwrap();
782 }
783 if phase >= 3 {
784 let mut complete = r.clone();
785 complete.path = complete.final_path.clone().unwrap();
786 complete.status = "complete".into();
787 sidecar(&complete).unwrap();
788 }
789 if phase == 4 {
790 let lock = rusqlite::Connection::open(dir.path().join("radio.db")).unwrap();
792 lock.execute_batch("BEGIN IMMEDIATE").unwrap();
793 assert!(complete_finalization(&store, &mut r).is_err());
794 lock.execute_batch("ROLLBACK").unwrap();
795 }
796 recover(&store).unwrap();
797 recover(&store).unwrap();
798 let saved = store.recordings(1).unwrap().remove(0);
799 assert_eq!(saved.status, "complete");
800 assert_eq!(saved.reconnects, 2);
801 assert_eq!(fs::read(&saved.path).unwrap(), b"verified audio");
802 assert_eq!(
803 serde_json::from_slice::<Recording>(
804 &fs::read(format!("{}.json", saved.path)).unwrap()
805 )
806 .unwrap()
807 .id,
808 saved.id
809 );
810 assert!(!Path::new(&r.path).exists());
811 }
812 }
813
814 #[test]
815 fn successful_sidecar_retry_clears_recovery_pending_state() {
816 let dir = tempfile::tempdir().unwrap();
817 let store = Store::open(&dir.path().join("radio.db")).unwrap();
818 let mut r = pending(dir.path());
819 r.status = "recording".into();
820 r.path = dir.path().join("missing/old.part").to_string_lossy().into();
821 store.save_recording(&r).unwrap();
822 assert_eq!(recover(&store).unwrap().len(), 1);
823 assert_eq!(store.unfinished_recordings().unwrap().len(), 1);
824 let mut retry = store.recordings(1).unwrap().remove(0);
825 assert!(retry.recovery_pending);
826 retry.error = Some("diagnostic wording has changed".into());
827 store.save_recording(&retry).unwrap();
828 assert_eq!(store.unfinished_recordings().unwrap().len(), 1);
829 fs::create_dir(dir.path().join("missing")).unwrap();
830 assert!(recover(&store).unwrap().is_empty());
831 assert!(store.unfinished_recordings().unwrap().is_empty());
832 let saved = store.recordings(1).unwrap().remove(0);
833 assert_eq!(saved.status, "interrupted");
834 assert!(!saved.recovery_pending);
835 assert!(saved.error.as_deref().unwrap().contains("音频文件缺失"));
836 assert!(Path::new(&format!("{}.json", saved.path)).exists());
837 assert!(recover(&store).unwrap().is_empty());
838 }
839
840 #[test]
841 fn recovery_selection_uses_the_flag_instead_of_error_text() {
842 let dir = tempfile::tempdir().unwrap();
843 let store = Store::open(&dir.path().join("radio.db")).unwrap();
844 let mut record = pending(dir.path());
845 record.status = "interrupted".into();
846 record.error = Some("恢复失败: diagnostic text alone".into());
847 store.save_recording(&record).unwrap();
848 assert!(store.unfinished_recordings().unwrap().is_empty());
849 record.recovery_pending = true;
850 record.error = None;
851 store.save_recording(&record).unwrap();
852 assert_eq!(store.unfinished_recordings().unwrap().len(), 1);
853 assert!(recover(&store).unwrap().is_empty());
854 assert!(store.unfinished_recordings().unwrap().is_empty());
855 }
856
857 #[test]
858 fn version_one_database_migrates_legacy_recovery_state_once() {
859 let dir = tempfile::tempdir().unwrap();
860 let path = dir.path().join("legacy.db");
861 let mut record = pending(dir.path());
862 record.status = "interrupted".into();
863 record.error = Some("恢复失败: old-format sidecar failure".into());
864 let mut json = serde_json::to_value(&record).unwrap();
865 json.as_object_mut().unwrap().remove("recovery_pending");
866 let conn = rusqlite::Connection::open(&path).unwrap();
867 conn.execute_batch("CREATE TABLE recordings (id TEXT PRIMARY KEY,status TEXT NOT NULL,json TEXT NOT NULL);
868 CREATE TABLE stations (uuid TEXT PRIMARY KEY,name TEXT NOT NULL,search TEXT NOT NULL,
869 country TEXT NOT NULL,languages TEXT NOT NULL,tags TEXT NOT NULL,bitrate INTEGER NOT NULL,
870 popularity INTEGER NOT NULL,custom INTEGER NOT NULL,active INTEGER NOT NULL,json TEXT NOT NULL);
871 CREATE TABLE meta (key TEXT PRIMARY KEY,value TEXT NOT NULL);
872 CREATE TABLE favorites (uuid TEXT PRIMARY KEY REFERENCES stations(uuid),created_at TEXT NOT NULL);
873 CREATE TABLE history (id INTEGER PRIMARY KEY,uuid TEXT NOT NULL REFERENCES stations(uuid),played_at TEXT NOT NULL);
874 CREATE INDEX history_station ON history(uuid);
875 PRAGMA user_version=1;").unwrap();
876 conn.execute(
877 "INSERT INTO recordings VALUES (?1,?2,?3)",
878 rusqlite::params![record.id, record.status, json.to_string()],
879 )
880 .unwrap();
881 drop(conn);
882 let store = Store::open(&path).unwrap();
883 assert!(store.unfinished_recordings().unwrap()[0].recovery_pending);
884 assert!(recover(&store).unwrap().is_empty());
885 assert!(!store.recordings(1).unwrap()[0].recovery_pending);
886 drop(store);
887 let store = Store::open(&path).unwrap();
888 assert!(store.unfinished_recordings().unwrap().is_empty());
889 let conn = rusqlite::Connection::open(&path).unwrap();
890 assert_eq!(
891 conn.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))
892 .unwrap(),
893 11
894 );
895 }
896
897 #[test]
898 fn publication_never_overwrites_an_existing_file() {
899 let dir = tempfile::tempdir().unwrap();
900 let store = Store::open(&dir.path().join("radio.db")).unwrap();
901 let mut r = pending(dir.path());
902 store.save_recording(&r).unwrap();
903 fs::write(r.final_path.as_ref().unwrap(), b"other recording").unwrap();
904 assert!(complete_finalization(&store, &mut r).is_err());
905 assert_eq!(
906 fs::read(r.final_path.as_ref().unwrap()).unwrap(),
907 b"other recording"
908 );
909 assert_eq!(fs::read(&r.path).unwrap(), b"verified audio");
910 fs::remove_file(r.final_path.as_ref().unwrap()).unwrap();
911 recover(&store).unwrap();
912 assert_eq!(store.recordings(1).unwrap()[0].status, "complete");
913 }
914
915 #[test]
916 fn publication_rejects_matching_contents_and_symlink_destinations() {
917 use std::os::unix::fs::symlink;
918 for symlink_target in [false, true] {
919 let dir = tempfile::tempdir().unwrap();
920 let store = Store::open(&dir.path().join("radio.db")).unwrap();
921 let mut r = pending(dir.path());
922 let final_path = PathBuf::from(r.final_path.as_ref().unwrap());
923 if symlink_target {
924 symlink(&r.path, &final_path).unwrap();
925 } else {
926 fs::copy(&r.path, &final_path).unwrap();
927 }
928 assert!(complete_finalization(&store, &mut r).is_err());
929 assert_eq!(fs::read(&r.path).unwrap(), b"verified audio");
930 assert_eq!(fs::read(final_path).unwrap(), b"verified audio");
931 assert_eq!(r.status, "finalizing");
932 }
933 }
934}