1use crate::error::{FetchiumError, FetchiumResult};
4use dirs;
5use rusqlite::{params, Connection};
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct Subscription {
11 pub id: String,
12 pub topic: String,
13 pub interval_secs: u64,
15 pub notify_method: NotifyMethod,
16 pub last_checked_at: Option<String>,
17 pub created_at: String,
18 pub enabled: bool,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum NotifyMethod {
25 Stdout,
26 File { path: String },
27 Webhook { url: String },
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct NewFinding {
33 pub title: String,
34 pub url: String,
35 pub snippet: String,
36 pub published: Option<String>,
37}
38
39pub struct SubscriptionStore {
41 conn: Connection,
42}
43
44impl SubscriptionStore {
45 pub fn new(db_path: &std::path::Path) -> FetchiumResult<Self> {
46 let conn = Connection::open(db_path)?;
47 conn.execute_batch(
48 "CREATE TABLE IF NOT EXISTS subscriptions (
49 id TEXT PRIMARY KEY,
50 topic TEXT NOT NULL,
51 interval_secs INTEGER NOT NULL DEFAULT 86400,
52 notify_json TEXT NOT NULL DEFAULT '\"stdout\"',
53 last_checked_at TEXT,
54 created_at TEXT NOT NULL,
55 enabled INTEGER NOT NULL DEFAULT 1
56 );",
57 )?;
58 Ok(Self { conn })
59 }
60
61 pub fn add(
62 &self,
63 topic: &str,
64 interval_secs: u64,
65 notify: &NotifyMethod,
66 ) -> FetchiumResult<String> {
67 let id = uuid::Uuid::new_v4().to_string();
68 let now = chrono::Utc::now().to_rfc3339();
69 let notify_json = serde_json::to_string(notify)?;
70 self.conn.execute(
71 "INSERT INTO subscriptions (id, topic, interval_secs, notify_json, created_at) VALUES (?1,?2,?3,?4,?5)",
72 params![id, topic, interval_secs as i64, notify_json, now],
73 )?;
74 Ok(id)
75 }
76
77 pub fn remove(&self, id: &str) -> FetchiumResult<bool> {
78 let n = self
79 .conn
80 .execute("DELETE FROM subscriptions WHERE id=?1", [id])?;
81 Ok(n > 0)
82 }
83
84 pub fn list(&self) -> FetchiumResult<Vec<Subscription>> {
85 let mut stmt = self.conn.prepare(
86 "SELECT id, topic, interval_secs, notify_json, last_checked_at, created_at, enabled
87 FROM subscriptions ORDER BY created_at DESC",
88 )?;
89 let rows = stmt.query_map([], |row| {
90 Ok((
91 row.get::<_, String>(0)?,
92 row.get::<_, String>(1)?,
93 row.get::<_, i64>(2)?,
94 row.get::<_, String>(3)?,
95 row.get::<_, Option<String>>(4)?,
96 row.get::<_, String>(5)?,
97 row.get::<_, i64>(6)?,
98 ))
99 })?;
100 let mut subs = Vec::new();
101 for row in rows {
102 let (id, topic, interval_secs, notify_json, last_checked_at, created_at, enabled) =
103 row?;
104 let notify_method: NotifyMethod =
105 serde_json::from_str(¬ify_json).unwrap_or(NotifyMethod::Stdout);
106 subs.push(Subscription {
107 id,
108 topic,
109 interval_secs: interval_secs as u64,
110 notify_method,
111 last_checked_at,
112 created_at,
113 enabled: enabled != 0,
114 });
115 }
116 Ok(subs)
117 }
118
119 pub fn mark_checked(&self, id: &str) -> FetchiumResult<()> {
120 let now = chrono::Utc::now().to_rfc3339();
121 self.conn.execute(
122 "UPDATE subscriptions SET last_checked_at=?1 WHERE id=?2",
123 params![now, id],
124 )?;
125 Ok(())
126 }
127
128 pub fn due(&self) -> FetchiumResult<Vec<Subscription>> {
130 let all = self.list()?;
131 let now = chrono::Utc::now();
132 Ok(all
133 .into_iter()
134 .filter(|s| {
135 if !s.enabled {
136 return false;
137 }
138 match &s.last_checked_at {
139 None => true,
140 Some(ts) => {
141 if let Ok(last) = ts.parse::<chrono::DateTime<chrono::Utc>>() {
142 let elapsed = (now - last).num_seconds() as u64;
143 elapsed >= s.interval_secs
144 } else {
145 true
146 }
147 }
148 }
149 })
150 .collect())
151 }
152
153 pub fn default_db_path() -> std::path::PathBuf {
155 dirs::home_dir()
156 .unwrap_or_else(|| std::path::PathBuf::from("."))
157 .join(".fetchium")
158 .join("subscriptions.db")
159 }
160
161 pub fn format_interval(secs: u64) -> String {
163 if secs < 3600 {
164 format!("{}m", secs / 60)
165 } else if secs < 86400 {
166 format!("{}h", secs / 3600)
167 } else {
168 format!("{}d", secs / 86400)
169 }
170 }
171}
172
173pub fn parse_interval(s: &str) -> FetchiumResult<u64> {
175 let bad = || FetchiumError::Config(format!("invalid interval: '{s}'"));
176 if let Some(n) = s.strip_suffix('s') {
177 Ok(n.parse::<u64>().map_err(|_| bad())?)
178 } else if let Some(n) = s.strip_suffix('m') {
179 Ok(n.parse::<u64>().map_err(|_| bad())? * 60)
180 } else if let Some(n) = s.strip_suffix('h') {
181 Ok(n.parse::<u64>().map_err(|_| bad())? * 3600)
182 } else if let Some(n) = s.strip_suffix('d') {
183 Ok(n.parse::<u64>().map_err(|_| bad())? * 86400)
184 } else {
185 s.parse::<u64>().map_err(|_| bad())
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 #[test]
194 fn test_parse_interval() {
195 assert_eq!(parse_interval("30m").unwrap(), 1800);
196 assert_eq!(parse_interval("2h").unwrap(), 7200);
197 assert_eq!(parse_interval("7d").unwrap(), 604800);
198 }
199
200 #[test]
201 fn test_subscription_store_roundtrip() {
202 let tmp = tempfile::NamedTempFile::new().unwrap();
203 let store = SubscriptionStore::new(tmp.path()).unwrap();
204 let id = store
205 .add("Rust async news", 86400, &NotifyMethod::Stdout)
206 .unwrap();
207 let list = store.list().unwrap();
208 assert_eq!(list.len(), 1);
209 assert_eq!(list[0].id, id);
210 store.remove(&id).unwrap();
211 assert!(store.list().unwrap().is_empty());
212 }
213}