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, Chapter, ShowSettings};
7pub use library::LibraryQuery;
8mod download;
9mod download_files;
10mod feed;
11mod storage;
12pub mod transcript;
13use crate::error::{DomainError, ErrorCode};
14pub use commands::{Action, DownloadAction, QueueAction, manage};
15pub(crate) use download::set_cli_progress;
16pub use download::{download, download_path};
17pub use feed::{Preview, discover, fetch, search};
18use serde::{Deserialize, Serialize};
19pub use transcript::Transcript;
20
21pub(crate) fn error(detail: &str) -> anyhow::Error {
22    DomainError::new(ErrorCode::PodcastFailed)
23        .with("detail", detail)
24        .into()
25}
26#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
27#[serde(default)]
28pub struct Feed {
29    pub failures: u32,
30    pub new_feed_url: Option<String>,
31    pub revision: u64,
32    pub id: String,
33    pub url: String,
34    pub title: String,
35    pub author: String,
36    pub description: String,
37    pub image: String,
38    pub website: String,
39    pub subscribed: bool,
40    pub etag: Option<String>,
41    pub modified: Option<String>,
42    pub refreshed_at: Option<String>,
43    pub error: Option<String>,
44}
45#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
46pub struct Episode {
47    #[serde(default)]
48    pub chapters: Vec<Chapter>,
49    #[serde(default)]
50    pub chapters_url: Option<String>,
51    #[serde(default)]
52    pub source_order: Option<u64>,
53    pub id: String,
54    pub feed_id: String,
55    pub guid: Option<String>,
56    pub title: String,
57    pub published: Option<String>,
58    pub description: String,
59    pub website: String,
60    pub url: String,
61    pub mime: String,
62    pub bytes: Option<u64>,
63    pub duration_ms: Option<u64>,
64    pub position_ms: u64,
65    pub observed_duration_ms: Option<u64>,
66    pub completed: bool,
67    #[serde(default)]
68    pub transcripts: Vec<Transcript>,
69}
70
71#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
72pub struct EpisodeMedia {
73    url: String,
74    bytes: Option<u64>,
75    duration_ms: Option<u64>,
76}
77
78#[derive(Debug, Serialize, Deserialize)]
79pub(crate) struct EpisodeProgress {
80    pub media: EpisodeMedia,
81    pub position_ms: u64,
82    pub observed_duration_ms: Option<u64>,
83    pub completed: bool,
84}
85
86impl Episode {
87    pub fn media(&self) -> EpisodeMedia {
88        EpisodeMedia {
89            url: self.url.clone(),
90            bytes: self.bytes,
91            duration_ms: self.duration_ms,
92        }
93    }
94
95    pub(crate) fn progress(&self) -> EpisodeProgress {
96        EpisodeProgress {
97            media: self.media(),
98            position_ms: self.position_ms,
99            observed_duration_ms: self.observed_duration_ms,
100            completed: self.completed,
101        }
102    }
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
106#[serde(default)]
107pub struct Download {
108    #[serde(skip)]
109    pub cleanup_eligible: bool,
110    pub total_bytes: Option<u64>,
111    pub bytes_per_second: u64,
112    pub retries: u8,
113    pub retry_at: Option<String>,
114    pub enqueued_at: Option<String>,
115    pub generation: u64,
116    pub url: String,
117    pub media: Option<EpisodeMedia>,
118    pub episode_id: String,
119    pub state: String,
120    pub bytes: u64,
121    pub etag: Option<String>,
122    pub modified: Option<String>,
123    pub path: String,
124    pub error: Option<String>,
125}
126
127impl Download {
128    pub(crate) fn matches_media(&self, episode: &Episode) -> bool {
129        self.url == episode.url && self.media.as_ref() == Some(&episode.media())
130    }
131
132    pub(crate) fn offline_path(&self, episode: &Episode) -> Option<&str> {
133        self.offline_path_if(episode, |path| std::path::Path::new(path).is_file())
134    }
135
136    fn offline_path_if(
137        &self,
138        episode: &Episode,
139        is_file: impl FnOnce(&str) -> bool,
140    ) -> Option<&str> {
141        (self.state == "complete" && self.matches_media(episode) && is_file(&self.path))
142            .then_some(self.path.as_str())
143    }
144}
145
146pub(crate) use storage::migrate;
147pub(crate) use storage::migrate_episode_order;
148pub(crate) use storage::migrate_library;
149pub(crate) use storage::register_functions;
150
151pub use commands::{parse_time, refresh, valid_speed};
152
153pub(crate) mod progressive;
154mod runtime;
155pub(crate) use runtime::{BrowsePage, BrowseSnapshot, Runtime};
156
157pub(crate) fn sanitize_output(value: &mut serde_json::Value) {
158    match value {
159        serde_json::Value::String(s) => *s = crate::clean_text(s),
160        serde_json::Value::Array(a) => a.iter_mut().for_each(sanitize_output),
161        serde_json::Value::Object(o) => o.values_mut().for_each(sanitize_output),
162        _ => {}
163    }
164}
165
166/// Human-readable podcast output; machine callers retain the JSON contracts.
167pub fn text_output(value: &serde_json::Value) -> String {
168    if let Some(rows) = value.get("items").unwrap_or(value).as_array() {
169        if rows.is_empty() {
170            return String::new();
171        }
172        let first = &rows[0];
173        let columns: &[&str] = if first.get("episode_id").is_some() {
174            &["title", "state", "bytes", "total_bytes", "episode_id"]
175        } else if first.get("feed_id").is_some() {
176            &[
177                "title",
178                "published",
179                "position_ms",
180                "duration_ms",
181                "completed",
182                "id",
183            ]
184        } else if first.get("subscribed").is_some() {
185            &["title", "author", "unplayed_count", "id"]
186        } else if first.get("chartRank").is_some() {
187            &[
188                "chartRank",
189                "collectionName",
190                "artistName",
191                "collectionViewUrl",
192            ]
193        } else if first.get("collectionName").is_some() {
194            &["collectionName", "artistName", "feedUrl"]
195        } else if first.get("command").is_some() {
196            &["title", "command"]
197        } else if first.get("ok").is_some() {
198            &["id", "ok", "error"]
199        } else {
200            &[]
201        };
202        if !columns.is_empty() {
203            let mut lines = vec![columns.join("\t")];
204            for row in rows {
205                lines.push(
206                    columns
207                        .iter()
208                        .map(|key| {
209                            let value = if *key == "state" && row["download_state"].is_string() {
210                                &row["download_state"]
211                            } else {
212                                &row[*key]
213                            };
214                            if value.is_null() {
215                                "—".into()
216                            } else {
217                                crate::clean_text(
218                                    &value
219                                        .as_str()
220                                        .map(str::to_owned)
221                                        .unwrap_or_else(|| value.to_string()),
222                                )
223                                .replace(['\n', '\t'], " ")
224                            }
225                        })
226                        .collect::<Vec<_>>()
227                        .join("\t"),
228                );
229            }
230            return lines.join("\n");
231        }
232    }
233    fn row(v: &serde_json::Value) -> String {
234        match v {
235            serde_json::Value::String(s) => s.clone(),
236            serde_json::Value::Object(fields) => fields
237                .iter()
238                .filter(|(_, v)| !v.is_null())
239                .map(|(key, value)| format!("{}: {}", key, text_output(value)))
240                .collect::<Vec<_>>()
241                .join("\n"),
242            other => other.to_string(),
243        }
244    }
245    if let Some(rows) = value.get("items").unwrap_or(value).as_array() {
246        rows.iter().map(row).collect::<Vec<_>>().join("\n")
247    } else {
248        row(value)
249    }
250}