Skip to main content

radio_cli/podcast/
mod.rs

1//! Public podcast subscriptions are independent of the radio catalog.
2mod commands;
3pub mod directory;
4mod extras;
5mod library;
6pub use extras::Bookmark;
7pub use library::LibraryQuery;
8pub(crate) mod direct;
9mod download;
10mod download_files;
11mod download_ownership;
12mod download_removal;
13mod download_stage;
14mod feed;
15mod storage;
16pub mod transcript;
17use crate::error::{DomainError, ErrorCode};
18pub use commands::{Action, DownloadAction, manage};
19pub(crate) use download::set_cli_progress;
20pub use download::{download, download_path};
21pub use feed::{Preview, discover, fetch, search};
22use serde::{Deserialize, Serialize};
23
24#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
25pub struct Transcript {
26    pub url: String,
27    pub mime: String,
28    pub language: Option<String>,
29}
30
31#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
32pub struct Chapter {
33    pub title: String,
34    pub position_ms: u64,
35}
36
37#[derive(Debug, Clone, Default, Serialize, Deserialize)]
38#[serde(default, deny_unknown_fields)]
39pub struct ShowSettings {
40    pub speed: Option<f64>,
41    pub sort: Option<String>,
42    pub skip_back: Option<u32>,
43    pub skip_forward: Option<u32>,
44    pub skip_intro: u32,
45    pub skip_outro: u32,
46    pub completion_seconds: u32,
47    pub auto_download: bool,
48    pub auto_cleanup: bool,
49}
50
51pub(crate) fn error(detail: &str) -> anyhow::Error {
52    DomainError::new(ErrorCode::PodcastFailed)
53        .with("detail", detail)
54        .into()
55}
56#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
57#[serde(default)]
58pub struct Feed {
59    pub failures: u32,
60    pub new_feed_url: Option<String>,
61    pub revision: u64,
62    pub id: String,
63    pub url: String,
64    pub title: String,
65    pub author: String,
66    pub description: String,
67    pub image: String,
68    pub website: String,
69    pub subscribed: bool,
70    pub etag: Option<String>,
71    pub modified: Option<String>,
72    pub refreshed_at: Option<String>,
73    pub error: Option<String>,
74}
75#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
76pub struct Episode {
77    #[serde(default)]
78    pub chapters: Vec<Chapter>,
79    #[serde(default)]
80    pub chapters_url: Option<String>,
81    #[serde(default)]
82    pub source_order: Option<u64>,
83    pub id: String,
84    pub feed_id: String,
85    pub guid: Option<String>,
86    pub title: String,
87    pub published: Option<String>,
88    pub description: String,
89    pub website: String,
90    pub url: String,
91    pub mime: String,
92    pub bytes: Option<u64>,
93    pub duration_ms: Option<u64>,
94    pub position_ms: u64,
95    pub observed_duration_ms: Option<u64>,
96    pub completed: bool,
97    #[serde(default)]
98    pub transcripts: Vec<Transcript>,
99}
100
101#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
102pub struct EpisodeMedia {
103    url: String,
104    bytes: Option<u64>,
105    duration_ms: Option<u64>,
106}
107
108#[derive(Debug, Serialize, Deserialize)]
109pub(crate) struct EpisodeProgress {
110    pub media: EpisodeMedia,
111    pub position_ms: u64,
112    pub observed_duration_ms: Option<u64>,
113    pub completed: bool,
114}
115
116impl Episode {
117    pub fn media(&self) -> EpisodeMedia {
118        EpisodeMedia {
119            url: self.url.clone(),
120            bytes: self.bytes,
121            duration_ms: self.duration_ms,
122        }
123    }
124
125    pub(crate) fn mark(&mut self, played: bool) {
126        self.completed = played;
127        self.position_ms = if played {
128            self.observed_duration_ms
129                .or(self.duration_ms)
130                .unwrap_or(self.position_ms)
131        } else {
132            0
133        };
134    }
135
136    pub(crate) fn progress(&self) -> EpisodeProgress {
137        EpisodeProgress {
138            media: self.media(),
139            position_ms: self.position_ms,
140            observed_duration_ms: self.observed_duration_ms,
141            completed: self.completed,
142        }
143    }
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
147#[serde(default)]
148pub struct Download {
149    #[serde(skip)]
150    pub cleanup_eligible: bool,
151    pub total_bytes: Option<u64>,
152    pub bytes_per_second: u64,
153    pub retries: u8,
154    pub retry_at: Option<String>,
155    pub enqueued_at: Option<String>,
156    pub generation: u64,
157    pub url: String,
158    pub media: Option<EpisodeMedia>,
159    pub episode_id: String,
160    pub state: String,
161    pub bytes: u64,
162    pub etag: Option<String>,
163    pub modified: Option<String>,
164    pub path: String,
165    pub error: Option<String>,
166}
167
168#[derive(Clone, Copy, Debug, PartialEq, Eq)]
169enum DownloadState<'a> {
170    Queued,
171    Downloading,
172    Paused,
173    Cancelled,
174    Failed,
175    Complete,
176    Removed,
177    Unknown(&'a str),
178}
179impl<'a> DownloadState<'a> {
180    fn as_str(self) -> &'a str {
181        match self {
182            Self::Queued => "queued",
183            Self::Downloading => "downloading",
184            Self::Paused => "paused",
185            Self::Cancelled => "cancelled",
186            Self::Failed => "failed",
187            Self::Complete => "complete",
188            Self::Removed => "removed",
189            Self::Unknown(raw) => raw,
190        }
191    }
192}
193
194impl Download {
195    fn phase(&self) -> DownloadState<'_> {
196        match self.state.as_str() {
197            "queued" => DownloadState::Queued,
198            "downloading" => DownloadState::Downloading,
199            "paused" => DownloadState::Paused,
200            "cancelled" => DownloadState::Cancelled,
201            "failed" => DownloadState::Failed,
202            "complete" => DownloadState::Complete,
203            "removed" => DownloadState::Removed,
204            raw => DownloadState::Unknown(raw),
205        }
206    }
207    fn set_phase(&mut self, phase: DownloadState<'_>) {
208        self.state = phase.as_str().into();
209    }
210
211    pub(crate) fn matches_media(&self, episode: &Episode) -> bool {
212        self.url == episode.url && self.media.as_ref() == Some(&episode.media())
213    }
214
215    pub(crate) fn offline_path(&self, episode: &Episode) -> Option<&str> {
216        self.offline_path_if(episode, |path| std::path::Path::new(path).is_file())
217    }
218
219    fn offline_path_if(
220        &self,
221        episode: &Episode,
222        is_file: impl FnOnce(&str) -> bool,
223    ) -> Option<&str> {
224        (self.phase() == DownloadState::Complete
225            && self.matches_media(episode)
226            && is_file(&self.path))
227        .then_some(self.path.as_str())
228    }
229}
230
231pub(crate) use storage::migrate;
232pub(crate) use storage::migrate_episode_order;
233pub(crate) use storage::migrate_library;
234pub(crate) use storage::register_functions;
235
236pub use commands::{parse_time, refresh};
237
238#[derive(Debug, Clone, clap::Subcommand)]
239pub enum QueueAction {
240    Start {
241        id: String,
242        #[arg(long)]
243        auto_next: bool,
244    },
245    Next {
246        id: String,
247        #[arg(skip)]
248        after: Option<String>,
249    },
250    List,
251    Add {
252        id: String,
253    },
254    Remove {
255        id: String,
256    },
257    Move {
258        id: String,
259        position: usize,
260    },
261    #[command(skip)]
262    MoveAdjacent {
263        id: String,
264        up: bool,
265    },
266    Clear,
267    Play {
268        #[arg(long)]
269        auto_next: bool,
270    },
271}
272
273pub fn valid_speed(rate: f64) -> anyhow::Result<f64> {
274    if !rate.is_finite() || !(0.5..=3.).contains(&rate) {
275        return Err(error(crate::t!("podcast_invalid_speed")));
276    }
277    Ok(rate)
278}
279
280pub(super) fn page_result<T: Serialize>(
281    items: &[T],
282    total: usize,
283    p: crate::model::Page,
284) -> serde_json::Value {
285    serde_json::json!({
286        "items": items,
287        "total": total,
288        "offset": p.offset,
289        "limit": if p.all { None } else { Some(p.limit) },
290        "has_more": p.offset.saturating_add(items.len()) < total,
291    })
292}
293
294pub(super) fn episode_details(
295    e: &Episode,
296    feed_title: &str,
297    author: &str,
298    saved: bool,
299    queued: bool,
300    download: Option<&Download>,
301    is_file: impl FnOnce(&str) -> bool,
302) -> serde_json::Value {
303    let mut value = serde_json::json!(e);
304    value["author"] = serde_json::json!(author);
305    value["feed_title"] = serde_json::json!(feed_title);
306    value["saved"] = serde_json::json!(saved);
307    value["queued"] = serde_json::json!(queued);
308    if let Some(d) = download {
309        value["download_state"] = serde_json::json!(if d.phase() == DownloadState::Complete
310            && d.offline_path_if(e, is_file).is_none()
311        {
312            "stale"
313        } else {
314            &d.state
315        });
316    }
317    value
318}
319
320#[cfg(test)]
321pub(crate) use commands::opml_for_test;
322#[cfg(test)]
323pub(crate) use feed::{parse as parse_feed_for_test, parse_reader_for_test};
324pub(crate) mod progressive;
325mod runtime;
326pub(crate) use runtime::{BrowsePage, BrowseSnapshot, Runtime};
327
328pub(crate) fn sanitize_output(value: &mut serde_json::Value) {
329    match value {
330        serde_json::Value::String(s) => *s = crate::clean_text(s),
331        serde_json::Value::Array(a) => a.iter_mut().for_each(sanitize_output),
332        serde_json::Value::Object(o) => o.values_mut().for_each(sanitize_output),
333        _ => {}
334    }
335}
336
337/// Human-readable podcast output; machine callers retain the JSON contracts.
338pub fn text_output(value: &serde_json::Value) -> String {
339    if let Some(rows) = value.get("items").unwrap_or(value).as_array() {
340        if rows.is_empty() {
341            return String::new();
342        }
343        let first = &rows[0];
344        let columns: &[&str] = if first.get("episode_id").is_some() {
345            &["title", "state", "bytes", "total_bytes", "episode_id"]
346        } else if first.get("feed_id").is_some() {
347            &[
348                "title",
349                "published",
350                "position_ms",
351                "duration_ms",
352                "completed",
353                "id",
354            ]
355        } else if first.get("subscribed").is_some() {
356            &["title", "author", "unplayed_count", "id"]
357        } else if first.get("chartRank").is_some() {
358            &[
359                "chartRank",
360                "collectionName",
361                "artistName",
362                "collectionViewUrl",
363            ]
364        } else if first.get("collectionName").is_some() {
365            &["collectionName", "artistName", "feedUrl"]
366        } else if first.get("command").is_some() {
367            &["title", "command"]
368        } else if first.get("ok").is_some() {
369            &["id", "ok", "error"]
370        } else {
371            &[]
372        };
373        if !columns.is_empty() {
374            let mut lines = vec![columns.join("\t")];
375            for row in rows {
376                lines.push(
377                    columns
378                        .iter()
379                        .map(|key| {
380                            let value = if *key == "state" && row["download_state"].is_string() {
381                                &row["download_state"]
382                            } else {
383                                &row[*key]
384                            };
385                            if value.is_null() {
386                                "—".into()
387                            } else {
388                                crate::clean_text(
389                                    &value
390                                        .as_str()
391                                        .map(str::to_owned)
392                                        .unwrap_or_else(|| value.to_string()),
393                                )
394                                .replace(['\n', '\t'], " ")
395                            }
396                        })
397                        .collect::<Vec<_>>()
398                        .join("\t"),
399                );
400            }
401            return lines.join("\n");
402        }
403    }
404    fn row(v: &serde_json::Value) -> String {
405        match v {
406            serde_json::Value::String(s) => s.clone(),
407            serde_json::Value::Object(fields) => fields
408                .iter()
409                .filter(|(_, v)| !v.is_null())
410                .map(|(key, value)| format!("{}: {}", key, text_output(value)))
411                .collect::<Vec<_>>()
412                .join("\n"),
413            other => other.to_string(),
414        }
415    }
416    if let Some(rows) = value.get("items").unwrap_or(value).as_array() {
417        rows.iter().map(row).collect::<Vec<_>>().join("\n")
418    } else {
419        row(value)
420    }
421}
422
423#[cfg(test)]
424mod download_state_tests {
425    use super::*;
426    #[test]
427    fn legacy_and_unknown_download_states_roundtrip_without_becoming_runnable() {
428        for raw in ["", "deferred-v2"] {
429            let json = if raw.is_empty() {
430                serde_json::json!({})
431            } else {
432                serde_json::json!({"state":raw})
433            };
434            let d: Download = serde_json::from_value(json).unwrap();
435            assert_eq!(d.phase(), DownloadState::Unknown(raw));
436            assert_eq!(serde_json::to_value(&d).unwrap()["state"], raw);
437        }
438        for state in [
439            DownloadState::Queued,
440            DownloadState::Downloading,
441            DownloadState::Paused,
442            DownloadState::Cancelled,
443            DownloadState::Failed,
444            DownloadState::Complete,
445            DownloadState::Removed,
446        ] {
447            let mut d = Download::default();
448            d.set_phase(state);
449            assert_eq!(d.phase(), state);
450        }
451    }
452}