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: add import-cookies command with auto-injection

Hanakobec6822bbca5
diff --git a/src-tauri/omniget-cli/src/commands/download.rs b/src-tauri/omniget-cli/src/commands/download.rs
index c4724ccf..b371dc55 100644
--- a/src-tauri/omniget-cli/src/commands/download.rs
+++ b/src-tauri/omniget-cli/src/commands/download.rs
@@ -61,13 +61,21 @@ pub async fn execute(
let msg = format!("Starting: {}", url);
pb.set_message(msg);
- // Build extra flags for proxy and subtitles
+ // Build extra flags for proxy, cookies, and subtitles
let mut extra_flags: Vec<String> = Vec::new();
if let Some(p) = &proxy {
extra_flags.push("--proxy".to_string());
extra_flags.push(p.clone());
}
+ // Auto-include cookie file if exists
+ if let Some(cookie_file) = reporter::default_cookie_path() {
+ if cookie_file.exists() {
+ extra_flags.push("--cookies".to_string());
+ extra_flags.push(cookie_file.display().to_string());
+ }
+ }
+
let download_subtitles = subs.is_some();
if let Some(lang) = &subs {
extra_flags.push("--write-subs".to_string());
diff --git a/src-tauri/omniget-cli/src/commands/import_cookies.rs b/src-tauri/omniget-cli/src/commands/import_cookies.rs
new file mode 100644
index 00000000..d6d2eafb
--- /dev/null
+++ b/src-tauri/omniget-cli/src/commands/import_cookies.rs
@@ -0,0 +1,56 @@
+use anyhow::Result;
+use std::path::PathBuf;
+
+use crate::cookies;
+use crate::output;
+
+pub async fn execute(file: String, name: Option<String>, dry_run: bool) -> Result<()> {
+ let path = PathBuf::from(&file);
+
+ if dry_run {
+ let preview = cookies::preview_import(&path)?;
+ if output::is_json_mode() {
+ let items: Vec<serde_json::Value> = preview
+ .iter()
+ .map(|(domain, count)| {
+ serde_json::json!({ "domain": domain, "cookies": count })
+ })
+ .collect();
+ output::print_json(&serde_json::json!({ "domains": items }));
+ } else {
+ println!("Preview ({} domains):", preview.len());
+ for (domain, count) in &preview {
+ println!(" {:<40} {} cookies", domain, count);
+ }
+ }
+ return Ok(());
+ }
+
+ let total = cookies::import_cookies_file(&path, name.as_deref())?;
+ let dest = if let Some(n) = &name {
+ cookies::default_cookie_file().map(|d| d.with_file_name(format!("cookies_{}.txt", n)))
+ } else {
+ cookies::default_cookie_file()
+ };
+
+ if output::is_json_mode() {
+ println!(
+ r#"{{"success":true,"total":{},"destination":"{}"}}"#,
+ total,
+ dest.as_deref().map(|p| p.display().to_string()).unwrap_or_default()
+ );
+ } else {
+ if let Some(d) = &dest {
+ println!("✓ Imported {} cookies → {}", total, d.display());
+ } else {
+ println!("✓ Imported {} cookies", total);
+ }
+ if let Some(n) = &name {
+ println!(" Account name: {}", n);
+ } else {
+ println!(" (default account)");
+ }
+ }
+
+ Ok(())
+}
diff --git a/src-tauri/omniget-cli/src/commands/info.rs b/src-tauri/omniget-cli/src/commands/info.rs
index ed16c9ce..1eedbed3 100644
--- a/src-tauri/omniget-cli/src/commands/info.rs
+++ b/src-tauri/omniget-cli/src/commands/info.rs
@@ -4,14 +4,24 @@ use omniget_core::core::ytdlp;
use crate::output;
use crate::reporter::find_yt_dlp;
+use crate::reporter;
pub async fn execute(url: String, proxy: Option<String>) -> Result<()> {
let ytdlp = find_yt_dlp().await?;
- let extra_flags: Vec<String> = match &proxy {
- Some(p) => vec!["--proxy".to_string(), p.clone()],
- None => vec![],
- };
+ let mut extra_flags: Vec<String> = Vec::new();
+ if let Some(p) = &proxy {
+ extra_flags.push("--proxy".to_string());
+ extra_flags.push(p.clone());
+ }
+
+ // Auto-include cookie file if exists
+ if let Some(cookie_file) = reporter::default_cookie_path() {
+ if cookie_file.exists() {
+ extra_flags.push("--cookies".to_string());
+ extra_flags.push(cookie_file.display().to_string());
+ }
+ }
let info = match tokio::time::timeout(
std::time::Duration::from_secs(120),
diff --git a/src-tauri/omniget-cli/src/commands/mod.rs b/src-tauri/omniget-cli/src/commands/mod.rs
index ec30ea93..a8b20fd7 100644
--- a/src-tauri/omniget-cli/src/commands/mod.rs
+++ b/src-tauri/omniget-cli/src/commands/mod.rs
@@ -1,3 +1,4 @@
pub mod download;
+pub mod import_cookies;
pub mod info;
pub mod batch;
diff --git a/src-tauri/omniget-cli/src/cookies.rs b/src-tauri/omniget-cli/src/cookies.rs
new file mode 100644
index 00000000..2a6a96f5
--- /dev/null
+++ b/src-tauri/omniget-cli/src/cookies.rs
@@ -0,0 +1,130 @@
+use anyhow::{Context, Result};
+use std::collections::HashMap;
+use std::path::PathBuf;
+
+use omniget_core::core::paths::app_data_dir;
+use omniget_core::core::cookie_parser::parse_cookie_input;
+
+const COOKIES_DIR: &str = "cookies";
+const DEFAULT_COOKIE_FILE: &str = "cookies.txt";
+
+/// Path to the default cookie file shared with the GUI
+pub fn default_cookie_file() -> Option<PathBuf> {
+ let dir = app_data_dir()?.join(COOKIES_DIR);
+ Some(dir.join(DEFAULT_COOKIE_FILE))
+}
+
+/// Parse a Netscape-format cookies.txt and return (domain, cookie_string) tuples
+pub fn parse_netscape_cookies(content: &str) -> Vec<(String, String)> {
+ let mut results: Vec<(String, String)> = Vec::new();
+ let mut current_domain: Option<String> = None;
+ let mut cookies_for_domain: Vec<(String, String)> = Vec::new();
+
+ for line in content.lines() {
+ let line = line.trim();
+ if line.is_empty() || line.starts_with('#') {
+ continue;
+ }
+
+ // Netscape format: domain flag path secure expiration name value
+ let fields: Vec<&str> = line.split('\t').collect();
+ if fields.len() >= 7 {
+ let domain = fields[0].to_string();
+ let name = fields[5].trim();
+ let value = fields[6].trim();
+
+ if !name.is_empty() && !value.is_empty() {
+ if current_domain.as_deref() != Some(&domain) {
+ // Flush previous domain
+ if let Some(d) = &current_domain {
+ if !cookies_for_domain.is_empty() {
+ let cookie_str = cookies_for_domain
+ .iter()
+ .map(|(n, v)| format!("{}={}", n, v))
+ .collect::<Vec<_>>()
+ .join("; ");
+ results.push((d.clone(), cookie_str));
+ }
+ }
+ current_domain = Some(domain.clone());
+ cookies_for_domain.clear();
+ }
+ cookies_for_domain.push((name.to_string(), value.to_string()));
+ }
+ }
+ }
+
+ // Flush last domain
+ if let Some(d) = current_domain {
+ if !cookies_for_domain.is_empty() {
+ let cookie_str = cookies_for_domain
+ .iter()
+ .map(|(n, v)| format!("{}={}", n, v))
+ .collect::<Vec<_>>()
+ .join("; ");
+ results.push((d, cookie_str));
+ }
+ }
+
+ results
+}
+
+/// Import a cookies.txt file into the app's cookie storage
+pub fn import_cookies_file(src_path: &PathBuf, name: Option<&str>) -> Result<usize> {
+ let content = std::fs::read_to_string(src_path)
+ .with_context(|| format!("Failed to read {}", src_path.display()))?;
+
+ let cookies_dir = app_data_dir()
+ .ok_or_else(|| anyhow::anyhow!("Cannot determine app data directory"))?
+ .join(COOKIES_DIR);
+
+ std::fs::create_dir_all(&cookies_dir)?;
+
+ let dest_file = if let Some(n) = name {
+ cookies_dir.join(format!("cookies_{}.txt", n))
+ } else {
+ cookies_dir.join(DEFAULT_COOKIE_FILE)
+ };
+
+ // Parse to validate and count
+ let parsed = parse_netscape_cookies(&content);
+ if parsed.is_empty() {
+ anyhow::bail!("No valid cookies found in file (expected Netscape format)");
+ }
+
+ // Copy the raw file (preserving original format for yt-dlp consumption)
+ // Normalize line endings but otherwise keep as-is
+ let normalized = content.replace("\r\n", "\n").replace('\r', "\n");
+ std::fs::write(&dest_file, normalized)
+ .with_context(|| format!("Failed to write {}", dest_file.display()))?;
+
+ Ok(parsed.iter().map(|(_, s)| s.split(';').count()).sum())
+}
+
+/// List showing what the cookie file would look like when consumed
+pub fn preview_import(src_path: &PathBuf) -> Result<Vec<(String, usize)>> {
+ let content = std::fs::read_to_string(src_path)
+ .with_context(|| format!("Failed to read {}", src_path.display()))?;
+
+ let parsed = parse_netscape_cookies(&content);
+ Ok(parsed
+ .into_iter()
+ .map(|(domain, cookies)| {
+ let count = cookies.split(';').count();
+ (domain, count)
+ })
+ .collect())
+}
+
+pub fn import_cookies_raw(input: &str, target_cookie: &str) -> Result<ParsedCookies> {
+ let parsed = parse_cookie_input(input, target_cookie);
+ Ok(ParsedCookies {
+ token: parsed.token,
+ cookie_string: parsed.cookie_string,
+ })
+}
+
+pub struct ParsedCookies {
+ pub token: String,
+ pub cookie_string: String,
+}
diff --git a/src-tauri/omniget-cli/src/main.rs b/src-tauri/omniget-cli/src/main.rs
index 9be31b08..14dd4fc4 100644
--- a/src-tauri/omniget-cli/src/main.rs
+++ b/src-tauri/omniget-cli/src/main.rs
@@ -1,6 +1,7 @@
use clap::Parser;
mod commands;
+mod cookies;
mod output;
mod reporter;
@@ -52,6 +53,16 @@ enum Commands {
#[arg(short, long)]
output: Option<String>,
},
+ /// Import a cookies.txt file (Netscape format)
+ ImportCookies {
+ file: String,
+
+ #[arg(short, long, help = "Account name (default: cookies.txt)")]
+ name: Option<String>,
+
+ #[arg(long, help = "Preview without importing")]
+ dry_run: bool,
+ },
}
#[tokio::main]
@@ -90,6 +101,9 @@ async fn main() -> anyhow::Result<()> {
} => {
commands::batch::execute(file, max_concurrent, output, cli.proxy).await?;
}
+ Commands::ImportCookies { file, name, dry_run } => {
+ commands::import_cookies::execute(file, name, dry_run).await?;
+ }
}
Ok(())