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