radio_cli/podcast/
extras.rs1use super::*;
3use crate::{config::Config, store::Store};
4use anyhow::Result;
5use rusqlite::params;
6use serde_json::{Value, json};
7use std::sync::{Arc, atomic::AtomicBool};
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct Bookmark {
11 pub id: String,
12 pub episode_id: String,
13 pub position_ms: u64,
14 pub note: String,
15}
16impl Store {
17 pub fn podcast_set_setting(&self, id: &str, key: &str, value: &str) -> Result<ShowSettings> {
18 let id = self.podcast_feed_id(id)?;
19 let tx = rusqlite::Transaction::new_unchecked(
20 &self.conn,
21 rusqlite::TransactionBehavior::Immediate,
22 )?;
23 let mut settings = serde_json::to_value(self.podcast_settings(&id)?)?;
24 if settings.get(key).is_none() {
25 return Err(error(crate::t!("podcast_invalid_setting")));
26 }
27 settings[key] = if value == "inherit"
28 && matches!(key, "speed" | "sort" | "skip_back" | "skip_forward")
29 {
30 Value::Null
31 } else if key == "sort" {
32 json!(value)
33 } else {
34 serde_json::from_str(value).map_err(|_| error(crate::t!("podcast_invalid_setting")))?
35 };
36 let settings: ShowSettings = serde_json::from_value(settings)
37 .map_err(|_| error(crate::t!("podcast_invalid_setting")))?;
38 if let Some(speed) = settings.speed {
39 valid_speed(speed)?;
40 }
41 if settings
42 .sort
43 .as_deref()
44 .is_some_and(|s| !matches!(s, "newest" | "oldest" | "title"))
45 || [
46 settings.skip_intro,
47 settings.skip_outro,
48 settings.completion_seconds,
49 settings.skip_back.unwrap_or(15),
50 settings.skip_forward.unwrap_or(15),
51 ]
52 .iter()
53 .any(|s| *s > 86400)
54 {
55 return Err(error(crate::t!("podcast_invalid_setting")));
56 }
57 self.set_meta(
58 &format!("podcast_settings:{id}"),
59 &serde_json::to_string(&settings)?,
60 )?;
61 self.conn.execute("UPDATE podcast_revision SET n=n+1", [])?;
62 tx.commit()?;
63 Ok(settings)
64 }
65 pub fn podcast_bookmarks(&self, episode: &str) -> Result<Vec<Bookmark>> {
66 let episode = self.podcast_episode_id(episode)?;
67 let mut stmt = self.conn.prepare("SELECT id,episode_id,position_ms,note FROM podcast_bookmarks WHERE episode_id=?1 ORDER BY position_ms,id")?;
68 Ok(stmt
69 .query_map([episode], |r| {
70 Ok(Bookmark {
71 id: r.get(0)?,
72 episode_id: r.get(1)?,
73 position_ms: r.get(2)?,
74 note: r.get(3)?,
75 })
76 })?
77 .collect::<rusqlite::Result<Vec<_>>>()?)
78 }
79 pub fn podcast_add_bookmark(&self, id: &str, position_ms: u64, note: &str) -> Result<Bookmark> {
80 let id = self.podcast_episode_id(id)?;
81 let b = Bookmark {
82 id: uuid::Uuid::new_v4().to_string(),
83 episode_id: id,
84 position_ms,
85 note: crate::clean_text(note),
86 };
87 self.conn.execute(
88 "INSERT INTO podcast_bookmarks VALUES (?1,?2,?3,?4)",
89 params![
90 b.id,
91 b.episode_id,
92 b.position_ms.min(i64::MAX as u64),
93 b.note
94 ],
95 )?;
96 Ok(b)
97 }
98 pub fn podcast_edit_bookmark(&self, id: &str, note: Option<&str>) -> Result<()> {
99 let changed = if let Some(note) = note {
100 self.conn.execute(
101 "UPDATE podcast_bookmarks SET note=?2 WHERE id=?1",
102 params![id, crate::clean_text(note)],
103 )?
104 } else {
105 self.conn
106 .execute("DELETE FROM podcast_bookmarks WHERE id=?1", [id])?
107 };
108 if changed == 0 {
109 return Err(error(crate::t!("podcast_not_found")));
110 }
111 Ok(())
112 }
113}
114pub(super) fn chapters(config: &Config, e: &Episode, stop: &Arc<AtomicBool>) -> Result<Value> {
115 let mut chapters = e.chapters.clone();
116 if let Some(url) = &e.chapters_url {
117 let remote = (|| -> Result<Vec<Chapter>> {
118 let response = super::feed::client(config)?
119 .get(url)
120 .send()
121 .map_err(super::feed::network_error)?;
122 let (_, data) = super::feed::body(response, stop)?;
123 let value: Value = serde_json::from_slice(&data)?;
124 let rows = value["chapters"]
125 .as_array()
126 .ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?;
127 if rows.len() > 10000 {
128 return Err(error(crate::t!("podcast_limit")));
129 }
130 let mut result = Vec::new();
131 for row in rows {
132 let seconds = row["startTime"]
133 .as_f64()
134 .filter(|n| n.is_finite() && *n >= 0. && *n < i64::MAX as f64 / 1000.)
135 .ok_or_else(|| error(crate::t!("podcast_invalid_time")))?;
136 result.push(Chapter {
137 title: crate::clean_text(row["title"].as_str().unwrap_or("")),
138 position_ms: (seconds * 1000.) as u64,
139 });
140 }
141 Ok(result)
142 })();
143 match remote {
144 Ok(rows) if !rows.is_empty() => chapters = rows,
145 Err(err) if chapters.is_empty() => return Err(err),
146 _ => {}
147 }
148 }
149 chapters.sort_by_key(|c| c.position_ms);
150 chapters.dedup_by_key(|c| c.position_ms);
151 let items: Vec<_> = chapters
152 .iter()
153 .map(|c| json!({"id":e.id,"title":c.title,"kind":"chapter","position_ms":c.position_ms}))
154 .collect();
155 Ok(json!({"items":items,"total":items.len(),"episode_id":e.id}))
156}