use super::{
download_ownership::{self, Ownership},
download_stage::Stage,
*,
};
use crate::{config::Config, store::Store};
use anyhow::{Context, Result};
use std::os::unix::fs::MetadataExt;
use std::{
fs,
io::{Read, Write},
path::{Path, PathBuf},
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::{Duration, Instant},
};
pub fn download_path(config: &Config, id: &str) -> PathBuf {
config
.settings
.podcasts
.directory
.clone()
.unwrap_or_else(|| config.data_dir.join("podcasts"))
.join(format!("{id}.audio"))
}
fn managed_destination(default: &Path, path: &Path) -> bool {
if path == default {
return true;
}
let stem = path.with_extension("");
path.extension() == default.extension()
&& stem
.extension()
.and_then(|v| v.to_str())
.is_some_and(|v| uuid::Uuid::try_parse(v).is_ok())
&& stem.with_extension("audio") == default
}
pub(super) fn remove(config: &Config, store: &Store, download: &mut Download) -> Result<()> {
remove_download(config, store, download, false).map(|_| ())
}
fn remove_download(
config: &Config,
store: &Store,
download: &mut Download,
automatic: bool,
) -> Result<bool> {
if download.phase() == DownloadState::Downloading {
return Err(error(crate::t!("podcast_download_busy")));
}
let path = if download.path.is_empty() {
download_path(config, &download.episode_id)
} else {
PathBuf::from(&download.path)
};
let identity_key = format!("podcast_download_inode:{}", download.episode_id);
let verified = store.meta(&identity_key)?;
download_removal::recover(&path, verified.as_deref())?;
let mut ownership = download_ownership::inspect(&path, verified.as_deref())?;
if ownership == Ownership::Verified {
ownership = download_removal::claim(&path, verified.as_deref())?;
}
if automatic && matches!(ownership, Ownership::Unverified | Ownership::Legacy) {
return Ok(false);
}
Stage::clear(store, &download.episode_id, &path)?;
store
.conn
.execute("DELETE FROM meta WHERE key=?1", [&identity_key])?;
download.set_phase(DownloadState::Removed);
download.bytes = 0;
download.generation = download.generation.saturating_add(1);
store.podcast_save_download(download)?;
Ok(true)
}
pub(super) fn cleanup(config: &Config, store: &Store, id: &str) -> Result<bool> {
store.podcast_download_transaction(id, |current| {
let Some(mut download) = current else {
return Ok(false);
};
if download.phase() != DownloadState::Complete
|| !managed_destination(&download_path(config, id), Path::new(&download.path))
{
return Ok(false);
}
let episode = store.podcast_episode(id)?;
if !episode.completed || !store.podcast_settings(&episode.feed_id)?.auto_cleanup {
return Ok(false);
}
let queued: bool = store.conn.query_row(
"SELECT EXISTS(SELECT 1 FROM podcast_queue WHERE episode_id=?1)",
[id],
|row| row.get(0),
)?;
if queued {
return Ok(false);
}
remove_download(config, store, &mut download, true)
})
}
pub fn download(config: &Config, id: &str, stop: &Arc<AtomicBool>) -> Result<Download> {
let store = Store::open(&config.data_dir.join("radio.db"))?;
let previous = store.podcast_download(id)?;
run(
config,
&store,
id,
stop,
previous,
download_ownership::stamp,
)
}
pub(super) fn foreground(
config: &Config,
store: &Store,
id: &str,
stop: &Arc<AtomicBool>,
) -> Result<Download> {
let mut current = Runtime::enqueue(store, id)?;
let generation = current.generation;
loop {
if stop.load(Ordering::Relaxed) {
store.podcast_download_transaction(id, |latest| {
if let Some(mut d) = latest
&& d.generation == generation
&& d.phase() != DownloadState::Complete
{
d.set_phase(DownloadState::Paused);
d.retry_at = None;
d.generation = d.generation.saturating_add(1);
store.podcast_save_download(&d)?;
}
Ok(())
})?;
return Err(DomainError::new(ErrorCode::Cancelled).into());
}
let result = run(
config,
store,
id,
stop,
Some(current),
download_ownership::stamp,
);
if result.is_ok() {
return result;
}
current = store
.podcast_download(id)?
.filter(|d| d.generation == generation)
.ok_or_else(|| DomainError::new(ErrorCode::Cancelled))?;
if stop.load(Ordering::Relaxed) {
continue;
}
let retry = current
.retry_at
.as_deref()
.and_then(|s| s.parse::<jiff::Timestamp>().ok())
.filter(|_| current.phase() == DownloadState::Queued);
let Some(retry) = retry else { return result };
if expected_download_progress() {
eprintln!(
"{}",
crate::t!("podcast_download_retry", "time" => crate::timestamp::format(retry))
);
}
while !stop.load(Ordering::Relaxed) && jiff::Timestamp::now() < retry {
std::thread::sleep(Duration::from_millis(250));
if store
.podcast_download(id)?
.is_none_or(|d| d.generation != generation)
{
return Err(DomainError::new(ErrorCode::Cancelled).into());
}
}
}
}
pub(super) fn scheduled(
config: &Config,
expected: &Download,
stop: &Arc<AtomicBool>,
) -> Result<Download> {
let store = Store::open(&config.data_dir.join("radio.db"))?;
let claimed = store
.podcast_claim_download(expected)?
.ok_or_else(|| DomainError::new(ErrorCode::Cancelled))?;
run(
config,
&store,
&expected.episode_id,
stop,
Some(claimed),
download_ownership::stamp,
)
}
fn run(
config: &Config,
store: &Store,
id: &str,
stop: &Arc<AtomicBool>,
previous: Option<Download>,
stamp_file: fn(&fs::File) -> std::io::Result<String>,
) -> Result<Download> {
let default = download_path(config, id);
let exists = previous.is_some();
let mut d = previous.unwrap_or_else(|| Download {
episode_id: id.into(),
..Default::default()
});
let previously_complete = d.phase() == DownloadState::Complete;
let previous_path = PathBuf::from(&d.path);
let mut final_path = if managed_destination(&default, &previous_path) {
previous_path.clone()
} else {
default.clone()
};
d.set_phase(DownloadState::Downloading);
d.error = None;
d.retry_at = None;
d.bytes_per_second = 0;
d.path = final_path.to_string_lossy().into_owned();
let identity_key = format!("podcast_download_inode:{id}");
let verified = store.podcast_download_transaction(id, |current| {
let recorded = store.meta(&identity_key)?;
match current {
Some(row)
if exists
&& row.generation == d.generation
&& Path::new(&row.path) == previous_path =>
{
if !row.path.is_empty() {
download_removal::recover(&previous_path, recorded.as_deref())?;
if previous_path.parent() != final_path.parent() {
Stage::clear(store, id, &previous_path)?;
}
}
store.podcast_download_update(&d)?;
}
None if !exists => store.podcast_save_download(&d)?,
_ => return Err(DomainError::new(ErrorCode::Cancelled).into()),
}
Ok(recorded)
})?;
let mut transient = false;
let mut retry_after = 0i64;
let result = (|| -> Result<()> {
let e = store.podcast_episode(id)?;
fs::create_dir_all(final_path.parent().unwrap()).with_context(|| {
format!(
"create download directory {}",
final_path.parent().unwrap().display()
)
})?;
let ownership = download_ownership::inspect(&final_path, verified.as_deref())?;
let recovered_content = previous_path == final_path
&& d.matches_media(&e)
&& ownership == Ownership::Unverified
&& download_ownership::matches_receipt(
&final_path,
verified.as_deref(),
d.bytes,
stop,
)?;
let mut occupied = ownership != Ownership::Missing;
if final_path.is_file()
&& previous_path == final_path
&& d.bytes > 0
&& fs::metadata(&final_path)?.len() == d.bytes
&& (ownership == Ownership::Verified
|| recovered_content
|| (ownership == Ownership::Legacy && previously_complete && d.matches_media(&e)))
{
if d.matches_media(&e) {
d.set_phase(DownloadState::Complete);
return store.podcast_download_transaction(id, |_| {
store.podcast_download_update(&d)?;
Stage::clear(store, id, &final_path)
});
}
occupied = store.podcast_download_transaction(id, |current| {
if current.is_none_or(|row| row.generation != d.generation) {
return Err(DomainError::new(ErrorCode::Cancelled).into());
}
let claimed = download_removal::claim(&final_path, verified.as_deref())?;
Ok(claimed == Ownership::Unverified || final_path.try_exists()?)
})?;
}
if occupied {
final_path = default.with_extension(format!("{}.audio", uuid::Uuid::new_v4()));
d.path = final_path.to_string_lossy().into_owned();
store.podcast_download_update(&d)?;
}
let (mut stage, existing) = store.podcast_download_transaction(id, |current| {
if current.is_none_or(|row| row.generation != d.generation) {
return Err(DomainError::new(ErrorCode::Cancelled).into());
}
Stage::reserve(store, id, &final_path)
})?;
let part = stage.path(&final_path);
let offset = if d.matches_media(&e)
&& (d.etag.as_ref().is_some_and(|v| !v.starts_with("W/")) || d.modified.is_some())
{
existing
} else {
0
};
let available = fs2::available_space(final_path.parent().unwrap())?;
if available
< (200u64 * 1024 * 1024).saturating_add(e.bytes.unwrap_or(0).saturating_sub(offset))
{
return Err(DomainError::new(ErrorCode::InsufficientSpace).into());
}
let client = super::feed::client(config)?;
let mut req = client
.get(super::feed::url(&e.url, None)?)
.header("Accept-Encoding", "identity");
if offset > 0 {
req = req.header("Range", format!("bytes={offset}-")).header(
"If-Range",
d.etag
.as_ref()
.filter(|v| !v.starts_with("W/"))
.or(d.modified.as_ref())
.unwrap(),
);
}
let mut r = req.send().map_err(|e| {
transient = e.is_timeout() || e.is_connect() || e.is_body();
super::feed::network_error(e)
})?;
if r.status() == 416 {
r = client
.get(&e.url)
.header("Accept-Encoding", "identity")
.send()
.map_err(|e| {
transient = e.is_timeout() || e.is_connect() || e.is_body();
super::feed::network_error(e)
})?;
}
if !r.status().is_success() {
transient = matches!(r.status().as_u16(), 408 | 429 | 500 | 502 | 503 | 504);
retry_after = r
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|v| {
v.parse().ok().or_else(|| {
jiff::fmt::rfc2822::parse(v)
.ok()
.map(|d| (d.timestamp() - jiff::Timestamp::now()).as_secs())
})
})
.unwrap_or(0);
return Err(error(&format!(
"{} {}",
crate::t!("podcast_http"),
r.status().as_u16()
)));
}
let append = r.status() == 206 && offset > 0;
let mut total_length = None;
let mut expected = r.content_length();
if r.status() == 206 {
let range = r
.headers()
.get("content-range")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let (start, end, total) = range
.strip_prefix("bytes ")
.and_then(|v| v.split_once('/'))
.and_then(|(r, t)| {
let (a, b) = r.split_once('-')?;
let start = a.parse::<u64>().ok()?;
let end = b.parse::<u64>().ok()?;
let total = t.parse::<u64>().ok()?;
Some((start, end, total))
})
.filter(|&(start, end, total)| {
start == offset
&& end >= start
&& total > end
&& expected.is_none_or(|length| length == end - start + 1)
})
.ok_or_else(|| error(crate::t!("podcast_invalid_range")))?;
if !append {
return Err(error(crate::t!("podcast_invalid_range")));
}
expected = Some(end - start + 1);
total_length = Some(total);
}
if append {
let validator = r.headers().get("etag").and_then(|v| v.to_str().ok());
if d.etag
.as_ref()
.filter(|v| !v.starts_with("W/"))
.is_some_and(|old| validator.is_some_and(|v| v != old))
{
return Err(error(crate::t!("podcast_invalid_range")));
}
}
let fresh = stage.is_unregistered();
let mut file = store.podcast_download_transaction(id, |current| {
if current.is_none_or(|current| current.generation != d.generation) {
return Err(DomainError::new(ErrorCode::Cancelled).into());
}
let file = stage
.open(
store,
id,
&final_path,
if append { offset } else { 0 },
stamp_file,
)
.with_context(|| format!("initialize download file {}", part.display()))?;
if !append {
if !fresh {
file.set_len(0)?;
}
file.sync_all()?;
}
d.etag = r
.headers()
.get("etag")
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
d.modified = r
.headers()
.get("last-modified")
.and_then(|v| v.to_str().ok())
.map(str::to_owned);
d.url = e.url.clone();
d.media = Some(e.media());
d.bytes = if append { offset } else { 0 };
store.podcast_download_update(&d)?;
Ok(file)
})?;
if fresh {
file.set_len(0)?;
}
let mut buf = [0; 65536];
let mut saved = Instant::now();
d.total_bytes = total_length
.or_else(|| expected.and_then(|n| n.checked_add(if append { offset } else { 0 })));
let start = d.bytes;
let started = Instant::now();
let show_progress = expected_download_progress();
loop {
if stop.load(Ordering::Relaxed) {
return Err(DomainError::new(ErrorCode::Cancelled).into());
}
if saved.elapsed() >= Duration::from_secs(1) {
if let Some(current) = store.podcast_download(id)?
&& matches!(
current.phase(),
DownloadState::Paused | DownloadState::Cancelled
)
{
d.state = current.state;
return Err(DomainError::new(ErrorCode::Cancelled).into());
}
if fs2::available_space(final_path.parent().unwrap())? < 200 * 1024 * 1024 {
return Err(DomainError::new(ErrorCode::InsufficientSpace).into());
}
d.bytes_per_second =
((d.bytes - start) as f64 / started.elapsed().as_secs_f64().max(0.001)) as u64;
store.podcast_download_update(&d)?;
if show_progress {
eprint!(
"\r{} / {} B · {} B/s",
d.bytes,
d.total_bytes
.map(|n| n.to_string())
.unwrap_or_else(|| "?".into()),
d.bytes_per_second
);
}
saved = Instant::now();
}
let n = r.read(&mut buf).map_err(|e| {
transient = true;
error(&format!("{}: {}", crate::t!("podcast_network"), e.kind()))
})?;
if n == 0 {
break;
}
file.write_all(&buf[..n])?;
d.bytes += n as u64;
}
file.sync_all()?;
if expected.is_some_and(|n| n != d.bytes - start)
|| total_length.is_some_and(|n| n != d.bytes)
|| d.bytes == 0
{
return Err(error(crate::t!("podcast_invalid_download")));
}
let output = crate::process::output(
std::process::Command::new(&config.settings.ffprobe)
.args([
"-v",
"error",
"-select_streams",
"a:0",
"-show_entries",
"stream=codec_type",
"-of",
"csv=p=0",
])
.arg(&part),
Duration::from_secs(config.settings.probe_timeout_secs),
stop,
)?;
if !String::from_utf8_lossy(&output).contains("audio") {
return Err(error(crate::t!("podcast_invalid_download")));
}
let identity = if download_ownership::marked_identity(stage.identity()).is_some() {
stage.identity().to_owned()
} else {
download_ownership::content_receipt(&file, stop)?
};
store.podcast_download_transaction(id, |_| {
stage.check_current(store, id)?;
store.podcast_download_update(&d)?;
store.set_meta(&identity_key, &identity)
})?;
store.podcast_download_transaction(id, |current| {
if !current.is_some_and(|row| {
row.generation == d.generation && row.phase() == DownloadState::Downloading
}) || stop.load(Ordering::Relaxed)
{
return Err(DomainError::new(ErrorCode::Cancelled).into());
}
stage.check_current(store, id)?;
let written = file.metadata()?;
let staged = fs::symlink_metadata(&part)?;
if (written.dev(), written.ino()) != (staged.dev(), staged.ino()) {
return Err(error(crate::t!("podcast_invalid_download")));
}
crate::files::publish_noclobber(&part, &final_path).map_err(|err| {
if err
.downcast_ref::<std::io::Error>()
.is_some_and(|e| e.kind() == std::io::ErrorKind::AlreadyExists)
{
error(crate::t!("podcast_file_exists"))
} else {
err
}
})?;
d.set_phase(DownloadState::Complete);
store.podcast_download_update(&d)?;
Stage::clear(store, id, &final_path)
})?;
Ok(())
})();
if expected_download_progress() {
eprintln!(
"\r{} / {} B",
d.bytes,
d.total_bytes
.map(|n| n.to_string())
.unwrap_or_else(|| "?".into())
);
}
if result.is_ok() {
return Ok(d);
}
if let Err(e) = &result {
if !matches!(d.phase(), DownloadState::Paused | DownloadState::Cancelled) {
d.set_phase(if stop.load(Ordering::Relaxed) {
DownloadState::Queued
} else {
DownloadState::Failed
});
}
if transient && d.retries < 3 && d.phase() == DownloadState::Failed {
let delay = [5i64, 30, 120][usize::from(d.retries)].max(retry_after);
d.retries += 1;
let delay = jiff::Timestamp::now()
.checked_add(jiff::SignedDuration::from_secs(delay))
.unwrap_or(jiff::Timestamp::MAX);
d.retry_at = Some(crate::timestamp::format(delay));
d.set_phase(DownloadState::Queued);
}
d.error = Some(crate::clean_text(&format!("{e:#}")));
}
if let Err(update) = store.podcast_download_update(&d) {
result?;
return Err(update);
}
result?;
Ok(d)
}
thread_local! { static CLI_PROGRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
pub(crate) fn set_cli_progress(enabled: bool) {
CLI_PROGRESS.set(enabled);
}
fn expected_download_progress() -> bool {
CLI_PROGRESS.get()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::{Server, config, fixture, response};
use std::sync::atomic::AtomicUsize;
#[test]
fn unmarked_publication_recovers_after_the_completion_write_fails() -> Result<()> {
let requests = Arc::new(AtomicUsize::new(0));
let count = requests.clone();
let audio = fixture("libmp3lame", "mp3");
let body = audio.clone();
let server = Server::new(move |_, stream| {
count.fetch_add(1, Ordering::Relaxed);
response(stream, 200, "audio/mpeg", &body);
});
for (linked, changed) in [(false, false), (true, false), (true, true)] {
let before = requests.load(Ordering::Relaxed);
let root = tempfile::tempdir()?;
let mut config = config(root.path());
let db = config.data_dir.join("radio.db");
let store = Store::open(&db)?;
let preview = Preview {
feed: Feed {
url: format!("{}/feed", server.url),
..Default::default()
},
episodes: vec![Episode {
guid: Some("episode".into()),
url: format!("{}/audio", server.url),
..Default::default()
}],
};
let feed = store.podcast_subscribe(&preview, &preview.feed.url)?;
let episode = store.podcast_episodes(&feed.id)?.remove(0);
let path = download_path(&config, &episode.id);
let stop = Arc::default();
store.conn.execute_batch("CREATE TRIGGER fail_complete BEFORE UPDATE ON podcast_downloads
WHEN json_extract(NEW.json,'$.state')='complete' BEGIN SELECT RAISE(ABORT,'injected completion failure'); END;")?;
let err = run(&config, &store, &episode.id, &stop, None, |file| {
let m = file.metadata()?;
Ok(format!("{}:{}", m.dev(), m.ino()))
})
.unwrap_err();
assert!(err.to_string().contains("injected completion failure"));
assert_eq!(fs::read(&path)?, audio);
assert_eq!(requests.load(Ordering::Relaxed), before + 1);
let stage = Stage::load(&store, &episode.id)?.unwrap();
let part = stage.path(&path);
if linked {
fs::hard_link(&path, &part)?;
}
if changed {
fs::write(&path, vec![0x53; audio.len()])?;
} else {
config.settings.ffprobe = "/missing-probe".into();
}
store.conn.execute_batch("DROP TRIGGER fail_complete")?;
drop(store);
let reopened = Store::open(&db)?;
let resumed = foreground(&config, &reopened, &episode.id, &stop)?;
assert_eq!(resumed.phase(), DownloadState::Complete);
assert_eq!(fs::read(&resumed.path)?, audio);
assert!(!part.exists());
if changed {
assert_ne!(Path::new(&resumed.path), path);
assert_eq!(fs::read(&path)?, vec![0x53; audio.len()]);
assert_eq!(requests.load(Ordering::Relaxed), before + 2);
} else {
assert_eq!(Path::new(&resumed.path), path);
assert_eq!(requests.load(Ordering::Relaxed), before + 1);
let removed = manage(
&config,
&reopened,
Action::Downloads {
action: DownloadAction::Remove { id: episode.id },
},
&stop,
)?;
assert_eq!(removed["state"], "removed");
assert_eq!(fs::read(path)?, audio);
}
}
Ok(())
}
}