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