Skip to main content

radio_cli/podcast/
storage.rs

1use super::*;
2use crate::store::Store;
3use anyhow::Result;
4use rusqlite::{OptionalExtension, TransactionBehavior, params};
5
6const EPISODE_NEWEST_ORDER: &str = "CASE WHEN json_valid(json) THEN json_extract(json,'$.published') END DESC,
7    CASE WHEN json_valid(json) THEN COALESCE(json_extract(json,'$.source_order'),legacy_order) END,id";
8
9fn episode_page_sql() -> String {
10    format!(
11        "SELECT e.json,p.position_ms,p.duration_ms,p.completed FROM podcast_episodes e
12         LEFT JOIN podcast_progress p ON p.episode_id=e.id WHERE e.feed_id=?1
13         AND (?2='' OR instr(podcast_lower(json_extract(e.json,'$.title')),?2)>0)
14         ORDER BY {EPISODE_NEWEST_ORDER} LIMIT ?3 OFFSET ?4",
15    )
16}
17
18pub(crate) fn register_functions(conn: &rusqlite::Connection) -> Result<()> {
19    use rusqlite::functions::FunctionFlags;
20
21    conn.create_scalar_function(
22        "podcast_lower",
23        1,
24        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
25        |context| Ok(context.get::<String>(0)?.to_lowercase()),
26    )?;
27    Ok(())
28}
29
30pub(super) fn register_download_availability(
31    conn: &rusqlite::Connection,
32    files: std::sync::Arc<super::download_files::DownloadFiles>,
33) -> Result<()> {
34    use rusqlite::{Error, functions::FunctionFlags};
35
36    // Availability also depends on the filesystem, so this function is not deterministic.
37    conn.create_scalar_function(
38        "podcast_download_available",
39        2,
40        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DIRECTONLY,
41        move |context| {
42            let Some(download) = context.get::<Option<String>>(0)? else {
43                return Ok(false);
44            };
45            let d: Download = serde_json::from_str(&download)
46                .map_err(|e| Error::UserFunctionError(Box::new(e)))?;
47            if d.state != "complete" {
48                return Ok(false);
49            }
50            let episode = context.get::<String>(1)?;
51            let e: Episode = serde_json::from_str(&episode)
52                .map_err(|e| Error::UserFunctionError(Box::new(e)))?;
53            Ok(d.offline_path_if(&e, |path| files.observed_file(path))
54                .is_some())
55        },
56    )?;
57    Ok(())
58}
59
60pub(crate) fn migrate(conn: &rusqlite::Connection) -> Result<()> {
61    conn.execute_batch("CREATE TABLE IF NOT EXISTS podcast_feeds(id TEXT PRIMARY KEY,url TEXT NOT NULL UNIQUE,subscribed INTEGER NOT NULL,json TEXT NOT NULL);
62    CREATE TABLE IF NOT EXISTS podcast_aliases(url TEXT PRIMARY KEY,feed_id TEXT NOT NULL REFERENCES podcast_feeds(id));
63    CREATE TABLE IF NOT EXISTS podcast_episodes(id TEXT PRIMARY KEY,feed_id TEXT NOT NULL REFERENCES podcast_feeds(id),identity TEXT NOT NULL,json TEXT NOT NULL,UNIQUE(feed_id,identity));
64    CREATE TABLE IF NOT EXISTS podcast_progress(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id),position_ms INTEGER NOT NULL,duration_ms INTEGER,completed INTEGER NOT NULL,updated_at TEXT NOT NULL);
65    CREATE TABLE IF NOT EXISTS podcast_history(id INTEGER PRIMARY KEY,episode_id TEXT NOT NULL REFERENCES podcast_episodes(id),played_at TEXT NOT NULL);
66    CREATE TABLE IF NOT EXISTS podcast_downloads(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id),json TEXT NOT NULL);
67    CREATE TABLE IF NOT EXISTS podcast_queue(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id),position INTEGER NOT NULL);
68    CREATE INDEX IF NOT EXISTS podcast_feed_episodes ON podcast_episodes(feed_id);")?;
69    Ok(())
70}
71
72pub(crate) fn migrate_library(conn: &rusqlite::Connection) -> Result<()> {
73    conn.execute_batch("CREATE TABLE IF NOT EXISTS podcast_bookmarks(id TEXT PRIMARY KEY,episode_id TEXT NOT NULL REFERENCES podcast_episodes(id),position_ms INTEGER NOT NULL,note TEXT NOT NULL);
74    CREATE INDEX IF NOT EXISTS podcast_bookmark_episode ON podcast_bookmarks(episode_id,position_ms);
75    CREATE TABLE IF NOT EXISTS podcast_saved(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id));
76    CREATE TABLE IF NOT EXISTS podcast_inbox(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id));")?;
77    conn.execute_batch("CREATE TABLE IF NOT EXISTS podcast_revision(n INTEGER NOT NULL); INSERT INTO podcast_revision SELECT 0 WHERE NOT EXISTS(SELECT 1 FROM podcast_revision);
78        CREATE INDEX IF NOT EXISTS podcast_history_episode ON podcast_history(episode_id,played_at DESC);")?;
79    for table in [
80        "podcast_feeds",
81        "podcast_episodes",
82        "podcast_progress",
83        "podcast_downloads",
84        "podcast_queue",
85        "podcast_saved",
86        "podcast_inbox",
87        "podcast_bookmarks",
88        "podcast_history",
89    ] {
90        for operation in ["INSERT", "UPDATE", "DELETE"] {
91            conn.execute_batch(&format!("CREATE TRIGGER IF NOT EXISTS changed_{table}_{operation} AFTER {operation} ON {table} BEGIN UPDATE podcast_revision SET n=n+1; END;"))?;
92        }
93    }
94    Ok(())
95}
96
97pub(crate) fn migrate_episode_order(conn: &rusqlite::Connection) -> Result<()> {
98    // A rowid cannot appear in an index expression. Save the old fallback for
99    // episodes without a source position so existing pages keep their order.
100    conn.execute_batch(&format!(
101        "DROP INDEX IF EXISTS podcast_episode_dates;
102         ALTER TABLE podcast_episodes ADD COLUMN legacy_order INTEGER;
103         UPDATE podcast_episodes SET legacy_order=rowid
104         WHERE CASE WHEN json_valid(json) THEN json_extract(json,'$.source_order') IS NULL END;
105         CREATE INDEX podcast_episode_dates ON podcast_episodes(feed_id,{EPISODE_NEWEST_ORDER});"
106    ))?;
107    Ok(())
108}
109
110impl Store {
111    pub fn podcast_revision(&self) -> Result<u64> {
112        Ok(self
113            .conn
114            .query_row("SELECT n FROM podcast_revision", [], |r| r.get(0))?)
115    }
116    pub(crate) fn podcast_unplayed_count(&self, feed: &str) -> Result<usize> {
117        Ok(self.conn.query_row("SELECT count(*) FROM podcast_episodes e LEFT JOIN podcast_progress p ON p.episode_id=e.id WHERE e.feed_id=?1 AND COALESCE(p.completed,0)=0", [feed], |r| r.get(0))?)
118    }
119    pub fn podcast_feeds(&self) -> Result<Vec<Feed>> {
120        let mut stmt = self.conn.prepare("SELECT json FROM podcast_feeds WHERE subscribed=1 ORDER BY json_extract(json,'$.title'),id")?;
121        let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
122        rows.map(|r| Ok(serde_json::from_str(&r?)?)).collect()
123    }
124    pub fn podcast_feed_id(&self, value: &str) -> Result<String> {
125        let mut stmt = self.conn.prepare("SELECT id FROM podcast_feeds WHERE id=?1 OR json_extract(json,'$.title')=?1 ORDER BY id=?1 DESC,id")?;
126        let ids = stmt
127            .query_map([value], |r| r.get::<_, String>(0))?
128            .collect::<rusqlite::Result<Vec<_>>>()?;
129        match ids.as_slice() {
130            [id] => Ok(id.clone()),
131            [id, ..] if id == value => Ok(id.clone()),
132            [] => Err(error(crate::t!("podcast_not_found"))),
133            _ => Err(error(&format!(
134                "{}: {}",
135                crate::t!("podcast_ambiguous"),
136                ids.join(", ")
137            ))),
138        }
139    }
140    pub fn podcast_episode_id(&self, value: &str) -> Result<String> {
141        let exists: bool = self.conn.query_row(
142            "SELECT EXISTS(SELECT 1 FROM podcast_episodes WHERE id=?1)",
143            [value],
144            |r| r.get(0),
145        )?;
146        if exists {
147            return Ok(value.into());
148        }
149        let (feed, title) = value
150            .split_once("::")
151            .ok_or_else(|| error(crate::t!("podcast_not_found")))?;
152        let feed = self.podcast_feed_id(feed)?;
153        let mut stmt = self.conn.prepare("SELECT id FROM podcast_episodes WHERE feed_id=?1 AND json_extract(json,'$.title')=?2 ORDER BY id")?;
154        let ids = stmt
155            .query_map(params![feed, title], |r| r.get::<_, String>(0))?
156            .collect::<rusqlite::Result<Vec<_>>>()?;
157        match ids.as_slice() {
158            [id] => Ok(id.clone()),
159            [] => Err(error(crate::t!("podcast_not_found"))),
160            _ => Err(error(&format!(
161                "{}: {}",
162                crate::t!("podcast_ambiguous"),
163                ids.join(", ")
164            ))),
165        }
166    }
167    pub fn podcast_feed(&self, id: &str) -> Result<Feed> {
168        let id = self.podcast_feed_id(id)?;
169        let json: Option<String> = self
170            .conn
171            .query_row("SELECT json FROM podcast_feeds WHERE id=?1", [id], |r| {
172                r.get(0)
173            })
174            .optional()?;
175        Ok(serde_json::from_str(
176            &json.ok_or_else(|| error(crate::t!("podcast_not_found")))?,
177        )?)
178    }
179    pub fn podcast_by_url(&self, url: &str) -> Result<Option<Feed>> {
180        let id: Option<String> = self.conn.query_row("SELECT id FROM podcast_feeds WHERE url=?1 UNION SELECT feed_id FROM podcast_aliases WHERE url=?1 LIMIT 1",[url],|r|r.get(0)).optional()?;
181        id.map(|id| self.podcast_feed(&id)).transpose()
182    }
183    pub fn podcast_subscribe(&self, preview: &Preview, requested: &str) -> Result<Feed> {
184        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
185        let mut feed = self
186            .podcast_by_url(requested)?
187            .or(self.podcast_by_url(&preview.feed.url)?)
188            .unwrap_or_else(|| Feed {
189                id: uuid::Uuid::new_v4().to_string(),
190                ..Default::default()
191            });
192        let id = feed.id.clone();
193        let revision = feed.revision.saturating_add(1);
194        feed = preview.feed.clone();
195        feed.revision = revision;
196        feed.id = id;
197        feed.subscribed = true;
198        self.podcast_write(&feed)?;
199        for url in [requested, &feed.url] {
200            self.conn.execute(
201                "INSERT INTO podcast_aliases VALUES (?1,?2) ON CONFLICT(url) DO NOTHING",
202                params![url, feed.id],
203            )?;
204        }
205        self.podcast_merge(&feed.id, &preview.episodes, false)?;
206        tx.commit()?;
207        Ok(feed)
208    }
209    pub(crate) fn podcast_write(&self, feed: &Feed) -> Result<()> {
210        self.conn.execute("INSERT INTO podcast_feeds VALUES (?1,?2,?3,?4) ON CONFLICT(id) DO UPDATE SET url=excluded.url,subscribed=excluded.subscribed,json=excluded.json",params![feed.id,feed.url,feed.subscribed,serde_json::to_string(feed)?])?;
211        Ok(())
212    }
213    pub(crate) fn podcast_refresh_error(&self, f: &Feed) -> Result<()> {
214        self.conn.execute("UPDATE podcast_feeds SET json=?2 WHERE id=?1 AND subscribed=1 AND json_extract(json,'$.revision')=?3",params![f.id,serde_json::to_string(f)?,f.revision])?;
215        Ok(())
216    }
217    pub fn podcast_refresh_merge(&self, old: &Feed, preview: Option<Preview>) -> Result<()> {
218        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
219        let current = self.podcast_feed(&old.id)?;
220        if !current.subscribed || current.revision != old.revision {
221            return Ok(());
222        }
223        let mut feed = preview.as_ref().map(|p| p.feed.clone()).unwrap_or(current);
224        feed.id = old.id.clone();
225        feed.subscribed = true;
226        feed.error = None;
227        feed.failures = 0;
228        feed.revision = old.revision.saturating_add(1);
229        feed.refreshed_at = Some(chrono::Utc::now().to_rfc3339());
230        if self
231            .podcast_by_url(&feed.url)?
232            .is_some_and(|owner| owner.id != feed.id)
233        {
234            return Err(error(crate::t!("podcast_url_conflict")));
235        }
236        self.podcast_write(&feed)?;
237        self.conn.execute(
238            "INSERT OR IGNORE INTO podcast_aliases VALUES (?1,?2)",
239            params![feed.url, feed.id],
240        )?;
241        if let Some(p) = preview {
242            self.podcast_merge(&feed.id, &p.episodes, true)?;
243        }
244        tx.commit()?;
245        Ok(())
246    }
247    fn podcast_merge(&self, feed_id: &str, episodes: &[Episode], baseline: bool) -> Result<()> {
248        let settings = self.podcast_settings(feed_id)?;
249        for (order, item) in episodes.iter().enumerate() {
250            let identity = item
251                .guid
252                .as_ref()
253                .map(|g| format!("guid:{g}"))
254                .unwrap_or_else(|| format!("url:{}", item.url));
255            let old: Option<String> = self
256                .conn
257                .query_row(
258                    "SELECT json FROM podcast_episodes WHERE feed_id=?1 AND identity=?2",
259                    params![feed_id, identity],
260                    |r| r.get(0),
261                )
262                .optional()?;
263            let mut e = item.clone();
264            e.source_order = e.source_order.or(Some(order as u64));
265            e.feed_id = feed_id.into();
266            let new_episode = old.is_none();
267            e.id = if let Some(old) = old {
268                let old: Episode = serde_json::from_str(&old)?;
269                if (old.bytes.is_some() && e.bytes.is_some() && old.bytes != e.bytes)
270                    || (old.duration_ms.is_some()
271                        && e.duration_ms.is_some()
272                        && old.duration_ms != e.duration_ms)
273                {
274                    self.conn.execute(
275                        "UPDATE podcast_progress SET completed=0 WHERE episode_id=?1",
276                        [&old.id],
277                    )?;
278                }
279                old.id
280            } else {
281                uuid::Uuid::new_v4().to_string()
282            };
283            self.conn.execute("INSERT INTO podcast_episodes(id,feed_id,identity,json) VALUES (?1,?2,?3,?4) ON CONFLICT(feed_id,identity) DO UPDATE SET json=excluded.json",params![e.id,feed_id,identity,serde_json::to_string(&e)?])?;
284            if baseline && new_episode {
285                if settings.auto_download && !e.completed {
286                    self.podcast_save_download(&Download {
287                        episode_id: e.id.clone(),
288                        state: "queued".into(),
289                        enqueued_at: Some(chrono::Utc::now().to_rfc3339()),
290                        ..Default::default()
291                    })?;
292                }
293                self.conn
294                    .execute("INSERT OR IGNORE INTO podcast_inbox VALUES (?1)", [&e.id])?;
295            }
296        }
297        Ok(())
298    }
299    pub fn podcast_unsubscribe(&self, id: &str) -> Result<()> {
300        let mut f = self.podcast_feed(id)?;
301        f.subscribed = false;
302        f.revision = f.revision.saturating_add(1);
303        self.podcast_write(&f)
304    }
305    pub fn podcast_episode(&self, id: &str) -> Result<Episode> {
306        let resolved = self.podcast_episode_id(id)?;
307        let id = resolved.as_str();
308        let json: Option<String> = self
309            .conn
310            .query_row("SELECT json FROM podcast_episodes WHERE id=?1", [id], |r| {
311                r.get(0)
312            })
313            .optional()?;
314        let mut e: Episode =
315            serde_json::from_str(&json.ok_or_else(|| error(crate::t!("podcast_not_found")))?)?;
316        let p=self.conn.query_row("SELECT position_ms,duration_ms,completed FROM podcast_progress WHERE episode_id=?1",[id],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional()?;
317        if let Some((pos, dur, done)) = p {
318            e.position_ms = pos;
319            e.observed_duration_ms = dur;
320            e.completed = done;
321        }
322        Ok(e)
323    }
324    pub fn podcast_episodes(&self, id: &str) -> Result<Vec<Episode>> {
325        let feed = self.podcast_feed(id)?;
326        self.podcast_episode_rows(&feed.id, "", -1, 0)
327    }
328    pub(crate) fn podcast_episode_position(&self, feed: &str, id: &str) -> Result<Option<usize>> {
329        Ok(self
330            .conn
331            .query_row(
332                &format!(
333                    "SELECT position FROM (
334                        SELECT id,row_number() OVER (ORDER BY {EPISODE_NEWEST_ORDER})-1 AS position
335                        FROM podcast_episodes WHERE feed_id=?1
336                     ) WHERE id=?2",
337                ),
338                params![feed, id],
339                |r| r.get(0),
340            )
341            .optional()?)
342    }
343    pub fn podcast_episodes_page(
344        &self,
345        id: &str,
346        query: &str,
347        page: &crate::cli::Page,
348    ) -> Result<(Vec<Episode>, usize)> {
349        let feed = self.podcast_feed(id)?;
350        let id = feed.id.as_str();
351        let query = query.to_lowercase();
352        self.read_snapshot(|store| {
353            store.podcast_feed(id)?;
354            let total = store.conn.query_row(
355                "SELECT count(*) FROM podcast_episodes WHERE feed_id=?1
356                 AND (?2='' OR instr(podcast_lower(json_extract(json,'$.title')),?2)>0)",
357                params![id, query],
358                |r| r.get(0),
359            )?;
360            let items = store.podcast_episode_rows(
361                id,
362                &query,
363                if page.all { -1 } else { i64::from(page.limit) },
364                page.offset.min(i64::MAX as usize) as i64,
365            )?;
366            Ok((items, total))
367        })
368    }
369    fn podcast_episode_rows(
370        &self,
371        id: &str,
372        query: &str,
373        limit: i64,
374        offset: i64,
375    ) -> Result<Vec<Episode>> {
376        let mut stmt = self.conn.prepare_cached(&episode_page_sql())?;
377        let rows = stmt.query_map(params![id, query, limit, offset], |r| {
378            Ok((
379                r.get::<_, String>(0)?,
380                r.get::<_, Option<u64>>(1)?,
381                r.get::<_, Option<u64>>(2)?,
382                r.get::<_, Option<bool>>(3)?,
383            ))
384        })?;
385        rows.map(|row| {
386            let (json, position, duration, completed) = row?;
387            let mut episode: Episode = serde_json::from_str(&json)?;
388            if let Some(position) = position {
389                episode.position_ms = position;
390                episode.observed_duration_ms = duration;
391                episode.completed = completed.unwrap_or(false);
392            }
393            Ok(episode)
394        })
395        .collect()
396    }
397    /// Save progress only while the supplied media snapshot is still current.
398    pub fn podcast_progress(
399        &self,
400        episode: &Episode,
401        pos: u64,
402        duration: Option<u64>,
403        completed: bool,
404    ) -> Result<()> {
405        self.podcast_save_progress(
406            &episode.id,
407            &EpisodeProgress {
408                media: episode.media(),
409                position_ms: pos,
410                observed_duration_ms: duration,
411                completed,
412            },
413        )
414    }
415    pub(crate) fn podcast_save_progress(&self, id: &str, progress: &EpisodeProgress) -> Result<()> {
416        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
417        Self::write_podcast_progress(&tx, id, progress)?;
418        tx.commit()?;
419        Ok(())
420    }
421    pub(crate) fn write_podcast_progress(
422        tx: &rusqlite::Transaction<'_>,
423        id: &str,
424        progress: &EpisodeProgress,
425    ) -> Result<()> {
426        let json: Option<String> = tx
427            .query_row("SELECT json FROM podcast_episodes WHERE id=?1", [id], |r| {
428                r.get(0)
429            })
430            .optional()?;
431        let Some(json) = json else { return Ok(()) };
432        let episode: Episode = serde_json::from_str(&json)?;
433        // The write transaction also excludes refreshes between this check and
434        // the UPSERT. An old media snapshot must not undo a refresh's reset.
435        if episode.media() != progress.media {
436            return Ok(());
437        }
438        tx.execute("INSERT INTO podcast_progress VALUES (?1,?2,?3,?4,?5) ON CONFLICT(episode_id) DO UPDATE SET position_ms=excluded.position_ms,duration_ms=COALESCE(excluded.duration_ms,duration_ms),completed=excluded.completed,updated_at=excluded.updated_at",params![id,progress.position_ms.min(i64::MAX as u64),progress.observed_duration_ms.map(|d|d.min(i64::MAX as u64)),progress.completed,chrono::Utc::now().to_rfc3339()])?;
439        Ok(())
440    }
441    pub fn podcast_played(&self, id: &str) -> Result<()> {
442        self.conn.execute(
443            "INSERT INTO podcast_history(episode_id,played_at) VALUES (?1,?2)",
444            params![id, chrono::Utc::now().to_rfc3339()],
445        )?;
446        self.set_meta("pref_last_episode", id)?;
447        self.set_meta("pref_last_media", "episode")
448    }
449    pub fn podcast_download(&self, id: &str) -> Result<Option<Download>> {
450        let json: Option<String> = self
451            .conn
452            .query_row(
453                "SELECT json FROM podcast_downloads WHERE episode_id=?1",
454                [id],
455                |r| r.get(0),
456            )
457            .optional()?;
458        json.map(|j| Ok(serde_json::from_str(&j)?)).transpose()
459    }
460    pub(crate) fn podcast_claim_download(&self, expected: &Download) -> Result<Option<Download>> {
461        let json: Option<String> = self
462            .conn
463            .query_row(
464                "UPDATE podcast_downloads
465                 SET json=json_set(json,'$.state','downloading','$.error',NULL,'$.generation',?4)
466                 WHERE episode_id=?1 AND json_extract(json,'$.state')=?2
467                 AND json_extract(json,'$.state') IN ('queued','downloading')
468                 AND COALESCE(json_extract(json,'$.generation'),0)=?3
469                 RETURNING json",
470                params![
471                    expected.episode_id,
472                    expected.state,
473                    expected.generation,
474                    expected.generation.saturating_add(1)
475                ],
476                |r| r.get(0),
477            )
478            .optional()?;
479        json.map(|j| Ok(serde_json::from_str(&j)?)).transpose()
480    }
481    pub(crate) fn podcast_download_transaction<T>(
482        &self,
483        id: &str,
484        update: impl FnOnce(Option<Download>) -> Result<T>,
485    ) -> Result<T> {
486        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
487        let value = update(self.podcast_download(id)?)?;
488        tx.commit()?;
489        Ok(value)
490    }
491    pub(crate) fn podcast_download_update(&self, d: &Download) -> Result<()> {
492        let changed=self.conn.execute("UPDATE podcast_downloads SET json=?2 WHERE episode_id=?1 AND COALESCE(json_extract(json,'$.generation'),0)=?3",params![d.episode_id,serde_json::to_string(d)?,d.generation])?;
493        if changed == 0 {
494            return Err(DomainError::new(ErrorCode::Cancelled).into());
495        }
496        Ok(())
497    }
498    pub fn podcast_save_download(&self, d: &Download) -> Result<()> {
499        self.conn.execute("INSERT INTO podcast_downloads VALUES (?1,?2) ON CONFLICT(episode_id) DO UPDATE SET json=excluded.json",params![d.episode_id,serde_json::to_string(d)?])?;
500        Ok(())
501    }
502    pub fn podcast_downloads(&self) -> Result<Vec<Download>> {
503        let mut stmt = self
504            .conn
505            .prepare("SELECT json FROM podcast_downloads ORDER BY COALESCE(json_extract(json,'$.enqueued_at'),''),rowid")?;
506        stmt.query_map([], |r| r.get::<_, String>(0))?
507            .map(|j| Ok(serde_json::from_str(&j?)?))
508            .collect()
509    }
510    pub fn podcast_queue(&self) -> Result<Vec<Episode>> {
511        let mut stmt = self
512            .conn
513            .prepare("SELECT episode_id FROM podcast_queue ORDER BY position,rowid")?;
514        stmt.query_map([], |r| r.get::<_, String>(0))?
515            .map(|id| self.podcast_episode(&id?))
516            .collect()
517    }
518    pub fn podcast_queue_set(&self, ids: &[String]) -> Result<()> {
519        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
520        self.podcast_queue_write(ids)?;
521        tx.commit()?;
522        Ok(())
523    }
524    pub fn podcast_queue_update(&self, action: QueueAction) -> Result<Vec<Episode>> {
525        self.podcast_queue_update_revision(action)
526            .map(|(items, _)| items)
527    }
528    pub(crate) fn podcast_queue_revision(&self) -> Result<u64> {
529        Ok(self
530            .meta("podcast_queue_revision")?
531            .and_then(|v| v.parse().ok())
532            .unwrap_or(0))
533    }
534    pub(crate) fn podcast_queue_snapshot(&self) -> Result<(Vec<Episode>, u64)> {
535        self.read_snapshot(|store| Ok((store.podcast_queue()?, store.podcast_queue_revision()?)))
536    }
537    pub(crate) fn podcast_queue_update_revision(
538        &self,
539        action: QueueAction,
540    ) -> Result<(Vec<Episode>, u64)> {
541        if matches!(action, QueueAction::List) {
542            return self.podcast_queue_snapshot();
543        }
544        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
545        let mut ids = self
546            .conn
547            .prepare("SELECT episode_id FROM podcast_queue ORDER BY position,rowid")?
548            .query_map([], |r| r.get::<_, String>(0))?
549            .collect::<rusqlite::Result<Vec<_>>>()?;
550        let mut changed = true;
551        match action {
552            QueueAction::Add { id } => {
553                self.podcast_episode(&id)?;
554                if !ids.contains(&id) {
555                    ids.push(id);
556                }
557            }
558            QueueAction::Next { id, after } => {
559                self.podcast_episode(&id)?;
560                if after.as_ref() == Some(&id) {
561                    return Err(error(crate::t!("podcast_invalid_time")));
562                }
563                ids.retain(|v| v != &id);
564                let position = after
565                    .and_then(|after| ids.iter().position(|v| v == &after))
566                    .map_or(0, |p| p + 1);
567                ids.insert(position, id);
568            }
569            QueueAction::Remove { id } => ids.retain(|v| v != &id),
570            QueueAction::Clear => ids.clear(),
571            QueueAction::Move { id, position } => {
572                if position == 0 || position > ids.len() || !ids.contains(&id) {
573                    return Err(error(crate::t!("podcast_invalid_time")));
574                }
575                ids.retain(|v| v != &id);
576                ids.insert(position - 1, id);
577            }
578            QueueAction::MoveAdjacent { id, up } => {
579                let current = ids
580                    .iter()
581                    .position(|v| v == &id)
582                    .ok_or_else(|| error(crate::t!("podcast_not_found")))?;
583                let target = if up {
584                    current.saturating_sub(1)
585                } else {
586                    (current + 1).min(ids.len() - 1)
587                };
588                changed = current != target;
589                ids.swap(current, target);
590            }
591            QueueAction::Play { .. } | QueueAction::Start { .. } => {
592                return Err(error(crate::t!("podcast_playback_only")));
593            }
594            QueueAction::List => unreachable!(),
595        }
596        if changed {
597            self.podcast_queue_write(&ids)?;
598        }
599        let items = self.podcast_queue()?;
600        let revision = self.podcast_queue_revision()?;
601        tx.commit()?;
602        Ok((items, revision))
603    }
604    pub(crate) fn podcast_queue_complete(
605        &self,
606        id: &str,
607    ) -> Result<(Vec<Episode>, u64, Vec<String>)> {
608        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
609        let before = self.podcast_queue()?;
610        let earlier = before
611            .iter()
612            .take_while(|e| e.id != id)
613            .map(|e| e.id.clone())
614            .collect();
615        let ids = before
616            .into_iter()
617            .filter(|e| e.id != id)
618            .map(|e| e.id)
619            .collect::<Vec<_>>();
620        self.podcast_queue_write(&ids)?;
621        let items = self.podcast_queue()?;
622        let revision = self.podcast_queue_revision()?;
623        tx.commit()?;
624        Ok((items, revision, earlier))
625    }
626    fn podcast_queue_write(&self, ids: &[String]) -> Result<()> {
627        self.conn.execute("DELETE FROM podcast_queue", [])?;
628        for (i, id) in ids.iter().enumerate() {
629            self.conn.execute(
630                "INSERT OR IGNORE INTO podcast_queue VALUES (?1,?2)",
631                params![id, i],
632            )?;
633        }
634        self.conn.execute(
635            "INSERT INTO meta(key,value) VALUES ('podcast_queue_revision','1')
636            ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1",
637            [],
638        )?;
639        Ok(())
640    }
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646
647    #[test]
648    fn schema_ten_episode_order_keeps_legacy_rows_and_uses_the_date_index() {
649        let dir = tempfile::tempdir().unwrap();
650        let path = dir.path().join("radio.db");
651        let store = Store::open(&path).unwrap();
652        let preview = Preview {
653            feed: Feed {
654                url: "https://example.test/rss".into(),
655                ..Default::default()
656            },
657            episodes: [
658                ("Undated", None, 0),
659                ("Legacy", Some("2026-01-01T00:00:00Z"), 70),
660                ("Newest", Some("2026-01-02T00:00:00Z"), 0),
661                ("First on day", Some("2026-01-01T00:00:00Z"), 1),
662                ("Last on day", Some("2026-01-01T00:00:00Z"), 3),
663            ]
664            .into_iter()
665            .map(|(title, published, order)| Episode {
666                title: title.into(),
667                url: format!("https://example.test/{}", title.replace(' ', "-")),
668                published: published.map(str::to_owned),
669                source_order: Some(order),
670                ..Default::default()
671            })
672            .collect(),
673        };
674        let feed = store
675            .podcast_subscribe(&preview, &preview.feed.url)
676            .unwrap();
677        crate::test_support::strip_podcast_episode_order(&store.conn);
678        store
679            .conn
680            .execute_batch(
681                "UPDATE podcast_episodes SET json=json_remove(json,'$.source_order') WHERE rowid=2;
682             CREATE INDEX podcast_episode_dates ON podcast_episodes(
683                 feed_id,CASE WHEN json_valid(json) THEN json_extract(json,'$.published') END DESC,
684                 CASE WHEN json_valid(json) THEN json_extract(json,'$.source_order') END,id);
685             PRAGMA user_version=10;",
686            )
687            .unwrap();
688        drop(store);
689
690        let store = Store::open(&path).unwrap();
691        let episodes = store.podcast_episodes(&feed.id).unwrap();
692        assert_eq!(
693            episodes
694                .iter()
695                .map(|e| e.title.as_str())
696                .collect::<Vec<_>>(),
697            ["Newest", "First on day", "Legacy", "Last on day", "Undated"],
698        );
699        let legacy = &episodes[2];
700        assert_eq!(legacy.source_order, None);
701        assert_eq!(
702            store
703                .podcast_episode_position(&feed.id, &legacy.id)
704                .unwrap(),
705            Some(2)
706        );
707        let page = crate::cli::Page {
708            offset: 2,
709            limit: 2,
710            all: false,
711        };
712        let (rows, total) = store.podcast_episodes_page(&feed.id, "", &page).unwrap();
713        assert_eq!(rows, episodes[2..4]);
714        assert_eq!(total, episodes.len());
715        let plan = store
716            .conn
717            .prepare(&format!("EXPLAIN QUERY PLAN {}", episode_page_sql()))
718            .unwrap()
719            .query_map(params![feed.id, "", page.limit, page.offset as i64], |r| {
720                r.get::<_, String>(3)
721            })
722            .unwrap()
723            .collect::<rusqlite::Result<Vec<_>>>()
724            .unwrap();
725        assert!(
726            plan.iter().any(|row| row.contains("podcast_episode_dates")),
727            "{plan:?}"
728        );
729        assert!(
730            !plan.iter().any(|row| row.contains("TEMP B-TREE")),
731            "{plan:?}"
732        );
733    }
734    use std::sync::{Arc, Barrier, atomic::AtomicBool};
735
736    fn queue_fixture() -> (tempfile::TempDir, crate::config::Config, Vec<Episode>) {
737        let dir = tempfile::tempdir().unwrap();
738        let config = crate::test_support::config(dir.path());
739        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
740        let preview = Preview {
741            feed: Feed {
742                url: "https://example.test/rss".into(),
743                ..Default::default()
744            },
745            episodes: (0..2)
746                .map(|i| Episode {
747                    guid: Some(i.to_string()),
748                    url: format!("https://example.test/{i}.mp3"),
749                    ..Default::default()
750                })
751                .collect(),
752        };
753        let feed = store
754            .podcast_subscribe(&preview, &preview.feed.url)
755            .unwrap();
756        let episodes = store.podcast_episodes(&feed.id).unwrap();
757        (dir, config, episodes)
758    }
759
760    #[test]
761    fn downloaded_filter_only_probes_members_of_the_selected_collection() {
762        let (_dir, config, episodes) = queue_fixture();
763        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
764        let episode = &episodes[0];
765        let path = config.data_dir.join("local.audio");
766        std::fs::write(&path, b"fixture").unwrap();
767        store
768            .podcast_save_download(&Download {
769                episode_id: episode.id.clone(),
770                state: "complete".into(),
771                url: episode.url.clone(),
772                media: Some(episode.media()),
773                path: path.to_str().unwrap().into(),
774                ..Default::default()
775            })
776            .unwrap();
777        let files = Arc::new(super::super::download_files::DownloadFiles::default());
778        for view in ["inbox", "history", "saved", "continue"] {
779            let query = LibraryQuery {
780                view: view.into(),
781                downloaded: true,
782                ..Default::default()
783            };
784            let page = store.podcast_library_with_files(&query, &files).unwrap();
785            assert_eq!(page["total"], 0, "{view}");
786            assert!(
787                files.take_observations().is_empty(),
788                "{view} probed an excluded file"
789            );
790        }
791        store.podcast_save_episode(&episode.id, false).unwrap();
792        let query = LibraryQuery {
793            view: "saved".into(),
794            downloaded: true,
795            ..Default::default()
796        };
797        let page = store.podcast_library_with_files(&query, &files).unwrap();
798        assert_eq!(page["total"], 1);
799        assert_eq!(page["items"][0]["id"], episode.id);
800        assert_eq!(
801            files.take_observations().get(path.to_str().unwrap()),
802            Some(&true)
803        );
804    }
805
806    #[test]
807    fn downloaded_library_releases_the_read_snapshot_before_probing_files() {
808        let (_dir, config, episodes) = queue_fixture();
809        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
810        let episode = &episodes[0];
811        let audio = config.data_dir.join("local.audio");
812        std::fs::write(&audio, b"fixture").unwrap();
813        store
814            .podcast_save_download(&Download {
815                episode_id: episode.id.clone(),
816                state: "complete".into(),
817                url: episode.url.clone(),
818                media: Some(episode.media()),
819                path: audio.to_string_lossy().into_owned(),
820                ..Default::default()
821            })
822            .unwrap();
823        let mut files = super::super::download_files::DownloadFiles::default();
824        files.before_probe = Some(|path| {
825            let db = std::path::Path::new(path).with_file_name("radio.db");
826            let writer = rusqlite::Connection::open(db).unwrap();
827            writer.busy_timeout(std::time::Duration::ZERO).unwrap();
828            writer
829                .execute(
830                    "INSERT INTO meta(key,value) VALUES ('checkpoint-test','ok')",
831                    [],
832                )
833                .unwrap();
834            let busy: i64 = writer
835                .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get(0))
836                .unwrap();
837            assert_eq!(busy, 0);
838        });
839        let query = LibraryQuery {
840            downloaded: true,
841            ..Default::default()
842        };
843        let result = store
844            .podcast_library_with_files(&query, &std::sync::Arc::new(files))
845            .unwrap();
846        assert_eq!(result["total"], 1);
847        assert_eq!(result["items"][0]["id"], episode.id);
848        assert_eq!(result["items"][0]["download_state"], "complete");
849    }
850
851    #[test]
852    fn cli_marks_cannot_overwrite_progress_after_a_concurrent_media_refresh() {
853        use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
854        use std::{sync::mpsc, time::Duration};
855
856        for state in ["played", "unplayed"] {
857            for changed in ["duration", "bytes", "url", "title", "unchanged"] {
858                let dir = tempfile::tempdir().unwrap();
859                let config = crate::test_support::config(dir.path());
860                let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
861                let mut preview = Preview {
862                    feed: Feed {
863                        url: "https://example.test/rss".into(),
864                        ..Default::default()
865                    },
866                    episodes: vec![Episode {
867                        guid: Some("episode".into()),
868                        url: "https://example.test/audio".into(),
869                        duration_ms: Some(20000),
870                        bytes: Some(100),
871                        ..Default::default()
872                    }],
873                };
874                let feed = store
875                    .podcast_subscribe(&preview, &preview.feed.url)
876                    .unwrap();
877                let episode = store.podcast_episodes(&feed.id).unwrap().remove(0);
878                store
879                    .podcast_progress(&episode, 15000, Some(20000), true)
880                    .unwrap();
881
882                let (ready, wait) = mpsc::channel();
883                let (release, go) = mpsc::channel();
884                let id = episode.id.clone();
885                let worker = std::thread::spawn(move || {
886                    let mut store = Store::open(&config.data_dir.join("radio.db")).unwrap();
887                    let mut synchronized = false;
888                    // Mark has read its media snapshot before requesting the
889                    // write transaction. The INSERT hook catches the old path
890                    // which bypassed that transaction and its media guard.
891                    store
892                        .conn
893                        .authorizer(Some(move |context: AuthContext<'_>| {
894                            if !synchronized
895                                && matches!(
896                                    context.action,
897                                    AuthAction::Transaction {
898                                        operation: TransactionOperation::Begin
899                                    } | AuthAction::Insert {
900                                        table_name: "podcast_progress"
901                                    }
902                                )
903                            {
904                                synchronized = true;
905                                ready.send(()).unwrap();
906                                go.recv_timeout(Duration::from_secs(3)).unwrap();
907                            }
908                            Authorization::Allow
909                        }))
910                        .unwrap();
911                    manage(
912                        &config,
913                        &store,
914                        Action::Mark {
915                            id,
916                            state: state.into(),
917                        },
918                        &Arc::new(AtomicBool::new(false)),
919                    )
920                    .unwrap()
921                });
922                wait.recv_timeout(Duration::from_secs(3)).unwrap();
923                match changed {
924                    "duration" => preview.episodes[0].duration_ms = Some(40000),
925                    "bytes" => preview.episodes[0].bytes = Some(200),
926                    "url" => preview.episodes[0].url = "https://example.test/new-audio".into(),
927                    "title" => preview.episodes[0].title = "Updated title".into(),
928                    "unchanged" => {}
929                    _ => unreachable!(),
930                }
931                store.podcast_refresh_merge(&feed, Some(preview)).unwrap();
932                let mut expected = store.podcast_episode(&episode.id).unwrap();
933                if matches!(changed, "title" | "unchanged") {
934                    expected.completed = state == "played";
935                    expected.position_ms = if expected.completed { 20000 } else { 0 };
936                }
937                release.send(()).unwrap();
938                let result = worker.join().unwrap();
939                assert_eq!(
940                    store.podcast_episode(&episode.id).unwrap(),
941                    expected,
942                    "{state}: {changed}"
943                );
944                assert_eq!(result, serde_json::to_value(&expected).unwrap());
945            }
946        }
947    }
948
949    #[test]
950    fn download_controls_read_the_generation_after_a_concurrent_claim() {
951        use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
952        use std::sync::mpsc;
953        for control in ["pause", "cancel", "enqueue"] {
954            let (_dir, config, episodes) = queue_fixture();
955            let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
956            let snapshot = Download {
957                episode_id: episodes[0].id.clone(),
958                state: "queued".into(),
959                generation: 7,
960                ..Default::default()
961            };
962            store.podcast_save_download(&snapshot).unwrap();
963            let (ready, wait) = mpsc::channel();
964            let (release, go) = mpsc::channel();
965            let id = snapshot.episode_id.clone();
966            let config = config.clone();
967            let worker = std::thread::spawn(move || {
968                let mut store = Store::open(&config.data_dir.join("radio.db")).unwrap();
969                let mut synchronized = false;
970                // Pause immediately before acquiring the write lock. Without
971                // a transaction this hook runs at INSERT, after the stale read.
972                store
973                    .conn
974                    .authorizer(Some(move |context: AuthContext<'_>| {
975                        if !synchronized
976                            && matches!(
977                                context.action,
978                                AuthAction::Transaction {
979                                    operation: TransactionOperation::Begin
980                                } | AuthAction::Insert {
981                                    table_name: "podcast_downloads"
982                                }
983                            )
984                        {
985                            synchronized = true;
986                            ready.send(()).unwrap();
987                            go.recv_timeout(std::time::Duration::from_secs(3)).unwrap();
988                        }
989                        Authorization::Allow
990                    }))
991                    .unwrap();
992                if control == "enqueue" {
993                    Runtime::enqueue(&store, &id).unwrap();
994                } else {
995                    manage(
996                        &config,
997                        &store,
998                        Action::Downloads {
999                            action: if control == "pause" {
1000                                DownloadAction::Pause { id: id.clone() }
1001                            } else {
1002                                DownloadAction::Cancel { id: id.clone() }
1003                            },
1004                        },
1005                        &Arc::new(AtomicBool::new(false)),
1006                    )
1007                    .unwrap();
1008                }
1009            });
1010            wait.recv_timeout(std::time::Duration::from_secs(3))
1011                .unwrap();
1012            let mut claimed = store.podcast_claim_download(&snapshot).unwrap().unwrap();
1013            claimed.bytes = 123;
1014            store.podcast_download_update(&claimed).unwrap();
1015            release.send(()).unwrap();
1016            worker.join().unwrap();
1017            let current = store
1018                .podcast_download(&snapshot.episode_id)
1019                .unwrap()
1020                .unwrap();
1021            assert_eq!(current.generation, claimed.generation + 1, "{control}");
1022            assert_eq!(current.bytes, 123);
1023            assert_eq!(
1024                current.state,
1025                match control {
1026                    "pause" => "paused",
1027                    "cancel" => "cancelled",
1028                    _ => "queued",
1029                }
1030            );
1031            assert!(store.podcast_download_update(&claimed).is_err());
1032        }
1033    }
1034
1035    #[test]
1036    fn concurrent_queue_additions_preserve_both_updates() {
1037        use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
1038        let (_dir, config, episodes) = queue_fixture();
1039        let barrier = Arc::new(Barrier::new(2));
1040        let workers: Vec<_> = episodes
1041            .iter()
1042            .map(|e| {
1043                let config = config.clone();
1044                let id = e.id.clone();
1045                let barrier = barrier.clone();
1046                std::thread::spawn(move || {
1047                    let mut store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1048                    let mut synchronized = false;
1049                    // Align the first write transactions. Reading before BEGIN
1050                    // makes both workers overwrite the same old queue snapshot.
1051                    store
1052                        .conn
1053                        .authorizer(Some(move |context: AuthContext<'_>| {
1054                            if !synchronized
1055                                && matches!(
1056                                    context.action,
1057                                    AuthAction::Transaction {
1058                                        operation: TransactionOperation::Begin
1059                                    }
1060                                )
1061                            {
1062                                synchronized = true;
1063                                barrier.wait();
1064                            }
1065                            Authorization::Allow
1066                        }))
1067                        .unwrap();
1068                    manage(
1069                        &config,
1070                        &store,
1071                        Action::Queue {
1072                            action: QueueAction::Add { id },
1073                        },
1074                        &Arc::new(AtomicBool::new(false)),
1075                    )
1076                    .unwrap();
1077                })
1078            })
1079            .collect();
1080        for worker in workers {
1081            worker.join().unwrap();
1082        }
1083        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1084        let mut actual: Vec<_> = store
1085            .podcast_queue()
1086            .unwrap()
1087            .into_iter()
1088            .map(|e| e.id)
1089            .collect();
1090        let mut expected: Vec<_> = episodes.into_iter().map(|e| e.id).collect();
1091        actual.sort();
1092        expected.sort();
1093        assert_eq!(actual, expected);
1094    }
1095
1096    #[test]
1097    fn listing_the_queue_is_read_only() {
1098        let (_dir, config, episodes) = queue_fixture();
1099        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1100        store.podcast_queue_set(&[episodes[0].id.clone()]).unwrap();
1101        store.conn.execute_batch("PRAGMA query_only=ON").unwrap();
1102        let value = manage(
1103            &config,
1104            &store,
1105            Action::Queue {
1106                action: QueueAction::List,
1107            },
1108            &Arc::new(AtomicBool::new(false)),
1109        )
1110        .unwrap();
1111        assert_eq!(value[0]["id"], episodes[0].id);
1112    }
1113
1114    #[test]
1115    fn queue_edits_preserve_order_and_rollback_invalid_moves() {
1116        let (_dir, config, episodes) = queue_fixture();
1117        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1118        for episode in [&episodes[0], &episodes[1], &episodes[0]] {
1119            store
1120                .podcast_queue_update(QueueAction::Add {
1121                    id: episode.id.clone(),
1122                })
1123                .unwrap();
1124        }
1125        let reordered = store
1126            .podcast_queue_update(QueueAction::Move {
1127                id: episodes[0].id.clone(),
1128                position: 2,
1129            })
1130            .unwrap();
1131        assert_eq!(
1132            reordered.iter().map(|e| &e.id).collect::<Vec<_>>(),
1133            vec![&episodes[1].id, &episodes[0].id]
1134        );
1135        assert!(
1136            store
1137                .podcast_queue_update(QueueAction::Move {
1138                    id: episodes[0].id.clone(),
1139                    position: 3,
1140                })
1141                .is_err()
1142        );
1143        assert_eq!(store.podcast_queue().unwrap(), reordered);
1144        let remaining = store
1145            .podcast_queue_update(QueueAction::Remove {
1146                id: episodes[1].id.clone(),
1147            })
1148            .unwrap();
1149        assert_eq!(remaining.len(), 1);
1150        assert_eq!(remaining[0].id, episodes[0].id);
1151        assert!(
1152            store
1153                .podcast_queue_update(QueueAction::Clear)
1154                .unwrap()
1155                .is_empty()
1156        );
1157    }
1158}