Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

feat(database): implement SQLite integration for channel management

Tonhofa955c289844
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 9a168abe..fdf0d42f 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -19,6 +19,18 @@ dependencies = [
"cpufeatures 0.2.17",
]
+[[package]]
+name = "ahash"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "version_check",
+ "zerocopy",
+]
+
[[package]]
name = "aho-corasick"
version = "1.1.4"
@@ -1328,6 +1340,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
+ "subtle",
]
[[package]]
@@ -1644,6 +1657,18 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "fallible-iterator"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
+
+[[package]]
+name = "fallible-streaming-iterator"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
+
[[package]]
name = "fastrand"
version = "1.9.0"
@@ -2357,6 +2382,9 @@ name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
+dependencies = [
+ "ahash",
+]
[[package]]
name = "hashbrown"
@@ -2378,6 +2406,15 @@ dependencies = [
"foldhash 0.2.0",
]
+[[package]]
+name = "hashlink"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
+dependencies = [
+ "hashbrown 0.14.5",
+]
+
[[package]]
name = "heck"
version = "0.4.1"
@@ -2414,6 +2451,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hmac"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+dependencies = [
+ "digest",
+]
+
[[package]]
name = "home"
version = "0.5.12"
@@ -3269,6 +3315,17 @@ dependencies = [
"url",
]
+[[package]]
+name = "libsqlite3-sys"
+version = "0.30.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
+dependencies = [
+ "cc",
+ "pkg-config",
+ "vcpkg",
+]
+
[[package]]
name = "linux-raw-sys"
version = "0.3.8"
@@ -3405,6 +3462,16 @@ version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
+[[package]]
+name = "md-5"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
+dependencies = [
+ "cfg-if",
+ "digest",
+]
+
[[package]]
name = "memchr"
version = "2.8.0"
@@ -3518,6 +3585,12 @@ dependencies = [
"windows-sys 0.60.2",
]
+[[package]]
+name = "murmur3"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9252111cf132ba0929b6f8e030cac2a24b507f3a4d6db6fb2896f27b354c714b"
+
[[package]]
name = "native-tls"
version = "0.2.18"
@@ -3984,7 +4057,7 @@ dependencies = [
[[package]]
name = "omniget"
-version = "0.6.2"
+version = "0.6.3"
dependencies = [
"aes",
"anyhow",
@@ -3998,17 +4071,23 @@ dependencies = [
"discord-rich-presence",
"filetime",
"futures",
+ "hex 0.4.3",
+ "hmac",
"keepawake",
"libloading 0.8.9",
"librqbit",
"m3u8-rs",
+ "md-5",
+ "murmur3",
"omniget-core",
"omniget-plugin-sdk",
"once_cell",
"open",
+ "qrcode",
"rand 0.10.0",
"regex",
"reqwest 0.12.28",
+ "rusqlite",
"sanitize-filename",
"serde",
"serde_json",
@@ -4029,6 +4108,7 @@ dependencies = [
"tauri-plugin-single-instance",
"tauri-plugin-store",
"tauri-plugin-updater",
+ "thiserror 1.0.69",
"tokio",
"tokio-util",
"tower-http",
@@ -4656,6 +4736,12 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "qrcode"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
+
[[package]]
name = "quanta"
version = "0.12.6"
@@ -5137,6 +5223,20 @@ dependencies = [
"libc",
]
+[[package]]
+name = "rusqlite"
+version = "0.32.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
+dependencies = [
+ "bitflags 2.11.0",
+ "fallible-iterator",
+ "fallible-streaming-iterator",
+ "hashlink",
+ "libsqlite3-sys",
+ "smallvec",
+]
+
[[package]]
name = "rust-ini"
version = "0.21.3"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 8a25ba35..a83692d4 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -4,7 +4,7 @@ resolver = "2"
[package]
name = "omniget"
-version = "0.6.2"
+version = "0.6.3"
description = "A Tauri App"
authors = ["you"]
edition = "2021"
@@ -49,12 +49,19 @@ tokio-util = { version = "0.7", features = ["rt"] }
url = "2"
urlencoding = "2"
rand = "0.10.0"
+rusqlite = { version = "0.32", features = ["bundled"] }
base64 = "0.22.1"
filetime = "0.2.27"
zip = { version = "2", default-features = false, features = ["deflate"] }
tar = "0.4"
xz2 = { version = "0.1", features = ["static"] }
sha2 = "0.10"
+md-5 = "0.10"
+murmur3 = "0.5"
+hex = "0.4"
+thiserror = "1"
+hmac = "0.12"
+qrcode = { version = "0.14", default-features = false, features = ["svg"] }
open = "5"
omniget-core = { path = "omniget-core", features = ["desktop"] }
omniget-plugin-sdk = { path = "omniget-plugin-sdk" }
diff --git a/src-tauri/src/core/channels.rs b/src-tauri/src/core/channels.rs
index a2f8c00d..fb3ec028 100644
--- a/src-tauri/src/core/channels.rs
+++ b/src-tauri/src/core/channels.rs
@@ -1,12 +1,13 @@
-use serde::{Deserialize, Serialize};
use std::collections::hash_map::DefaultHasher;
-use std::collections::HashMap;
use std::hash::{Hash, Hasher};
-use std::io::Write;
use std::path::PathBuf;
-use std::sync::{Mutex, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
+use rusqlite::{params, Connection};
+use serde::{Deserialize, Serialize};
+
+use crate::core::db;
+
const CHANNELS_FILE: &str = "channels.json";
const MAX_SEEN_IDS: usize = 500;
@@ -49,118 +50,173 @@ struct ChannelsFile {
channels: Vec<ChannelFollow>,
}
-static STORE: OnceLock<Mutex<HashMap<String, ChannelFollow>>> = OnceLock::new();
+pub fn id_for_url(url: &str) -> String {
+ let mut hasher = DefaultHasher::new();
+ url.trim().hash(&mut hasher);
+ format!("ch{:016x}", hasher.finish())
+}
-fn store() -> &'static Mutex<HashMap<String, ChannelFollow>> {
- STORE.get_or_init(|| Mutex::new(HashMap::new()))
+fn schema(conn: &Connection) -> rusqlite::Result<()> {
+ conn.execute_batch(
+ "CREATE TABLE IF NOT EXISTS channels (
+ id TEXT PRIMARY KEY,
+ url TEXT NOT NULL,
+ title TEXT NOT NULL,
+ added_at_ms INTEGER NOT NULL,
+ last_checked_ms INTEGER,
+ seen_ids TEXT NOT NULL DEFAULT '[]',
+ enabled INTEGER NOT NULL DEFAULT 1,
+ auto_download INTEGER NOT NULL DEFAULT 0,
+ interval_minutes INTEGER NOT NULL DEFAULT 60
+ );",
+ )
}
-fn file_path() -> Option<PathBuf> {
- crate::core::paths::app_data_dir().map(|d| d.join(CHANNELS_FILE))
+fn row_to_channel(row: &rusqlite::Row) -> rusqlite::Result<ChannelFollow> {
+ let added: i64 = row.get(3)?;
+ let last: Option<i64> = row.get(4)?;
+ let seen_json: String = row.get(5)?;
+ let enabled: i64 = row.get(6)?;
+ let auto: i64 = row.get(7)?;
+ let interval: i64 = row.get(8)?;
+ Ok(ChannelFollow {
+ id: row.get(0)?,
+ url: row.get(1)?,
+ title: row.get(2)?,
+ added_at_ms: added as u64,
+ last_checked_ms: last.map(|v| v as u64),
+ seen_ids: serde_json::from_str(&seen_json).unwrap_or_default(),
+ enabled: enabled != 0,
+ auto_download: auto != 0,
+ interval_minutes: interval as u32,
+ })
}
-pub fn id_for_url(url: &str) -> String {
- let mut hasher = DefaultHasher::new();
- url.trim().hash(&mut hasher);
- format!("ch{:016x}", hasher.finish())
+fn db_upsert(conn: &Connection, ch: &ChannelFollow) -> rusqlite::Result<()> {
+ let seen = serde_json::to_string(&ch.seen_ids).unwrap_or_else(|_| "[]".to_string());
+ conn.execute(
+ "INSERT OR REPLACE INTO channels
+ (id, url, title, added_at_ms, last_checked_ms, seen_ids,
+ enabled, auto_download, interval_minutes)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)",
+ params![
+ ch.id,
+ ch.url,
+ ch.title,
+ ch.added_at_ms as i64,
+ ch.last_checked_ms.map(|v| v as i64),
+ seen,
+ ch.enabled as i64,
+ ch.auto_download as i64,
+ ch.interval_minutes as i64,
+ ],
+ )?;
+ Ok(())
}
-fn write_to_disk(channels: &HashMap<String, ChannelFollow>) {
- let Some(path) = file_path() else { return };
- let Some(parent) = path.parent() else { return };
- if let Err(e) = std::fs::create_dir_all(parent) {
- tracing::warn!("[channels] create_dir_all failed: {}", e);
- return;
+fn db_get(conn: &Connection, id: &str) -> rusqlite::Result<Option<ChannelFollow>> {
+ let mut stmt = conn.prepare(
+ "SELECT id, url, title, added_at_ms, last_checked_ms, seen_ids,
+ enabled, auto_download, interval_minutes
+ FROM channels WHERE id = ?1",
+ )?;
+ let mut rows = stmt.query_map(params![id], row_to_channel)?;
+ match rows.next() {
+ Some(r) => Ok(Some(r?)),
+ None => Ok(None),
}
- let file_data = ChannelsFile {
- channels: channels.values().cloned().collect(),
+}
+
+fn db_all(conn: &Connection) -> rusqlite::Result<Vec<ChannelFollow>> {
+ let mut stmt = conn.prepare(
+ "SELECT id, url, title, added_at_ms, last_checked_ms, seen_ids,
+ enabled, auto_download, interval_minutes
+ FROM channels ORDER BY added_at_ms ASC",
+ )?;
+ let rows = stmt.query_map([], row_to_channel)?;
+ rows.collect()
+}
+
+fn json_path() -> Option<PathBuf> {
+ crate::core::paths::app_data_dir().map(|d| d.join(CHANNELS_FILE))
+}
+
+fn import_legacy_json(conn: &Connection) {
+ let Some(path) = json_path() else { return };
+ let Ok(content) = std::fs::read_to_string(&path) else {
+ return;
};
- let serialized = match serde_json::to_string_pretty(&file_data) {
- Ok(s) => s,
- Err(e) => {
- tracing::warn!("[channels] serialize failed: {}", e);
- return;
+ match serde_json::from_str::<ChannelsFile>(&content) {
+ Ok(parsed) => {
+ for ch in parsed.channels {
+ let _ = db_upsert(conn, &ch);
+ }
+ tracing::info!("[channels] imported legacy JSON into SQLite");
}
- };
- let tmp = path.with_extension("json.tmp");
- let write_result = (|| -> std::io::Result<()> {
- let mut f = std::fs::File::create(&tmp)?;
- f.write_all(serialized.as_bytes())?;
- f.sync_all()?;
- Ok(())
- })();
- if let Err(e) = write_result {
- tracing::warn!("[channels] write tmp failed: {}", e);
- let _ = std::fs::remove_file(&tmp);
- return;
- }
- if let Err(e) = std::fs::rename(&tmp, &path) {
- tracing::warn!("[channels] rename failed: {}", e);
- let _ = std::fs::remove_file(&tmp);
+ Err(e) => tracing::warn!("[channels] legacy JSON parse failed: {}", e),
}
+ let _ = std::fs::rename(&path, path.with_extension("json.imported"));
}
pub fn init_from_disk() {
- let Some(path) = file_path() else { return };
- let content = match std::fs::read_to_string(&path) {
- Ok(c) => c,
- Err(_) => return,
- };
- let parsed: ChannelsFile = match serde_json::from_str(&content) {
- Ok(v) => v,
- Err(e) => {
- tracing::warn!("[channels] parse failed: {}", e);
- return;
- }
- };
- let mut guard = store().lock().unwrap();
- guard.clear();
- for ch in parsed.channels {
- guard.insert(ch.id.clone(), ch);
- }
+ db::with_conn(|c| {
+ schema(c)?;
+ Ok(())
+ });
+ db::with_conn(|c| {
+ import_legacy_json(c);
+ Ok(())
+ });
}
pub fn list() -> Vec<ChannelFollow> {
- let guard = store().lock().unwrap();
- let mut v: Vec<ChannelFollow> = guard.values().cloned().collect();
- v.sort_by(|a, b| a.added_at_ms.cmp(&b.added_at_ms));
- v
+ db::with_conn(db_all).unwrap_or_default()
}
pub fn get(id: &str) -> Option<ChannelFollow> {
- store().lock().unwrap().get(id).cloned()
+ db::with_conn(|c| db_get(c, id)).flatten()
}
pub fn add(url: String, title: String) -> ChannelFollow {
let id = id_for_url(&url);
- let mut guard = store().lock().unwrap();
- let entry = guard.entry(id.clone()).or_insert_with(|| ChannelFollow {
- id: id.clone(),
+ db::with_conn(|c| {
+ let existing = db_get(c, &id)?;
+ let mut ch = existing.unwrap_or_else(|| ChannelFollow {
+ id: id.clone(),
+ url: url.trim().to_string(),
+ title: title.clone(),
+ added_at_ms: now_ms(),
+ last_checked_ms: None,
+ seen_ids: Vec::new(),
+ enabled: true,
+ auto_download: false,
+ interval_minutes: default_interval(),
+ });
+ if !title.is_empty() {
+ ch.title = title.clone();
+ }
+ db_upsert(c, &ch)?;
+ Ok(ch)
+ })
+ .unwrap_or_else(|| ChannelFollow {
+ id,
url: url.trim().to_string(),
- title: title.clone(),
+ title,
added_at_ms: now_ms(),
last_checked_ms: None,
seen_ids: Vec::new(),
enabled: true,
auto_download: false,
interval_minutes: default_interval(),
- });
- if !title.is_empty() {
- entry.title = title;
- }
- let result = entry.clone();
- write_to_disk(&guard);
- result
+ })
}
pub fn remove(id: &str) -> bool {
- let mut guard = store().lock().unwrap();
- if guard.remove(id).is_some() {
- write_to_disk(&guard);
- true
- } else {
- false
- }
+ db::with_conn(|c| {
+ let n = c.execute("DELETE FROM channels WHERE id = ?1", params![id])?;
+ Ok(n > 0)
+ })
+ .unwrap_or(false)
}
pub fn update(
@@ -169,34 +225,26 @@ pub fn update(
auto_download: Option<bool>,
interval_minutes: Option<u32>,
) -> Option<ChannelFollow> {
- let mut guard = store().lock().unwrap();
- let ch = guard.get_mut(id)?;
- if let Some(v) = enabled {
- ch.enabled = v;
- }
- if let Some(v) = auto_download {
- ch.auto_download = v;
- }
- if let Some(v) = interval_minutes {
- ch.interval_minutes = v.max(5);
- }
- let result = ch.clone();
- write_to_disk(&guard);
- Some(result)
+ db::with_conn(|c| {
+ let Some(mut ch) = db_get(c, id)? else {
+ return Ok(None);
+ };
+ if let Some(v) = enabled {
+ ch.enabled = v;
+ }
+ if let Some(v) = auto_download {
+ ch.auto_download = v;
+ }
+ if let Some(v) = interval_minutes {
+ ch.interval_minutes = v.max(5);
+ }
+ db_upsert(c, &ch)?;
+ Ok(Some(ch))
+ })
+ .flatten()
}
-// Records the poll result: marks checked-now and folds newly seen video ids
-// into the channel's bounded seen set. Returns the ids that were NOT seen
-// before (the genuinely new videos) so the caller can notify/auto-download.
-pub fn record_poll(id: &str, fetched_ids: &[String]) -> Vec<String> {
- let mut guard = store().lock().unwrap();
- let Some(ch) = guard.get_mut(id) else {
- return Vec::new();
- };
- ch.last_checked_ms = Some(now_ms());
-
- // First successful poll establishes a baseline without flagging the whole
- // back catalogue as "new".
+fn fold_seen(ch: &mut ChannelFollow, fetched_ids: &[String]) -> Vec<String> {
let first_poll = ch.seen_ids.is_empty();
let known: std::collections::HashSet<&String> = ch.seen_ids.iter().collect();
let new_ids: Vec<String> = fetched_ids
@@ -214,8 +262,8 @@ pub fn record_poll(id: &str, fetched_ids: &[String]) -> Vec<String> {
let overflow = ch.seen_ids.len() - MAX_SEEN_IDS;
ch.seen_ids.drain(0..overflow);
}
+ ch.last_checked_ms = Some(now_ms());
- write_to_disk(&guard);
if first_poll {
Vec::new()
} else {
@@ -223,10 +271,42 @@ pub fn record_poll(id: &str, fetched_ids: &[String]) -> Vec<String> {
}
}
+pub fn record_poll(id: &str, fetched_ids: &[String]) -> Vec<String> {
+ db::with_conn(|c| {
+ let Some(mut ch) = db_get(c, id)? else {
+ return Ok(Vec::new());
+ };
+ let new_ids = fold_seen(&mut ch, fetched_ids);
+ db_upsert(c, &ch)?;
+ Ok(new_ids)
+ })
+ .unwrap_or_default()
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ fn conn() -> Connection {
+ let c = Connection::open_in_memory().unwrap();
+ schema(&c).unwrap();
+ c
+ }
+
+ fn mk(id: &str) -> ChannelFollow {
+ ChannelFollow {
+ id: id.to_string(),
+ url: format!("https://x.test/{}", id),
+ title: id.to_string(),
+ added_at_ms: 1000,
+ last_checked_ms: None,
+ seen_ids: Vec::new(),
+ enabled: true,
+ auto_download: false,
+ interval_minutes: 60,
+ }
+ }
+
#[test]
fn id_is_stable_and_trimmed() {
assert_eq!(
@@ -239,4 +319,52 @@ mod tests {
);
assert!(id_for_url("https://x.test/c").starts_with("ch"));
}
+
+ #[test]
+ fn upsert_get_all_roundtrip() {
+ let c = conn();
+ db_upsert(&c, &mk("ch1")).unwrap();
+ db_upsert(&c, &mk("ch2")).unwrap();
+ assert_eq!(db_all(&c).unwrap().len(), 2);
+ let got = db_get(&c, "ch1").unwrap().unwrap();
+ assert_eq!(got.url, "https://x.test/ch1");
+ assert!(db_get(&c, "missing").unwrap().is_none());
+ }
+
+ #[test]
+ fn fold_seen_first_poll_baselines() {
+ let mut ch = mk("ch1");
+ let new = fold_seen(&mut ch, &["a".into(), "b".into()]);
+ assert!(new.is_empty(), "first poll should not flag back-catalogue");
+ assert_eq!(ch.seen_ids.len(), 2);
+ assert!(ch.last_checked_ms.is_some());
+ }
+
+ #[test]
+ fn fold_seen_reports_only_new() {
+ let mut ch = mk("ch1");
+ ch.seen_ids = vec!["a".into(), "b".into()];
+ let new = fold_seen(&mut ch, &["b".into(), "c".into(), "d".into()]);
+ assert_eq!(new, vec!["c".to_string(), "d".to_string()]);
+ assert_eq!(ch.seen_ids.len(), 4);
+ }
+
+ #[test]
+ fn fold_seen_bounds_seen_ids() {
+ let mut ch = mk("ch1");
+ ch.seen_ids = (0..MAX_SEEN_IDS).map(|i| format!("old{}", i)).collect();
+ fold_seen(&mut ch, &["new1".into(), "new2".into()]);
+ assert_eq!(ch.seen_ids.len(), MAX_SEEN_IDS);
+ assert_eq!(ch.seen_ids.last().unwrap(), "new2");
+ }
+
+ #[test]
+ fn seen_ids_persist_through_db() {
+ let c = conn();
+ let mut ch = mk("ch1");
+ ch.seen_ids = vec!["x".into(), "y".into()];
+ db_upsert(&c, &ch).unwrap();
+ let got = db_get(&c, "ch1").unwrap().unwrap();
+ assert_eq!(got.seen_ids, vec!["x".to_string(), "y".to_string()]);
+ }
}