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 (history_join, in_history) = if q.view == "history" {
63 ("JOIN (SELECT episode_id,MAX(played_at) AS played_at FROM podcast_history GROUP BY episode_id) h ON h.episode_id=e.id", "1")
64 } else { ("", "0") };
65 let candidates = format!("(?1 IS NULL OR e.feed_id=?1)
66 AND (?2='' OR instr(podcast_lower(json_extract(e.json,'$.title')),?2)>0)
67 AND (?3='all' OR (?3='played' AND COALESCE(p.completed,0)=1)
68 OR (?3='unplayed' AND COALESCE(p.completed,0)=0)
69 OR (?3='progress' AND COALESCE(p.completed,0)=0 AND p.position_ms>0))
70 AND ((?4='all' AND f.subscribed=1) OR (?4='continue' AND COALESCE(p.completed,0)=0 AND p.position_ms>0)
71 OR (?4='history' AND {in_history}) OR (?4='saved' AND s.episode_id IS NOT NULL)
72 OR (?4='inbox' AND i.episode_id IS NOT NULL AND f.subscribed=1))");
73 let filter = if q.downloaded {
75 format!("CASE WHEN {candidates} THEN podcast_download_available(d.json,e.json) ELSE 0 END")
76 } else {
77 candidates
78 };
79 let base = format!("FROM podcast_episodes e JOIN podcast_feeds f ON f.id=e.feed_id
80 LEFT JOIN podcast_progress p ON p.episode_id=e.id
81 LEFT JOIN podcast_downloads d ON d.episode_id=e.id
82 LEFT JOIN podcast_saved s ON s.episode_id=e.id
83 LEFT JOIN podcast_inbox i ON i.episode_id=e.id
84 {history_join}
85 WHERE {filter}");
86 let query = q.query.to_lowercase();
87 let args = params![q.feed, query, q.status, q.view];
88 let total: usize = store.conn.query_row(&format!("SELECT count(*) {base}"), args, |r| r.get(0))?;
89 let order = if q.view == "history" { "h.played_at DESC,e.id" }
90 else if q.view == "continue" { "p.updated_at DESC,e.id" }
91 else { match q.sort.as_str() {
92 "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",
93 "title" => "podcast_lower(json_extract(e.json,'$.title')),e.id",
94 _ => "json_extract(e.json,'$.published') DESC,COALESCE(json_extract(e.json,'$.source_order'),e.legacy_order),e.id",
95 }};
96 let sql = format!("SELECT e.json,p.position_ms,p.duration_ms,p.completed,
97 COALESCE(json_extract(f.json,'$.title'),''), COALESCE(json_extract(f.json,'$.author'),''),
98 s.episode_id IS NOT NULL,EXISTS(SELECT 1 FROM podcast_queue q WHERE q.episode_id=e.id),
99 d.json {base} ORDER BY {order} LIMIT ?5 OFFSET ?6");
100 let mut stmt = store.conn.prepare(&sql)?;
101 let mut page = stmt.query(params![q.feed, query, q.status, q.view,
102 if q.page.all { -1 } else { i64::from(q.page.limit) }, q.page.offset.min(i64::MAX as usize) as i64])?;
103 let mut rows = Vec::new();
104 while let Some(row) = page.next()? {
105 let episode = super::storage::episode_from_row(row)?;
106 let download = row.get::<_,Option<String>>(8)?.as_deref().map(serde_json::from_str).transpose()?;
107 rows.push(super::commands::episode_details(&episode,&row.get::<_,String>(4)?,&row.get::<_,String>(5)?,row.get(6)?,row.get(7)?,
108 download.as_ref(),|path| files.observed_file(path)));
109 }
110 let mut value = super::commands::page_result(&rows, total, q.page.clone());
111 if let Some(feed) = &q.feed { value["feed_title"] = json!(store.podcast_feed(feed)?.title); }
112 Ok(value)
113 });
114 let removed = self.conn.remove_function("podcast_download_available", 2);
115 let value = result?;
116 removed?;
117 Ok(value)
118 }
119 pub fn podcast_save_episode(&self, id: &str, remove: bool) -> Result<()> {
120 let id = self.podcast_episode_id(id)?;
121 if remove {
122 self.conn
123 .execute("DELETE FROM podcast_saved WHERE episode_id=?1", [id])?;
124 } else {
125 self.conn
126 .execute("INSERT OR IGNORE INTO podcast_saved VALUES (?1)", [id])?;
127 }
128 Ok(())
129 }
130 pub fn podcast_dismiss_inbox(&self, id: &str) -> Result<()> {
131 let id = self.podcast_episode_id(id)?;
132 self.conn
133 .execute("DELETE FROM podcast_inbox WHERE episode_id=?1", [id])?;
134 Ok(())
135 }
136}