1mod commands;
3pub mod directory;
4mod extras;
5mod library;
6pub use extras::{Bookmark, Chapter, ShowSettings};
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, QueueAction, 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};
23pub use transcript::Transcript;
24
25pub(crate) fn error(detail: &str) -> anyhow::Error {
26 DomainError::new(ErrorCode::PodcastFailed)
27 .with("detail", detail)
28 .into()
29}
30#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
31#[serde(default)]
32pub struct Feed {
33 pub failures: u32,
34 pub new_feed_url: Option<String>,
35 pub revision: u64,
36 pub id: String,
37 pub url: String,
38 pub title: String,
39 pub author: String,
40 pub description: String,
41 pub image: String,
42 pub website: String,
43 pub subscribed: bool,
44 pub etag: Option<String>,
45 pub modified: Option<String>,
46 pub refreshed_at: Option<String>,
47 pub error: Option<String>,
48}
49#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
50pub struct Episode {
51 #[serde(default)]
52 pub chapters: Vec<Chapter>,
53 #[serde(default)]
54 pub chapters_url: Option<String>,
55 #[serde(default)]
56 pub source_order: Option<u64>,
57 pub id: String,
58 pub feed_id: String,
59 pub guid: Option<String>,
60 pub title: String,
61 pub published: Option<String>,
62 pub description: String,
63 pub website: String,
64 pub url: String,
65 pub mime: String,
66 pub bytes: Option<u64>,
67 pub duration_ms: Option<u64>,
68 pub position_ms: u64,
69 pub observed_duration_ms: Option<u64>,
70 pub completed: bool,
71 #[serde(default)]
72 pub transcripts: Vec<Transcript>,
73}
74
75#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
76pub struct EpisodeMedia {
77 url: String,
78 bytes: Option<u64>,
79 duration_ms: Option<u64>,
80}
81
82#[derive(Debug, Serialize, Deserialize)]
83pub(crate) struct EpisodeProgress {
84 pub media: EpisodeMedia,
85 pub position_ms: u64,
86 pub observed_duration_ms: Option<u64>,
87 pub completed: bool,
88}
89
90impl Episode {
91 pub fn media(&self) -> EpisodeMedia {
92 EpisodeMedia {
93 url: self.url.clone(),
94 bytes: self.bytes,
95 duration_ms: self.duration_ms,
96 }
97 }
98
99 pub(crate) fn mark(&mut self, played: bool) {
100 self.completed = played;
101 self.position_ms = if played {
102 self.observed_duration_ms
103 .or(self.duration_ms)
104 .unwrap_or(self.position_ms)
105 } else {
106 0
107 };
108 }
109
110 pub(crate) fn progress(&self) -> EpisodeProgress {
111 EpisodeProgress {
112 media: self.media(),
113 position_ms: self.position_ms,
114 observed_duration_ms: self.observed_duration_ms,
115 completed: self.completed,
116 }
117 }
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
121#[serde(default)]
122pub struct Download {
123 #[serde(skip)]
124 pub cleanup_eligible: bool,
125 pub total_bytes: Option<u64>,
126 pub bytes_per_second: u64,
127 pub retries: u8,
128 pub retry_at: Option<String>,
129 pub enqueued_at: Option<String>,
130 pub generation: u64,
131 pub url: String,
132 pub media: Option<EpisodeMedia>,
133 pub episode_id: String,
134 pub state: String,
135 pub bytes: u64,
136 pub etag: Option<String>,
137 pub modified: Option<String>,
138 pub path: String,
139 pub error: Option<String>,
140}
141
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143enum DownloadState<'a> {
144 Queued,
145 Downloading,
146 Paused,
147 Cancelled,
148 Failed,
149 Complete,
150 Removed,
151 Unknown(&'a str),
152}
153impl<'a> DownloadState<'a> {
154 fn as_str(self) -> &'a str {
155 match self {
156 Self::Queued => "queued",
157 Self::Downloading => "downloading",
158 Self::Paused => "paused",
159 Self::Cancelled => "cancelled",
160 Self::Failed => "failed",
161 Self::Complete => "complete",
162 Self::Removed => "removed",
163 Self::Unknown(raw) => raw,
164 }
165 }
166}
167
168impl Download {
169 fn phase(&self) -> DownloadState<'_> {
170 match self.state.as_str() {
171 "queued" => DownloadState::Queued,
172 "downloading" => DownloadState::Downloading,
173 "paused" => DownloadState::Paused,
174 "cancelled" => DownloadState::Cancelled,
175 "failed" => DownloadState::Failed,
176 "complete" => DownloadState::Complete,
177 "removed" => DownloadState::Removed,
178 raw => DownloadState::Unknown(raw),
179 }
180 }
181 fn set_phase(&mut self, phase: DownloadState<'_>) {
182 self.state = phase.as_str().into();
183 }
184
185 pub(crate) fn matches_media(&self, episode: &Episode) -> bool {
186 self.url == episode.url && self.media.as_ref() == Some(&episode.media())
187 }
188
189 pub(crate) fn offline_path(&self, episode: &Episode) -> Option<&str> {
190 self.offline_path_if(episode, |path| std::path::Path::new(path).is_file())
191 }
192
193 fn offline_path_if(
194 &self,
195 episode: &Episode,
196 is_file: impl FnOnce(&str) -> bool,
197 ) -> Option<&str> {
198 (self.phase() == DownloadState::Complete
199 && self.matches_media(episode)
200 && is_file(&self.path))
201 .then_some(self.path.as_str())
202 }
203}
204
205pub(crate) use storage::migrate;
206pub(crate) use storage::migrate_episode_order;
207pub(crate) use storage::migrate_library;
208pub(crate) use storage::register_functions;
209
210pub use commands::{parse_time, refresh, valid_speed};
211
212pub(crate) mod progressive;
213mod runtime;
214pub(crate) use runtime::{BrowsePage, BrowseSnapshot, Runtime};
215
216pub(crate) fn sanitize_output(value: &mut serde_json::Value) {
217 match value {
218 serde_json::Value::String(s) => *s = crate::clean_text(s),
219 serde_json::Value::Array(a) => a.iter_mut().for_each(sanitize_output),
220 serde_json::Value::Object(o) => o.values_mut().for_each(sanitize_output),
221 _ => {}
222 }
223}
224
225pub fn text_output(value: &serde_json::Value) -> String {
227 if let Some(rows) = value.get("items").unwrap_or(value).as_array() {
228 if rows.is_empty() {
229 return String::new();
230 }
231 let first = &rows[0];
232 let columns: &[&str] = if first.get("episode_id").is_some() {
233 &["title", "state", "bytes", "total_bytes", "episode_id"]
234 } else if first.get("feed_id").is_some() {
235 &[
236 "title",
237 "published",
238 "position_ms",
239 "duration_ms",
240 "completed",
241 "id",
242 ]
243 } else if first.get("subscribed").is_some() {
244 &["title", "author", "unplayed_count", "id"]
245 } else if first.get("chartRank").is_some() {
246 &[
247 "chartRank",
248 "collectionName",
249 "artistName",
250 "collectionViewUrl",
251 ]
252 } else if first.get("collectionName").is_some() {
253 &["collectionName", "artistName", "feedUrl"]
254 } else if first.get("command").is_some() {
255 &["title", "command"]
256 } else if first.get("ok").is_some() {
257 &["id", "ok", "error"]
258 } else {
259 &[]
260 };
261 if !columns.is_empty() {
262 let mut lines = vec![columns.join("\t")];
263 for row in rows {
264 lines.push(
265 columns
266 .iter()
267 .map(|key| {
268 let value = if *key == "state" && row["download_state"].is_string() {
269 &row["download_state"]
270 } else {
271 &row[*key]
272 };
273 if value.is_null() {
274 "—".into()
275 } else {
276 crate::clean_text(
277 &value
278 .as_str()
279 .map(str::to_owned)
280 .unwrap_or_else(|| value.to_string()),
281 )
282 .replace(['\n', '\t'], " ")
283 }
284 })
285 .collect::<Vec<_>>()
286 .join("\t"),
287 );
288 }
289 return lines.join("\n");
290 }
291 }
292 fn row(v: &serde_json::Value) -> String {
293 match v {
294 serde_json::Value::String(s) => s.clone(),
295 serde_json::Value::Object(fields) => fields
296 .iter()
297 .filter(|(_, v)| !v.is_null())
298 .map(|(key, value)| format!("{}: {}", key, text_output(value)))
299 .collect::<Vec<_>>()
300 .join("\n"),
301 other => other.to_string(),
302 }
303 }
304 if let Some(rows) = value.get("items").unwrap_or(value).as_array() {
305 rows.iter().map(row).collect::<Vec<_>>().join("\n")
306 } else {
307 row(value)
308 }
309}
310
311#[cfg(test)]
312mod download_state_tests {
313 use super::*;
314 #[test]
315 fn legacy_and_unknown_download_states_roundtrip_without_becoming_runnable() {
316 for raw in ["", "deferred-v2"] {
317 let json = if raw.is_empty() {
318 serde_json::json!({})
319 } else {
320 serde_json::json!({"state":raw})
321 };
322 let d: Download = serde_json::from_value(json).unwrap();
323 assert_eq!(d.phase(), DownloadState::Unknown(raw));
324 assert_eq!(serde_json::to_value(&d).unwrap()["state"], raw);
325 }
326 for state in [
327 DownloadState::Queued,
328 DownloadState::Downloading,
329 DownloadState::Paused,
330 DownloadState::Cancelled,
331 DownloadState::Failed,
332 DownloadState::Complete,
333 DownloadState::Removed,
334 ] {
335 let mut d = Download::default();
336 d.set_phase(state);
337 assert_eq!(d.phase(), state);
338 }
339 }
340}