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";
8pub(super) const EPISODE_NEWEST_ORDER_E: &str = "CASE WHEN json_valid(e.json) THEN json_extract(e.json,'$.published') END DESC,
9    CASE WHEN json_valid(e.json) THEN COALESCE(json_extract(e.json,'$.source_order'),e.legacy_order) END,e.id";
10
11fn episode_page_sql() -> String {
12    format!(
13        "SELECT e.json,p.position_ms,p.duration_ms,p.completed FROM podcast_episodes e
14         LEFT JOIN podcast_progress p ON p.episode_id=e.id WHERE e.feed_id=?1
15         AND (?2='' OR instr(podcast_lower(json_extract(e.json,'$.title')),?2)>0)
16         ORDER BY {EPISODE_NEWEST_ORDER} LIMIT ?3 OFFSET ?4",
17    )
18}
19
20fn read_episode_rows(
21    stmt: &mut rusqlite::Statement<'_>,
22    parameters: impl rusqlite::Params,
23) -> Result<Vec<Episode>> {
24    let mut rows = stmt.query(parameters)?;
25    let mut episodes = Vec::new();
26    while let Some(row) = rows.next()? {
27        episodes.push(episode_from_row(row)?);
28    }
29    Ok(episodes)
30}
31
32fn resolve_unique_id(ids: Vec<String>) -> Result<String> {
33    match ids.as_slice() {
34        [id] => Ok(id.clone()),
35        [] => Err(error(crate::t!("podcast_not_found"))),
36        _ => Err(error(&format!(
37            "{}: {}",
38            crate::t!("podcast_ambiguous"),
39            ids.join(", ")
40        ))),
41    }
42}
43
44pub(super) fn episode_from_row(row: &rusqlite::Row<'_>) -> Result<Episode> {
45    let mut episode: Episode = serde_json::from_str(&row.get::<_, String>(0)?)?;
46    if let Some(position) = row.get::<_, Option<u64>>(1)? {
47        episode.position_ms = position;
48        episode.observed_duration_ms = row.get(2)?;
49        episode.completed = row.get(3)?;
50    }
51    Ok(episode)
52}
53
54pub(crate) fn register_functions(conn: &rusqlite::Connection) -> Result<()> {
55    use rusqlite::functions::FunctionFlags;
56
57    conn.create_scalar_function(
58        "podcast_lower",
59        1,
60        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC,
61        |context| Ok(context.get::<String>(0)?.to_lowercase()),
62    )?;
63    Ok(())
64}
65
66pub(super) fn register_download_availability(
67    conn: &rusqlite::Connection,
68    files: std::sync::Arc<super::download_files::DownloadFiles>,
69) -> Result<()> {
70    use rusqlite::{Error, functions::FunctionFlags};
71
72    #[derive(Deserialize, Default)]
73    #[serde(default)]
74    struct DownloadCheck {
75        state: String,
76        url: String,
77        media: Option<EpisodeMedia>,
78        path: String,
79    }
80
81    #[derive(Deserialize, Default)]
82    #[serde(default)]
83    struct EpisodeCheck {
84        url: String,
85        bytes: Option<u64>,
86        duration_ms: Option<u64>,
87    }
88
89    // Availability also depends on the filesystem, so this function is not deterministic.
90    conn.create_scalar_function(
91        "podcast_download_available",
92        2,
93        FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DIRECTONLY,
94        move |context| {
95            let Some(download) = context.get::<Option<String>>(0)? else {
96                return Ok(false);
97            };
98            let d: DownloadCheck = serde_json::from_str(&download)
99                .map_err(|e| Error::UserFunctionError(Box::new(e)))?;
100            if d.state != "complete" {
101                return Ok(false);
102            }
103            let Some(media) = d.media else {
104                return Ok(false);
105            };
106            let episode = context.get::<String>(1)?;
107            let e: EpisodeCheck = serde_json::from_str(&episode)
108                .map_err(|e| Error::UserFunctionError(Box::new(e)))?;
109            Ok(d.url == e.url
110                && media.url == e.url
111                && media.bytes == e.bytes
112                && media.duration_ms == e.duration_ms
113                && files.observed_file(&d.path))
114        },
115    )?;
116    Ok(())
117}
118
119pub(crate) fn migrate(conn: &rusqlite::Connection) -> Result<()> {
120    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);
121    CREATE TABLE IF NOT EXISTS podcast_aliases(url TEXT PRIMARY KEY,feed_id TEXT NOT NULL REFERENCES podcast_feeds(id));
122    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));
123    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);
124    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);
125    CREATE TABLE IF NOT EXISTS podcast_downloads(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id),json TEXT NOT NULL);
126    CREATE TABLE IF NOT EXISTS podcast_queue(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id),position INTEGER NOT NULL);
127    CREATE INDEX IF NOT EXISTS podcast_feed_episodes ON podcast_episodes(feed_id);")?;
128    Ok(())
129}
130
131pub(crate) fn migrate_library(conn: &rusqlite::Connection) -> Result<()> {
132    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);
133    CREATE INDEX IF NOT EXISTS podcast_bookmark_episode ON podcast_bookmarks(episode_id,position_ms);
134    CREATE TABLE IF NOT EXISTS podcast_saved(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id));
135    CREATE TABLE IF NOT EXISTS podcast_inbox(episode_id TEXT PRIMARY KEY REFERENCES podcast_episodes(id));")?;
136    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);
137        CREATE INDEX IF NOT EXISTS podcast_history_episode ON podcast_history(episode_id,played_at DESC);")?;
138    for table in [
139        "podcast_feeds",
140        "podcast_episodes",
141        "podcast_progress",
142        "podcast_downloads",
143        "podcast_queue",
144        "podcast_saved",
145        "podcast_inbox",
146        "podcast_bookmarks",
147        "podcast_history",
148    ] {
149        for operation in ["INSERT", "UPDATE", "DELETE"] {
150            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;"))?;
151        }
152    }
153    Ok(())
154}
155
156pub(crate) fn migrate_episode_order(conn: &rusqlite::Connection) -> Result<()> {
157    // A rowid cannot appear in an index expression. Save the old fallback for
158    // episodes without a source position so existing pages keep their order.
159    conn.execute_batch(&format!(
160        "DROP INDEX IF EXISTS podcast_episode_dates;
161         ALTER TABLE podcast_episodes ADD COLUMN legacy_order INTEGER;
162         UPDATE podcast_episodes SET legacy_order=rowid
163         WHERE CASE WHEN json_valid(json) THEN json_extract(json,'$.source_order') IS NULL END;
164         CREATE INDEX podcast_episode_dates ON podcast_episodes(feed_id,{EPISODE_NEWEST_ORDER});"
165    ))?;
166    Ok(())
167}
168
169impl Store {
170    pub fn podcast_settings(&self, id: &str) -> Result<ShowSettings> {
171        let id = self.podcast_feed_id(id)?;
172        Ok(self
173            .meta(&format!("podcast_settings:{id}"))?
174            .map(|s| serde_json::from_str(&s))
175            .transpose()?
176            .unwrap_or_default())
177    }
178    pub fn podcast_revision(&self) -> Result<u64> {
179        Ok(self
180            .conn
181            .query_row("SELECT n FROM podcast_revision", [], |r| r.get(0))?)
182    }
183    pub fn podcast_feeds(&self) -> Result<Vec<Feed>> {
184        let mut stmt = self.conn.prepare("SELECT json FROM podcast_feeds WHERE subscribed=1 ORDER BY json_extract(json,'$.title'),id")?;
185        let rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
186        rows.map(|r| Ok(serde_json::from_str(&r?)?)).collect()
187    }
188    pub fn podcast_feed_id(&self, value: &str) -> Result<String> {
189        let exact: bool = self
190            .conn
191            .prepare_cached("SELECT EXISTS(SELECT 1 FROM podcast_feeds WHERE id=?1)")?
192            .query_row([value], |r| r.get(0))?;
193        if exact {
194            return Ok(value.into());
195        }
196        let mut stmt = self.conn.prepare_cached(
197            "SELECT id FROM podcast_feeds WHERE json_extract(json,'$.title')=?1 ORDER BY id",
198        )?;
199        let ids = stmt
200            .query_map([value], |r| r.get::<_, String>(0))?
201            .collect::<rusqlite::Result<Vec<_>>>()?;
202        resolve_unique_id(ids)
203    }
204    pub(super) fn podcast_subscribed_urls(
205        &self,
206    ) -> Result<std::collections::HashMap<String, String>> {
207        let mut stmt = self.conn.prepare_cached(
208            "SELECT url,id FROM podcast_feeds WHERE subscribed=1
209             UNION ALL
210             SELECT a.url,f.id FROM podcast_aliases a
211             JOIN podcast_feeds f ON f.id=a.feed_id WHERE f.subscribed=1",
212        )?;
213        let mut map = std::collections::HashMap::new();
214        for row in stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))? {
215            let (url, id) = row?;
216            map.entry(url).or_insert(id);
217        }
218        Ok(map)
219    }
220    pub(super) fn podcast_feeds_page_details(
221        &self,
222        query: &str,
223        page: &crate::model::Page,
224    ) -> Result<(Vec<serde_json::Value>, usize)> {
225        let query = query.to_lowercase();
226        let mut stmt = self.conn.prepare_cached(
227            "SELECT f.json, COALESCE(u.unplayed, 0), m.value
228             FROM podcast_feeds f
229             LEFT JOIN (
230                 SELECT e.feed_id, count(*) AS unplayed
231                 FROM podcast_episodes e
232                 LEFT JOIN podcast_progress p ON p.episode_id=e.id
233                 WHERE COALESCE(p.completed,0)=0
234                 GROUP BY e.feed_id
235             ) u ON u.feed_id=f.id
236             LEFT JOIN meta m ON m.key='podcast_settings:'||f.id
237             WHERE f.subscribed=1
238               AND (?1='' OR instr(podcast_lower(json_extract(f.json,'$.title')),?1)>0)
239             ORDER BY json_extract(f.json,'$.title'),f.id",
240        )?;
241        let all_rows = stmt
242            .query_map([&query], |r| {
243                Ok((
244                    r.get::<_, String>(0)?,
245                    r.get::<_, usize>(1)?,
246                    r.get::<_, Option<String>>(2)?,
247                ))
248            })?
249            .collect::<rusqlite::Result<Vec<_>>>()?;
250        let total = all_rows.len();
251        let limit = if page.all {
252            total
253        } else {
254            usize::from(page.limit)
255        };
256        let mut rows = Vec::with_capacity(limit.min(total.saturating_sub(page.offset)));
257        for (feed_json, unplayed, settings_json) in
258            all_rows.into_iter().skip(page.offset).take(limit)
259        {
260            let feed: Feed = serde_json::from_str(&feed_json)?;
261            let settings: ShowSettings = settings_json
262                .as_deref()
263                .and_then(|s| serde_json::from_str(s).ok())
264                .unwrap_or_default();
265            let mut value = serde_json::json!(feed);
266            value["unplayed_count"] = serde_json::json!(unplayed);
267            value["sort"] = serde_json::json!(settings.sort);
268            rows.push(value);
269        }
270        Ok((rows, total))
271    }
272    pub(super) fn podcast_episodes_details_page(
273        &self,
274        id: &str,
275        query: &str,
276        page: &crate::model::Page,
277        is_file: impl Fn(&str) -> bool,
278    ) -> Result<(String, Vec<serde_json::Value>, usize)> {
279        let resolved = self.podcast_feed_id(id)?;
280        let query = query.to_lowercase();
281        let feed = self.podcast_feed(&resolved)?;
282        let total: usize = self
283            .conn
284            .prepare_cached(
285                "SELECT count(*) FROM podcast_episodes WHERE feed_id=?1
286                 AND (?2='' OR instr(podcast_lower(json_extract(json,'$.title')),?2)>0)",
287            )?
288            .query_row(params![&feed.id, &query], |r| r.get(0))?;
289        let sql = format!(
290            "SELECT e.json,p.position_ms,p.duration_ms,p.completed,
291                    s.episode_id IS NOT NULL,
292                    EXISTS(SELECT 1 FROM podcast_queue q WHERE q.episode_id=e.id),
293                    d.json
294             FROM podcast_episodes e
295             LEFT JOIN podcast_progress p ON p.episode_id=e.id
296             LEFT JOIN podcast_saved s ON s.episode_id=e.id
297             LEFT JOIN podcast_downloads d ON d.episode_id=e.id
298             WHERE e.feed_id=?1
299               AND (?2='' OR instr(podcast_lower(json_extract(e.json,'$.title')),?2)>0)
300             ORDER BY {EPISODE_NEWEST_ORDER_E} LIMIT ?3 OFFSET ?4"
301        );
302        let mut stmt = self.conn.prepare_cached(&sql)?;
303        let mut rows = stmt.query(params![
304            &feed.id,
305            &query,
306            if page.all { -1 } else { i64::from(page.limit) },
307            page.offset.min(i64::MAX as usize) as i64,
308        ])?;
309        let mut items = Vec::new();
310        while let Some(row) = rows.next()? {
311            let episode = episode_from_row(row)?;
312            let saved: bool = row.get(4)?;
313            let queued: bool = row.get(5)?;
314            let download: Option<Download> = row
315                .get::<_, Option<String>>(6)?
316                .as_deref()
317                .map(serde_json::from_str)
318                .transpose()?;
319            items.push(episode_details(
320                &episode,
321                &feed.title,
322                &feed.author,
323                saved,
324                queued,
325                download.as_ref(),
326                &is_file,
327            ));
328        }
329        Ok((feed.title, items, total))
330    }
331    pub(super) fn podcast_downloads_details(
332        &self,
333        is_file: impl Fn(&str) -> bool,
334    ) -> Result<Vec<serde_json::Value>> {
335        let mut stmt = self.conn.prepare_cached(
336            "SELECT e.json,p.position_ms,p.duration_ms,p.completed,
337                    COALESCE(json_extract(f.json,'$.title'),''),
338                    COALESCE(json_extract(f.json,'$.author'),''),
339                    s.episode_id IS NOT NULL,
340                    EXISTS(SELECT 1 FROM podcast_queue q WHERE q.episode_id=e.id),
341                    d.json
342             FROM podcast_downloads d
343             JOIN podcast_episodes e ON e.id=d.episode_id
344             JOIN podcast_feeds f ON f.id=e.feed_id
345             LEFT JOIN podcast_progress p ON p.episode_id=e.id
346             LEFT JOIN podcast_saved s ON s.episode_id=e.id
347             ORDER BY d.episode_id",
348        )?;
349        let mut rows = stmt.query([])?;
350        let mut out = Vec::new();
351        while let Some(row) = rows.next()? {
352            let episode = episode_from_row(row)?;
353            let feed_title: String = row.get(4)?;
354            let feed_author: String = row.get(5)?;
355            let saved: bool = row.get(6)?;
356            let queued: bool = row.get(7)?;
357            let download: Download = serde_json::from_str(&row.get::<_, String>(8)?)?;
358            let mut value = episode_details(
359                &episode,
360                &feed_title,
361                &feed_author,
362                saved,
363                queued,
364                Some(&download),
365                &is_file,
366            );
367            value
368                .as_object_mut()
369                .unwrap()
370                .extend(serde_json::json!(download).as_object().unwrap().clone());
371            out.push(value);
372        }
373        Ok(out)
374    }
375    pub(super) fn podcast_queue_details(
376        &self,
377        is_file: impl Fn(&str) -> bool,
378    ) -> Result<Vec<serde_json::Value>> {
379        let mut stmt = self.conn.prepare_cached(
380            "SELECT e.json,p.position_ms,p.duration_ms,p.completed,
381                    COALESCE(json_extract(f.json,'$.title'),''),
382                    COALESCE(json_extract(f.json,'$.author'),''),
383                    s.episode_id IS NOT NULL,
384                    d.json
385             FROM podcast_queue q
386             JOIN podcast_episodes e ON e.id=q.episode_id
387             JOIN podcast_feeds f ON f.id=e.feed_id
388             LEFT JOIN podcast_progress p ON p.episode_id=e.id
389             LEFT JOIN podcast_saved s ON s.episode_id=e.id
390             LEFT JOIN podcast_downloads d ON d.episode_id=e.id
391             ORDER BY q.position",
392        )?;
393        let mut rows = stmt.query([])?;
394        let mut out = Vec::new();
395        while let Some(row) = rows.next()? {
396            let episode = episode_from_row(row)?;
397            let feed_title: String = row.get(4)?;
398            let feed_author: String = row.get(5)?;
399            let saved: bool = row.get(6)?;
400            let download: Option<Download> = row
401                .get::<_, Option<String>>(7)?
402                .as_deref()
403                .map(serde_json::from_str)
404                .transpose()?;
405            out.push(episode_details(
406                &episode,
407                &feed_title,
408                &feed_author,
409                saved,
410                true,
411                download.as_ref(),
412                &is_file,
413            ));
414        }
415        Ok(out)
416    }
417    pub fn podcast_episode_id(&self, value: &str) -> Result<String> {
418        let exists: bool = self.conn.query_row(
419            "SELECT EXISTS(SELECT 1 FROM podcast_episodes WHERE id=?1)",
420            [value],
421            |r| r.get(0),
422        )?;
423        if exists {
424            return Ok(value.into());
425        }
426        let (feed, title) = value
427            .split_once("::")
428            .ok_or_else(|| error(crate::t!("podcast_not_found")))?;
429        let feed = self.podcast_feed_id(feed)?;
430        let mut stmt = self.conn.prepare("SELECT id FROM podcast_episodes WHERE feed_id=?1 AND json_extract(json,'$.title')=?2 ORDER BY id")?;
431        let ids = stmt
432            .query_map(params![feed, title], |r| r.get::<_, String>(0))?
433            .collect::<rusqlite::Result<Vec<_>>>()?;
434        resolve_unique_id(ids)
435    }
436    pub fn podcast_feed(&self, id: &str) -> Result<Feed> {
437        let id = self.podcast_feed_id(id)?;
438        let json: Option<String> = self
439            .conn
440            .query_row("SELECT json FROM podcast_feeds WHERE id=?1", [id], |r| {
441                r.get(0)
442            })
443            .optional()?;
444        Ok(serde_json::from_str(
445            &json.ok_or_else(|| error(crate::t!("podcast_not_found")))?,
446        )?)
447    }
448    pub fn podcast_by_url(&self, url: &str) -> Result<Option<Feed>> {
449        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()?;
450        id.map(|id| self.podcast_feed(&id)).transpose()
451    }
452    pub fn podcast_subscribe(&self, preview: &Preview, requested: &str) -> Result<Feed> {
453        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
454        let mut feed = self
455            .podcast_by_url(requested)?
456            .or(self.podcast_by_url(&preview.feed.url)?)
457            .unwrap_or_else(|| Feed {
458                id: uuid::Uuid::new_v4().to_string(),
459                ..Default::default()
460            });
461        let id = feed.id.clone();
462        let revision = feed.revision.saturating_add(1);
463        feed = preview.feed.clone();
464        feed.revision = revision;
465        feed.id = id;
466        feed.subscribed = true;
467        self.podcast_write(&feed)?;
468        for url in [requested, &feed.url] {
469            self.conn.execute(
470                "INSERT INTO podcast_aliases VALUES (?1,?2) ON CONFLICT(url) DO NOTHING",
471                params![url, feed.id],
472            )?;
473        }
474        self.podcast_merge(&feed.id, &preview.episodes, false)?;
475        tx.commit()?;
476        Ok(feed)
477    }
478    pub(crate) fn podcast_write(&self, feed: &Feed) -> Result<()> {
479        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)?])?;
480        Ok(())
481    }
482    pub(crate) fn podcast_refresh_error(&self, f: &Feed) -> Result<()> {
483        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])?;
484        Ok(())
485    }
486    pub fn podcast_refresh_merge(&self, old: &Feed, preview: Option<Preview>) -> Result<()> {
487        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
488        let current = self.podcast_feed(&old.id)?;
489        if !current.subscribed || current.revision != old.revision {
490            return Ok(());
491        }
492        let mut feed = preview.as_ref().map(|p| p.feed.clone()).unwrap_or(current);
493        feed.id = old.id.clone();
494        feed.subscribed = true;
495        feed.error = None;
496        feed.failures = 0;
497        feed.revision = old.revision.saturating_add(1);
498        feed.refreshed_at = Some(crate::timestamp::now());
499        if self
500            .podcast_by_url(&feed.url)?
501            .is_some_and(|owner| owner.id != feed.id)
502        {
503            return Err(error(crate::t!("podcast_url_conflict")));
504        }
505        self.podcast_write(&feed)?;
506        self.conn.execute(
507            "INSERT OR IGNORE INTO podcast_aliases VALUES (?1,?2)",
508            params![feed.url, feed.id],
509        )?;
510        if let Some(p) = preview {
511            self.podcast_merge(&feed.id, &p.episodes, true)?;
512        }
513        tx.commit()?;
514        Ok(())
515    }
516    fn podcast_merge(&self, feed_id: &str, episodes: &[Episode], baseline: bool) -> Result<()> {
517        let settings = self.podcast_settings(feed_id)?;
518        let mut existing: std::collections::HashMap<String, (String, String)> = {
519            let mut stmt = self
520                .conn
521                .prepare_cached("SELECT identity,id,json FROM podcast_episodes WHERE feed_id=?1")?;
522            stmt.query_map([feed_id], |r| {
523                Ok((
524                    r.get::<_, String>(0)?,
525                    (r.get::<_, String>(1)?, r.get::<_, String>(2)?),
526                ))
527            })?
528            .collect::<rusqlite::Result<_>>()?
529        };
530        let mut upsert_stmt = self.conn.prepare_cached(
531            "INSERT INTO podcast_episodes(id,feed_id,identity,json) VALUES (?1,?2,?3,?4)
532             ON CONFLICT(feed_id,identity) DO UPDATE SET json=excluded.json
533             WHERE podcast_episodes.json IS NOT excluded.json",
534        )?;
535        let mut reset_progress_stmt = self
536            .conn
537            .prepare_cached("UPDATE podcast_progress SET completed=0 WHERE episode_id=?1")?;
538        let mut inbox_stmt = self
539            .conn
540            .prepare_cached("INSERT OR IGNORE INTO podcast_inbox VALUES (?1)")?;
541        for (order, item) in episodes.iter().enumerate() {
542            let identity = item
543                .guid
544                .as_ref()
545                .map(|g| format!("guid:{g}"))
546                .unwrap_or_else(|| format!("url:{}", item.url));
547            let mut e = item.clone();
548            e.source_order = e.source_order.or(Some(order as u64));
549            e.feed_id = feed_id.into();
550            let old_entry = existing.get(&identity);
551            let new_episode = old_entry.is_none();
552            if let Some((old_id, old_json)) = old_entry {
553                e.id = old_id.clone();
554                let new_json = serde_json::to_string(&e)?;
555                if new_json == *old_json {
556                    continue;
557                }
558                let old: Episode = serde_json::from_str(old_json)?;
559                if (old.bytes.is_some() && e.bytes.is_some() && old.bytes != e.bytes)
560                    || (old.duration_ms.is_some()
561                        && e.duration_ms.is_some()
562                        && old.duration_ms != e.duration_ms)
563                {
564                    reset_progress_stmt.execute([&old.id])?;
565                }
566                upsert_stmt.execute(params![e.id, feed_id, identity, new_json])?;
567                existing.insert(identity, (e.id, new_json));
568            } else {
569                e.id = uuid::Uuid::new_v4().to_string();
570                let new_json = serde_json::to_string(&e)?;
571                upsert_stmt.execute(params![e.id, feed_id, identity, new_json])?;
572                existing.insert(identity, (e.id.clone(), new_json));
573                if baseline && new_episode {
574                    if settings.auto_download && !e.completed {
575                        self.podcast_save_download(&Download {
576                            episode_id: e.id.clone(),
577                            state: DownloadState::Queued.as_str().into(),
578                            enqueued_at: Some(crate::timestamp::now()),
579                            ..Default::default()
580                        })?;
581                    }
582                    inbox_stmt.execute([&e.id])?;
583                }
584            }
585        }
586        Ok(())
587    }
588    pub fn podcast_unsubscribe(&self, id: &str) -> Result<()> {
589        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
590        let mut f = self.podcast_feed(id)?;
591        f.subscribed = false;
592        f.revision = f.revision.saturating_add(1);
593        self.podcast_write(&f)?;
594        tx.commit()?;
595        Ok(())
596    }
597    pub fn podcast_episode(&self, id: &str) -> Result<Episode> {
598        let resolved = self.podcast_episode_id(id)?;
599        self.conn
600            .prepare_cached(
601                "SELECT e.json,p.position_ms,p.duration_ms,p.completed
602                 FROM podcast_episodes e
603                 LEFT JOIN podcast_progress p ON p.episode_id=e.id
604                 WHERE e.id=?1",
605            )?
606            .query_row([resolved.as_str()], |row| {
607                episode_from_row(row).map_err(|e| {
608                    rusqlite::Error::FromSqlConversionFailure(
609                        0,
610                        rusqlite::types::Type::Text,
611                        e.into(),
612                    )
613                })
614            })
615            .optional()?
616            .ok_or_else(|| error(crate::t!("podcast_not_found")))
617    }
618    pub fn podcast_episodes(&self, id: &str) -> Result<Vec<Episode>> {
619        let feed = self.podcast_feed(id)?;
620        self.podcast_episode_rows(&feed.id, "", -1, 0)
621    }
622    pub(crate) fn podcast_episode_position(&self, feed: &str, id: &str) -> Result<Option<usize>> {
623        Ok(self
624            .conn
625            .query_row(
626                &format!(
627                    "SELECT position FROM (
628                        SELECT id,row_number() OVER (ORDER BY {EPISODE_NEWEST_ORDER})-1 AS position
629                        FROM podcast_episodes WHERE feed_id=?1
630                     ) WHERE id=?2",
631                ),
632                params![feed, id],
633                |r| r.get(0),
634            )
635            .optional()?)
636    }
637    pub fn podcast_episodes_page(
638        &self,
639        id: &str,
640        query: &str,
641        page: &crate::model::Page,
642    ) -> Result<(Vec<Episode>, usize)> {
643        let feed = self.podcast_feed(id)?;
644        let id = feed.id.as_str();
645        let query = query.to_lowercase();
646        self.read_snapshot(|store| {
647            store.podcast_feed(id)?;
648            let total = store.conn.query_row(
649                "SELECT count(*) FROM podcast_episodes WHERE feed_id=?1
650                 AND (?2='' OR instr(podcast_lower(json_extract(json,'$.title')),?2)>0)",
651                params![id, query],
652                |r| r.get(0),
653            )?;
654            let items = store.podcast_episode_rows(
655                id,
656                &query,
657                if page.all { -1 } else { i64::from(page.limit) },
658                page.offset.min(i64::MAX as usize) as i64,
659            )?;
660            Ok((items, total))
661        })
662    }
663    fn podcast_episode_rows(
664        &self,
665        id: &str,
666        query: &str,
667        limit: i64,
668        offset: i64,
669    ) -> Result<Vec<Episode>> {
670        let mut stmt = self.conn.prepare_cached(&episode_page_sql())?;
671        read_episode_rows(&mut stmt, params![id, query, limit, offset])
672    }
673    /// Save progress only while the supplied media snapshot is still current.
674    pub fn podcast_progress(
675        &self,
676        episode: &Episode,
677        pos: u64,
678        duration: Option<u64>,
679        completed: bool,
680    ) -> Result<()> {
681        self.podcast_save_progress(
682            &episode.id,
683            &EpisodeProgress {
684                media: episode.media(),
685                position_ms: pos,
686                observed_duration_ms: duration,
687                completed,
688            },
689        )
690    }
691    pub(crate) fn podcast_save_progress(&self, id: &str, progress: &EpisodeProgress) -> Result<()> {
692        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
693        Self::write_podcast_progress(&tx, id, progress)?;
694        tx.commit()?;
695        Ok(())
696    }
697    pub(crate) fn write_podcast_progress(
698        tx: &rusqlite::Transaction<'_>,
699        id: &str,
700        progress: &EpisodeProgress,
701    ) -> Result<()> {
702        let json: Option<String> = tx
703            .query_row("SELECT json FROM podcast_episodes WHERE id=?1", [id], |r| {
704                r.get(0)
705            })
706            .optional()?;
707        let Some(json) = json else { return Ok(()) };
708        let episode: Episode = serde_json::from_str(&json)?;
709        // The write transaction also excludes refreshes between this check and
710        // the UPSERT. An old media snapshot must not undo a refresh's reset.
711        if episode.media() != progress.media {
712            return Ok(());
713        }
714        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,crate::timestamp::now()])?;
715        Ok(())
716    }
717    pub fn podcast_played(&self, id: &str) -> Result<()> {
718        self.save_session(
719            &Default::default(),
720            &[(
721                crate::store::Played::Episode(id.into()),
722                crate::timestamp::now(),
723            )],
724        )
725    }
726    pub fn podcast_download(&self, id: &str) -> Result<Option<Download>> {
727        let json: Option<String> = self
728            .conn
729            .query_row(
730                "SELECT json FROM podcast_downloads WHERE episode_id=?1",
731                [id],
732                |r| r.get(0),
733            )
734            .optional()?;
735        json.map(|j| Ok(serde_json::from_str(&j)?)).transpose()
736    }
737    pub(crate) fn podcast_claim_download(&self, expected: &Download) -> Result<Option<Download>> {
738        let json: Option<String> = self
739            .conn
740            .query_row(
741                "UPDATE podcast_downloads
742                 SET json=json_set(json,'$.state','downloading','$.error',NULL,'$.generation',?4)
743                 WHERE episode_id=?1 AND json_extract(json,'$.state')=?2
744                 AND json_extract(json,'$.state') IN ('queued','downloading')
745                 AND COALESCE(json_extract(json,'$.generation'),0)=?3
746                 RETURNING json",
747                params![
748                    expected.episode_id,
749                    expected.state,
750                    expected.generation,
751                    expected.generation.saturating_add(1)
752                ],
753                |r| r.get(0),
754            )
755            .optional()?;
756        json.map(|j| Ok(serde_json::from_str(&j)?)).transpose()
757    }
758    pub(crate) fn podcast_download_transaction<T>(
759        &self,
760        id: &str,
761        update: impl FnOnce(Option<Download>) -> Result<T>,
762    ) -> Result<T> {
763        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
764        let value = update(self.podcast_download(id)?)?;
765        tx.commit()?;
766        Ok(value)
767    }
768    pub(crate) fn podcast_download_update(&self, d: &Download) -> Result<()> {
769        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])?;
770        if changed == 0 {
771            return Err(DomainError::new(ErrorCode::Cancelled).into());
772        }
773        Ok(())
774    }
775    pub fn podcast_save_download(&self, d: &Download) -> Result<()> {
776        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)?])?;
777        Ok(())
778    }
779    pub(super) fn scheduled_downloads(&self) -> Result<Vec<Download>> {
780        let mut stmt = self.conn.prepare_cached(
781            "SELECT d.json, json_extract(d.json,'$.state')='complete'
782             FROM podcast_downloads d JOIN podcast_episodes e ON e.id=d.episode_id
783             LEFT JOIN podcast_progress p ON p.episode_id=e.id
784             LEFT JOIN meta m ON m.key='podcast_settings:' || e.feed_id
785             WHERE json_extract(d.json,'$.state') IN ('queued','downloading')
786                OR (json_extract(d.json,'$.state')='complete'
787                    AND COALESCE(p.completed,json_extract(e.json,'$.completed'),0)
788                    AND json_extract(m.value,'$.auto_cleanup')
789                    AND NOT EXISTS(SELECT 1 FROM podcast_queue q WHERE q.episode_id=e.id))
790             ORDER BY COALESCE(json_extract(d.json,'$.enqueued_at'),''),d.rowid",
791        )?;
792        let mut rows = stmt.query([])?;
793        let mut downloads = Vec::new();
794        while let Some(row) = rows.next()? {
795            let mut download: Download = serde_json::from_str(&row.get::<_, String>(0)?)?;
796            download.cleanup_eligible = row.get(1)?;
797            downloads.push(download);
798        }
799        Ok(downloads)
800    }
801    pub fn podcast_downloads(&self) -> Result<Vec<Download>> {
802        let mut stmt = self
803            .conn
804            .prepare("SELECT json FROM podcast_downloads ORDER BY COALESCE(json_extract(json,'$.enqueued_at'),''),rowid")?;
805        stmt.query_map([], |r| r.get::<_, String>(0))?
806            .map(|j| Ok(serde_json::from_str(&j?)?))
807            .collect()
808    }
809    pub fn podcast_queue(&self) -> Result<Vec<Episode>> {
810        let mut stmt = self.conn.prepare_cached(
811            "SELECT e.json,p.position_ms,p.duration_ms,p.completed FROM podcast_queue q
812             LEFT JOIN podcast_episodes e ON e.id=q.episode_id
813             LEFT JOIN podcast_progress p ON p.episode_id=q.episode_id
814             ORDER BY q.position,q.rowid",
815        )?;
816        read_episode_rows(&mut stmt, [])
817    }
818    fn queue_ids(&self) -> Result<Vec<String>> {
819        Ok(self
820            .conn
821            .prepare_cached("SELECT episode_id FROM podcast_queue ORDER BY position,rowid")?
822            .query_map([], |r| r.get(0))?
823            .collect::<rusqlite::Result<_>>()?)
824    }
825    pub fn podcast_queue_set(&self, ids: &[String]) -> Result<()> {
826        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
827        let mut seen = std::collections::HashSet::new();
828        let unique: Vec<_> = ids.iter().filter(|id| seen.insert(*id)).cloned().collect();
829        if unique != self.queue_ids()? {
830            self.podcast_queue_write(&unique)?;
831        }
832        tx.commit()?;
833        Ok(())
834    }
835    pub fn podcast_queue_update(&self, action: QueueAction) -> Result<Vec<Episode>> {
836        self.podcast_queue_update_revision(action)
837            .map(|(items, _)| items)
838    }
839    pub(crate) fn podcast_queue_revision(&self) -> Result<u64> {
840        Ok(self
841            .meta("podcast_queue_revision")?
842            .and_then(|v| v.parse().ok())
843            .unwrap_or(0))
844    }
845    pub(crate) fn podcast_queue_snapshot(&self) -> Result<(Vec<Episode>, u64)> {
846        self.read_snapshot(|store| Ok((store.podcast_queue()?, store.podcast_queue_revision()?)))
847    }
848    pub(crate) fn podcast_queue_update_revision(
849        &self,
850        action: QueueAction,
851    ) -> Result<(Vec<Episode>, u64)> {
852        if matches!(action, QueueAction::List) {
853            return self.podcast_queue_snapshot();
854        }
855        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
856        let original = self.queue_ids()?;
857        let mut ids = original.clone();
858        match action {
859            QueueAction::Add { id } => {
860                self.podcast_episode(&id)?;
861                if !ids.contains(&id) {
862                    ids.push(id);
863                }
864            }
865            QueueAction::Next { id, after } => {
866                self.podcast_episode(&id)?;
867                if after.as_ref() == Some(&id) {
868                    return Err(error(crate::t!("podcast_invalid_time")));
869                }
870                ids.retain(|v| v != &id);
871                let position = after
872                    .and_then(|after| ids.iter().position(|v| v == &after))
873                    .map_or(0, |p| p + 1);
874                ids.insert(position, id);
875            }
876            QueueAction::Remove { id } => ids.retain(|v| v != &id),
877            QueueAction::Clear => ids.clear(),
878            QueueAction::Move { id, position } => {
879                if position == 0 || position > ids.len() || !ids.contains(&id) {
880                    return Err(error(crate::t!("podcast_invalid_time")));
881                }
882                ids.retain(|v| v != &id);
883                ids.insert(position - 1, id);
884            }
885            QueueAction::MoveAdjacent { id, up } => {
886                let current = ids
887                    .iter()
888                    .position(|v| v == &id)
889                    .ok_or_else(|| error(crate::t!("podcast_not_found")))?;
890                let target = if up {
891                    current.saturating_sub(1)
892                } else {
893                    (current + 1).min(ids.len() - 1)
894                };
895                ids.swap(current, target);
896            }
897            QueueAction::Play { .. } | QueueAction::Start { .. } => {
898                return Err(error(crate::t!("podcast_playback_only")));
899            }
900            QueueAction::List => unreachable!(),
901        }
902        if ids != original {
903            self.podcast_queue_write(&ids)?;
904        }
905        let items = self.podcast_queue()?;
906        let revision = self.podcast_queue_revision()?;
907        tx.commit()?;
908        Ok((items, revision))
909    }
910    pub(crate) fn podcast_queue_complete(
911        &self,
912        id: &str,
913    ) -> Result<(Vec<Episode>, u64, std::collections::HashSet<String>)> {
914        let tx = rusqlite::Transaction::new_unchecked(&self.conn, TransactionBehavior::Immediate)?;
915        let mut items = self.podcast_queue()?;
916        let earlier = items
917            .iter()
918            .take_while(|e| e.id != id)
919            .map(|e| e.id.clone())
920            .collect();
921        if tx.execute("DELETE FROM podcast_queue WHERE episode_id=?1", [id])? != 0 {
922            items.retain(|e| e.id != id);
923            self.advance_queue_revision()?;
924        }
925        let revision = self.podcast_queue_revision()?;
926        tx.commit()?;
927        Ok((items, revision, earlier))
928    }
929    fn podcast_queue_write(&self, ids: &[String]) -> Result<()> {
930        self.conn.execute("DELETE FROM podcast_queue", [])?;
931        for (i, id) in ids.iter().enumerate() {
932            self.conn.execute(
933                "INSERT OR IGNORE INTO podcast_queue VALUES (?1,?2)",
934                params![id, i],
935            )?;
936        }
937        self.advance_queue_revision()
938    }
939    fn advance_queue_revision(&self) -> Result<()> {
940        self.conn.execute(
941            "INSERT INTO meta(key,value) VALUES ('podcast_queue_revision','1')
942            ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1",
943            [],
944        )?;
945        Ok(())
946    }
947}
948
949#[cfg(test)]
950mod tests {
951    use super::*;
952
953    #[test]
954    fn schema_ten_episode_order_keeps_legacy_rows_and_uses_the_date_index() {
955        let dir = tempfile::tempdir().unwrap();
956        let path = dir.path().join("radio.db");
957        let store = Store::open(&path).unwrap();
958        let preview = Preview {
959            feed: Feed {
960                url: "https://example.test/rss".into(),
961                ..Default::default()
962            },
963            episodes: [
964                ("Undated", None, 0),
965                ("Legacy", Some("2026-01-01T00:00:00Z"), 70),
966                ("Newest", Some("2026-01-02T00:00:00Z"), 0),
967                ("First on day", Some("2026-01-01T00:00:00Z"), 1),
968                ("Last on day", Some("2026-01-01T00:00:00Z"), 3),
969            ]
970            .into_iter()
971            .map(|(title, published, order)| Episode {
972                title: title.into(),
973                url: format!("https://example.test/{}", title.replace(' ', "-")),
974                published: published.map(str::to_owned),
975                source_order: Some(order),
976                ..Default::default()
977            })
978            .collect(),
979        };
980        let feed = store
981            .podcast_subscribe(&preview, &preview.feed.url)
982            .unwrap();
983        crate::test_support::strip_podcast_episode_order(&store.conn);
984        store
985            .conn
986            .execute_batch(
987                "UPDATE podcast_episodes SET json=json_remove(json,'$.source_order') WHERE rowid=2;
988             CREATE INDEX podcast_episode_dates ON podcast_episodes(
989                 feed_id,CASE WHEN json_valid(json) THEN json_extract(json,'$.published') END DESC,
990                 CASE WHEN json_valid(json) THEN json_extract(json,'$.source_order') END,id);
991             PRAGMA user_version=10;",
992            )
993            .unwrap();
994        drop(store);
995
996        let store = Store::open(&path).unwrap();
997        let episodes = store.podcast_episodes(&feed.id).unwrap();
998        assert_eq!(
999            episodes
1000                .iter()
1001                .map(|e| e.title.as_str())
1002                .collect::<Vec<_>>(),
1003            ["Newest", "First on day", "Legacy", "Last on day", "Undated"],
1004        );
1005        let legacy = &episodes[2];
1006        assert_eq!(legacy.source_order, None);
1007        assert_eq!(
1008            store
1009                .podcast_episode_position(&feed.id, &legacy.id)
1010                .unwrap(),
1011            Some(2)
1012        );
1013        let page = crate::model::Page {
1014            offset: 2,
1015            limit: 2,
1016            all: false,
1017        };
1018        let (rows, total) = store.podcast_episodes_page(&feed.id, "", &page).unwrap();
1019        assert_eq!(rows, episodes[2..4]);
1020        assert_eq!(total, episodes.len());
1021        let plan = store
1022            .conn
1023            .prepare(&format!("EXPLAIN QUERY PLAN {}", episode_page_sql()))
1024            .unwrap()
1025            .query_map(params![feed.id, "", page.limit, page.offset as i64], |r| {
1026                r.get::<_, String>(3)
1027            })
1028            .unwrap()
1029            .collect::<rusqlite::Result<Vec<_>>>()
1030            .unwrap();
1031        assert!(
1032            plan.iter().any(|row| row.contains("podcast_episode_dates")),
1033            "{plan:?}"
1034        );
1035        assert!(
1036            !plan.iter().any(|row| row.contains("TEMP B-TREE")),
1037            "{plan:?}"
1038        );
1039    }
1040    use std::sync::{Arc, Barrier, atomic::AtomicBool};
1041
1042    fn queue_fixture() -> (tempfile::TempDir, crate::config::Config, Vec<Episode>) {
1043        let dir = tempfile::tempdir().unwrap();
1044        let config = crate::test_support::config(dir.path());
1045        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1046        let preview = Preview {
1047            feed: Feed {
1048                url: "https://example.test/rss".into(),
1049                ..Default::default()
1050            },
1051            episodes: (0..2)
1052                .map(|i| Episode {
1053                    guid: Some(i.to_string()),
1054                    url: format!("https://example.test/{i}.mp3"),
1055                    ..Default::default()
1056                })
1057                .collect(),
1058        };
1059        let feed = store
1060            .podcast_subscribe(&preview, &preview.feed.url)
1061            .unwrap();
1062        let episodes = store.podcast_episodes(&feed.id).unwrap();
1063        (dir, config, episodes)
1064    }
1065
1066    #[test]
1067    fn unsubscribing_preserves_a_refresh_committed_before_the_write_lock() -> Result<()> {
1068        use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
1069        let (_dir, config, episodes) = queue_fixture();
1070        let path = config.data_dir.join("radio.db");
1071        let mut store = Store::open(&path)?;
1072        let feed = store.podcast_feed(&episodes[0].feed_id)?;
1073        let old = feed.clone();
1074        let mut refreshed = false;
1075        store
1076            .conn
1077            .authorizer(Some(move |context: AuthContext<'_>| {
1078                if !refreshed
1079                    && matches!(
1080                        context.action,
1081                        AuthAction::Transaction {
1082                            operation: TransactionOperation::Begin
1083                        } | AuthAction::Insert {
1084                            table_name: "podcast_feeds"
1085                        }
1086                    )
1087                {
1088                    refreshed = true;
1089                    let mut updated = old.clone();
1090                    updated.title = "Updated".into();
1091                    Store::open(&path)
1092                        .unwrap()
1093                        .podcast_refresh_merge(
1094                            &old,
1095                            Some(Preview {
1096                                feed: updated,
1097                                episodes: vec![],
1098                            }),
1099                        )
1100                        .unwrap();
1101                }
1102                Authorization::Allow
1103            }))?;
1104        store.podcast_unsubscribe(&feed.id)?;
1105        let saved = store.podcast_feed(&feed.id)?;
1106        assert_eq!(saved.title, "Updated");
1107        assert_eq!(saved.revision, feed.revision + 2);
1108        assert!(!saved.subscribed);
1109        Ok(())
1110    }
1111
1112    #[test]
1113    fn downloaded_filter_only_probes_members_of_the_selected_collection() {
1114        let (_dir, config, episodes) = queue_fixture();
1115        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1116        let episode = &episodes[0];
1117        let path = config.data_dir.join("local.audio");
1118        std::fs::write(&path, b"fixture").unwrap();
1119        store
1120            .podcast_save_download(&Download {
1121                episode_id: episode.id.clone(),
1122                state: "complete".into(),
1123                url: episode.url.clone(),
1124                media: Some(episode.media()),
1125                path: path.to_str().unwrap().into(),
1126                ..Default::default()
1127            })
1128            .unwrap();
1129        let files = Arc::new(super::super::download_files::DownloadFiles::default());
1130        for view in ["inbox", "history", "saved", "continue"] {
1131            let query = LibraryQuery {
1132                view: view.into(),
1133                downloaded: true,
1134                ..Default::default()
1135            };
1136            let page = store.podcast_library_with_files(&query, &files).unwrap();
1137            assert_eq!(page["total"], 0, "{view}");
1138            assert!(
1139                files.take_observations().is_empty(),
1140                "{view} probed an excluded file"
1141            );
1142        }
1143        store.podcast_save_episode(&episode.id, false).unwrap();
1144        let query = LibraryQuery {
1145            view: "saved".into(),
1146            downloaded: true,
1147            ..Default::default()
1148        };
1149        let page = store.podcast_library_with_files(&query, &files).unwrap();
1150        assert_eq!(page["total"], 1);
1151        assert_eq!(page["items"][0]["id"], episode.id);
1152        assert_eq!(
1153            files.take_observations().get(path.to_str().unwrap()),
1154            Some(&true)
1155        );
1156    }
1157
1158    #[test]
1159    fn downloaded_library_releases_the_read_snapshot_before_probing_files() {
1160        let (_dir, config, episodes) = queue_fixture();
1161        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1162        let episode = &episodes[0];
1163        let audio = config.data_dir.join("local.audio");
1164        std::fs::write(&audio, b"fixture").unwrap();
1165        store
1166            .podcast_save_download(&Download {
1167                episode_id: episode.id.clone(),
1168                state: "complete".into(),
1169                url: episode.url.clone(),
1170                media: Some(episode.media()),
1171                path: audio.to_string_lossy().into_owned(),
1172                ..Default::default()
1173            })
1174            .unwrap();
1175        let mut files = super::super::download_files::DownloadFiles::default();
1176        files.before_probe = Some(|path| {
1177            let db = std::path::Path::new(path).with_file_name("radio.db");
1178            let writer = rusqlite::Connection::open(db).unwrap();
1179            writer.busy_timeout(std::time::Duration::ZERO).unwrap();
1180            writer
1181                .execute(
1182                    "INSERT INTO meta(key,value) VALUES ('checkpoint-test','ok')",
1183                    [],
1184                )
1185                .unwrap();
1186            let busy: i64 = writer
1187                .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get(0))
1188                .unwrap();
1189            assert_eq!(busy, 0);
1190        });
1191        let query = LibraryQuery {
1192            downloaded: true,
1193            ..Default::default()
1194        };
1195        let result = store
1196            .podcast_library_with_files(&query, &std::sync::Arc::new(files))
1197            .unwrap();
1198        assert_eq!(result["total"], 1);
1199        assert_eq!(result["items"][0]["id"], episode.id);
1200        assert_eq!(result["items"][0]["download_state"], "complete");
1201    }
1202
1203    #[test]
1204    fn cli_marks_cannot_overwrite_progress_after_a_concurrent_media_refresh() {
1205        use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
1206        use std::{sync::mpsc, time::Duration};
1207
1208        for state in ["played", "unplayed"] {
1209            for changed in ["duration", "bytes", "url", "title", "unchanged"] {
1210                let dir = tempfile::tempdir().unwrap();
1211                let config = crate::test_support::config(dir.path());
1212                let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1213                let mut preview = Preview {
1214                    feed: Feed {
1215                        url: "https://example.test/rss".into(),
1216                        ..Default::default()
1217                    },
1218                    episodes: vec![Episode {
1219                        guid: Some("episode".into()),
1220                        url: "https://example.test/audio".into(),
1221                        duration_ms: Some(20000),
1222                        bytes: Some(100),
1223                        ..Default::default()
1224                    }],
1225                };
1226                let feed = store
1227                    .podcast_subscribe(&preview, &preview.feed.url)
1228                    .unwrap();
1229                let episode = store.podcast_episodes(&feed.id).unwrap().remove(0);
1230                store
1231                    .podcast_progress(&episode, 15000, Some(20000), true)
1232                    .unwrap();
1233
1234                let (ready, wait) = mpsc::channel();
1235                let (release, go) = mpsc::channel();
1236                let id = episode.id.clone();
1237                let worker = std::thread::spawn(move || {
1238                    let mut store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1239                    let mut synchronized = false;
1240                    // Mark has read its media snapshot before requesting the
1241                    // write transaction. The INSERT hook catches the old path
1242                    // which bypassed that transaction and its media guard.
1243                    store
1244                        .conn
1245                        .authorizer(Some(move |context: AuthContext<'_>| {
1246                            if !synchronized
1247                                && matches!(
1248                                    context.action,
1249                                    AuthAction::Transaction {
1250                                        operation: TransactionOperation::Begin
1251                                    } | AuthAction::Insert {
1252                                        table_name: "podcast_progress"
1253                                    }
1254                                )
1255                            {
1256                                synchronized = true;
1257                                ready.send(()).unwrap();
1258                                go.recv_timeout(Duration::from_secs(3)).unwrap();
1259                            }
1260                            Authorization::Allow
1261                        }))
1262                        .unwrap();
1263                    manage(
1264                        &config,
1265                        &store,
1266                        Action::Mark {
1267                            id,
1268                            state: state.into(),
1269                        },
1270                        &Arc::new(AtomicBool::new(false)),
1271                    )
1272                    .unwrap()
1273                });
1274                wait.recv_timeout(Duration::from_secs(3)).unwrap();
1275                match changed {
1276                    "duration" => preview.episodes[0].duration_ms = Some(40000),
1277                    "bytes" => preview.episodes[0].bytes = Some(200),
1278                    "url" => preview.episodes[0].url = "https://example.test/new-audio".into(),
1279                    "title" => preview.episodes[0].title = "Updated title".into(),
1280                    "unchanged" => {}
1281                    _ => unreachable!(),
1282                }
1283                store.podcast_refresh_merge(&feed, Some(preview)).unwrap();
1284                let mut expected = store.podcast_episode(&episode.id).unwrap();
1285                if matches!(changed, "title" | "unchanged") {
1286                    expected.completed = state == "played";
1287                    expected.position_ms = if expected.completed { 20000 } else { 0 };
1288                }
1289                release.send(()).unwrap();
1290                let result = worker.join().unwrap();
1291                assert_eq!(
1292                    store.podcast_episode(&episode.id).unwrap(),
1293                    expected,
1294                    "{state}: {changed}"
1295                );
1296                assert_eq!(result, serde_json::to_value(&expected).unwrap());
1297            }
1298        }
1299    }
1300
1301    #[test]
1302    fn download_controls_read_the_generation_after_a_concurrent_claim() {
1303        use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
1304        use std::sync::mpsc;
1305        for control in ["pause", "cancel", "enqueue"] {
1306            let (_dir, config, episodes) = queue_fixture();
1307            let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1308            let snapshot = Download {
1309                episode_id: episodes[0].id.clone(),
1310                state: "queued".into(),
1311                generation: 7,
1312                ..Default::default()
1313            };
1314            store.podcast_save_download(&snapshot).unwrap();
1315            let (ready, wait) = mpsc::channel();
1316            let (release, go) = mpsc::channel();
1317            let id = snapshot.episode_id.clone();
1318            let config = config.clone();
1319            let worker = std::thread::spawn(move || {
1320                let mut store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1321                let mut synchronized = false;
1322                // Pause immediately before acquiring the write lock. Without
1323                // a transaction this hook runs at INSERT, after the stale read.
1324                store
1325                    .conn
1326                    .authorizer(Some(move |context: AuthContext<'_>| {
1327                        if !synchronized
1328                            && matches!(
1329                                context.action,
1330                                AuthAction::Transaction {
1331                                    operation: TransactionOperation::Begin
1332                                } | AuthAction::Insert {
1333                                    table_name: "podcast_downloads"
1334                                }
1335                            )
1336                        {
1337                            synchronized = true;
1338                            ready.send(()).unwrap();
1339                            go.recv_timeout(std::time::Duration::from_secs(3)).unwrap();
1340                        }
1341                        Authorization::Allow
1342                    }))
1343                    .unwrap();
1344                if control == "enqueue" {
1345                    super::download::enqueue(&store, &id).unwrap();
1346                } else {
1347                    manage(
1348                        &config,
1349                        &store,
1350                        Action::Downloads {
1351                            action: if control == "pause" {
1352                                DownloadAction::Pause { id: id.clone() }
1353                            } else {
1354                                DownloadAction::Cancel { id: id.clone() }
1355                            },
1356                        },
1357                        &Arc::new(AtomicBool::new(false)),
1358                    )
1359                    .unwrap();
1360                }
1361            });
1362            wait.recv_timeout(std::time::Duration::from_secs(3))
1363                .unwrap();
1364            let mut claimed = store.podcast_claim_download(&snapshot).unwrap().unwrap();
1365            claimed.bytes = 123;
1366            store.podcast_download_update(&claimed).unwrap();
1367            release.send(()).unwrap();
1368            worker.join().unwrap();
1369            let current = store
1370                .podcast_download(&snapshot.episode_id)
1371                .unwrap()
1372                .unwrap();
1373            assert_eq!(current.generation, claimed.generation + 1, "{control}");
1374            assert_eq!(current.bytes, 123);
1375            assert_eq!(
1376                current.state,
1377                match control {
1378                    "pause" => "paused",
1379                    "cancel" => "cancelled",
1380                    _ => "queued",
1381                }
1382            );
1383            assert!(store.podcast_download_update(&claimed).is_err());
1384        }
1385    }
1386
1387    #[test]
1388    fn concurrent_queue_additions_preserve_both_updates() {
1389        use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
1390        let (_dir, config, episodes) = queue_fixture();
1391        let barrier = Arc::new(Barrier::new(2));
1392        let workers: Vec<_> = episodes
1393            .iter()
1394            .map(|e| {
1395                let config = config.clone();
1396                let id = e.id.clone();
1397                let barrier = barrier.clone();
1398                std::thread::spawn(move || {
1399                    let mut store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1400                    let mut synchronized = false;
1401                    // Align the first write transactions. Reading before BEGIN
1402                    // makes both workers overwrite the same old queue snapshot.
1403                    store
1404                        .conn
1405                        .authorizer(Some(move |context: AuthContext<'_>| {
1406                            if !synchronized
1407                                && matches!(
1408                                    context.action,
1409                                    AuthAction::Transaction {
1410                                        operation: TransactionOperation::Begin
1411                                    }
1412                                )
1413                            {
1414                                synchronized = true;
1415                                barrier.wait();
1416                            }
1417                            Authorization::Allow
1418                        }))
1419                        .unwrap();
1420                    manage(
1421                        &config,
1422                        &store,
1423                        Action::Queue {
1424                            action: QueueAction::Add { id },
1425                        },
1426                        &Arc::new(AtomicBool::new(false)),
1427                    )
1428                    .unwrap();
1429                })
1430            })
1431            .collect();
1432        for worker in workers {
1433            worker.join().unwrap();
1434        }
1435        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1436        let mut actual: Vec<_> = store
1437            .podcast_queue()
1438            .unwrap()
1439            .into_iter()
1440            .map(|e| e.id)
1441            .collect();
1442        let mut expected: Vec<_> = episodes.into_iter().map(|e| e.id).collect();
1443        actual.sort();
1444        expected.sort();
1445        assert_eq!(actual, expected);
1446    }
1447
1448    #[test]
1449    fn completing_an_episode_only_removes_its_queue_entry() -> Result<()> {
1450        let (_dir, config, episodes) = queue_fixture();
1451        let store = Store::open(&config.data_dir.join("radio.db"))?;
1452        store.podcast_queue_set(&episodes.iter().map(|e| e.id.clone()).collect::<Vec<_>>())?;
1453        store.podcast_progress(&episodes[1], 100, Some(200), false)?;
1454        let revision = store.podcast_revision()?;
1455        let (remaining, queue_revision, _) = store.podcast_queue_complete(&episodes[0].id)?;
1456        assert_eq!(remaining.len(), 1);
1457        assert_eq!(remaining[0].id, episodes[1].id);
1458        assert_eq!(remaining[0].position_ms, 100);
1459        assert_eq!(store.podcast_revision()?, revision + 1);
1460        assert_eq!(
1461            store.podcast_queue_complete(&episodes[0].id)?.1,
1462            queue_revision
1463        );
1464        Ok(())
1465    }
1466
1467    #[test]
1468    fn listing_the_queue_is_read_only() {
1469        let (_dir, config, episodes) = queue_fixture();
1470        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1471        store.podcast_queue_set(&[episodes[0].id.clone()]).unwrap();
1472        store.conn.execute_batch("PRAGMA query_only=ON").unwrap();
1473        let value = manage(
1474            &config,
1475            &store,
1476            Action::Queue {
1477                action: QueueAction::List,
1478            },
1479            &Arc::new(AtomicBool::new(false)),
1480        )
1481        .unwrap();
1482        assert_eq!(value[0]["id"], episodes[0].id);
1483    }
1484
1485    #[test]
1486    fn repeated_episode_starts_in_one_batch_remain_separate_events() -> Result<()> {
1487        use crate::store::Played;
1488        let (_dir, config, episodes) = queue_fixture();
1489        let store = Store::open(&config.data_dir.join("radio.db"))?;
1490        let events: Vec<_> = [0, 1, 0]
1491            .map(|i| {
1492                (
1493                    Played::Episode(episodes[i].id.clone()),
1494                    crate::timestamp::now(),
1495                )
1496            })
1497            .into();
1498        store.save_session(&Default::default(), &events)?;
1499        let ids = store
1500            .conn
1501            .prepare("SELECT episode_id FROM podcast_history ORDER BY id")?
1502            .query_map([], |r| r.get::<_, String>(0))?
1503            .collect::<rusqlite::Result<Vec<_>>>()?;
1504        assert_eq!(
1505            ids,
1506            [
1507                episodes[0].id.clone(),
1508                episodes[1].id.clone(),
1509                episodes[0].id.clone()
1510            ]
1511        );
1512        assert_eq!(
1513            store.meta("pref_last_episode")?,
1514            Some(episodes[0].id.clone())
1515        );
1516        Ok(())
1517    }
1518    #[test]
1519    fn schedule_reads_only_runnable_downloads_and_eligible_completions() -> Result<()> {
1520        let (_dir, config, episodes) = queue_fixture();
1521        let store = Store::open(&config.data_dir.join("radio.db"))?;
1522        for (e, state) in episodes.iter().zip(["queued", "complete", "future-state"]) {
1523            store.podcast_save_download(&Download {
1524                episode_id: e.id.clone(),
1525                state: state.into(),
1526                ..Default::default()
1527            })?;
1528        }
1529        let candidates = || -> Result<Vec<_>> {
1530            Ok(store
1531                .scheduled_downloads()?
1532                .into_iter()
1533                .map(|d| (d.episode_id, d.cleanup_eligible))
1534                .collect())
1535        };
1536        assert_eq!(candidates()?, [(episodes[0].id.clone(), false)]);
1537        let e = &episodes[1];
1538        store.podcast_progress(e, 100, Some(100), true)?;
1539        store.podcast_set_setting(&e.feed_id, "auto_cleanup", "true")?;
1540        assert_eq!(
1541            candidates()?,
1542            [(episodes[0].id.clone(), false), (e.id.clone(), true)]
1543        );
1544        store.podcast_queue_set(std::slice::from_ref(&e.id))?;
1545        assert_eq!(candidates()?, [(episodes[0].id.clone(), false)]);
1546        Ok(())
1547    }
1548
1549    #[test]
1550    fn equivalent_edits_keep_the_queue_revision_and_rows() -> Result<()> {
1551        let (_dir, config, episodes) = queue_fixture();
1552        let store = Store::open(&config.data_dir.join("radio.db"))?;
1553        store.podcast_queue_update(QueueAction::Clear)?;
1554        assert_eq!(store.podcast_queue_revision()?, 0);
1555        let id = episodes[0].id.clone();
1556        store.podcast_queue_set(std::slice::from_ref(&id))?;
1557        let before = store.conn.total_changes();
1558        store.podcast_queue_set(&[id.clone(), id.clone()])?;
1559        for action in [
1560            QueueAction::Add { id: id.clone() },
1561            QueueAction::Next {
1562                id: id.clone(),
1563                after: None,
1564            },
1565            QueueAction::Move { id, position: 1 },
1566            QueueAction::Remove {
1567                id: episodes[1].id.clone(),
1568            },
1569        ] {
1570            store.podcast_queue_update(action)?;
1571        }
1572        assert_eq!(store.conn.total_changes(), before);
1573        Ok(())
1574    }
1575
1576    #[test]
1577    fn queue_edits_preserve_order_and_rollback_invalid_moves() {
1578        let (_dir, config, episodes) = queue_fixture();
1579        let store = Store::open(&config.data_dir.join("radio.db")).unwrap();
1580        for episode in [&episodes[0], &episodes[1], &episodes[0]] {
1581            store
1582                .podcast_queue_update(QueueAction::Add {
1583                    id: episode.id.clone(),
1584                })
1585                .unwrap();
1586        }
1587        let reordered = store
1588            .podcast_queue_update(QueueAction::Move {
1589                id: episodes[0].id.clone(),
1590                position: 2,
1591            })
1592            .unwrap();
1593        assert_eq!(
1594            reordered.iter().map(|e| &e.id).collect::<Vec<_>>(),
1595            vec![&episodes[1].id, &episodes[0].id]
1596        );
1597        assert!(
1598            store
1599                .podcast_queue_update(QueueAction::Move {
1600                    id: episodes[0].id.clone(),
1601                    position: 3,
1602                })
1603                .is_err()
1604        );
1605        assert_eq!(store.podcast_queue().unwrap(), reordered);
1606        let remaining = store
1607            .podcast_queue_update(QueueAction::Remove {
1608                id: episodes[1].id.clone(),
1609            })
1610            .unwrap();
1611        assert_eq!(remaining.len(), 1);
1612        assert_eq!(remaining[0].id, episodes[0].id);
1613        assert!(
1614            store
1615                .podcast_queue_update(QueueAction::Clear)
1616                .unwrap()
1617                .is_empty()
1618        );
1619    }
1620}