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(nami): implement SQLite media ledger and TikTok audio safeguard

IGECT92dfcaed3c25
diff --git a/src-tauri/src/commands/nami/args.rs b/src-tauri/src/commands/nami/args.rs
index e7566182..f7a3bda1 100644
--- a/src-tauri/src/commands/nami/args.rs
+++ b/src-tauri/src/commands/nami/args.rs
@@ -102,6 +102,10 @@ pub fn build_gallery_dl_args(options: &GalleryDlArgsOptions) -> Vec<String> {
args.push("-o".to_string());
args.push("include=posts,reels".to_string());
}
+ if options.platform.eq_ignore_ascii_case("tiktok") {
+ args.push("-o".to_string());
+ args.push("format=best".to_string());
+ }
args.push("--sleep-request".to_string());
args.push(sleep_delay.to_string());
}
@@ -129,6 +133,10 @@ pub fn build_gallery_dl_args(options: &GalleryDlArgsOptions) -> Vec<String> {
}
}
_ => {
+ if options.platform.eq_ignore_ascii_case("tiktok") {
+ args.push("-o".to_string());
+ args.push("format=best".to_string());
+ }
args.push("--sleep-request".to_string());
args.push(sleep_delay.to_string());
}
@@ -303,4 +311,25 @@ mod tests {
assert_eq!(dash_dash_pos, args.len() - 2);
assert_eq!(args[args.len() - 1], "https://www.tiktok.com/@creator");
}
+
+ #[test]
+ fn test_gallery_dl_args_tiktok_format_best_safeguard() {
+ let dest = PathBuf::from("C:/downloads/Nami/tiktok/creator/videos");
+ let opts = GalleryDlArgsOptions {
+ dest_dir: &dest,
+ content_type: "videos",
+ platform: "tiktok",
+ clean_url: "https://www.tiktok.com/@creator",
+ username: "creator",
+ cookie_path: None,
+ custom_ua: None,
+ proxy: None,
+ skip_replies: None,
+ };
+
+ let args = build_gallery_dl_args(&opts);
+ let format_pos = args.iter().position(|r| r == "format=best");
+ assert!(format_pos.is_some(), "gallery-dl must include format=best for TikTok to prevent silent DASH streams");
+ assert_eq!(args[format_pos.unwrap() - 1], "-o");
+ }
}
diff --git a/src-tauri/src/commands/nami/dispatcher.rs b/src-tauri/src/commands/nami/dispatcher.rs
index 00edbfab..6481bc99 100644
--- a/src-tauri/src/commands/nami/dispatcher.rs
+++ b/src-tauri/src/commands/nami/dispatcher.rs
@@ -489,6 +489,13 @@ fn run_single_stage(
};
let gdl_args = build_gallery_dl_args(&gdl_opts);
+ let target_context = Some((
+ final_dest.clone(),
+ platform_name.to_string(),
+ username.clone(),
+ url.to_string(),
+ ));
+
let gdl_result = run_process_stream(
app,
gallery_bin,
@@ -498,6 +505,7 @@ fn run_single_stage(
media_type_name,
stage_index,
stage_total,
+ target_context.clone(),
)?;
sync_cross_engine_archives(&final_dest);
@@ -535,6 +543,7 @@ fn run_single_stage(
media_type_name,
stage_index,
stage_total,
+ target_context,
)?;
sync_cross_engine_archives(&final_dest);
return Ok(yt_result);
@@ -553,6 +562,7 @@ fn run_process_stream(
stage_label: &str,
stage_index: u32,
stage_total: u32,
+ target_context: Option<(PathBuf, String, String, String)>,
) -> Result<DownloadResult, String> {
let mut cmd = Command::new(executable);
cmd.args(args);
@@ -592,6 +602,31 @@ fn run_process_stream(
if let Some(pos) = line.find("FILE_OK:") {
let filename = line[pos + "FILE_OK:".len()..].trim();
let count = files_downloaded.fetch_add(1, Ordering::SeqCst) + 1;
+ if let Some((ref dest, ref plat, ref author, ref page_url)) = target_context {
+ let full_path = dest.join(filename);
+ let size = fs::metadata(&full_path).ok().map(|m| m.len());
+ let stem = Path::new(filename)
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or(filename);
+ let post_id = stem
+ .split(['_', '-', ' '])
+ .last()
+ .unwrap_or(stem)
+ .to_string();
+ let record = crate::commands::nami::ledger::NamiMediaRecord {
+ id: format!("{}_{}", plat.to_lowercase(), stem),
+ platform: plat.to_lowercase(),
+ post_id,
+ author: Some(author.clone()),
+ url: page_url.clone(),
+ file_path: full_path.to_string_lossy().to_string(),
+ file_size: size,
+ sha256: None,
+ downloaded_at: chrono::Utc::now().timestamp(),
+ };
+ let _ = crate::commands::nami::ledger::record_media(&record);
+ }
let _ = app.emit(
&format!("download_{}", download_id),
DownloadProgress {
@@ -604,6 +639,38 @@ fn run_process_stream(
);
} else if line.contains("[download]") && line.contains("Destination:") {
let count = files_downloaded.fetch_add(1, Ordering::SeqCst) + 1;
+ if let Some(dest_pos) = line.find("Destination:") {
+ let raw_dest = line[dest_pos + "Destination:".len()..].trim();
+ let full_path = PathBuf::from(raw_dest);
+ let filename = full_path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or(raw_dest);
+ let size = fs::metadata(&full_path).ok().map(|m| m.len());
+ let stem = Path::new(filename)
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or(filename);
+ let post_id = stem
+ .split(['_', '-', ' '])
+ .last()
+ .unwrap_or(stem)
+ .to_string();
+ if let Some((_, ref plat, ref author, ref page_url)) = target_context {
+ let record = crate::commands::nami::ledger::NamiMediaRecord {
+ id: format!("{}_{}", plat.to_lowercase(), stem),
+ platform: plat.to_lowercase(),
+ post_id,
+ author: Some(author.clone()),
+ url: page_url.clone(),
+ file_path: full_path.to_string_lossy().to_string(),
+ file_size: size,
+ sha256: None,
+ downloaded_at: chrono::Utc::now().timestamp(),
+ };
+ let _ = crate::commands::nami::ledger::record_media(&record);
+ }
+ }
let _ = app.emit(
&format!("download_{}", download_id),
DownloadProgress {
diff --git a/src-tauri/src/commands/nami/ledger.rs b/src-tauri/src/commands/nami/ledger.rs
new file mode 100644
index 00000000..dda2135d
--- /dev/null
+++ b/src-tauri/src/commands/nami/ledger.rs
@@ -0,0 +1,330 @@
+use std::path::Path;
+use rusqlite::{params, Connection};
+use serde::{Deserialize, Serialize};
+
+use crate::core::db;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct NamiMediaRecord {
+ pub id: String,
+ pub platform: String,
+ pub post_id: String,
+ pub author: Option<String>,
+ pub url: String,
+ pub file_path: String,
+ pub file_size: Option<u64>,
+ pub sha256: Option<String>,
+ pub downloaded_at: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ReconcileResult {
+ pub checked: usize,
+ pub removed: usize,
+}
+
+pub fn init_schema_on(conn: &Connection) -> rusqlite::Result<()> {
+ conn.execute_batch(
+ "CREATE TABLE IF NOT EXISTS nami_media (
+ id TEXT PRIMARY KEY,
+ platform TEXT NOT NULL,
+ post_id TEXT NOT NULL,
+ author TEXT,
+ url TEXT,
+ file_path TEXT NOT NULL,
+ file_size INTEGER,
+ sha256 TEXT,
+ downloaded_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS idx_nami_media_platform ON nami_media(platform);
+ CREATE INDEX IF NOT EXISTS idx_nami_media_post_id ON nami_media(platform, post_id);
+ CREATE INDEX IF NOT EXISTS idx_nami_media_author ON nami_media(author);",
+ )
+}
+
+pub fn init() {
+ let _ = db::with_conn(|conn| init_schema_on(conn));
+}
+
+pub fn record_media_on(conn: &Connection, record: &NamiMediaRecord) -> rusqlite::Result<()> {
+ init_schema_on(conn)?;
+ conn.execute(
+ "INSERT OR REPLACE INTO nami_media (id, platform, post_id, author, url, file_path, file_size, sha256, downloaded_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
+ params![
+ record.id,
+ record.platform.to_lowercase(),
+ record.post_id,
+ record.author,
+ record.url,
+ record.file_path,
+ record.file_size.map(|s| s as i64),
+ record.sha256,
+ record.downloaded_at,
+ ],
+ )?;
+ Ok(())
+}
+
+pub fn record_media(record: &NamiMediaRecord) -> Result<(), String> {
+ db::with_conn(|conn| record_media_on(conn, record))
+ .ok_or_else(|| "Failed to access SQLite database".to_string())
+}
+
+pub fn has_media_on(conn: &Connection, platform: &str, post_id: &str) -> rusqlite::Result<bool> {
+ init_schema_on(conn)?;
+ let mut stmt = conn.prepare_cached(
+ "SELECT 1 FROM nami_media WHERE platform = ?1 AND post_id = ?2 LIMIT 1",
+ )?;
+ let exists = stmt.exists(params![platform.to_lowercase(), post_id])?;
+ Ok(exists)
+}
+
+pub fn has_media(platform: &str, post_id: &str) -> bool {
+ db::with_conn(|conn| has_media_on(conn, platform, post_id)).unwrap_or(false)
+}
+
+pub fn get_history_on(
+ conn: &Connection,
+ platform: Option<&str>,
+ limit: u32,
+ offset: u32,
+) -> rusqlite::Result<Vec<NamiMediaRecord>> {
+ init_schema_on(conn)?;
+ let mut records = Vec::new();
+
+ if let Some(p) = platform {
+ let mut stmt = conn.prepare_cached(
+ "SELECT id, platform, post_id, author, url, file_path, file_size, sha256, downloaded_at
+ FROM nami_media
+ WHERE platform = ?1
+ ORDER BY downloaded_at DESC
+ LIMIT ?2 OFFSET ?3",
+ )?;
+ let rows = stmt.query_map(params![p.to_lowercase(), limit, offset], row_to_record)?;
+ for row in rows {
+ records.push(row?);
+ }
+ } else {
+ let mut stmt = conn.prepare_cached(
+ "SELECT id, platform, post_id, author, url, file_path, file_size, sha256, downloaded_at
+ FROM nami_media
+ ORDER BY downloaded_at DESC
+ LIMIT ?1 OFFSET ?2",
+ )?;
+ let rows = stmt.query_map(params![limit, offset], row_to_record)?;
+ for row in rows {
+ records.push(row?);
+ }
+ }
+
+ Ok(records)
+}
+
+pub fn get_history(
+ platform: Option<&str>,
+ limit: u32,
+ offset: u32,
+) -> Result<Vec<NamiMediaRecord>, String> {
+ db::with_conn(|conn| get_history_on(conn, platform, limit, offset))
+ .ok_or_else(|| "Failed to query history from database".to_string())
+}
+
+pub fn delete_record_on(conn: &Connection, id: &str) -> rusqlite::Result<bool> {
+ init_schema_on(conn)?;
+ let rows = conn.execute("DELETE FROM nami_media WHERE id = ?1", params![id])?;
+ Ok(rows > 0)
+}
+
+pub fn delete_record(id: &str) -> Result<bool, String> {
+ db::with_conn(|conn| delete_record_on(conn, id))
+ .ok_or_else(|| "Failed to delete record from database".to_string())
+}
+
+pub fn reconcile_disk_on(conn: &Connection) -> rusqlite::Result<ReconcileResult> {
+ init_schema_on(conn)?;
+ let mut stmt = conn.prepare_cached("SELECT id, file_path FROM nami_media")?;
+ let rows = stmt.query_map([], |row| {
+ Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
+ })?;
+
+ let mut to_delete = Vec::new();
+ let mut checked = 0;
+
+ for row in rows {
+ let (id, file_path) = row?;
+ checked += 1;
+ let p = Path::new(&file_path);
+ if let Some(parent) = p.parent() {
+ if parent.exists() && !p.exists() {
+ to_delete.push(id);
+ }
+ }
+ }
+
+ let removed = to_delete.len();
+ for id in to_delete {
+ conn.execute("DELETE FROM nami_media WHERE id = ?1", params![id])?;
+ }
+
+ Ok(ReconcileResult { checked, removed })
+}
+
+pub fn reconcile_disk() -> Result<ReconcileResult, String> {
+ db::with_conn(|conn| reconcile_disk_on(conn))
+ .ok_or_else(|| "Failed to reconcile disk with database".to_string())
+}
+
+fn row_to_record(row: &rusqlite::Row) -> rusqlite::Result<NamiMediaRecord> {
+ let size_raw: Option<i64> = row.get(6)?;
+ Ok(NamiMediaRecord {
+ id: row.get(0)?,
+ platform: row.get(1)?,
+ post_id: row.get(2)?,
+ author: row.get(3)?,
+ url: row.get(4)?,
+ file_path: row.get(5)?,
+ file_size: size_raw.map(|s| s as u64),
+ sha256: row.get(7)?,
+ downloaded_at: row.get(8)?,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_record_and_has_media() {
+ let conn = Connection::open_in_memory().unwrap();
+ init_schema_on(&conn).unwrap();
+
+ let record = NamiMediaRecord {
+ id: "tiktok_123456789".to_string(),
+ platform: "tiktok".to_string(),
+ post_id: "123456789".to_string(),
+ author: Some("creator".to_string()),
+ url: "https://www.tiktok.com/@creator/video/123456789".to_string(),
+ file_path: "/downloads/Nami/TikTok/creator/video.mp4".to_string(),
+ file_size: Some(10485760),
+ sha256: Some("abcdef123456".to_string()),
+ downloaded_at: 1731280000,
+ };
+
+ assert!(!has_media_on(&conn, "tiktok", "123456789").unwrap());
+ record_media_on(&conn, &record).unwrap();
+ assert!(has_media_on(&conn, "tiktok", "123456789").unwrap());
+ assert!(has_media_on(&conn, "TikTok", "123456789").unwrap());
+ assert!(!has_media_on(&conn, "instagram", "123456789").unwrap());
+ }
+
+ #[test]
+ fn test_get_history_pagination_and_filter() {
+ let conn = Connection::open_in_memory().unwrap();
+ init_schema_on(&conn).unwrap();
+
+ for i in 1..=5 {
+ let record = NamiMediaRecord {
+ id: format!("instagram_{}", i),
+ platform: "instagram".to_string(),
+ post_id: format!("{}", i),
+ author: Some("ig_creator".to_string()),
+ url: format!("https://instagram.com/p/{}", i),
+ file_path: format!("/downloads/{}.jpg", i),
+ file_size: Some(5000),
+ sha256: None,
+ downloaded_at: 1731280000 + i,
+ };
+ record_media_on(&conn, &record).unwrap();
+ }
+
+ let history = get_history_on(&conn, Some("instagram"), 3, 0).unwrap();
+ assert_eq!(history.len(), 3);
+ assert_eq!(history[0].id, "instagram_5");
+ assert_eq!(history[1].id, "instagram_4");
+ assert_eq!(history[2].id, "instagram_3");
+
+ let paged = get_history_on(&conn, Some("instagram"), 3, 3).unwrap();
+ assert_eq!(paged.len(), 2);
+ assert_eq!(paged[0].id, "instagram_2");
+ assert_eq!(paged[1].id, "instagram_1");
+ }
+
+ #[test]
+ fn test_delete_record() {
+ let conn = Connection::open_in_memory().unwrap();
+ init_schema_on(&conn).unwrap();
+
+ let record = NamiMediaRecord {
+ id: "x_100".to_string(),
+ platform: "x".to_string(),
+ post_id: "100".to_string(),
+ author: Some("user".to_string()),
+ url: "https://x.com/user/status/100".to_string(),
+ file_path: "/downloads/100.mp4".to_string(),
+ file_size: None,
+ sha256: None,
+ downloaded_at: 1731280000,
+ };
+
+ record_media_on(&conn, &record).unwrap();
+ assert!(has_media_on(&conn, "x", "100").unwrap());
+
+ assert!(delete_record_on(&conn, "x_100").unwrap());
+ assert!(!has_media_on(&conn, "x", "100").unwrap());
+ assert!(!delete_record_on(&conn, "x_100").unwrap());
+ }
+
+ #[test]
+ fn test_reconcile_disk_removes_missing_files() {
+ let conn = Connection::open_in_memory().unwrap();
+ init_schema_on(&conn).unwrap();
+
+ let temp_dir = std::env::temp_dir().join(format!(
+ "nami_test_{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&temp_dir).unwrap();
+ let existing_file = temp_dir.join("present.mp4");
+ std::fs::write(&existing_file, "content").unwrap();
+ let missing_file = temp_dir.join("missing.mp4");
+
+ let rec_present = NamiMediaRecord {
+ id: "rec_1".to_string(),
+ platform: "tiktok".to_string(),
+ post_id: "p1".to_string(),
+ author: None,
+ url: "https://tiktok.com/1".to_string(),
+ file_path: existing_file.to_string_lossy().to_string(),
+ file_size: Some(7),
+ sha256: None,
+ downloaded_at: 100,
+ };
+ let rec_missing = NamiMediaRecord {
+ id: "rec_2".to_string(),
+ platform: "tiktok".to_string(),
+ post_id: "p2".to_string(),
+ author: None,
+ url: "https://tiktok.com/2".to_string(),
+ file_path: missing_file.to_string_lossy().to_string(),
+ file_size: Some(10),
+ sha256: None,
+ downloaded_at: 200,
+ };
+
+ record_media_on(&conn, &rec_present).unwrap();
+ record_media_on(&conn, &rec_missing).unwrap();
+
+ let res = reconcile_disk_on(&conn).unwrap();
+ assert_eq!(res.checked, 2);
+ assert_eq!(res.removed, 1);
+
+ assert!(has_media_on(&conn, "tiktok", "p1").unwrap());
+ assert!(!has_media_on(&conn, "tiktok", "p2").unwrap());
+
+ let _ = std::fs::remove_dir_all(&temp_dir);
+ }
+}
diff --git a/src-tauri/src/commands/nami/mod.rs b/src-tauri/src/commands/nami/mod.rs
index 057a6a84..654b22fe 100644
--- a/src-tauri/src/commands/nami/mod.rs
+++ b/src-tauri/src/commands/nami/mod.rs
@@ -6,6 +6,7 @@ pub mod cookies;
pub mod dispatcher;
pub mod fetcher;
pub mod http;
+pub mod ledger;
use chrono::Utc;
pub use dispatcher::{DownloadProgress, DownloadResult};
@@ -372,6 +373,25 @@ pub fn nami_delete_profile(platform: String, profile_url: String) -> Result<Stri
Ok("Profile deleted".to_string())
}
+#[command]
+pub async fn nami_get_history(
+ platform: Option<String>,
+ limit: Option<u32>,
+ offset: Option<u32>,
+) -> Result<Vec<ledger::NamiMediaRecord>, String> {
+ ledger::get_history(platform.as_deref(), limit.unwrap_or(50), offset.unwrap_or(0))
+}
+
+#[command]
+pub async fn nami_reconcile_disk() -> Result<ledger::ReconcileResult, String> {
+ ledger::reconcile_disk()
+}
+
+#[command]
+pub async fn nami_delete_history_record(id: String) -> Result<bool, String> {
+ ledger::delete_record(&id)
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 0ff9116c..ac04cb6d 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1292,6 +1292,9 @@ pub fn run() {
commands::nami::nami_load_profiles,
commands::nami::nami_save_profile,
commands::nami::nami_delete_profile,
+ commands::nami::nami_get_history,
+ commands::nami::nami_reconcile_disk,
+ commands::nami::nami_delete_history_record,
])
.build(tauri::generate_context!())
.expect("error while building tauri application")
diff --git a/src/lib/api/nami.test.ts b/src/lib/api/nami.test.ts
new file mode 100644
index 00000000..25351056
--- /dev/null
+++ b/src/lib/api/nami.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: vi.fn(async (cmd: string, args?: Record<string, unknown>) => {
+ if (cmd === 'nami_get_history') {
+ return [
+ {
+ id: 'tiktok_123',
+ platform: 'tiktok',
+ post_id: '123',
+ author: 'creator',
+ url: 'https://tiktok.com/@creator/video/123',
+ file_path: '/path/to/video.mp4',
+ file_size: 1024,
+ sha256: null,
+ downloaded_at: 1731280000
+ }
+ ];
+ }
+ if (cmd === 'nami_reconcile_disk') {
+ return { checked: 10, removed: 2 };
+ }
+ if (cmd === 'nami_delete_history_record') {
+ return true;
+ }
+ return null;
+ })
+}));
+
+import { loadNamiHistory, reconcileNamiDisk, deleteNamiHistoryRecord } from './nami';
+
+describe('nami api history and ledger', () => {
+ it('calls nami_get_history and returns records', async () => {
+ const history = await loadNamiHistory('tiktok', 10, 0);
+ expect(history.length).toBe(1);
+ expect(history[0].id).toBe('tiktok_123');
+ expect(history[0].platform).toBe('tiktok');
+ });
+
+ it('calls nami_reconcile_disk and returns count', async () => {
+ const res = await reconcileNamiDisk();
+ expect(res.checked).toBe(10);
+ expect(res.removed).toBe(2);
+ });
+
+ it('calls nami_delete_history_record and returns status', async () => {
+ const ok = await deleteNamiHistoryRecord('tiktok_123');
+ expect(ok).toBe(true);
+ });
+});
diff --git a/src/lib/api/nami.ts b/src/lib/api/nami.ts
index 9f19b86c..194fc613 100644
--- a/src/lib/api/nami.ts
+++ b/src/lib/api/nami.ts
@@ -124,3 +124,40 @@ export async function deleteProfile(platform: string, profileUrl: string): Promi
export function generateDownloadId(): string {
return `dl_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
}
+
+export interface NamiMediaRecord {
+ id: string;
+ platform: string;
+ post_id: string;
+ author?: string | null;
+ url: string;
+ file_path: string;
+ file_size?: number | null;
+ sha256?: string | null;
+ downloaded_at: number;
+}
+
+export interface ReconcileResult {
+ checked: number;
+ removed: number;
+}
+
+export async function loadNamiHistory(
+ platform?: string | null,
+ limit = 50,
+ offset = 0
+): Promise<NamiMediaRecord[]> {
+ return await invoke<NamiMediaRecord[]>('nami_get_history', {
+ platform: platform ?? null,
+ limit,
+ offset,
+ });
+}
+
+export async function reconcileNamiDisk(): Promise<ReconcileResult> {
+ return await invoke<ReconcileResult>('nami_reconcile_disk');
+}
+
+export async function deleteNamiHistoryRecord(id: string): Promise<boolean> {
+ return await invoke<boolean>('nami_delete_history_record', { id });
+}