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