Skip to main content

radio_cli/podcast/
library.rs

1//! Local collections share a stable, filtered query before pagination.
2use crate::{cli::Page, store::Store};
3use anyhow::Result;
4use clap::Args;
5use rusqlite::params;
6use serde_json::{Value, json};
7
8#[derive(Debug, Clone, Args)]
9pub struct LibraryQuery {
10    #[arg(default_value = "all", value_parser = ["all", "inbox", "continue", "history", "saved"])]
11    pub view: String,
12    #[arg(long)]
13    pub feed: Option<String>,
14    #[arg(long, default_value = "")]
15    pub query: String,
16    #[arg(long, default_value = "all", value_parser = ["all", "unplayed", "progress", "played"])]
17    pub status: String,
18    #[arg(long, default_value = "newest", value_parser = ["newest", "oldest", "title"])]
19    pub sort: String,
20    #[arg(long)]
21    pub downloaded: bool,
22    #[command(flatten)]
23    pub page: Page,
24}
25impl Default for LibraryQuery {
26    fn default() -> Self {
27        Self {
28            view: "all".into(),
29            feed: None,
30            query: String::new(),
31            status: "all".into(),
32            sort: "newest".into(),
33            downloaded: false,
34            page: Page {
35                offset: 0,
36                limit: 100,
37                all: false,
38            },
39        }
40    }
41}
42impl Store {
43    pub fn podcast_library(&self, q: &LibraryQuery) -> Result<Value> {
44        let mut q = q.clone();
45        q.feed = q
46            .feed
47            .as_deref()
48            .map(|id| self.podcast_feed_id(id))
49            .transpose()?;
50        self.read_snapshot(|store| {
51            let base = "FROM podcast_episodes e JOIN podcast_feeds f ON f.id=e.feed_id
52                LEFT JOIN podcast_progress p ON p.episode_id=e.id
53                LEFT JOIN podcast_downloads d ON d.episode_id=e.id
54                LEFT JOIN podcast_saved s ON s.episode_id=e.id
55                LEFT JOIN podcast_inbox i ON i.episode_id=e.id
56                LEFT JOIN (SELECT episode_id,MAX(played_at) AS played_at FROM podcast_history GROUP BY episode_id) h ON h.episode_id=e.id
57                WHERE (?1 IS NULL OR e.feed_id=?1)
58                AND (?2='' OR instr(podcast_lower(json_extract(e.json,'$.title')),?2)>0)
59                AND (?3='all' OR (?3='played' AND COALESCE(p.completed,0)=1)
60                  OR (?3='unplayed' AND COALESCE(p.completed,0)=0)
61                  OR (?3='progress' AND COALESCE(p.completed,0)=0 AND p.position_ms>0))
62                AND (?4=0 OR json_extract(d.json,'$.state')='complete')
63                AND ((?5='all' AND f.subscribed=1) OR (?5='continue' AND COALESCE(p.completed,0)=0 AND p.position_ms>0)
64                  OR (?5='history' AND h.played_at IS NOT NULL) OR (?5='saved' AND s.episode_id IS NOT NULL)
65                  OR (?5='inbox' AND i.episode_id IS NOT NULL AND f.subscribed=1))";
66            let query = q.query.to_lowercase();
67            let args = params![q.feed, query, q.status, q.downloaded, q.view];
68            let total: usize = store.conn.query_row(&format!("SELECT count(*) {base}"), args, |r| r.get(0))?;
69            let order = if q.view == "history" { "h.played_at DESC,e.id" }
70                else if q.view == "continue" { "p.updated_at DESC,e.id" }
71                else { match q.sort.as_str() {
72                    "oldest" => "json_extract(e.json,'$.published') IS NULL,json_extract(e.json,'$.published'),COALESCE(json_extract(e.json,'$.source_order'),e.rowid),e.id",
73                    "title" => "podcast_lower(json_extract(e.json,'$.title')),e.id",
74                    _ => "json_extract(e.json,'$.published') DESC,COALESCE(json_extract(e.json,'$.source_order'),e.rowid),e.id",
75                }};
76            let sql = format!("SELECT e.id {base} ORDER BY {order} LIMIT ?6 OFFSET ?7");
77            let mut stmt = store.conn.prepare(&sql)?;
78            let ids = stmt.query_map(params![q.feed, query, q.status, q.downloaded, q.view,
79                if q.page.all { -1 } else { i64::from(q.page.limit) }, q.page.offset as i64], |r| r.get::<_, String>(0))?
80                .collect::<rusqlite::Result<Vec<_>>>()?;
81            let rows = ids.iter().map(|id| super::commands::episode_value(store, &store.podcast_episode(id)?)).collect::<Result<Vec<_>>>()?;
82            let mut value = super::commands::page_result(&rows, total, q.page.clone());
83            if let Some(feed) = &q.feed { value["feed_title"] = json!(store.podcast_feed(feed)?.title); }
84            Ok(value)
85        })
86    }
87    pub fn podcast_save_episode(&self, id: &str, remove: bool) -> Result<()> {
88        let id = self.podcast_episode_id(id)?;
89        if remove {
90            self.conn
91                .execute("DELETE FROM podcast_saved WHERE episode_id=?1", [id])?;
92        } else {
93            self.conn
94                .execute("INSERT OR IGNORE INTO podcast_saved VALUES (?1)", [id])?;
95        }
96        Ok(())
97    }
98    pub fn podcast_dismiss_inbox(&self, id: &str) -> Result<()> {
99        let id = self.podcast_episode_id(id)?;
100        self.conn
101            .execute("DELETE FROM podcast_inbox WHERE episode_id=?1", [id])?;
102        Ok(())
103    }
104}