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 zero-extension browser cookie bridge and settings UI

IGECT03710590cdda
diff --git a/src-tauri/src/commands/nami/args.rs b/src-tauri/src/commands/nami/args.rs
index f5099bab..8afa6997 100644
--- a/src-tauri/src/commands/nami/args.rs
+++ b/src-tauri/src/commands/nami/args.rs
@@ -19,6 +19,7 @@ pub struct GalleryDlArgsOptions<'a> {
pub clean_url: &'a str,
pub username: &'a str,
pub cookie_path: Option<&'a str>,
+ pub browser_cookie_arg: Option<&'a str>,
pub custom_ua: Option<&'a str>,
pub proxy: Option<&'a str>,
pub skip_replies: Option<bool>,
@@ -31,6 +32,7 @@ pub struct YtDlpArgsOptions<'a> {
pub platform: &'a str,
pub clean_url: &'a str,
pub cookie_path: Option<&'a str>,
+ pub browser_cookie_arg: Option<&'a str>,
pub proxy: Option<&'a str>,
pub skip_replies: Option<bool>,
pub break_on_existing: Option<bool>,
@@ -156,6 +158,11 @@ pub fn build_gallery_dl_args(options: &GalleryDlArgsOptions) -> Vec<String> {
args.push("--cookies".to_string());
args.push(cookie_path.to_string());
}
+ } else if let Some(browser_cookie) = options.browser_cookie_arg {
+ if !browser_cookie.trim().is_empty() {
+ args.push("--cookies-from-browser".to_string());
+ args.push(browser_cookie.to_string());
+ }
}
if options.platform.eq_ignore_ascii_case("x") && options.skip_replies == Some(true) {
@@ -235,6 +242,11 @@ pub fn build_yt_dlp_args(options: &YtDlpArgsOptions) -> Vec<String> {
args.push("--cookies".to_string());
args.push(cookie_path.to_string());
}
+ } else if let Some(browser_cookie) = options.browser_cookie_arg {
+ if !browser_cookie.trim().is_empty() {
+ args.push("--cookies-from-browser".to_string());
+ args.push(browser_cookie.to_string());
+ }
}
if options.platform.eq_ignore_ascii_case("x") && options.skip_replies == Some(true) {
@@ -264,6 +276,7 @@ mod tests {
clean_url: "https://www.instagram.com/test/",
username: "test",
cookie_path: Some("C:/cookies/ig.txt"),
+ browser_cookie_arg: None,
custom_ua: None,
proxy: None,
skip_replies: None,
@@ -292,6 +305,7 @@ mod tests {
clean_url: "https://x.com/test",
username: "test",
cookie_path: None,
+ browser_cookie_arg: None,
custom_ua: None,
proxy: None,
skip_replies: Some(true),
@@ -311,6 +325,7 @@ mod tests {
platform: "tiktok",
clean_url: "https://www.tiktok.com/@creator",
cookie_path: None,
+ browser_cookie_arg: None,
proxy: None,
skip_replies: None,
break_on_existing: None,
@@ -338,6 +353,7 @@ mod tests {
clean_url: "https://www.tiktok.com/@creator",
username: "creator",
cookie_path: None,
+ browser_cookie_arg: None,
custom_ua: None,
proxy: None,
skip_replies: None,
@@ -360,6 +376,7 @@ mod tests {
clean_url: "https://www.instagram.com/creator/",
username: "creator",
cookie_path: None,
+ browser_cookie_arg: None,
custom_ua: None,
proxy: None,
skip_replies: None,
@@ -380,6 +397,7 @@ mod tests {
platform: "tiktok",
clean_url: "https://www.tiktok.com/@creator",
cookie_path: None,
+ browser_cookie_arg: None,
proxy: None,
skip_replies: None,
break_on_existing: Some(true),
@@ -388,4 +406,47 @@ mod tests {
let args = build_yt_dlp_args(&opts);
assert!(args.contains(&"--break-on-existing".to_string()));
}
+
+ #[test]
+ fn test_gallery_dl_args_cookies_from_browser() {
+ let dest = PathBuf::from("C:/downloads/Nami/instagram/creator/all");
+ let opts = GalleryDlArgsOptions {
+ dest_dir: &dest,
+ content_type: "all",
+ platform: "instagram",
+ clean_url: "https://www.instagram.com/creator/",
+ username: "creator",
+ cookie_path: None,
+ browser_cookie_arg: Some("chrome"),
+ custom_ua: None,
+ proxy: None,
+ skip_replies: None,
+ abort_after_duplicates: None,
+ };
+
+ let args = build_gallery_dl_args(&opts);
+ let browser_cookie_pos = args.iter().position(|r| r == "--cookies-from-browser");
+ assert!(browser_cookie_pos.is_some());
+ assert_eq!(args[browser_cookie_pos.unwrap() + 1], "chrome");
+ }
+
+ #[test]
+ fn test_yt_dlp_args_cookies_from_browser() {
+ let dest = PathBuf::from("C:/downloads/Nami/tiktok/creator/videos");
+ let opts = YtDlpArgsOptions {
+ dest_dir: &dest,
+ platform: "tiktok",
+ clean_url: "https://www.tiktok.com/@creator",
+ cookie_path: None,
+ browser_cookie_arg: Some("firefox:/profiles/default"),
+ proxy: None,
+ skip_replies: None,
+ break_on_existing: None,
+ };
+
+ let args = build_yt_dlp_args(&opts);
+ let browser_cookie_pos = args.iter().position(|r| r == "--cookies-from-browser");
+ assert!(browser_cookie_pos.is_some());
+ assert_eq!(args[browser_cookie_pos.unwrap() + 1], "firefox:/profiles/default");
+ }
}
diff --git a/src-tauri/src/commands/nami/cookies.rs b/src-tauri/src/commands/nami/cookies.rs
index 1d798939..e0819d2a 100644
--- a/src-tauri/src/commands/nami/cookies.rs
+++ b/src-tauri/src/commands/nami/cookies.rs
@@ -1,10 +1,39 @@
#![allow(clippy::all)]
#![allow(warnings)]
+use rusqlite::Connection;
+use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
+use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
+pub struct DetectedBrowser {
+ pub id: String,
+ pub name: String,
+ pub engine: String,
+ pub profile_dir: String,
+ pub available: bool,
+ pub is_default: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct BrowserIdentity {
+ pub id: String,
+ pub name: String,
+ pub engine: String,
+}
+
+struct BrowserCandidateDef {
+ id: &'static str,
+ name: &'static str,
+ engine: &'static str,
+ win_dirs: &'static [&'static str],
+ mac_dirs: &'static [&'static str],
+ linux_dirs: &'static [&'static str],
+}
+
pub struct SafeCookieSandbox {
pub temp_path: PathBuf,
}
@@ -61,6 +90,974 @@ impl Drop for SafeCookieSandbox {
}
}
+pub struct ResolvedCookies {
+ pub sandbox: Option<SafeCookieSandbox>,
+ pub browser_arg: Option<String>,
+}
+
+impl ResolvedCookies {
+ pub fn empty() -> Self {
+ Self {
+ sandbox: None,
+ browser_arg: None,
+ }
+ }
+
+ pub fn cookie_file_path(&self) -> Option<&Path> {
+ self.sandbox.as_ref().map(|s| s.path())
+ }
+
+ pub fn browser_arg(&self) -> Option<&str> {
+ self.browser_arg.as_deref()
+ }
+
+ pub fn has_cookies(&self) -> bool {
+ self.sandbox.is_some() || self.browser_arg.is_some()
+ }
+}
+
+pub fn parse_windows_default_browser_prog_id(raw_output: &str) -> Option<String> {
+ if raw_output.is_empty() {
+ return None;
+ }
+ for line in raw_output.lines() {
+ let trimmed = line.trim();
+ if let Some(pos) = trimmed.find("ProgId") {
+ let after = trimmed[pos + "ProgId".len()..].trim();
+ let parts: Vec<&str> = after.split_whitespace().collect();
+ if parts.len() == 2 && parts[0].starts_with("REG_") {
+ let prog_id = parts[1].trim();
+ if !prog_id.is_empty()
+ && prog_id
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '-')
+ {
+ return Some(prog_id.to_string());
+ }
+ }
+ }
+ }
+ None
+}
+
+pub fn map_prog_id_to_browser_id(prog_id: &str, command_output: Option<&str>) -> BrowserIdentity {
+ let p_lower = prog_id.to_ascii_lowercase();
+ let cmd = command_output.unwrap_or("").to_ascii_lowercase();
+
+ if p_lower.contains("helium") || cmd.contains("helium") {
+ return BrowserIdentity {
+ id: "helium".to_string(),
+ name: "Helium".to_string(),
+ engine: "chrome".to_string(),
+ };
+ }
+ if p_lower.starts_with("chromehtml")
+ || p_lower.contains("chrome")
+ || cmd.contains("chrome.exe")
+ {
+ return BrowserIdentity {
+ id: "chrome".to_string(),
+ name: "Google Chrome".to_string(),
+ engine: "chrome".to_string(),
+ };
+ }
+ if p_lower.starts_with("msedge")
+ || p_lower.contains("edge")
+ || p_lower.starts_with("appxq0fevzme2pys62n3e0fbqsw5cj08ege9")
+ || cmd.contains("msedge.exe")
+ {
+ return BrowserIdentity {
+ id: "edge".to_string(),
+ name: "Microsoft Edge".to_string(),
+ engine: "edge".to_string(),
+ };
+ }
+ if p_lower.starts_with("brave") || p_lower.contains("brave") || cmd.contains("brave.exe") {
+ return BrowserIdentity {
+ id: "brave".to_string(),
+ name: "Brave Browser".to_string(),
+ engine: "brave".to_string(),
+ };
+ }
+ if p_lower.starts_with("firefox")
+ || p_lower.contains("firefox")
+ || cmd.contains("firefox.exe")
+ {
+ return BrowserIdentity {
+ id: "firefox".to_string(),
+ name: "Mozilla Firefox".to_string(),
+ engine: "firefox".to_string(),
+ };
+ }
+ if p_lower.contains("zen") || cmd.contains("zen") {
+ return BrowserIdentity {
+ id: "zen".to_string(),
+ name: "Zen Browser".to_string(),
+ engine: "firefox".to_string(),
+ };
+ }
+ if p_lower.starts_with("opera") || p_lower.contains("opera") || cmd.contains("opera.exe") {
+ return BrowserIdentity {
+ id: "opera".to_string(),
+ name: "Opera".to_string(),
+ engine: "opera".to_string(),
+ };
+ }
+ if p_lower.starts_with("vivaldi") || p_lower.contains("vivaldi") || cmd.contains("vivaldi.exe")
+ {
+ return BrowserIdentity {
+ id: "vivaldi".to_string(),
+ name: "Vivaldi".to_string(),
+ engine: "vivaldi".to_string(),
+ };
+ }
+
+ BrowserIdentity {
+ id: if p_lower.is_empty() {
+ "chromium".to_string()
+ } else {
+ p_lower
+ },
+ name: if prog_id.is_empty() {
+ "Chromium".to_string()
+ } else {
+ prog_id.to_string()
+ },
+ engine: "chromium".to_string(),
+ }
+}
+
+pub fn parse_mac_default_browser_bundle_id(raw_output: &str) -> Option<String> {
+ if raw_output.is_empty() {
+ return None;
+ }
+ let blocks: Vec<&str> = raw_output.split(|c| c == '{' || c == '}').collect();
+ let mut http_bundle: Option<String> = None;
+
+ for block in blocks {
+ let is_https = block.contains("LSHandlerURLScheme = https")
+ || block.contains("LSHandlerURLScheme = \"https\"");
+ let is_http = block.contains("LSHandlerURLScheme = http")
+ || block.contains("LSHandlerURLScheme = \"http\"");
+ if !is_https && !is_http {
+ continue;
+ }
+
+ let role_section = if let Some(pos) = block.find("LSHandlerRoleAll") {
+ Some(&block[pos..])
+ } else if let Some(pos) = block.find("LSHandlerRoleViewer") {
+ Some(&block[pos..])
+ } else {
+ None
+ };
+
+ if let Some(role_str) = role_section {
+ if let Some(eq_pos) = role_str.find('=') {
+ let rest = &role_str[eq_pos + 1..];
+ let semi_pos = rest.find(';').unwrap_or(rest.len());
+ let bundle = rest[..semi_pos]
+ .trim()
+ .trim_matches('"')
+ .trim_matches('\'')
+ .trim();
+ if !bundle.is_empty() {
+ if is_https {
+ return Some(bundle.to_string());
+ }
+ if http_bundle.is_none() {
+ http_bundle = Some(bundle.to_string());
+ }
+ }
+ }
+ }
+ }
+ http_bundle
+}
+
+pub fn map_bundle_id_to_browser_id(bundle_id: &str) -> BrowserIdentity {
+ let lower = bundle_id.to_ascii_lowercase();
+ if lower.contains("helium") {
+ return BrowserIdentity {
+ id: "helium".to_string(),
+ name: "Helium".to_string(),
+ engine: "chrome".to_string(),
+ };
+ }
+ if lower.contains("chrome") {
+ return BrowserIdentity {
+ id: "chrome".to_string(),
+ name: "Google Chrome".to_string(),
+ engine: "chrome".to_string(),
+ };
+ }
+ if lower.contains("edge") {
+ return BrowserIdentity {
+ id: "edge".to_string(),
+ name: "Microsoft Edge".to_string(),
+ engine: "edge".to_string(),
+ };
+ }
+ if lower.contains("brave") {
+ return BrowserIdentity {
+ id: "brave".to_string(),
+ name: "Brave Browser".to_string(),
+ engine: "brave".to_string(),
+ };
+ }
+ if lower.contains("firefox") {
+ return BrowserIdentity {
+ id: "firefox".to_string(),
+ name: "Mozilla Firefox".to_string(),
+ engine: "firefox".to_string(),
+ };
+ }
+ if lower.contains("zen") {
+ return BrowserIdentity {
+ id: "zen".to_string(),
+ name: "Zen Browser".to_string(),
+ engine: "firefox".to_string(),
+ };
+ }
+ if lower.contains("opera") {
+ return BrowserIdentity {
+ id: "opera".to_string(),
+ name: "Opera".to_string(),
+ engine: "opera".to_string(),
+ };
+ }
+ if lower.contains("vivaldi") {
+ return BrowserIdentity {
+ id: "vivaldi".to_string(),
+ name: "Vivaldi".to_string(),
+ engine: "vivaldi".to_string(),
+ };
+ }
+ if lower.contains("safari") {
+ return BrowserIdentity {
+ id: "safari".to_string(),
+ name: "Safari".to_string(),
+ engine: "safari".to_string(),
+ };
+ }
+ BrowserIdentity {
+ id: lower,
+ name: bundle_id.to_string(),
+ engine: "chromium".to_string(),
+ }
+}
+
+pub fn parse_linux_default_browser_desktop(raw_output: &str) -> Option<String> {
+ if raw_output.is_empty() {
+ return None;
+ }
+ for line in raw_output.lines() {
+ let trimmed = line.trim();
+ if !trimmed.is_empty() && !trimmed.starts_with("ERROR:") && !trimmed.contains("not found") {
+ if trimmed.ends_with(".desktop")
+ || trimmed
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_')
+ {
+ return Some(trimmed.to_string());
+ }
+ }
+ }
+ None
+}
+
+pub fn map_linux_desktop_to_browser_id(desktop_file: &str) -> BrowserIdentity {
+ let lower = desktop_file.to_ascii_lowercase();
+ if lower.contains("helium") {
+ return BrowserIdentity {
+ id: "helium".to_string(),
+ name: "Helium".to_string(),
+ engine: "chrome".to_string(),
+ };
+ }
+ if lower.contains("chrome") {
+ return BrowserIdentity {
+ id: "chrome".to_string(),
+ name: "Google Chrome".to_string(),
+ engine: "chrome".to_string(),
+ };
+ }
+ if lower.contains("edge") {
+ return BrowserIdentity {
+ id: "edge".to_string(),
+ name: "Microsoft Edge".to_string(),
+ engine: "edge".to_string(),
+ };
+ }
+ if lower.contains("brave") {
+ return BrowserIdentity {
+ id: "brave".to_string(),
+ name: "Brave Browser".to_string(),
+ engine: "brave".to_string(),
+ };
+ }
+ if lower.contains("firefox") {
+ return BrowserIdentity {
+ id: "firefox".to_string(),
+ name: "Mozilla Firefox".to_string(),
+ engine: "firefox".to_string(),
+ };
+ }
+ if lower.contains("zen") {
+ return BrowserIdentity {
+ id: "zen".to_string(),
+ name: "Zen Browser".to_string(),
+ engine: "firefox".to_string(),
+ };
+ }
+ if lower.contains("opera") {
+ return BrowserIdentity {
+ id: "opera".to_string(),
+ name: "Opera".to_string(),
+ engine: "opera".to_string(),
+ };
+ }
+ if lower.contains("vivaldi") {
+ return BrowserIdentity {
+ id: "vivaldi".to_string(),
+ name: "Vivaldi".to_string(),
+ engine: "vivaldi".to_string(),
+ };
+ }
+ BrowserIdentity {
+ id: lower.trim_end_matches(".desktop").to_string(),
+ name: desktop_file.to_string(),
+ engine: "chromium".to_string(),
+ }
+}
+
+pub fn detect_system_default_browser() -> Option<String> {
+ #[cfg(target_os = "windows")]
+ {
+ let out = Command::new("reg")
+ .args([
+ "query",
+ "HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice",
+ "/v",
+ "ProgId",
+ ])
+ .output()
+ .ok()
+ .and_then(|o| String::from_utf8(o.stdout).ok())
+ .unwrap_or_default();
+
+ if let Some(prog_id) = parse_windows_default_browser_prog_id(&out) {
+ let cmd_out = Command::new("reg")
+ .args(["query", &format!("HKCR\\{}\\shell\\open\\command", prog_id)])
+ .output()
+ .ok()
+ .and_then(|o| String::from_utf8(o.stdout).ok());
+ return Some(map_prog_id_to_browser_id(&prog_id, cmd_out.as_deref()).id);
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ {
+ let out = Command::new("defaults")
+ .args([
+ "read",
+ "com.apple.LaunchServices/com.apple.launchservices.secure",
+ "LSHandlers",
+ ])
+ .output()
+ .ok()
+ .and_then(|o| String::from_utf8(o.stdout).ok())
+ .unwrap_or_default();
+
+ if let Some(bundle_id) = parse_mac_default_browser_bundle_id(&out) {
+ return Some(map_bundle_id_to_browser_id(&bundle_id).id);
+ }
+ }
+
+ #[cfg(target_os = "linux")]
+ {
+ let out = Command::new("xdg-settings")
+ .args(["get", "default-web-browser"])
+ .output()
+ .ok()
+ .and_then(|o| String::from_utf8(o.stdout).ok())
+ .unwrap_or_default();
+
+ if let Some(desktop) = parse_linux_default_browser_desktop(&out) {
+ return Some(map_linux_desktop_to_browser_id(&desktop).id);
+ }
+
+ let mime_out = Command::new("xdg-mime")
+ .args(["query", "default", "x-scheme-handler/https"])
+ .output()
+ .ok()
+ .and_then(|o| String::from_utf8(o.stdout).ok())
+ .unwrap_or_default();
+
+ if let Some(desktop) = parse_linux_default_browser_desktop(&mime_out) {
+ return Some(map_linux_desktop_to_browser_id(&desktop).id);
+ }
+ }
+
+ None
+}
+
+pub fn list_detected_browsers() -> Vec<DetectedBrowser> {
+ let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/"));
+ let default_id = detect_system_default_browser();
+
+ let candidates: [BrowserCandidateDef; 9] = [
+ BrowserCandidateDef {
+ id: "chrome",
+ name: "Google Chrome",
+ engine: "chrome",
+ win_dirs: &[
+ "Google/Chrome/User Data",
+ ],
+ mac_dirs: &[
+ "Library/Application Support/Google/Chrome",
+ ],
+ linux_dirs: &[
+ ".config/google-chrome",
+ ".var/app/com.google.Chrome/config/google-chrome",
+ ".config/chromium",
+ ".var/app/org.chromium.Chromium/config/chromium",
+ ".config/google-chrome-for-testing",
+ ],
+ },
+ BrowserCandidateDef {
+ id: "edge",
+ name: "Microsoft Edge",
+ engine: "edge",
+ win_dirs: &[
+ "Microsoft/Edge/User Data",
+ ],
+ mac_dirs: &[
+ "Library/Application Support/Microsoft Edge",
+ ],
+ linux_dirs: &[
+ ".config/microsoft-edge",
+ ".var/app/com.microsoft.Edge/config/microsoft-edge",
+ ],
+ },
+ BrowserCandidateDef {
+ id: "brave",
+ name: "Brave Browser",
+ engine: "brave",
+ win_dirs: &[
+ "BraveSoftware/Brave-Browser/User Data",
+ ],
+ mac_dirs: &[
+ "Library/Application Support/BraveSoftware/Brave-Browser",
+ ],
+ linux_dirs: &[
+ ".config/BraveSoftware/Brave-Browser",
+ ".var/app/com.brave.Browser/config/BraveSoftware/Brave-Browser",
+ ],
+ },
+ BrowserCandidateDef {
+ id: "firefox",
+ name: "Mozilla Firefox",
+ engine: "firefox",
+ win_dirs: &[
+ "Mozilla/Firefox/Profiles",
+ "Mozilla/Firefox",
+ ],
+ mac_dirs: &[
+ "Library/Application Support/Firefox/Profiles",
+ "Library/Application Support/Firefox",
+ ],
+ linux_dirs: &[
+ ".mozilla/firefox",
+ ".config/mozilla/firefox",
+ ".var/app/org.mozilla.firefox/.mozilla/firefox",
+ ],
+ },
+ BrowserCandidateDef {
+ id: "zen",
+ name: "Zen Browser",
+ engine: "firefox",
+ win_dirs: &[
+ "zen/Profiles",
+ "zen",
+ ],
+ mac_dirs: &[
+ "Library/Application Support/zen/Profiles",
+ "Library/Application Support/zen",
+ ],
+ linux_dirs: &[
+ ".zen",
+ ".var/app/app.zen_browser.zen/.zen",
+ ],
+ },
+ BrowserCandidateDef {
+ id: "helium",
+ name: "Helium",
+ engine: "chrome",
+ win_dirs: &[
+ "imput/Helium/User Data",
+ ],
+ mac_dirs: &[
+ "Library/Application Support/net.imput.Helium",
+ ],
+ linux_dirs: &[
+ ".config/helium",
+ ".var/app/net.imput.Helium/config/helium",
+ ],
+ },
+ BrowserCandidateDef {
+ id: "opera",
+ name: "Opera",
+ engine: "opera",
+ win_dirs: &[
+ "Opera Software/Opera Stable",
+ ],
+ mac_dirs: &[
+ "Library/Application Support/com.operasoftware.Opera",
+ ],
+ linux_dirs: &[
+ ".config/opera",
+ ".var/app/com.opera.Opera/config/opera",
+ ],
+ },
+ BrowserCandidateDef {
+ id: "vivaldi",
+ name: "Vivaldi",
+ engine: "vivaldi",
+ win_dirs: &[
+ "Vivaldi/User Data",
+ ],
+ mac_dirs: &[
+ "Library/Application Support/Vivaldi",
+ ],
+ linux_dirs: &[
+ ".config/vivaldi",
+ ".var/app/com.vivaldi.Vivaldi/config/vivaldi",
+ ],
+ },
+ BrowserCandidateDef {
+ id: "librewolf",
+ name: "LibreWolf",
+ engine: "firefox",
+ win_dirs: &[
+ "librewolf/Profiles",
+ ],
+ mac_dirs: &[
+ "Library/Application Support/librewolf/Profiles",
+ ],
+ linux_dirs: &[
+ ".librewolf",
+ ".var/app/io.gitlab.librewolf-community/.librewolf",
+ ],
+ },
+ ];
+
+ let mut result = Vec::new();
+
+ for c in &candidates {
+ let (dirs, prefix): (&[&str], PathBuf) = if cfg!(target_os = "windows") {
+ let app_data = std::env::var("LOCALAPPDATA")
+ .map(PathBuf::from)
+ .unwrap_or_else(|_| home.join("AppData").join("Local"));
+ (c.win_dirs, app_data)
+ } else if cfg!(target_os = "macos") {
+ (c.mac_dirs, home.clone())
+ } else {
+ (c.linux_dirs, home.clone())
+ };
+
+ let mut found_dir = PathBuf::new();
+ let mut available = false;
+
+ for d in dirs {
+ let check = prefix.join(d);
+ if check.exists() {
+ found_dir = check;
+ available = true;
+ break;
+ }
+ }
+
+ if !available && !dirs.is_empty() {
+ found_dir = prefix.join(dirs[0]);
+ }
+
+ let is_default = default_id.as_deref() == Some(c.id);
+
+ result.push(DetectedBrowser {
+ id: c.id.to_string(),
+ name: c.name.to_string(),
+ engine: c.engine.to_string(),
+ profile_dir: found_dir.to_string_lossy().to_string(),
+ available,
+ is_default,
+ });
+ }
+
+ result
+}
+
+pub fn find_gecko_profile_dir(base_dir: &Path) -> Option<PathBuf> {
+ if !base_dir.exists() {
+ return None;
+ }
+
+ if base_dir.join("cookies.sqlite").exists() {
+ return Some(base_dir.to_path_buf());
+ }
+
+ let ini_path = base_dir.join("profiles.ini");
+ if ini_path.exists() {
+ if let Ok(content) = fs::read_to_string(&ini_path) {
+ let mut default_path: Option<String> = None;
+ let mut first_path: Option<String> = None;
+ let mut current_path: Option<String> = None;
+ let mut current_is_default = false;
+
+ for line in content.lines() {
+ let trimmed = line.trim();
+ if trimmed.starts_with('[') {
+ if let Some(cp) = current_path.take() {
+ if current_is_default && default_path.is_none() {
+ default_path = Some(cp.clone());
+ }
+ if first_path.is_none() {
+ first_path = Some(cp);
+ }
+ }
+ current_is_default = false;
+ } else if let Some(p) = trimmed.strip_prefix("Path=") {
+ current_path = Some(p.trim().to_string());
+ } else if trimmed == "Default=1" {
+ current_is_default = true;
+ }
+ }
+ if let Some(cp) = current_path {
+ if current_is_default && default_path.is_none() {
+ default_path = Some(cp.clone());
+ }
+ if first_path.is_none() {
+ first_path = Some(cp);
+ }
+ }
+
+ let chosen_rel = default_path.or(first_path);
+ if let Some(rel) = chosen_rel {
+ let full = if Path::new(&rel).is_absolute() {
+ PathBuf::from(rel)
+ } else {
+ base_dir.join(rel)
+ };
+ if full.join("cookies.sqlite").exists() {
+ return Some(full);
+ }
+ }
+ }
+ }
+
+ if let Ok(entries) = fs::read_dir(base_dir) {
+ let mut subdirs: Vec<PathBuf> = Vec::new();
+ for entry in entries.flatten() {
+ if let Ok(ft) = entry.file_type() {
+ if ft.is_dir() {
+ subdirs.push(entry.path());
+ }
+ }
+ }
+ subdirs.sort_by(|a, b| {
+ let a_name = a.file_name().and_then(|n| n.to_str()).unwrap_or("");
+ let b_name = b.file_name().and_then(|n| n.to_str()).unwrap_or("");
+ let a_score = if a_name.contains("default-release") {
+ 2
+ } else if a_name.contains("default") {
+ 1
+ } else {
+ 0
+ };
+ let b_score = if b_name.contains("default-release") {
+ 2
+ } else if b_name.contains("default") {
+ 1
+ } else {
+ 0
+ };
+ b_score.cmp(&a_score)
+ });
+
+ for dir in subdirs {
+ if dir.join("cookies.sqlite").exists() {
+ return Some(dir);
+ }
+ }
+ }
+
+ None
+}
+
+pub fn extract_gecko_cookies_to_netscape(
+ profile_dir: &Path,
+ platform_domains: &[&str],
+) -> Option<String> {
+ let sqlite_file = profile_dir.join("cookies.sqlite");
+ if !sqlite_file.exists() {
+ return None;
+ }
+
+ let timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0);
+ let rand_suffix: u32 = rand::random();
+ let temp_db = std::env::temp_dir().join(format!(
+ "omniget_gecko_{}_{:x}.sqlite",
+ timestamp, rand_suffix
+ ));
+ let temp_wal = std::env::temp_dir().join(format!(
+ "omniget_gecko_{}_{:x}.sqlite-wal",
+ timestamp, rand_suffix
+ ));
+ let src_wal = profile_dir.join("cookies.sqlite-wal");
+
+ if fs::copy(&sqlite_file, &temp_db).is_err() {
+ return None;
+ }
+ if src_wal.exists() {
+ let _ = fs::copy(&src_wal, &temp_wal);
+ }
+
+ let result = (|| -> Result<String, rusqlite::Error> {
+ let conn = Connection::open_with_flags(
+ &temp_db,
+ rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
+ )?;
+
+ let mut query =
+ "SELECT host, path, isSecure, expiry, name, value, isHttpOnly FROM moz_cookies"
+ .to_string();
+ if !platform_domains.is_empty() {
+ let clauses: Vec<String> = platform_domains
+ .iter()
+ .map(|_| "host LIKE ?".to_string())
+ .collect();
+ query.push_str(" WHERE ");
+ query.push_str(&clauses.join(" OR "));
+ }
+
+ let mut stmt = conn.prepare(&query)?;
+ let mut rows = if platform_domains.is_empty() {
+ stmt.query([])?
+ } else {
+ let params: Vec<&dyn rusqlite::ToSql> = platform_domains
+ .iter()
+ .map(|d| d as &dyn rusqlite::ToSql)
+ .collect();
+ stmt.query(params.as_slice())?
+ };
+
+ let mut lines = vec!["# Netscape HTTP Cookie File".to_string()];
+ let mut count = 0;
+
+ while let Some(row) = rows.next()? {
+ let host: String = row.get(0).unwrap_or_default();
+ let path: String = row.get(1).unwrap_or_else(|_| "/".to_string());
+ let is_secure: i64 = row.get(2).unwrap_or(0);
+ let mut expiry: i64 = row.get(3).unwrap_or(0);
+ let name: String = row.get(4).unwrap_or_default();
+ let value: String = row.get(5).unwrap_or_default();
+ let is_http_only: i64 = row.get(6).unwrap_or(0);
+
+ if host.is_empty() || name.is_empty() {
+ continue;
+ }
+
+ if expiry > 100_000_000_000_000 {
+ expiry /= 1_000_000;
+ } else if expiry > 100_000_000_000 {
+ expiry /= 1_000;
+ }
+
+ let domain = if is_http_only == 1 {
+ format!("#HttpOnly_{}", host)
+ } else {
+ host.clone()
+ };
+ let sub = if host.starts_with('.') {
+ "TRUE"
+ } else {
+ "FALSE"
+ };
+ let sec = if is_secure == 1 { "TRUE" } else { "FALSE" };
+
+ lines.push(format!(
+ "{}\t{}\t{}\t{}\t{}\t{}\t{}",
+ domain, sub, path, sec, expiry, name, value
+ ));
+ count += 1;
+ }
+
+ if count == 0 {
+ return Ok(String::new());
+ }
+
+ lines.push(String::new());
+ Ok(lines.join("\n"))
+ })();
+
+ let _ = fs::remove_file(&temp_db);
+ let _ = fs::remove_file(&temp_wal);
+
+ match result {
+ Ok(s) if !s.is_empty() => Some(s),
+ _ => None,
+ }
+}
+
+pub fn resolve_browser_cookie_arg(
+ browser_id: &str,
+ profile_dir: Option<&str>,
+) -> Option<String> {
+ let trimmed = browser_id.trim();
+ if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("none") {
+ return None;
+ }
+
+ let lower = trimmed.to_ascii_lowercase();
+ if lower == "auto" {
+ let def = detect_system_default_browser();
+ return def.and_then(|id| resolve_browser_cookie_arg(&id, None));
+ }
+ if lower == "zen" {
+ if let Some(prof) = profile_dir {
+ let p = Path::new(prof);
+ if let Some(gecko) = find_gecko_profile_dir(p) {
+ return Some(format!("firefox:{}", gecko.display()));
+ }
+ return Some(format!("firefox:{}", prof));
+ }
+ let detected = list_detected_browsers();
+ if let Some(zen) = detected.iter().find(|b| b.id == "zen" && b.available) {
+ let p = Path::new(&zen.profile_dir);
+ if let Some(gecko) = find_gecko_profile_dir(p) {
+ return Some(format!("firefox:{}", gecko.display()));
+ }
+ return Some(format!("firefox:{}", zen.profile_dir));
+ }
+ return Some("firefox".to_string());
+ }
+ if lower == "helium" {
+ if let Some(prof) = profile_dir {
+ return Some(format!("chrome:{}", prof));
+ }
+ let detected = list_detected_browsers();
+ if let Some(helium) = detected.iter().find(|b| b.id == "helium" && b.available) {
+ return Some(format!("chrome:{}", helium.profile_dir));
+ }
+ return Some("chrome".to_string());
+ }
+ if lower == "firefox" {
+ if let Some(prof) = profile_dir {
+ let p = Path::new(prof);
+ if let Some(gecko) = find_gecko_profile_dir(p) {
+ return Some(format!("firefox:{}", gecko.display()));
+ }
+ return Some(format!("firefox:{}", prof));
+ }
+ return Some("firefox".to_string());
+ }
+ Some(lower)
+}
+
+pub fn get_platform_cookie_domains(platform: &str) -> Vec<&'static str> {
+ match platform.to_lowercase().as_str() {
+ "instagram" => vec!["%instagram.com%"],
+ "tiktok" => vec!["%tiktok.com%"],
+ "facebook" => vec!["%facebook.com%", "%fb.com%"],
+ "x" | "twitter" => vec!["%x.com%", "%twitter.com%"],
+ _ => vec![],
+ }
+}
+
+pub fn resolve_active_cookies(
+ platform: &str,
+ manual_path: Option<&str>,
+ browser_selection: Option<&str>,
+ app_data_dir: &Path,
+) -> ResolvedCookies {
+ let temp_base = app_data_dir.join("nami").join("temp");
+
+ if let Some(candidate) = find_candidate_cookie(platform, manual_path, app_data_dir) {
+ if let Ok(sb) = SafeCookieSandbox::create(&candidate, &temp_base) {
+ return ResolvedCookies {
+ sandbox: Some(sb),
+ browser_arg: None,
+ };
+ }
+ }
+
+ let b_choice = browser_selection.unwrap_or("auto").trim();
+ if b_choice.is_empty() || b_choice.eq_ignore_ascii_case("none") {
+ return ResolvedCookies::empty();
+ }
+
+ let target_browser = if b_choice.eq_ignore_ascii_case("auto") {
+ detect_system_default_browser().unwrap_or_else(|| "chrome".to_string())
+ } else {
+ b_choice.to_ascii_lowercase()
+ };
+
+ let browsers = list_detected_browsers();
+ let matched_browser = browsers.iter().find(|b| b.id == target_browser);
+
+ if target_browser == "firefox" || target_browser == "zen" || target_browser == "librewolf" {
+ if let Some(b) = matched_browser {
+ if b.available {
+ let prof_path = Path::new(&b.profile_dir);
+ if let Some(gecko_dir) = find_gecko_profile_dir(prof_path) {
+ let domains = get_platform_cookie_domains(platform);
+ if let Some(netscape_data) =
+ extract_gecko_cookies_to_netscape(&gecko_dir, &domains)
+ {
+ let timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0);
+ let rand_suffix: u32 = rand::random();
+ let temp_file = temp_base.join(format!(
+ "browser_cookies_{}_{:x}.txt",
+ timestamp, rand_suffix
+ ));
+ let _ = fs::create_dir_all(&temp_base);
+ if fs::write(&temp_file, netscape_data).is_ok() {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = fs::set_permissions(
+ &temp_file,
+ fs::Permissions::from_mode(0o600),
+ );
+ }
+ return ResolvedCookies {
+ sandbox: Some(SafeCookieSandbox {
+ temp_path: temp_file,
+ }),
+ browser_arg: None,
+ };
+ }
+ }
+ }
+ }
+ }
+ }
+
+ let browser_arg = resolve_browser_cookie_arg(
+ &target_browser,
+ matched_browser.map(|b| b.profile_dir.as_str()),
+ );
+ ResolvedCookies {
+ sandbox: None,
+ browser_arg,
+ }
+}
+
pub fn find_candidate_cookie(
platform: &str,
custom_path: Option<&str>,
@@ -126,9 +1123,137 @@ mod tests {
assert!(temp_file_path.exists());
assert_ne!(temp_file_path, master);
}
- // After exiting block, sandbox is dropped and temp file is automatically cleaned up
assert!(!temp_file_path.exists());
let _ = fs::remove_dir_all(&temp_dir);
}
+
+ #[test]
+ fn test_parse_windows_default_browser_prog_id() {
+ let chrome_raw = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice\r\n ProgId REG_SZ ChromeHTML\r\n";
+ assert_eq!(parse_windows_default_browser_prog_id(chrome_raw), Some("ChromeHTML".to_string()));
+
+ let helium_raw = " ProgId REG_SZ HeliumHTM\r\n";
+ assert_eq!(parse_windows_default_browser_prog_id(helium_raw), Some("HeliumHTM".to_string()));
+
+ let firefox_raw = " ProgId REG_SZ FirefoxURL-308046B0AF4A39CB\r\n";
+ assert_eq!(parse_windows_default_browser_prog_id(firefox_raw), Some("FirefoxURL-308046B0AF4A39CB".to_string()));
+
+ let injection_raw = " ProgId REG_SZ ChromeHTML & calc.exe\r\n";
+ assert_eq!(parse_windows_default_browser_prog_id(injection_raw), None);
+
+ assert_eq!(parse_windows_default_browser_prog_id(""), None);
+ }
+
+ #[test]
+ fn test_map_prog_id_to_browser_id() {
+ let chrome = map_prog_id_to_browser_id("ChromeHTML", None);
+ assert_eq!(chrome.id, "chrome");
+ assert_eq!(chrome.name, "Google Chrome");
+
+ let edge = map_prog_id_to_browser_id("MSEdgeHTM", None);
+ assert_eq!(edge.id, "edge");
+
+ let edge_uwp = map_prog_id_to_browser_id("AppXq0fevzme2pys62n3e0fbqsw5cj08ege9", None);
+ assert_eq!(edge_uwp.id, "edge");
+
+ let brave = map_prog_id_to_browser_id("BraveHTML", None);
+ assert_eq!(brave.id, "brave");
+
+ let firefox = map_prog_id_to_browser_id("FirefoxURL-308046B0AF4A39CB", None);
+ assert_eq!(firefox.id, "firefox");
+
+ let helium = map_prog_id_to_browser_id("CustomProgId", Some("\"C:\\imput\\Helium\\chrome.exe\" %1"));
+ assert_eq!(helium.id, "helium");
+
+ let zen = map_prog_id_to_browser_id("ZenURL", Some("\"C:\\Zen\\zen.exe\" %1"));
+ assert_eq!(zen.id, "zen");
+ }
+
+ #[test]
+ fn test_parse_mac_and_linux_default_browser() {
+ let mac_output = r#"
+ (
+ {
+ LSHandlerRoleAll = "com.google.chrome";
+ LSHandlerURLScheme = https;
+ }
+ )
+ "#;
+ assert_eq!(parse_mac_default_browser_bundle_id(mac_output), Some("com.google.chrome".to_string()));
+ let mac_browser = map_bundle_id_to_browser_id("com.google.chrome");
+ assert_eq!(mac_browser.id, "chrome");
+
+ let linux_output = "google-chrome.desktop\n";
+ assert_eq!(parse_linux_default_browser_desktop(linux_output), Some("google-chrome.desktop".to_string()));
+ let linux_browser = map_linux_desktop_to_browser_id("google-chrome.desktop");
+ assert_eq!(linux_browser.id, "chrome");
+
+ let zen_linux = map_linux_desktop_to_browser_id("app.zen_browser.zen.desktop");
+ assert_eq!(zen_linux.id, "zen");
+ assert_eq!(zen_linux.engine, "firefox");
+ }
+
+ #[test]
+ fn test_resolve_browser_cookie_arg() {
+ assert_eq!(resolve_browser_cookie_arg("chrome", None), Some("chrome".to_string()));
+ assert_eq!(resolve_browser_cookie_arg("firefox", None), Some("firefox".to_string()));
+ assert_eq!(resolve_browser_cookie_arg("none", None), None);
+ assert_eq!(resolve_browser_cookie_arg("", None), None);
+
+ let zen_arg = resolve_browser_cookie_arg("zen", Some("/home/user/.zen/profile.default"));
+ assert!(zen_arg.unwrap().starts_with("firefox:"));
+ }
+
+ #[test]
+ fn test_gecko_profile_detection_and_sqlite_cookie_extraction() {
+ let temp_dir = std::env::temp_dir().join(format!("nami_gecko_test_{}", rand::random::<u32>()));
+ let _ = fs::create_dir_all(&temp_dir);
+
+ let profile_dir = temp_dir.join("profile.default-release");
+ let _ = fs::create_dir_all(&profile_dir);
+
+ let db_path = profile_dir.join("cookies.sqlite");
+ {
+ let conn = Connection::open(&db_path).expect("Create test sqlite db");
+ conn.execute(
+ "CREATE TABLE moz_cookies (
+ id INTEGER PRIMARY KEY,
+ host TEXT,
+ path TEXT,
+ isSecure INTEGER,
+ expiry INTEGER,
+ name TEXT,
+ value TEXT,
+ isHttpOnly INTEGER
+ )",
+ [],
+ ).unwrap();
+
+ conn.execute(
+ "INSERT INTO moz_cookies (host, path, isSecure, expiry, name, value, isHttpOnly)
+ VALUES ('.instagram.com', '/', 1, 1750000000, 'sessionid', 'mock_ig_session_123', 1)",
+ [],
+ ).unwrap();
+
+ conn.execute(
+ "INSERT INTO moz_cookies (host, path, isSecure, expiry, name, value, isHttpOnly)
+ VALUES ('.facebook.com', '/', 1, 1750000000, 'c_user', '10002345', 0)",
+ [],
+ ).unwrap();
+ }
+
+ let resolved_profile = find_gecko_profile_dir(&temp_dir);
+ assert_eq!(resolved_profile, Some(profile_dir.clone()));
+
+ let ig_cookies = extract_gecko_cookies_to_netscape(&profile_dir, &["%instagram.com%"]);
+ assert!(ig_cookies.is_some());
+ let content = ig_cookies.unwrap();
+ assert!(content.contains("# Netscape HTTP Cookie File"));
+ assert!(content.contains("#HttpOnly_.instagram.com"));
+ assert!(content.contains("sessionid\tmock_ig_session_123"));
+ assert!(!content.contains("facebook.com"));
+
+ let _ = fs::remove_dir_all(&temp_dir);
+ }
}
diff --git a/src-tauri/src/commands/nami/dispatcher.rs b/src-tauri/src/commands/nami/dispatcher.rs
index 639ec6d2..ef52389a 100644
--- a/src-tauri/src/commands/nami/dispatcher.rs
+++ b/src-tauri/src/commands/nami/dispatcher.rs
@@ -4,7 +4,7 @@
use super::args::{
build_gallery_dl_args, build_yt_dlp_args, GalleryDlArgsOptions, YtDlpArgsOptions,
};
-use super::cookies::{find_candidate_cookie, SafeCookieSandbox};
+use super::cookies::{find_candidate_cookie, resolve_active_cookies, SafeCookieSandbox};
use super::fetcher::{ensure_latest_gallery_dl, resolve_gallery_dl, resolve_yt_dlp};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
@@ -290,16 +290,26 @@ pub async fn execute_download_workflow(
// 2. Discover and create ephemeral cookie sandbox if cookies exist
let platform_name = detect_platform_name(&url);
- let resolved_cookie_path =
- find_candidate_cookie(platform_name, cookies_file.as_deref(), &app_data_dir);
- let temp_base = app_data_dir.join("nami").join("temp");
- let cookie_sandbox = resolved_cookie_path
- .as_deref()
- .and_then(|p| SafeCookieSandbox::create(p, &temp_base).ok());
- let active_cookie_str = cookie_sandbox
- .as_ref()
- .map(|s| s.path().to_string_lossy().to_string());
+ let browser_setting: Option<String> = {
+ let settings_path = app_data_dir.join("app_settings.json");
+ fs::read_to_string(&settings_path)
+ .ok()
+ .and_then(|c| serde_json::from_str::<super::AppSettings>(&c).ok())
+ .and_then(|s| s.browser_cookies)
+ };
+
+ let resolved_cookies = resolve_active_cookies(
+ platform_name,
+ cookies_file.as_deref(),
+ browser_setting.as_deref(),
+ &app_data_dir,
+ );
+
+ let active_cookie_str = resolved_cookies
+ .cookie_file_path()
+ .map(|p| p.to_string_lossy().to_string());
+ let active_browser_arg = resolved_cookies.browser_arg().map(|s| s.to_string());
// 3. Plan stages
let mut sub_types: Vec<&str> = match content_type.as_str() {
@@ -310,7 +320,7 @@ pub async fn execute_download_workflow(
_ => vec!["photos", "videos"],
};
- if platform_name == "Instagram" && active_cookie_str.is_some() && content_type == "all" {
+ if platform_name == "Instagram" && resolved_cookies.has_cookies() && content_type == "all" {
sub_types.push("stories");
sub_types.push("highlights");
}
@@ -356,6 +366,7 @@ pub async fn execute_download_workflow(
&url,
&output_dir,
active_cookie_str.as_deref(),
+ active_browser_arg.as_deref(),
sub_type,
&reg,
platform_name,
@@ -429,6 +440,7 @@ fn run_single_stage(
url: &str,
output_dir: &str,
cookie_path: Option<&str>,
+ browser_cookie_arg: Option<&str>,
content_type: &str,
reg: &DownloadRegistration,
platform_name: &str,
@@ -486,6 +498,7 @@ fn run_single_stage(
clean_url: url,
username: &username,
cookie_path,
+ browser_cookie_arg,
custom_ua: None,
proxy: None,
skip_replies,
@@ -533,6 +546,7 @@ fn run_single_stage(
platform: platform_name,
clean_url: url,
cookie_path,
+ browser_cookie_arg,
proxy: None,
skip_replies,
break_on_existing: early_exit_threshold.map(|t| t > 0),
diff --git a/src-tauri/src/commands/nami/mod.rs b/src-tauri/src/commands/nami/mod.rs
index c28f6f77..29900b4e 100644
--- a/src-tauri/src/commands/nami/mod.rs
+++ b/src-tauri/src/commands/nami/mod.rs
@@ -31,6 +31,8 @@ pub struct Profile {
pub struct AppSettings {
pub output_directory: Option<String>,
pub cookies_file: Option<String>,
+ #[serde(default)]
+ pub browser_cookies: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
@@ -195,12 +197,14 @@ pub async fn nami_cancel_download(download_id: String) -> Result<String, String>
pub fn nami_save_app_settings(
output_directory: Option<String>,
cookies_file: Option<String>,
+ browser_cookies: Option<String>,
) -> Result<String, String> {
let _storage_guard = NAMI_STORAGE_LOCK.lock().unwrap_or_else(|p| p.into_inner());
let settings = AppSettings {
output_directory,
cookies_file,
+ browser_cookies,
};
let config_dir = omniget_nami_dir()?;
@@ -221,6 +225,7 @@ pub fn nami_load_app_settings() -> Result<AppSettings, String> {
return Ok(AppSettings {
output_directory: None,
cookies_file: None,
+ browser_cookies: None,
});
}
@@ -231,6 +236,79 @@ pub fn nami_load_app_settings() -> Result<AppSettings, String> {
Ok(settings)
}
+#[command]
+pub fn nami_detect_browsers() -> Result<Vec<cookies::DetectedBrowser>, String> {
+ Ok(cookies::list_detected_browsers())
+}
+
+#[command]
+pub fn nami_extract_browser_cookies(
+ browser_id: String,
+ platform: String,
+) -> Result<Option<String>, String> {
+ let browsers = cookies::list_detected_browsers();
+ let target = if browser_id.eq_ignore_ascii_case("auto") {
+ cookies::detect_system_default_browser().unwrap_or_else(|| "chrome".to_string())
+ } else {
+ browser_id.to_ascii_lowercase()
+ };
+
+ let matched = browsers.into_iter().find(|b| b.id == target);
+ let browser = match matched {
+ Some(b) => b,
+ None => return Err(format!("Browser '{}' is not recognized or installed", browser_id)),
+ };
+
+ if !browser.available {
+ return Err(format!(
+ "Browser '{}' profile directory was not found on this system",
+ browser.name
+ ));
+ }
+
+ if browser.engine == "firefox" {
+ let prof_path = PathBuf::from(&browser.profile_dir);
+ let gecko_dir = cookies::find_gecko_profile_dir(&prof_path)
+ .ok_or_else(|| format!("Could not find cookies.sqlite in '{}' profile", browser.name))?;
+ let domains = cookies::get_platform_cookie_domains(&platform);
+ let netscape_data = cookies::extract_gecko_cookies_to_netscape(&gecko_dir, &domains)
+ .ok_or_else(|| {
+ format!(
+ "No active session cookies found in {} for {}",
+ browser.name, platform
+ )
+ })?;
+
+ let config_dir = omniget_nami_dir()?;
+ let cookies_dir = config_dir.join("cookies");
+ fs::create_dir_all(&cookies_dir).map_err(|e| e.to_string())?;
+
+ let file_name = format!("{}.com_cookies.txt", platform.to_lowercase());
+ let target_path = cookies_dir.join(&file_name);
+ fs::write(&target_path, &netscape_data).map_err(|e| e.to_string())?;
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = fs::set_permissions(&target_path, fs::Permissions::from_mode(0o600));
+ }
+
+ let line_count = netscape_data
+ .lines()
+ .filter(|l| !l.starts_with('#') && !l.trim().is_empty())
+ .count();
+ return Ok(Some(format!(
+ "Successfully extracted {} cookies from {}",
+ line_count, browser.name
+ )));
+ }
+
+ Ok(Some(format!(
+ "{} verified and connected via native browser engine bridge",
+ browser.name
+ )))
+}
+
#[command]
pub fn nami_load_profiles(platform: String) -> Result<Vec<Profile>, String> {
validate_profile_platform(&platform)?;
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index c728cfc7..da183bb5 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1297,6 +1297,8 @@ pub fn run() {
commands::nami::nami_delete_history_record,
commands::nami::nami_pull_creator,
commands::nami::nami_pull_all_creators,
+ commands::nami::nami_detect_browsers,
+ commands::nami::nami_extract_browser_cookies,
])
.build(tauri::generate_context!())
.expect("error while building tauri application")
diff --git a/src/components/nami/SettingsManager.svelte b/src/components/nami/SettingsManager.svelte
index 271d0b90..c3bb7c5d 100644
--- a/src/components/nami/SettingsManager.svelte
+++ b/src/components/nami/SettingsManager.svelte
@@ -1,30 +1,55 @@
<script lang="ts">
import { open } from '@tauri-apps/plugin-dialog';
- import { getOutputDir, getCookiesFile, loadSettings, saveSettings } from '$lib/stores/nami_settings_store.svelte';
+ import {
+ getOutputDir,
+ getCookiesFile,
+ getBrowserCookies,
+ loadSettings,
+ saveSettings,
+ } from '$lib/stores/nami_settings_store.svelte';
+ import { detectBrowsers, extractBrowserCookies, type DetectedBrowser } from '$lib/api/nami';
import { onMount } from 'svelte';
import { t } from '$lib/i18n';
let outputDir = $state('');
let cookiesFile = $state('');
+ let browserCookies = $state('auto');
+ let detectedBrowsers = $state<DetectedBrowser[]>([]);
let saving = $state(false);
+ let testingBridge = $state(false);
let saveStatus = $state('');
let saveStatusType = $state<'success' | 'error'>('success');
+ let bridgeStatus = $state('');
+ let bridgeStatusType = $state<'success' | 'error'>('success');
let statusTimer: ReturnType<typeof setTimeout> | null = null;
+ let bridgeTimer: ReturnType<typeof setTimeout> | null = null;
let isDirty = $derived(
outputDir.trim() !== getOutputDir().trim() ||
- cookiesFile.trim() !== getCookiesFile().trim()
+ cookiesFile.trim() !== getCookiesFile().trim() ||
+ browserCookies.trim() !== getBrowserCookies().trim()
);
onMount(async () => {
await loadSettings();
outputDir = getOutputDir();
cookiesFile = getCookiesFile();
+ browserCookies = getBrowserCookies();
+
+ try {
+ detectedBrowsers = await detectBrowsers();
+ } catch (err) {
+ console.warn('Failed to detect browsers:', err);
+ }
});
async function browseOutputDir() {
try {
- const selected = await open({ directory: true, multiple: false, title: $t('nami.select_output_dir_title') });
+ const selected = await open({
+ directory: true,
+ multiple: false,
+ title: $t('nami.select_output_dir_title'),
+ });
if (selected && typeof selected === 'string') outputDir = selected;
} catch (err) {
console.error('Failed to open directory dialog:', err);
@@ -33,7 +58,11 @@
async function browseCookiesFile() {
try {
- const selected = await open({ directory: false, multiple: false, title: $t('nami.select_cookies_title') });
+ const selected = await open({
+ directory: false,
+ multiple: false,
+ title: $t('nami.select_cookies_title'),
+ });
if (selected && typeof selected === 'string') cookiesFile = selected;
} catch (err) {
console.error('Failed to open file dialog:', err);
@@ -44,6 +73,30 @@
cookiesFile = '';
}
+ async function handleTestBridge() {
+ testingBridge = true;
+ bridgeStatus = '';
+ if (bridgeTimer) {
+ clearTimeout(bridgeTimer);
+ bridgeTimer = null;
+ }
+ try {
+ const result = await extractBrowserCookies(browserCookies, 'instagram');
+ bridgeStatus = result || 'Bridge verified successfully';
+ bridgeStatusType = 'success';
+ bridgeTimer = setTimeout(() => {
+ bridgeStatus = '';
+ bridgeTimer = null;
+ }, 5000);
+ } catch (err) {
+ console.error('Failed to test cookie bridge:', err);
+ bridgeStatus = typeof err === 'string' ? err : 'Bridge test failed';
+ bridgeStatusType = 'error';
+ } finally {
+ testingBridge = false;
+ }
+ }
+
async function handleSave() {
saving = true;
saveStatus = '';
@@ -52,9 +105,10 @@
statusTimer = null;
}
try {
- await saveSettings(outputDir, cookiesFile);
+ await saveSettings(outputDir, cookiesFile, browserCookies);
outputDir = getOutputDir();
cookiesFile = getCookiesFile();
+ browserCookies = getBrowserCookies();
saveStatus = 'nami.settings_saved';
saveStatusType = 'success';
statusTimer = setTimeout(() => {
@@ -84,6 +138,18 @@
</div>
{/if}
+ {#if bridgeStatus}
+ <div
+ class="sm-alert"
+ class:success={bridgeStatusType === 'success'}
+ class:error={bridgeStatusType === 'error'}
+ role="status"
+ aria-live="polite"
+ >
+ <span>{bridgeStatus}</span>
+ </div>
+ {/if}
+
<div class="sm-group">
<div class="sm-row">
<svg class="sm-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round" aria-hidden="true">
@@ -104,27 +170,62 @@
<div class="sm-row">
<svg class="sm-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round" aria-hidden="true">
- <path d="M4.3 2h4.4L12 5.3V13a.7.7 0 0 1-.7.7H4.3a.7.7 0 0 1-.7-.7V2.7A.7.7 0 0 1 4.3 2Z" />
- <path d="M8.7 2v3.3H12" />
+ <circle cx="8" cy="8" r="6.2" />
+ <path d="M1.8 8h12.4M8 1.8c2 2 3.1 4.1 3.1 6.2s-1.1 4.2-3.1 6.2c-2-2-3.1-4.1-3.1-6.2S6 3.8 8 1.8z" />
</svg>
- <span class="sm-label">{$t('nami.cookies_label')}</span>
- <input
- id="cookies-file"
- aria-label={$t('nami.cookies_file_aria')}
- type="text"
- bind:value={cookiesFile}
- placeholder={$t('nami.choose_cookies_placeholder')}
- autocomplete="off"
- spellcheck="false"
- />
- {#if cookiesFile}
- <button type="button" class="sm-clear-btn" onclick={clearCookies} title={$t('nami.clear_cookies_file')}>×</button>
+ <span class="sm-label">{$t('nami.browser_cookies_label')}</span>
+ <select
+ id="browser-cookies"
+ aria-label={$t('nami.browser_cookies_aria')}
+ bind:value={browserCookies}
+ class="sm-select"
+ >
+ <option value="auto">{$t('nami.browser_cookies_auto')}</option>
+ {#each detectedBrowsers as b}
+ <option value={b.id}>
+ {b.name} {b.available ? '✓' : ''} {b.is_default ? '(Default)' : ''}
+ </option>
+ {/each}
+ <option value="custom">{$t('nami.browser_cookies_manual')}</option>
+ <option value="none">{$t('nami.browser_cookies_disabled')}</option>
+ </select>
+ {#if browserCookies !== 'none' && browserCookies !== 'custom'}
+ <button
+ type="button"
+ class="sm-test-btn"
+ onclick={handleTestBridge}
+ disabled={testingBridge}
+ >
+ {testingBridge ? $t('nami.testing_cookies') : $t('nami.test_extract_cookies')}
+ </button>
{/if}
- <button type="button" class="sm-choose-btn" onclick={browseCookiesFile}>{$t('nami.choose')}</button>
</div>
+
+ {#if browserCookies === 'custom' || (cookiesFile && browserCookies !== 'none')}
+ <div class="sm-row">
+ <svg class="sm-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round" aria-hidden="true">
+ <path d="M4.3 2h4.4L12 5.3V13a.7.7 0 0 1-.7.7H4.3a.7.7 0 0 1-.7-.7V2.7A.7.7 0 0 1 4.3 2Z" />
+ <path d="M8.7 2v3.3H12" />
+ </svg>
+ <span class="sm-label">{$t('nami.cookies_label')}</span>
+ <input
+ id="cookies-file"
+ aria-label={$t('nami.cookies_file_aria')}
+ type="text"
+ bind:value={cookiesFile}
+ placeholder={$t('nami.choose_cookies_placeholder')}
+ autocomplete="off"
+ spellcheck="false"
+ />
+ {#if cookiesFile}
+ <button type="button" class="sm-clear-btn" onclick={clearCookies} title={$t('nami.clear_cookies_file')}>×</button>
+ {/if}
+ <button type="button" class="sm-choose-btn" onclick={browseCookiesFile}>{$t('nami.choose')}</button>
+ </div>
+ {/if}
</div>
- <p class="sm-hint">{$t('nami.cookies_hint')}</p>
+ <p class="sm-hint">{$t('nami.cookies_bridge_hint')}</p>
<div class="sm-actions">
<button
@@ -210,10 +311,27 @@
opacity: 0.8;
}
- .sm-row input:focus {
+ .sm-row input:focus-visible {
outline: none;
}
+ .sm-select {
+ flex: 1;
+ border: 1px solid var(--oo-border);
+ background: var(--oo-card-bg, var(--oo-group-bg));
+ color: var(--oo-text);
+ font-size: 12.5px;
+ border-radius: 6px;
+ padding: 5px 8px;
+ min-width: 0;
+ cursor: pointer;
+ }
+
+ .sm-select:focus-visible {
+ outline: 2px solid var(--oo-accent);
+ outline-offset: 1px;
+ }
+
.sm-clear-btn {
background: transparent;
border: none;
@@ -230,7 +348,8 @@
color: var(--error);
}
- .sm-choose-btn {
+ .sm-choose-btn,
+ .sm-test-btn {
min-height: 34px;
padding: 6px 12px;
border-radius: 6px;
@@ -241,17 +360,25 @@
color: var(--oo-text);
flex-shrink: 0;
cursor: pointer;
- transition: background 150ms ease;
+ transition: background 150ms ease, border-color 150ms ease;
}
- .sm-choose-btn:hover {
+ .sm-choose-btn:hover,
+ .sm-test-btn:hover:not(:disabled) {
background: color-mix(in srgb, var(--oo-text) 5%, var(--oo-group-bg));
+ border-color: var(--oo-accent);
+ }
+
+ .sm-test-btn:disabled {
+ opacity: 0.6;
+ cursor: not-allowed;
}
.sm-hint {
font-size: 11.5px;
color: var(--oo-text-secondary);
margin: -6px 0 0;
+ line-height: 1.4;
}
.sm-actions {
@@ -286,12 +413,14 @@
align-items: flex-start;
flex-wrap: wrap;
}
- .sm-row input {
+ .sm-row input,
+ .sm-select {
order: 3;
flex-basis: calc(100% - 24px);
text-align: left;
}
- .sm-choose-btn {
+ .sm-choose-btn,
+ .sm-test-btn {
margin-left: auto;
}
}
diff --git a/src/lib/api/nami.test.ts b/src/lib/api/nami.test.ts
index fa2ee9a2..344795f5 100644
--- a/src/lib/api/nami.test.ts
+++ b/src/lib/api/nami.test.ts
@@ -53,11 +53,46 @@ vi.mock('@tauri-apps/api/core', () => ({
],
};
}
+ if (cmd === 'nami_detect_browsers') {
+ return [
+ {
+ id: 'chrome',
+ name: 'Google Chrome',
+ engine: 'chrome',
+ profile_dir: '/path/to/chrome',
+ available: true,
+ is_default: true,
+ },
+ {
+ id: 'firefox',
+ name: 'Mozilla Firefox',
+ engine: 'firefox',
+ profile_dir: '/path/to/firefox',
+ available: false,
+ is_default: false,
+ },
+ ];
+ }
+ if (cmd === 'nami_extract_browser_cookies') {
+ return 'Successfully extracted 8 cookies from Mozilla Firefox';
+ }
+ if (cmd === 'nami_save_app_settings') {
+ return 'Settings saved successfully';
+ }
return null;
})
}));
-import { loadNamiHistory, reconcileNamiDisk, deleteNamiHistoryRecord, pullCreator, pullAllCreators } from './nami';
+import {
+ loadNamiHistory,
+ reconcileNamiDisk,
+ deleteNamiHistoryRecord,
+ pullCreator,
+ pullAllCreators,
+ detectBrowsers,
+ extractBrowserCookies,
+ saveAppSettings,
+} from './nami';
describe('nami api history and ledger', () => {
it('calls nami_get_history and returns records', async () => {
@@ -91,4 +126,21 @@ describe('nami api history and ledger', () => {
expect(summary.succeeded).toBe(1);
expect(summary.total_downloaded).toBe(2);
});
+
+ it('calls nami_detect_browsers and returns detected browsers', async () => {
+ const browsers = await detectBrowsers();
+ expect(browsers.length).toBe(2);
+ expect(browsers[0].id).toBe('chrome');
+ expect(browsers[0].is_default).toBe(true);
+ });
+
+ it('calls nami_extract_browser_cookies and returns result string', async () => {
+ const res = await extractBrowserCookies('firefox', 'instagram');
+ expect(res).toContain('extracted 8 cookies');
+ });
+
+ it('calls nami_save_app_settings with browserCookies', async () => {
+ const res = await saveAppSettings('/downloads', null, 'chrome');
+ expect(res).toBe('Settings saved successfully');
+ });
});
diff --git a/src/lib/api/nami.ts b/src/lib/api/nami.ts
index c29092d7..0394bfe5 100644
--- a/src/lib/api/nami.ts
+++ b/src/lib/api/nami.ts
@@ -27,6 +27,16 @@ export interface DownloadProgress {
export interface AppSettings {
output_directory: string | null;
cookies_file: string | null;
+ browser_cookies?: string | null;
+}
+
+export interface DetectedBrowser {
+ id: string;
+ name: string;
+ engine: string;
+ profile_dir: string;
+ available: boolean;
+ is_default: boolean;
}
export interface DependencyStatus {
@@ -98,11 +108,27 @@ export async function listenToDownloadProgress(
export async function saveAppSettings(
outputDirectory: string | null,
- cookiesFile: string | null
+ cookiesFile: string | null,
+ browserCookies?: string | null
): Promise<string> {
return await invoke<string>('nami_save_app_settings', {
outputDirectory,
- cookiesFile
+ cookiesFile,
+ browserCookies: browserCookies ?? null
+ });
+}
+
+export async function detectBrowsers(): Promise<DetectedBrowser[]> {
+ return await invoke<DetectedBrowser[]>('nami_detect_browsers');
+}
+
+export async function extractBrowserCookies(
+ browserId: string,
+ platform: string
+): Promise<string | null> {
+ return await invoke<string | null>('nami_extract_browser_cookies', {
+ browserId,
+ platform
});
}
diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.json
index 6b52161e..69c7c1eb 100644
--- a/src/lib/i18n/el.json
+++ b/src/lib/i18n/el.json
@@ -5393,7 +5393,15 @@
"sync_all_creators": "Συγχρονισμός όλων",
"syncing_creator": "Συγχρονισμός...",
"pull_success": "Συγχρονίστηκε {{name}}: {{count}} νέα αρχεία",
- "pull_all_success": "Συγχρονίστηκαν {{total}} δημιουργοί: {{count}} νέα αρχεία"
+ "pull_all_success": "Συγχρονίστηκαν {{total}} δημιουργοί: {{count}} νέα αρχεία",
+ "browser_cookies_label": "Cookies Προγράμματος Περιήγησης",
+ "browser_cookies_aria": "Επιλέξτε πρόγραμμα περιήγησης για αυτόματη εξαγωγή cookies",
+ "browser_cookies_auto": "Αυτόματο (Προεπιλεγμένο Πρόγραμμα Περιήγησης)",
+ "browser_cookies_manual": "Χειροκίνητο Αρχείο Cookies (.txt)",
+ "browser_cookies_disabled": "Απενεργοποιημένο",
+ "test_extract_cookies": "Δοκιμή Γέφυρας",
+ "testing_cookies": "Δοκιμή...",
+ "cookies_bridge_hint": "Αυτόματη ανάγνωση cookies σύνδεσης από το πρόγραμμα περιήγησης χωρίς επεκτάσεις."
},
"tray": {
"quit": "Quit",
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index 9bf9ea0d..b0cdcb3f 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -5401,6 +5401,14 @@
"sync_all_creators": "Sync All",
"syncing_creator": "Syncing...",
"pull_success": "Synced {{name}}: {{count}} new files",
- "pull_all_success": "Synced {{total}} creators: {{count}} new files"
+ "pull_all_success": "Synced {{total}} creators: {{count}} new files",
+ "browser_cookies_label": "Browser Cookies",
+ "browser_cookies_aria": "Select browser for automatic cookie extraction",
+ "browser_cookies_auto": "Auto (Default Browser)",
+ "browser_cookies_manual": "Manual Cookie File (.txt)",
+ "browser_cookies_disabled": "Disabled / None",
+ "test_extract_cookies": "Test Bridge",
+ "testing_cookies": "Testing...",
+ "cookies_bridge_hint": "Zero-extension bridge automatically reads session cookies from your browser for private stories and highlights."
}
}
diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.json
index fbe13ee1..5dd12853 100644
--- a/src/lib/i18n/es.json
+++ b/src/lib/i18n/es.json
@@ -5393,7 +5393,15 @@
"sync_all_creators": "Sincronizar todo",
"syncing_creator": "Sincronizando...",
"pull_success": "Sincronizado {{name}}: {{count}} nuevos archivos",
- "pull_all_success": "Sincronizados {{total}} creadores: {{count}} nuevos archivos"
+ "pull_all_success": "Sincronizados {{total}} creadores: {{count}} nuevos archivos",
+ "browser_cookies_label": "Cookies del Navegador",
+ "browser_cookies_aria": "Seleccione navegador para extracción automática de cookies",
+ "browser_cookies_auto": "Automático (Navegador predeterminado)",
+ "browser_cookies_manual": "Archivo manual de cookies (.txt)",
+ "browser_cookies_disabled": "Desactivado",
+ "test_extract_cookies": "Probar puente",
+ "testing_cookies": "Probando...",
+ "cookies_bridge_hint": "El puente sin extensiones lee automáticamente las cookies de sesión del navegador."
},
"tray": {
"quit": "Quit",
diff --git a/src/lib/i18n/fa.json b/src/lib/i18n/fa.json
index c1ce70fe..e73528fc 100644
--- a/src/lib/i18n/fa.json
+++ b/src/lib/i18n/fa.json
@@ -5393,7 +5393,15 @@
"sync_all_creators": "همگام‌سازی همه",
"syncing_creator": "در حال همگام‌سازی...",
"pull_success": "همگام‌سازی {{name}}: {{count}} فایل جدید",
- "pull_all_success": "همگام‌سازی {{total}} سازنده: {{count}} فایل جدید"
+ "pull_all_success": "همگام‌سازی {{total}} سازنده: {{count}} فایل جدید",
+ "browser_cookies_label": "کوکی‌های مرورگر",
+ "browser_cookies_aria": "انتخاب مرورگر برای استخراج خودکار کوکی",
+ "browser_cookies_auto": "خودکار (مرورگر پیش‌فرض)",
+ "browser_cookies_manual": "فایل کوکی دستی (.txt)",
+ "browser_cookies_disabled": "غیرفعال",
+ "test_extract_cookies": "آزمایش پل",
+ "testing_cookies": "در حال آزمایش...",
+ "cookies_bridge_hint": "پل بدون افزونه کوکی‌های نشست را برای استوری‌ها خودکار می‌خواند."
},
"tray": {
"quit": "Quit",
diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.json
index 48db82c0..ccd494ab 100644
--- a/src/lib/i18n/fr.json
+++ b/src/lib/i18n/fr.json
@@ -5393,7 +5393,15 @@
"sync_all_creators": "Synchroniser tout",
"syncing_creator": "Synchronisation...",
"pull_success": "Synchronisé {{name}} : {{count}} nouveaux fichiers",
- "pull_all_success": "Synchronisé {{total}} créateurs : {{count}} nouveaux fichiers"
+ "pull_all_success": "Synchronisé {{total}} créateurs : {{count}} nouveaux fichiers",
+ "browser_cookies_label": "Cookies du Navigateur",
+ "browser_cookies_aria": "Sélectionnez le navigateur pour l'extraction automatique des cookies",
+ "browser_cookies_auto": "Automatique (Navigateur par défaut)",
+ "browser_cookies_manual": "Fichier Cookie Manuel (.txt)",
+ "browser_cookies_disabled": "Désactivé",
+ "test_extract_cookies": "Tester le pont",
+ "testing_cookies": "Test en cours...",
+ "cookies_bridge_hint": "La passerelle sans extension lit automatiquement les cookies de session depuis votre navigateur."
},
"tray": {
"quit": "Quit",
diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.json
index 796c12bd..adc2dc87 100644
--- a/src/lib/i18n/it.json
+++ b/src/lib/i18n/it.json
@@ -5393,7 +5393,15 @@
"sync_all_creators": "Sincronizza tutti",
"syncing_creator": "Sincronizzazione...",
"pull_success": "Sincronizzato {{name}}: {{count}} nuovi file",
- "pull_all_success": "Sincronizzati {{total}} autori: {{count}} nuovi file"
+ "pull_all_success": "Sincronizzati {{total}} autori: {{count}} nuovi file",
+ "browser_cookies_label": "Cookie del Browser",
+ "browser_cookies_aria": "Seleziona il browser per l'estrazione automatica dei cookie",
+ "browser_cookies_auto": "Automatico (Browser Predefinito)",
+ "browser_cookies_manual": "File Cookie Manuale (.txt)",
+ "browser_cookies_disabled": "Disattivato",
+ "test_extract_cookies": "Testa Bridge",
+ "testing_cookies": "Test in corso...",
+ "cookies_bridge_hint": "Il bridge zero-estensioni legge automaticamente i cookie di sessione dal browser."
},
"tray": {
"quit": "Quit",
diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.json
index 25904676..741cceba 100644
--- a/src/lib/i18n/ja.json
+++ b/src/lib/i18n/ja.json
@@ -5393,7 +5393,15 @@
"sync_all_creators": "すべて同期",
"syncing_creator": "同期中...",
"pull_success": "{{name}} を同期しました: {{count}} 件の新規ファイル",
- "pull_all_success": "{{total}} 名のクリエイターを同期しました: {{count}} 件の新規ファイル"
+ "pull_all_success": "{{total}} 名のクリエイターを同期しました: {{count}} 件の新規ファイル",
+ "browser_cookies_label": "ブラウザ Cookie",
+ "browser_cookies_aria": "Cookie 自動抽出用のブラウザを選択",
+ "browser_cookies_auto": "自動(既定のブラウザ)",
+ "browser_cookies_manual": "手動 Cookie ファイル (.txt)",
+ "browser_cookies_disabled": "無効",
+ "test_extract_cookies": "ブリッジをテスト",
+ "testing_cookies": "テスト中...",
+ "cookies_bridge_hint": "拡張機能なしでブラウザからセッション Cookie を自動的に読み込みます。"
},
"tray": {
"quit": "Quit",
diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.ts
index ce08f70f..c0aa1172 100644
--- a/src/lib/i18n/keys.ts
+++ b/src/lib/i18n/keys.ts
@@ -546,6 +546,11 @@ export type TranslationKeys =
| 'nami.add'
| 'nami.add_one'
+ | 'nami.browser_cookies_aria'
+ | 'nami.browser_cookies_auto'
+ | 'nami.browser_cookies_disabled'
+ | 'nami.browser_cookies_label'
+ | 'nami.browser_cookies_manual'
| 'nami.cancelling'
| 'nami.choose'
| 'nami.choose_cookies_placeholder'
@@ -558,6 +563,7 @@ export type TranslationKeys =
| 'nami.content_stories'
| 'nami.content_type_aria'
| 'nami.content_videos'
+ | 'nami.cookies_bridge_hint'
| 'nami.cookies_file_aria'
| 'nami.cookies_hint'
| 'nami.cookies_label'
@@ -634,6 +640,8 @@ export type TranslationKeys =
| 'nami.tab_history'
| 'nami.tab_profiles'
| 'nami.tab_settings'
+ | 'nami.test_extract_cookies'
+ | 'nami.testing_cookies'
| 'nami.view_log'
| 'nav.about'
diff --git a/src/lib/i18n/lo.json b/src/lib/i18n/lo.json
index 33500290..4bd50b3f 100644
--- a/src/lib/i18n/lo.json
+++ b/src/lib/i18n/lo.json
@@ -5393,7 +5393,15 @@
"sync_all_creators": "ຊິງຄ໌ທັງໝົດ",
"syncing_creator": "ກຳລັງຊິງຄ໌...",
"pull_success": "ຊິງຄ໌ {{name}} ແລ້ວ: {{count}} ໄຟລ໌ໃໝ່",
- "pull_all_success": "ຊິງຄ໌ {{total}} ຜູ້ສ້າງແລ້ວ: {{count}} ໄຟລ໌ໃໝ່"
+ "pull_all_success": "ຊິງຄ໌ {{total}} ຜູ້ສ້າງແລ້ວ: {{count}} ໄຟລ໌ໃໝ່",
+ "browser_cookies_label": "ຄຸກກີ້ຂອງບຣາວເຊີ",
+ "browser_cookies_aria": "ເລືອກບຣາວເຊີສຳລັບການດຶງຄຸກກີ້ອັດຕະໂນມັດ",
+ "browser_cookies_auto": "ອັດຕະໂນມັດ (ບຣາວເຊີເລີ່ມຕົ້ນ)",
+ "browser_cookies_manual": "ໄຟລ໌ຄຸກກີ້ດ້ວຍຕົນເອງ (.txt)",
+ "browser_cookies_disabled": "ປິດໃຊ້ງານ",
+ "test_extract_cookies": "ທົດສອບການເຊື່ອມຕໍ່",
+ "testing_cookies": "ກຳລັງທົດສອບ...",
+ "cookies_bridge_hint": "ລະບົບຈະອ່ານຄຸກກີ້ເຊດຊັນຈາກບຣາວເຊີຂອງທ່ານໂດຍອັດຕະໂນມັດ."
},
"tray": {
"quit": "Quit",
diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.json
index 51bf2a1c..54dcfb83 100644
--- a/src/lib/i18n/pt.json
+++ b/src/lib/i18n/pt.json
@@ -5393,7 +5393,15 @@
"sync_all_creators": "Sincronizar todos",
"syncing_creator": "Sincronizando...",
"pull_success": "Sincronizado {{name}}: {{count}} novos arquivos",
- "pull_all_success": "Sincronizados {{total}} criadores: {{count}} novos arquivos"
+ "pull_all_success": "Sincronizados {{total}} criadores: {{count}} novos arquivos",
+ "browser_cookies_label": "Cookies do Navegador",
+ "browser_cookies_aria": "Selecione o navegador para extração automática de cookies",
+ "browser_cookies_auto": "Automático (Navegador Padrão)",
+ "browser_cookies_manual": "Arquivo Manual de Cookies (.txt)",
+ "browser_cookies_disabled": "Desativado",
+ "test_extract_cookies": "Testar Ponte",
+ "testing_cookies": "Testando...",
+ "cookies_bridge_hint": "A ponte sem extensão lê automaticamente cookies de sessão do seu navegador."
},
"tray": {
"quit": "Quit",
diff --git a/src/lib/i18n/ru.json b/src/lib/i18n/ru.json
index 2be29cb4..3dc1209b 100644
--- a/src/lib/i18n/ru.json
+++ b/src/lib/i18n/ru.json
@@ -5401,6 +5401,14 @@
"sync_all_creators": "Сверить все",
"syncing_creator": "Сверка...",
"pull_success": "Сверено {{name}}: {{count}} новых файлов",
- "pull_all_success": "Сверено {{total}} авторов: {{count}} новых файлов"
+ "pull_all_success": "Сверено {{total}} авторов: {{count}} новых файлов",
+ "browser_cookies_label": "Куки браузера",
+ "browser_cookies_aria": "Выберите браузер для автоизвлечения куки",
+ "browser_cookies_auto": "Авто (браузер по умолчанию)",
+ "browser_cookies_manual": "Файл куки вручную (.txt)",
+ "browser_cookies_disabled": "Отключено",
+ "test_extract_cookies": "Проверить мост",
+ "testing_cookies": "Проверка...",
+ "cookies_bridge_hint": "Мост без расширений автоматически читает сессионные куки из браузера для историй и хайлайтс."
}
}
diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.json
index 82655627..6ae5ced4 100644
--- a/src/lib/i18n/zh-TW.json
+++ b/src/lib/i18n/zh-TW.json
@@ -5393,7 +5393,15 @@
"sync_all_creators": "同步全部",
"syncing_creator": "同步中...",
"pull_success": "已同步 {{name}}:{{count}} 個新檔案",
- "pull_all_success": "已同步 {{total}} 位創作者:{{count}} 個新檔案"
+ "pull_all_success": "已同步 {{total}} 位創作者:{{count}} 個新檔案",
+ "browser_cookies_label": "瀏覽器 Cookie",
+ "browser_cookies_aria": "選取用於自動擷取 Cookie 的瀏覽器",
+ "browser_cookies_auto": "自動(預設瀏覽器)",
+ "browser_cookies_manual": "手動 Cookie 檔案 (.txt)",
+ "browser_cookies_disabled": "已停用",
+ "test_extract_cookies": "測試橋接",
+ "testing_cookies": "測試中...",
+ "cookies_bridge_hint": "無擴充功能橋接會自動從您的瀏覽器讀取工作階段 Cookie,用於下載限時動態與精選。"
},
"tray": {
"quit": "Quit",
diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.json
index ffedac79..b783a272 100644
--- a/src/lib/i18n/zh.json
+++ b/src/lib/i18n/zh.json
@@ -5393,7 +5393,15 @@
"sync_all_creators": "同步全部",
"syncing_creator": "同步中...",
"pull_success": "已同步 {{name}}:{{count}} 个新文件",
- "pull_all_success": "已同步 {{total}} 位创作者:{{count}} 个新文件"
+ "pull_all_success": "已同步 {{total}} 位创作者:{{count}} 个新文件",
+ "browser_cookies_label": "浏览器 Cookie",
+ "browser_cookies_aria": "选择用于自动提取 Cookie 的浏览器",
+ "browser_cookies_auto": "自动(默认浏览器)",
+ "browser_cookies_manual": "手动 Cookie 文件 (.txt)",
+ "browser_cookies_disabled": "已禁用",
+ "test_extract_cookies": "测试桥接",
+ "testing_cookies": "正在测试...",
+ "cookies_bridge_hint": "无插件桥接会自动从您的浏览器读取会话 Cookie,用于下载快拍与精选。"
},
"tray": {
"quit": "退出",
diff --git a/src/lib/stores/nami_settings_store.svelte.ts b/src/lib/stores/nami_settings_store.svelte.ts
index 96e40c3e..9230dd51 100644
--- a/src/lib/stores/nami_settings_store.svelte.ts
+++ b/src/lib/stores/nami_settings_store.svelte.ts
@@ -2,6 +2,7 @@ import { saveAppSettings, loadAppSettings } from "$lib/api/nami";
let outputDir = $state("");
let cookiesFile = $state("");
+let browserCookies = $state("auto");
let loaded = $state(false);
export function getOutputDir(): string {
@@ -12,6 +13,10 @@ export function getCookiesFile(): string {
return cookiesFile;
}
+export function getBrowserCookies(): string {
+ return browserCookies;
+}
+
export function isLoaded(): boolean {
return loaded;
}
@@ -33,6 +38,7 @@ export async function loadSettings() {
const settings = await loadAppSettings();
outputDir = settings.output_directory ?? "";
cookiesFile = settings.cookies_file ?? "";
+ browserCookies = settings.browser_cookies ?? "auto";
} catch (error) {
console.error("Failed to load settings:", error);
} finally {
@@ -40,12 +46,22 @@ export async function loadSettings() {
}
}
-export async function saveSettings(newOutputDir: string, newCookiesFile: string): Promise<void> {
+export async function saveSettings(
+ newOutputDir: string,
+ newCookiesFile: string,
+ newBrowserCookies?: string
+): Promise<void> {
const cleanOutputDir = cleanPathLike(newOutputDir);
const cleanCookiesFile = newCookiesFile.trim() ? cleanPathLike(newCookiesFile) : "";
+ const cleanBrowserCookies = newBrowserCookies !== undefined ? newBrowserCookies.trim() : browserCookies;
- await saveAppSettings(cleanOutputDir || null, cleanCookiesFile || null);
+ await saveAppSettings(
+ cleanOutputDir || null,
+ cleanCookiesFile || null,
+ cleanBrowserCookies || null
+ );
outputDir = cleanOutputDir;
cookiesFile = cleanCookiesFile;
+ browserCookies = cleanBrowserCookies;
}