1use super::download_files::DownloadFiles;
3use crate::{model::Page, store::Store};
4use anyhow::Result;
5use clap::Args;
6use serde_json::{Value, json};
7use std::sync::Arc;
8
9#[derive(Debug, Clone, Args)]
10pub struct LibraryQuery {
11 #[arg(default_value = "all", value_parser = ["all", "inbox", "continue", "history", "saved"])]
12 pub view: String,
13 #[arg(long)]
14 pub feed: Option<String>,
15 #[arg(long, default_value = "")]
16 pub query: String,
17 #[arg(long, default_value = "all", value_parser = ["all", "unplayed", "progress", "played"])]
18 pub status: String,
19 #[arg(long, default_value = "newest", value_parser = ["newest", "oldest", "title"])]
20 pub sort: String,
21 #[arg(long)]
22 pub downloaded: bool,
23 #[command(flatten)]
24 pub page: Page,
25}
26impl Default for LibraryQuery {
27 fn default() -> Self {
28 Self {
29 view: "all".into(),
30 feed: None,
31 query: String::new(),
32 status: "all".into(),
33 sort: "newest".into(),
34 downloaded: false,
35 page: Page {
36 offset: 0,
37 limit: 100,
38 all: false,
39 },
40 }
41 }
42}
43impl Store {
44 pub fn podcast_library(&self, q: &LibraryQuery) -> Result<Value> {
45 self.podcast_library_with_files(q, &Arc::default())
46 }
47
48 pub(super) fn podcast_library_with_files(
49 &self,
50 q: &LibraryQuery,
51 files: &Arc<DownloadFiles>,
52 ) -> Result<Value> {
53 let mut q = q.clone();
54 q.feed = q
55 .feed
56 .as_deref()
57 .map(|id| self.podcast_feed_id(id))
58 .transpose()?;
59 super::storage::register_download_availability(&self.conn, files.clone())?;
60 let result = files.read_page_with(|| {
61 self.read_snapshot(|store| {
62 let mut clauses = Vec::new();
65 let mut args: Vec<rusqlite::types::Value> = Vec::new();
66 let from = match q.view.as_str() {
67 "saved" => "FROM podcast_saved s
68 CROSS JOIN podcast_episodes e ON e.id=s.episode_id
69 JOIN podcast_feeds f ON f.id=e.feed_id
70 LEFT JOIN podcast_progress p ON p.episode_id=e.id
71 LEFT JOIN podcast_downloads d ON d.episode_id=e.id",
72 "inbox" => {
73 clauses.push("f.subscribed=1");
74 "FROM podcast_inbox i
75 CROSS JOIN podcast_episodes e ON e.id=i.episode_id
76 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 }
81 "continue" => {
82 clauses.push("p.completed=0 AND p.position_ms>0");
83 "FROM podcast_progress p
84 CROSS JOIN podcast_episodes e ON e.id=p.episode_id
85 JOIN podcast_feeds f ON f.id=e.feed_id
86 LEFT JOIN podcast_downloads d ON d.episode_id=e.id
87 LEFT JOIN podcast_saved s ON s.episode_id=e.id"
88 }
89 "history" => "FROM (SELECT episode_id,MAX(played_at) AS played_at FROM podcast_history GROUP BY episode_id) h
90 CROSS JOIN podcast_episodes e ON e.id=h.episode_id
91 JOIN podcast_feeds f ON f.id=e.feed_id
92 LEFT JOIN podcast_progress p ON p.episode_id=e.id
93 LEFT JOIN podcast_downloads d ON d.episode_id=e.id
94 LEFT JOIN podcast_saved s ON s.episode_id=e.id",
95 _ if q.downloaded => {
96 clauses.push("f.subscribed=1");
97 "FROM podcast_downloads d
98 CROSS JOIN podcast_episodes e ON e.id=d.episode_id
99 JOIN podcast_feeds f ON f.id=e.feed_id
100 LEFT JOIN podcast_progress p ON p.episode_id=e.id
101 LEFT JOIN podcast_saved s ON s.episode_id=e.id"
102 }
103 _ => {
104 clauses.push("f.subscribed=1");
105 "FROM podcast_episodes e
106 JOIN podcast_feeds f ON f.id=e.feed_id
107 LEFT JOIN podcast_progress p ON p.episode_id=e.id
108 LEFT JOIN podcast_downloads d ON d.episode_id=e.id
109 LEFT JOIN podcast_saved s ON s.episode_id=e.id"
110 }
111 };
112 if let Some(feed) = &q.feed {
113 clauses.push("e.feed_id=?");
114 args.push(feed.clone().into());
115 }
116 let query = q.query.to_lowercase();
117 if !query.is_empty() {
118 clauses.push("instr(podcast_lower(json_extract(e.json,'$.title')),?)>0");
119 args.push(query.into());
120 }
121 match q.status.as_str() {
122 "played" => clauses.push("COALESCE(p.completed,0)=1"),
123 "unplayed" => clauses.push("COALESCE(p.completed,0)=0"),
124 "progress" => clauses.push("COALESCE(p.completed,0)=0 AND p.position_ms>0"),
125 _ => {}
126 }
127 let candidates = if clauses.is_empty() {
128 "1".to_owned()
129 } else {
130 clauses.join(" AND ")
131 };
132 let filter = if q.downloaded {
135 format!("CASE WHEN {candidates} THEN podcast_download_available(d.json,e.json) ELSE 0 END")
136 } else {
137 candidates
138 };
139 let base = format!("{from} WHERE {filter}");
140 let total: usize = store
141 .conn
142 .prepare_cached(&format!("SELECT count(*) {base}"))?
143 .query_row(rusqlite::params_from_iter(&args), |r| r.get(0))?;
144 let order = if q.view == "history" {
145 "h.played_at DESC,e.id"
146 } else if q.view == "continue" {
147 "p.updated_at DESC,e.id"
148 } else {
149 match q.sort.as_str() {
150 "oldest" => {
151 "json_extract(e.json,'$.published') IS NULL,json_extract(e.json,'$.published'),COALESCE(json_extract(e.json,'$.source_order'),e.legacy_order),e.id"
152 }
153 "title" => "podcast_lower(json_extract(e.json,'$.title')),e.id",
154 _ => super::storage::EPISODE_NEWEST_ORDER_E,
155 }
156 };
157 let sql = format!(
158 "SELECT e.json,p.position_ms,p.duration_ms,p.completed,
159 COALESCE(json_extract(f.json,'$.title'),''), COALESCE(json_extract(f.json,'$.author'),''),
160 s.episode_id IS NOT NULL,EXISTS(SELECT 1 FROM podcast_queue q WHERE q.episode_id=e.id),
161 d.json {base} ORDER BY {order} LIMIT ? OFFSET ?"
162 );
163 args.push(
164 (if q.page.all {
165 -1
166 } else {
167 i64::from(q.page.limit)
168 })
169 .into(),
170 );
171 args.push((q.page.offset.min(i64::MAX as usize) as i64).into());
172 let mut stmt = store.conn.prepare_cached(&sql)?;
173 let mut page = stmt.query(rusqlite::params_from_iter(&args))?;
174 let mut rows = Vec::new();
175 while let Some(row) = page.next()? {
176 let episode = super::storage::episode_from_row(row)?;
177 let download = row
178 .get::<_, Option<String>>(8)?
179 .as_deref()
180 .map(serde_json::from_str)
181 .transpose()?;
182 rows.push(super::episode_details(
183 &episode,
184 &row.get::<_, String>(4)?,
185 &row.get::<_, String>(5)?,
186 row.get(6)?,
187 row.get(7)?,
188 download.as_ref(),
189 |path| files.observed_file(path),
190 ));
191 }
192 let mut value = super::page_result(&rows, total, q.page.clone());
193 if let Some(feed) = &q.feed {
194 value["feed_title"] = json!(store.podcast_feed(feed)?.title);
195 }
196 Ok(value)
197 })
198 });
199 let removed = self.conn.remove_function("podcast_download_available", 2);
200 let value = result?;
201 removed?;
202 Ok(value)
203 }
204 pub fn podcast_save_episode(&self, id: &str, remove: bool) -> Result<()> {
205 let id = self.podcast_episode_id(id)?;
206 if remove {
207 self.conn
208 .execute("DELETE FROM podcast_saved WHERE episode_id=?1", [id])?;
209 } else {
210 self.conn
211 .execute("INSERT OR IGNORE INTO podcast_saved VALUES (?1)", [id])?;
212 }
213 Ok(())
214 }
215 pub fn podcast_dismiss_inbox(&self, id: &str) -> Result<()> {
216 let id = self.podcast_episode_id(id)?;
217 self.conn
218 .execute("DELETE FROM podcast_inbox WHERE episode_id=?1", [id])?;
219 Ok(())
220 }
221}