lib.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. // -*- coding: utf-8 -*-
  2. //
  3. // Copyright (C) 2024-2025 Michael Büsch <m@bues.ch>
  4. // Copyright (C) 2020 Marco Lochen
  5. //
  6. // This program is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU General Public License as published by
  8. // the Free Software Foundation, either version 2 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // This program is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. //
  19. // SPDX-License-Identifier: GPL-2.0-or-later
  20. #![forbid(unsafe_code)]
  21. mod error;
  22. use crate::error::Error;
  23. use anyhow::{self as ah, format_err as err, Context as _};
  24. use chrono::{DateTime, Utc};
  25. use rusqlite::{Connection, OpenFlags, Row};
  26. use sha2::{Digest as _, Sha256};
  27. use std::{
  28. path::{Path, PathBuf},
  29. sync::{Arc, Mutex},
  30. time::{Duration, Instant},
  31. };
  32. use tokio::task::spawn_blocking;
  33. pub const DEBUG: bool = true;
  34. const TIMEOUT: Duration = Duration::from_millis(10_000);
  35. // Keys for the global kv_int_int key-value store.
  36. const KV_KEY_FEED_UPDATE_REV: i64 = 1;
  37. pub fn get_prefix() -> PathBuf {
  38. option_env!("FEEDREADER_PREFIX").unwrap_or("/").into()
  39. }
  40. pub fn get_varlib() -> PathBuf {
  41. get_prefix().join("var/lib/feedreader")
  42. }
  43. fn sql_to_dt(timestamp: i64) -> DateTime<Utc> {
  44. DateTime::<Utc>::from_timestamp(timestamp, 0).unwrap_or_else(Utc::now)
  45. }
  46. fn dt_to_sql(dt: &DateTime<Utc>) -> i64 {
  47. dt.timestamp()
  48. }
  49. #[derive(Clone, Debug)]
  50. pub struct Feed {
  51. pub feed_id: Option<i64>,
  52. pub href: String,
  53. pub title: String,
  54. pub last_retrieval: DateTime<Utc>,
  55. pub next_retrieval: DateTime<Utc>,
  56. pub last_activity: DateTime<Utc>,
  57. pub disabled: bool,
  58. pub updated_items: i64,
  59. }
  60. impl Feed {
  61. fn from_sql_row(row: &Row<'_>) -> rusqlite::Result<Self> {
  62. Ok(Self {
  63. feed_id: Some(row.get(0)?),
  64. href: row.get(1)?,
  65. title: row.get(2)?,
  66. last_retrieval: sql_to_dt(row.get(3)?),
  67. next_retrieval: sql_to_dt(row.get(4)?),
  68. last_activity: sql_to_dt(row.get(5)?),
  69. disabled: row.get(6)?,
  70. updated_items: row.get(7)?,
  71. })
  72. }
  73. }
  74. #[derive(Clone, Debug)]
  75. pub struct FeedsExt {
  76. pub feed_update_revision: i64,
  77. }
  78. #[derive(Clone, Debug)]
  79. pub struct Item {
  80. pub item_id: Option<String>,
  81. pub feed_id: Option<i64>,
  82. pub retrieved: DateTime<Utc>,
  83. pub seen: bool,
  84. pub author: String,
  85. pub title: String,
  86. pub feed_item_id: String,
  87. pub link: String,
  88. pub published: DateTime<Utc>,
  89. pub summary: String,
  90. }
  91. impl Item {
  92. fn from_sql_row(row: &Row<'_>) -> rusqlite::Result<Self> {
  93. Ok(Self {
  94. item_id: Some(row.get(0)?),
  95. feed_id: Some(row.get(1)?),
  96. retrieved: sql_to_dt(row.get(2)?),
  97. seen: row.get(3)?,
  98. author: row.get(4)?,
  99. title: row.get(5)?,
  100. feed_item_id: row.get(6)?,
  101. link: row.get(7)?,
  102. published: sql_to_dt(row.get(8)?),
  103. summary: row.get(9)?,
  104. })
  105. }
  106. fn from_sql_row_extended(row: &Row<'_>) -> rusqlite::Result<(Self, ItemExt)> {
  107. let count: i64 = row.get(10)?;
  108. let max_seen: bool = row.get(11)?;
  109. let sum_seen: i64 = row.get(12)?;
  110. Ok((
  111. Self::from_sql_row(row)?,
  112. ItemExt {
  113. count,
  114. any_seen: max_seen,
  115. all_seen: sum_seen == count,
  116. },
  117. ))
  118. }
  119. pub async fn make_id(&self) -> String {
  120. let mut h = Sha256::new();
  121. h.update(&self.feed_item_id);
  122. h.update(&self.author);
  123. h.update(&self.title);
  124. h.update(&self.link);
  125. h.update(format!("{}", dt_to_sql(&self.published)));
  126. h.update(&self.summary);
  127. hex::encode(h.finalize())
  128. }
  129. }
  130. #[derive(Clone, Debug)]
  131. pub struct ItemExt {
  132. pub count: i64,
  133. pub any_seen: bool,
  134. pub all_seen: bool,
  135. }
  136. #[derive(Clone, Copy, PartialEq, Eq, Debug)]
  137. pub enum ItemStatus {
  138. New,
  139. Updated,
  140. Exists,
  141. }
  142. async fn transaction<F, R>(conn: Arc<Mutex<Connection>>, mut f: F) -> ah::Result<R>
  143. where
  144. F: FnMut(rusqlite::Transaction) -> Result<R, Error> + Send + 'static,
  145. R: Send + 'static,
  146. {
  147. spawn_blocking(move || {
  148. let timeout = Instant::now() + TIMEOUT;
  149. loop {
  150. let mut conn = conn.lock().expect("Mutex poisoned");
  151. let trans = conn.transaction()?;
  152. match f(trans) {
  153. Ok(r) => {
  154. break Ok(r);
  155. }
  156. Err(Error::Sql(
  157. e @ rusqlite::Error::SqliteFailure(
  158. rusqlite::ffi::Error {
  159. code: rusqlite::ffi::ErrorCode::DatabaseBusy,
  160. ..
  161. },
  162. ..,
  163. ),
  164. )) => {
  165. drop(conn); // unlock
  166. if Instant::now() >= timeout {
  167. break Err(e.into());
  168. }
  169. std::thread::sleep(Duration::from_millis(20));
  170. }
  171. Err(e) => {
  172. break Err(e.into());
  173. }
  174. }
  175. }
  176. })
  177. .await?
  178. }
  179. pub struct DbConn {
  180. conn: Arc<Mutex<Connection>>,
  181. }
  182. impl DbConn {
  183. async fn new(path: &Path) -> ah::Result<Self> {
  184. let path = path.to_path_buf();
  185. let conn = spawn_blocking(move || -> ah::Result<Connection> {
  186. let timeout = Instant::now() + TIMEOUT;
  187. loop {
  188. let conn = match Connection::open_with_flags(
  189. &path,
  190. OpenFlags::SQLITE_OPEN_READ_WRITE
  191. | OpenFlags::SQLITE_OPEN_CREATE
  192. | OpenFlags::SQLITE_OPEN_NO_MUTEX,
  193. ) {
  194. Ok(conn) => conn,
  195. Err(
  196. e @ rusqlite::Error::SqliteFailure(
  197. rusqlite::ffi::Error {
  198. code: rusqlite::ffi::ErrorCode::DatabaseBusy,
  199. ..
  200. },
  201. ..,
  202. ),
  203. ) => {
  204. if Instant::now() >= timeout {
  205. break Err(e.into());
  206. }
  207. std::thread::sleep(Duration::from_millis(20));
  208. continue;
  209. }
  210. Err(e) => {
  211. break Err(e.into());
  212. }
  213. };
  214. conn.busy_timeout(TIMEOUT)?;
  215. conn.set_prepared_statement_cache_capacity(64);
  216. break Ok(conn);
  217. }
  218. })
  219. .await?
  220. .context("Open SQLite database")?;
  221. Ok(Self {
  222. conn: Arc::new(Mutex::new(conn)),
  223. })
  224. }
  225. #[rustfmt::skip]
  226. pub async fn init(&mut self) -> ah::Result<()> {
  227. transaction(Arc::clone(&self.conn), move |t| {
  228. // Feeds table.
  229. t.execute(
  230. "\
  231. CREATE TABLE IF NOT EXISTS feeds (\
  232. feed_id INTEGER PRIMARY KEY, \
  233. href VARCHAR, \
  234. title VARCHAR, \
  235. last_retrieval TIMESTAMP, \
  236. next_retrieval TIMESTAMP, \
  237. last_activity TIMESTAMP, \
  238. disabled BOOLEAN, \
  239. updated_items INTEGER\
  240. )",
  241. [],
  242. )?;
  243. // Items table.
  244. t.execute(
  245. "\
  246. CREATE TABLE IF NOT EXISTS items (\
  247. item_id VARCHAR PRIMARY KEY, \
  248. feed_id INTEGER, \
  249. retrieved TIMESTAMP, \
  250. seen BOOLEAN, \
  251. author VARCHAR, \
  252. title VARCHAR, \
  253. feed_item_id VARCHAR, \
  254. link VARCHAR, \
  255. published TIMESTAMP, \
  256. summary VARCHAR, \
  257. FOREIGN KEY(feed_id) REFERENCES feeds(feed_id)\
  258. )",
  259. [],
  260. )?;
  261. // Global key-value store for integer keys and integer values.
  262. t.execute(
  263. "\
  264. CREATE TABLE IF NOT EXISTS kv_int_int (\
  265. key INTEGER PRIMARY KEY, \
  266. value INTEGER
  267. )",
  268. [],
  269. )?;
  270. // Create indices.
  271. t.execute("CREATE INDEX IF NOT EXISTS feed_id ON feeds(feed_id)", [])?;
  272. t.execute("CREATE INDEX IF NOT EXISTS item_id ON items(item_id)", [])?;
  273. t.execute("CREATE INDEX IF NOT EXISTS kv_int_int_key ON kv_int_int(key)", [])?;
  274. // Remove legacy table.
  275. t.execute("DROP TABLE IF EXISTS enclosures", [])?;
  276. // Remove dangling items.
  277. t.execute(
  278. "\
  279. DELETE FROM items \
  280. WHERE feed_id NOT IN (\
  281. SELECT feed_id FROM feeds\
  282. )\
  283. ",
  284. []
  285. )?;
  286. // Initialize feed update revision counter.
  287. t.execute(
  288. "\
  289. INSERT OR IGNORE INTO kv_int_int \
  290. VALUES(?, ?)\
  291. ",
  292. [ KV_KEY_FEED_UPDATE_REV, 1 ]
  293. )?;
  294. t.commit()?;
  295. Ok(())
  296. })
  297. .await
  298. }
  299. pub async fn vacuum(&mut self) -> ah::Result<()> {
  300. spawn_blocking({
  301. let conn = Arc::clone(&self.conn);
  302. move || {
  303. let conn = conn.lock().expect("Mutex poisoned");
  304. conn.execute("VACUUM", [])?;
  305. Ok(())
  306. }
  307. })
  308. .await?
  309. }
  310. async fn get_kv_int_int(&mut self, key: i64) -> ah::Result<i64> {
  311. transaction(Arc::clone(&self.conn), move |t| {
  312. let rev: i64 = t
  313. .prepare_cached(
  314. "\
  315. SELECT value FROM kv_int_int \
  316. WHERE \
  317. key = ?\
  318. ",
  319. )?
  320. .query([key])?
  321. .next()?
  322. .unwrap()
  323. .get(0)?;
  324. t.finish()?;
  325. Ok(rev)
  326. })
  327. .await
  328. }
  329. pub async fn update_feed(
  330. &mut self,
  331. feed: &Feed,
  332. items: &[Item],
  333. gc_thres: Option<DateTime<Utc>>,
  334. increment_update_revision: bool,
  335. ) -> ah::Result<()> {
  336. let feed = feed.clone();
  337. let items = items.to_vec();
  338. transaction(Arc::clone(&self.conn), move |t| {
  339. let Some(feed_id) = feed.feed_id else {
  340. return Err(Error::Ah(err!("update_feed(): Invalid feed. No feed_id.")));
  341. };
  342. t.prepare_cached(
  343. "\
  344. UPDATE feeds SET \
  345. href = ?, \
  346. title = ?, \
  347. last_retrieval = ?, \
  348. next_retrieval = ?, \
  349. last_activity = ?, \
  350. disabled = ?, \
  351. updated_items = ? \
  352. WHERE feed_id = ?\
  353. ",
  354. )?
  355. .execute((
  356. &feed.href,
  357. &feed.title,
  358. dt_to_sql(&feed.last_retrieval),
  359. dt_to_sql(&feed.next_retrieval),
  360. dt_to_sql(&feed.last_activity),
  361. feed.disabled,
  362. feed.updated_items,
  363. feed_id,
  364. ))?;
  365. for item in &items {
  366. let Some(item_id) = &item.item_id else {
  367. return Err(Error::Ah(err!("update_feed(): Invalid item. No item_id.")));
  368. };
  369. if item.feed_id.is_some() && item.feed_id != Some(feed_id) {
  370. return Err(Error::Ah(err!(
  371. "update_feed(): Invalid item. Invalid feed_id."
  372. )));
  373. }
  374. t.prepare_cached(
  375. "\
  376. INSERT INTO items \
  377. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\
  378. ",
  379. )?
  380. .execute((
  381. item_id,
  382. feed_id,
  383. dt_to_sql(&item.retrieved),
  384. item.seen,
  385. &item.author,
  386. &item.title,
  387. &item.feed_item_id,
  388. &item.link,
  389. dt_to_sql(&item.published),
  390. &item.summary,
  391. ))?;
  392. }
  393. if let Some(gc_thres) = gc_thres.as_ref() {
  394. t.prepare_cached(
  395. "\
  396. DELETE FROM items \
  397. WHERE \
  398. feed_id = ? AND \
  399. published < ? AND \
  400. seen = TRUE\
  401. ",
  402. )?
  403. .execute((feed_id, dt_to_sql(gc_thres)))?;
  404. }
  405. // Increment the feed update revision counter.
  406. if increment_update_revision {
  407. t.prepare_cached(
  408. "\
  409. UPDATE kv_int_int SET \
  410. value = value + 1 \
  411. WHERE key = ?\
  412. ",
  413. )?
  414. .execute([KV_KEY_FEED_UPDATE_REV])?;
  415. }
  416. t.commit()?;
  417. Ok(())
  418. })
  419. .await
  420. }
  421. pub async fn get_feed_update_revision(&mut self) -> ah::Result<i64> {
  422. self.get_kv_int_int(KV_KEY_FEED_UPDATE_REV).await
  423. }
  424. pub async fn add_feed(&mut self, href: &str) -> ah::Result<()> {
  425. let href = href.to_string();
  426. transaction(Arc::clone(&self.conn), move |t| {
  427. t.prepare_cached(
  428. "\
  429. INSERT INTO feeds \
  430. VALUES (?, ?, ?, ?, ?, ?, ?, ?)\
  431. ",
  432. )?
  433. .execute((
  434. None::<i64>,
  435. &href,
  436. "[New feed] Updating...",
  437. 0,
  438. 0,
  439. 0,
  440. false,
  441. 0,
  442. ))?;
  443. t.commit()?;
  444. Ok(())
  445. })
  446. .await
  447. }
  448. pub async fn delete_feeds(&mut self, feed_ids: &[i64]) -> ah::Result<()> {
  449. if !feed_ids.is_empty() {
  450. let feed_ids = feed_ids.to_vec();
  451. transaction(Arc::clone(&self.conn), move |t| {
  452. for feed_id in &feed_ids {
  453. t.prepare_cached(
  454. "\
  455. DELETE FROM items \
  456. WHERE feed_id = ?\
  457. ",
  458. )?
  459. .execute([feed_id])?;
  460. t.prepare_cached(
  461. "\
  462. DELETE FROM feeds \
  463. WHERE feed_id = ?\
  464. ",
  465. )?
  466. .execute([feed_id])?;
  467. }
  468. t.commit()?;
  469. Ok(())
  470. })
  471. .await
  472. } else {
  473. Ok(())
  474. }
  475. }
  476. pub async fn get_feeds_due(&mut self) -> ah::Result<Vec<Feed>> {
  477. let now = Utc::now();
  478. transaction(Arc::clone(&self.conn), move |t| {
  479. let feeds: Vec<Feed> = t
  480. .prepare_cached(
  481. "\
  482. SELECT * FROM feeds \
  483. WHERE \
  484. next_retrieval < ? AND \
  485. disabled == FALSE\
  486. ",
  487. )?
  488. .query_map([dt_to_sql(&now)], Feed::from_sql_row)?
  489. .map(|f| f.unwrap())
  490. .collect();
  491. t.finish()?;
  492. Ok(feeds)
  493. })
  494. .await
  495. }
  496. pub async fn get_next_due_time(&mut self) -> ah::Result<DateTime<Utc>> {
  497. transaction(Arc::clone(&self.conn), move |t| {
  498. let next_retrieval = t
  499. .prepare_cached(
  500. "\
  501. SELECT min(next_retrieval) FROM feeds \
  502. WHERE disabled == FALSE\
  503. ",
  504. )?
  505. .query([])?
  506. .next()?
  507. .unwrap()
  508. .get(0)?;
  509. t.finish()?;
  510. Ok(sql_to_dt(next_retrieval))
  511. })
  512. .await
  513. }
  514. pub async fn get_feeds(
  515. &mut self,
  516. active_feed_id: Option<i64>,
  517. ) -> ah::Result<(Vec<Feed>, FeedsExt)> {
  518. transaction(Arc::clone(&self.conn), move |t| {
  519. if let Some(active_feed_id) = active_feed_id {
  520. t.prepare_cached(
  521. "\
  522. UPDATE feeds \
  523. SET updated_items = 0 \
  524. WHERE feed_id = ?\
  525. ",
  526. )?
  527. .execute([active_feed_id])?;
  528. }
  529. let feeds: Vec<Feed> = t
  530. .prepare_cached(
  531. "\
  532. SELECT * FROM feeds \
  533. ORDER BY last_activity DESC\
  534. ",
  535. )?
  536. .query_map([], Feed::from_sql_row)?
  537. .map(|f| f.unwrap())
  538. .collect();
  539. let rev: i64 = t
  540. .prepare_cached(
  541. "\
  542. SELECT value FROM kv_int_int \
  543. WHERE \
  544. key = ?\
  545. ",
  546. )?
  547. .query([KV_KEY_FEED_UPDATE_REV])?
  548. .next()?
  549. .unwrap()
  550. .get(0)?;
  551. let feeds_ext = FeedsExt {
  552. feed_update_revision: rev,
  553. };
  554. if active_feed_id.is_some() {
  555. t.commit()?;
  556. } else {
  557. t.finish()?;
  558. }
  559. Ok((feeds, feeds_ext))
  560. })
  561. .await
  562. }
  563. pub async fn get_feed_items(&mut self, feed_id: i64) -> ah::Result<Vec<(Item, ItemExt)>> {
  564. transaction(Arc::clone(&self.conn), move |t| {
  565. let items: Vec<(Item, ItemExt)> = t
  566. .prepare_cached(
  567. "\
  568. SELECT \
  569. item_id, \
  570. feed_id, \
  571. max(retrieved), \
  572. seen, \
  573. author, \
  574. title, \
  575. feed_item_id, \
  576. link, \
  577. published, \
  578. summary, \
  579. count() as count, \
  580. max(seen) as any_seen, \
  581. sum(seen) as sum_seen \
  582. FROM items \
  583. WHERE feed_id = ? \
  584. GROUP BY feed_item_id \
  585. ORDER BY published DESC\
  586. ",
  587. )?
  588. .query_map([feed_id], Item::from_sql_row_extended)?
  589. .map(|i| i.unwrap())
  590. .collect();
  591. t.prepare_cached(
  592. "\
  593. UPDATE items \
  594. SET seen = TRUE \
  595. WHERE feed_id = ?\
  596. ",
  597. )?
  598. .execute([feed_id])?;
  599. t.commit()?;
  600. Ok(items)
  601. })
  602. .await
  603. }
  604. pub async fn get_feed_items_by_item_id(
  605. &mut self,
  606. feed_id: i64,
  607. item_id: &str,
  608. ) -> ah::Result<Vec<Item>> {
  609. let item_id = item_id.to_string();
  610. transaction(Arc::clone(&self.conn), move |t| {
  611. let items: Vec<Item> = t
  612. .prepare_cached(
  613. "\
  614. SELECT * FROM items \
  615. WHERE \
  616. feed_id = ? AND \
  617. feed_item_id IN (\
  618. SELECT feed_item_id FROM items \
  619. WHERE item_id = ?\
  620. ) \
  621. ORDER BY retrieved DESC\
  622. ",
  623. )?
  624. .query_map((feed_id, &item_id), Item::from_sql_row)?
  625. .map(|i| i.unwrap())
  626. .collect();
  627. t.prepare_cached(
  628. "\
  629. UPDATE items \
  630. SET seen = TRUE \
  631. WHERE feed_id = ?\
  632. ",
  633. )?
  634. .execute([feed_id])?;
  635. t.commit()?;
  636. Ok(items)
  637. })
  638. .await
  639. }
  640. pub async fn set_seen(&mut self, feed_id: Option<i64>) -> ah::Result<()> {
  641. transaction(Arc::clone(&self.conn), move |t| {
  642. if let Some(feed_id) = feed_id {
  643. t.prepare_cached(
  644. "\
  645. UPDATE items \
  646. SET seen = TRUE \
  647. WHERE feed_id = ?\
  648. ",
  649. )?
  650. .execute([feed_id])?;
  651. t.prepare_cached(
  652. "\
  653. UPDATE feeds \
  654. SET updated_items = 0 \
  655. WHERE feed_id = ?\
  656. ",
  657. )?
  658. .execute([feed_id])?;
  659. } else {
  660. t.prepare_cached(
  661. "\
  662. UPDATE items \
  663. SET seen = TRUE \
  664. ",
  665. )?
  666. .execute([])?;
  667. t.prepare_cached(
  668. "\
  669. UPDATE feeds \
  670. SET updated_items = 0 \
  671. ",
  672. )?
  673. .execute([])?;
  674. }
  675. t.commit()?;
  676. Ok(())
  677. })
  678. .await
  679. }
  680. pub async fn check_item_exists(&mut self, item: &Item) -> ah::Result<ItemStatus> {
  681. if let Some(item_id) = item.item_id.as_ref() {
  682. let item_id = item_id.clone();
  683. let feed_item_id = item.feed_item_id.clone();
  684. transaction(Arc::clone(&self.conn), move |t| {
  685. let feed_item_id_count: Vec<i64> = t
  686. .prepare_cached(
  687. "\
  688. SELECT count(feed_item_id) \
  689. FROM items \
  690. WHERE feed_item_id = ?\
  691. ",
  692. )?
  693. .query_map([&feed_item_id], |row| row.get(0))?
  694. .map(|c| c.unwrap())
  695. .collect();
  696. let item_id_count: Vec<i64> = t
  697. .prepare_cached(
  698. "\
  699. SELECT count(item_id) \
  700. FROM items \
  701. WHERE item_id = ?\
  702. ",
  703. )?
  704. .query_map([&item_id], |row| row.get(0))?
  705. .map(|c| c.unwrap())
  706. .collect();
  707. let feed_item_id_count = *feed_item_id_count.first().unwrap_or(&0);
  708. let item_id_count = *item_id_count.first().unwrap_or(&0);
  709. let status = if item_id_count == 0 && feed_item_id_count == 0 {
  710. ItemStatus::New
  711. } else if item_id_count == 0 {
  712. ItemStatus::Updated
  713. } else {
  714. ItemStatus::Exists
  715. };
  716. t.finish()?;
  717. Ok(status)
  718. })
  719. .await
  720. } else {
  721. Err(err!("check_item_exists(): Invalid item. No item_id."))
  722. }
  723. }
  724. }
  725. pub struct Db {
  726. path: PathBuf,
  727. }
  728. impl Db {
  729. pub async fn new(name: &str) -> ah::Result<Self> {
  730. if !name
  731. .chars()
  732. .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
  733. {
  734. return Err(err!("Invalid name"));
  735. }
  736. let path = get_varlib().join(format!("{name}.db"));
  737. Ok(Self { path })
  738. }
  739. pub async fn open(&self) -> ah::Result<DbConn> {
  740. DbConn::new(&self.path).await
  741. }
  742. }
  743. // vim: ts=4 sw=4 expandtab