Skip to main content

radio_cli/podcast/
extras.rs

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