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(omnibox): zero-click auto-download + stop surprise folder picker (#93)

InstaZDLL34deb3426371
diff --git a/package.json b/package.json
index 3bcdce44..7bb11462 100644
--- a/package.json
+++ b/package.json
@@ -28,6 +28,7 @@
"@kookyleo/graphviz-anywhere-web": "^0.1.8",
"@kookyleo/plantuml-little-web": "1.2026.2-3",
"@tauri-apps/api": "^2",
+ "@tauri-apps/plugin-clipboard-manager": "^2.3.2",
"@tauri-apps/plugin-dialog": "^2.6.0",
"@tauri-apps/plugin-opener": "^2",
"@tauri-apps/plugin-process": "^2.3.1",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a63c1673..9d5fea90 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -29,6 +29,9 @@ importers:
'@tauri-apps/api':
specifier: ^2
version: 2.10.1
+ '@tauri-apps/plugin-clipboard-manager':
+ specifier: ^2.3.2
+ version: 2.3.2
'@tauri-apps/plugin-dialog':
specifier: ^2.6.0
version: 2.6.0
@@ -804,6 +807,9 @@ packages:
engines: {node: '>= 10'}
hasBin: true
+ '@tauri-apps/[email protected]':
+ resolution: {integrity: sha512-CUlb5Hqi2oZbcZf4VUyUH53XWPPdtpw43EUpCza5HWZJwxEoDowFzNUDt1tRUXA8Uq+XPn17Ysfptip33sG4eQ==}
+
'@tauri-apps/[email protected]':
resolution: {integrity: sha512-q4Uq3eY87TdcYzXACiYSPhmpBA76shgmQswGkSVio4C82Sz2W4iehe9TnKYwbq7weHiL88Yw19XZm7v28+Micg==}
@@ -2516,6 +2522,10 @@ snapshots:
'@tauri-apps/cli-win32-ia32-msvc': 2.10.0
'@tauri-apps/cli-win32-x64-msvc': 2.10.0
+ '@tauri-apps/[email protected]':
+ dependencies:
+ '@tauri-apps/api': 2.10.1
+
'@tauri-apps/[email protected]':
dependencies:
'@tauri-apps/api': 2.10.1
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json
index fefff5ca..14e0ce47 100644
--- a/src-tauri/capabilities/default.json
+++ b/src-tauri/capabilities/default.json
@@ -10,6 +10,8 @@
"dialog:default",
"notification:default",
"fs:default",
+ "clipboard-manager:allow-read-text",
+ "clipboard-manager:allow-write-text",
"updater:default",
"process:allow-restart",
"core:window:allow-set-badge-count",
diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rs
index a6fe1791..5a94da57 100644
--- a/src-tauri/omniget-core/src/core/ytdlp.rs
+++ b/src-tauri/omniget-core/src/core/ytdlp.rs
@@ -15,6 +15,7 @@ use crate::models::media::{DownloadResult, FormatInfo};
type ExtCookiePathFn = Box<dyn Fn() -> PathBuf + Send + Sync>;
type GlobalCookieFileFn = Box<dyn Fn() -> Option<String> + Send + Sync>;
type CookiesFromBrowserFn = Box<dyn Fn() -> String + Send + Sync>;
+type ManualCookieHeaderFn = Box<dyn Fn() -> String + Send + Sync>;
type ExtRefererFn = Box<dyn Fn(&str) -> Option<String> + Send + Sync>;
type IncludeAutoSubsFn = Box<dyn Fn() -> bool + Send + Sync>;
type TranslateMetadataFn = Box<dyn Fn() -> Option<String> + Send + Sync>;
@@ -24,6 +25,7 @@ type SplitChaptersFn = Box<dyn Fn() -> bool + Send + Sync>;
static EXT_COOKIE_PATH_FN: OnceLock<ExtCookiePathFn> = OnceLock::new();
static GLOBAL_COOKIE_FILE_FN: OnceLock<GlobalCookieFileFn> = OnceLock::new();
static COOKIES_FROM_BROWSER_FN: OnceLock<CookiesFromBrowserFn> = OnceLock::new();
+static MANUAL_COOKIE_HEADER_FN: OnceLock<ManualCookieHeaderFn> = OnceLock::new();
static EXT_REFERER_FN: OnceLock<ExtRefererFn> = OnceLock::new();
static INCLUDE_AUTO_SUBS_FN: OnceLock<IncludeAutoSubsFn> = OnceLock::new();
static TRANSLATE_METADATA_FN: OnceLock<TranslateMetadataFn> = OnceLock::new();
@@ -42,6 +44,10 @@ pub fn set_cookies_from_browser_fn(f: impl Fn() -> String + Send + Sync + 'stati
let _ = COOKIES_FROM_BROWSER_FN.set(Box::new(f));
}
+pub fn set_manual_cookie_header_fn(f: impl Fn() -> String + Send + Sync + 'static) {
+ let _ = MANUAL_COOKIE_HEADER_FN.set(Box::new(f));
+}
+
pub fn set_ext_referer_fn(f: impl Fn(&str) -> Option<String> + Send + Sync + 'static) {
let _ = EXT_REFERER_FN.set(Box::new(f));
}
@@ -164,6 +170,21 @@ fn cookies_from_browser_setting() -> String {
.unwrap_or_default()
}
+fn manual_cookie_header_setting() -> Option<String> {
+ let raw = MANUAL_COOKIE_HEADER_FN.get().map(|f| f()).unwrap_or_default();
+ let trimmed = raw.trim();
+ if trimmed.is_empty() {
+ return None;
+ }
+
+ let parsed = crate::core::cookie_parser::parse_cookie_input(trimmed, "");
+ if !parsed.cookie_string.trim().is_empty() {
+ Some(parsed.cookie_string)
+ } else {
+ Some(trimmed.to_string())
+ }
+}
+
pub fn ext_cookie_path() -> PathBuf {
EXT_COOKIE_PATH_FN
.get()
@@ -285,6 +306,17 @@ fn proxy_args() -> Vec<String> {
}
}
+fn has_explicit_cookie_header(args: &[String]) -> bool {
+ args.windows(2).any(|pair| {
+ pair[0] == "--add-headers" && pair[1].to_ascii_lowercase().starts_with("cookie:")
+ })
+}
+
+fn append_cookie_header(args: &mut Vec<String>, cookie_header: &str) {
+ args.push("--add-headers".to_string());
+ args.push(format!("Cookie:{}", cookie_header));
+}
+
struct YtRateLimiter {
semaphore: tokio::sync::Semaphore,
last_request_ns: AtomicU64,
@@ -862,20 +894,41 @@ pub async fn get_video_info(
args.push(extractor_args.to_string());
}
- let extension_cookies = extension_cookie_file();
- let global_cf = global_cookie_file();
- if let Some(ref cf) = extension_cookies {
+ let explicit_cookie_header = has_explicit_cookie_header(extra_flags);
+ let manual_cookie_header = if explicit_cookie_header {
+ None
+ } else {
+ manual_cookie_header_setting()
+ };
+ let extension_cookies = if manual_cookie_header.is_none() {
+ extension_cookie_file()
+ } else {
+ None
+ };
+ let global_cf = if manual_cookie_header.is_none() {
+ global_cookie_file()
+ } else {
+ None
+ };
+ if let Some(ref cookie_header) = manual_cookie_header {
+ append_cookie_header(&mut args, cookie_header);
+ tracing::debug!("[yt-dlp] using manual cookie header from settings");
+ } else if let Some(ref cf) = extension_cookies {
args.push("--cookies".to_string());
args.push(cf.to_string_lossy().to_string());
} else if let Some(ref cf) = global_cf {
args.push("--cookies".to_string());
args.push(cf.clone());
- } else {
+ } else if !explicit_cookie_header {
let cfb = cookies_from_browser_setting();
if !cfb.is_empty() {
args.push("--cookies-from-browser".to_string());
args.push(cfb);
}
+ } else {
+ tracing::debug!(
+ "[yt-dlp] skipping cookies-from-browser because explicit Cookie header was provided"
+ );
}
args.extend(proxy_args());
@@ -1203,9 +1256,20 @@ pub async fn download_video(
std::fs::create_dir_all(output_dir)?;
- let global_cookie_file = global_cookie_file();
+ let explicit_cookie_header = has_explicit_cookie_header(extra_flags);
+ let manual_cookie_header = if explicit_cookie_header || cookie_file.is_some() {
+ None
+ } else {
+ manual_cookie_header_setting()
+ };
+ let manual_cookie_enabled = manual_cookie_header.is_some();
+ let global_cookie_file = if manual_cookie_enabled {
+ None
+ } else {
+ global_cookie_file()
+ };
- let ext_cookies = if cookie_file.is_none() && global_cookie_file.is_none() {
+ let ext_cookies = if cookie_file.is_none() && global_cookie_file.is_none() && !manual_cookie_enabled {
extension_cookie_file()
} else {
None
@@ -1216,7 +1280,11 @@ pub async fn download_video(
.or_else(|| global_cookie_file.map(std::path::PathBuf::from))
.or(ext_cookies);
- let cfb_setting = cookies_from_browser_setting();
+ let cfb_setting = if manual_cookie_enabled || explicit_cookie_header {
+ String::new()
+ } else {
+ cookies_from_browser_setting()
+ };
let mut base_args = vec!["-f".to_string(), format_selector];
base_args.extend(js_runtime_args());
@@ -1252,6 +1320,9 @@ pub async fn download_video(
base_args.push("--cookies".to_string());
base_args.push(cf.to_string_lossy().to_string());
}
+ if let Some(ref cookie_header) = manual_cookie_header {
+ append_cookie_header(&mut base_args, cookie_header);
+ }
if let Some(ref loc) = ffmpeg_location {
base_args.push("--ffmpeg-location".to_string());
@@ -1293,7 +1364,9 @@ pub async fn download_video(
let mut use_aria2c = aria2c_path.is_some()
&& mode != "audio"
&& effective_cookie_file.is_none()
- && cfb_setting.is_empty();
+ && cfb_setting.is_empty()
+ && !manual_cookie_enabled
+ && !explicit_cookie_header;
let effective_ua = ext_user_agent_for_url(url).unwrap_or_else(|| CHROME_UA.to_string());
base_args.extend([
@@ -1369,7 +1442,7 @@ pub async fn download_video(
let mut extra_args: Vec<String> = Vec::new();
let mut last_error = String::new();
let mut use_subtitles = should_download_subs;
- let mut use_cfb = !cfb_setting.is_empty();
+ let mut use_cfb = !cfb_setting.is_empty() && !explicit_cookie_header && !manual_cookie_enabled;
let mut format_already_simplified = false;
let mut last_was_429 = false;
diff --git a/src-tauri/omniget-core/src/models/settings.rs b/src-tauri/omniget-core/src/models/settings.rs
index b9a9b259..e7ab1094 100644
--- a/src-tauri/omniget-core/src/models/settings.rs
+++ b/src-tauri/omniget-core/src/models/settings.rs
@@ -89,6 +89,8 @@ pub struct DownloadSettings {
pub embed_thumbnail: bool,
#[serde(default)]
pub clipboard_detection: bool,
+ #[serde(default)]
+ pub auto_download_on_paste: bool,
#[serde(default = "default_filename_template")]
pub filename_template: String,
#[serde(default)]
@@ -139,6 +141,8 @@ pub struct AdvancedSettings {
pub torrent_listen_port: u16,
#[serde(default)]
pub cookies_from_browser: String,
+ #[serde(default)]
+ pub twitter_manual_cookie: String,
}
fn default_concurrent_fragments() -> u32 {
@@ -279,7 +283,7 @@ impl Default for AppSettings {
},
download: DownloadSettings {
default_output_dir: dirs::download_dir().unwrap_or_else(|| PathBuf::from(".")),
- always_ask_path: true,
+ always_ask_path: false,
video_quality: "720p".into(),
skip_existing: true,
download_attachments: true,
@@ -287,6 +291,7 @@ impl Default for AppSettings {
embed_metadata: true,
embed_thumbnail: true,
clipboard_detection: false,
+ auto_download_on_paste: false,
filename_template: default_filename_template(),
organize_by_platform: false,
download_subtitles: false,
@@ -313,6 +318,7 @@ impl Default for AppSettings {
stagger_delay_ms: 150,
torrent_listen_port: 6881,
cookies_from_browser: String::new(),
+ twitter_manual_cookie: String::new(),
},
telegram: TelegramSettings::default(),
proxy: ProxySettings::default(),
diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rs
index c84b54a2..1152dad0 100644
--- a/src-tauri/src/core/queue.rs
+++ b/src-tauri/src/core/queue.rs
@@ -981,7 +981,7 @@ async fn spawn_download_inner(
let info_start = std::time::Instant::now();
let info = match media_info {
- Some(i) => {
+ Some(i) if !i.available_qualities.is_empty() => {
tracing::info!(
"[queue] info for {} from cache/pre-fetched in {:?}",
item_id,
@@ -989,7 +989,7 @@ async fn spawn_download_inner(
);
i
}
- None => {
+ _ => {
tracing::debug!(
"[perf] spawn_download_inner {}: media_info is None, fetching info",
item_id
diff --git a/src-tauri/src/external_url.rs b/src-tauri/src/external_url.rs
index 194064b1..4b2e018b 100644
--- a/src-tauri/src/external_url.rs
+++ b/src-tauri/src/external_url.rs
@@ -298,7 +298,8 @@ pub async fn handle_external_url(
}
let settings = config::load_settings(app);
- let can_queue_directly = !settings.download.always_ask_path
+ let can_queue_directly = (!settings.download.always_ask_path
+ || settings.download.auto_download_on_paste)
&& has_valid_output_dir(&settings.download.default_output_dir);
let open_app_flag = crate::native_host::peek_extension_open_app(&url);
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 43bc36e0..fce5f9c0 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -145,6 +145,11 @@ pub fn run() {
.advanced
.cookies_from_browser
});
+ core::ytdlp::set_manual_cookie_header_fn(|| {
+ storage::config::load_settings_standalone()
+ .advanced
+ .twitter_manual_cookie
+ });
core::ytdlp::set_ext_referer_fn(|url| {
native_host::read_extension_metadata(url).and_then(|m| m.referer)
});
diff --git a/src-tauri/src/platforms/twitter/mod.rs b/src-tauri/src/platforms/twitter/mod.rs
index c1f3858f..15d2f360 100644
--- a/src-tauri/src/platforms/twitter/mod.rs
+++ b/src-tauri/src/platforms/twitter/mod.rs
@@ -46,6 +46,132 @@ impl Default for TwitterDownloader {
}
impl TwitterDownloader {
+ fn manual_cookie_string() -> Option<String> {
+ let raw = crate::storage::config::load_settings_standalone()
+ .advanced
+ .twitter_manual_cookie;
+ let trimmed = raw.trim();
+ if trimmed.is_empty() {
+ return None;
+ }
+
+ let parsed = crate::core::cookie_parser::parse_cookie_input(trimmed, "");
+ if !parsed.cookie_string.trim().is_empty() {
+ Some(parsed.cookie_string)
+ } else {
+ Some(trimmed.to_string())
+ }
+ }
+
+ fn request_cookie_header(guest_token: &str) -> String {
+ let guest_cookie = format!(
+ "guest_id={}",
+ urlencoding::encode(&format!("v1:{}", guest_token))
+ );
+
+ if let Some(manual) = Self::manual_cookie_string() {
+ format!("{}; {}", guest_cookie, manual)
+ } else {
+ guest_cookie
+ }
+ }
+
+ fn clone_media_array(value: &serde_json::Value) -> Option<Vec<serde_json::Value>> {
+ value
+ .as_array()
+ .filter(|items| !items.is_empty())
+ .cloned()
+ }
+
+ fn find_first_array_for_key(
+ value: &serde_json::Value,
+ target_key: &str,
+ ) -> Option<Vec<serde_json::Value>> {
+ match value {
+ serde_json::Value::Object(map) => {
+ if let Some(found) = map
+ .get(target_key)
+ .and_then(Self::clone_media_array)
+ .filter(|items| !items.is_empty())
+ {
+ return Some(found);
+ }
+
+ for child in map.values() {
+ if let Some(found) = Self::find_first_array_for_key(child, target_key) {
+ return Some(found);
+ }
+ }
+ }
+ serde_json::Value::Array(items) => {
+ for child in items {
+ if let Some(found) = Self::find_first_array_for_key(child, target_key) {
+ return Some(found);
+ }
+ }
+ }
+ _ => {}
+ }
+
+ None
+ }
+
+ fn media_arrays_from_tweet_result(tweet_result: &serde_json::Value) -> Option<Vec<serde_json::Value>> {
+ let candidate_paths = [
+ "/legacy/extended_entities/media",
+ "/tweet/legacy/extended_entities/media",
+ "/legacy/retweeted_status_result/result/legacy/extended_entities/media",
+ "/legacy/retweeted_status_result/result/tweet/legacy/extended_entities/media",
+ "/tweet/legacy/retweeted_status_result/result/legacy/extended_entities/media",
+ "/tweet/legacy/retweeted_status_result/result/tweet/legacy/extended_entities/media",
+ "/legacy/quoted_status_result/result/legacy/extended_entities/media",
+ "/legacy/quoted_status_result/result/tweet/legacy/extended_entities/media",
+ "/tweet/legacy/quoted_status_result/result/legacy/extended_entities/media",
+ "/tweet/legacy/quoted_status_result/result/tweet/legacy/extended_entities/media",
+ ];
+
+ for path in candidate_paths {
+ if let Some(items) = tweet_result
+ .pointer(path)
+ .and_then(Self::clone_media_array)
+ .filter(|items| !items.is_empty())
+ {
+ return Some(items);
+ }
+ }
+
+ Self::find_first_array_for_key(tweet_result, "media")
+ }
+
+ fn infer_media_type(media_item: &serde_json::Value) -> Option<TwitterMediaType> {
+ match media_item.get("type").and_then(|v| v.as_str()) {
+ Some("photo") => return Some(TwitterMediaType::Photo),
+ Some("video") => return Some(TwitterMediaType::Video),
+ Some("animated_gif") => return Some(TwitterMediaType::AnimatedGif),
+ _ => {}
+ }
+
+ if media_item
+ .pointer("/video_info/variants")
+ .and_then(|v| v.as_array())
+ .is_some()
+ || media_item
+ .pointer("/video/variants")
+ .and_then(|v| v.as_array())
+ .is_some()
+ {
+ return Some(TwitterMediaType::Video);
+ }
+
+ if media_item.get("media_url_https").and_then(|v| v.as_str()).is_some()
+ || media_item.get("media_url").and_then(|v| v.as_str()).is_some()
+ {
+ return Some(TwitterMediaType::Photo);
+ }
+
+ None
+ }
+
pub fn new() -> Self {
let mut builder = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
.user_agent(USER_AGENT)
@@ -138,10 +264,7 @@ impl TwitterDownloader {
urlencoding::encode(TWEET_FIELD_TOGGLES),
);
- let cookie_val = format!(
- "guest_id={}",
- urlencoding::encode(&format!("v1:{}", guest_token))
- );
+ let cookie_val = Self::request_cookie_header(guest_token);
let response = self
.client
@@ -157,6 +280,7 @@ impl TwitterDownloader {
.await?;
let status = response.status();
+ tracing::debug!("[twitter] graphql tweet_id={} status={}", tweet_id, status);
if status == reqwest::StatusCode::FORBIDDEN
|| status == reqwest::StatusCode::TOO_MANY_REQUESTS
@@ -243,7 +367,18 @@ impl TwitterDownloader {
tweet_id, token
);
- let response = self.client.get(&url).send().await?;
+ let mut request = self.client.get(&url);
+ if let Some(cookie) = Self::manual_cookie_string() {
+ request = request.header("Cookie", cookie);
+ }
+
+ let response = request.send().await?;
+ tracing::debug!(
+ "[twitter] syndication tweet_id={} token={} status={}",
+ tweet_id,
+ token,
+ response.status()
+ );
if !response.status().is_success() {
return Err(anyhow!(
@@ -285,6 +420,11 @@ impl TwitterDownloader {
.get("__typename")
.and_then(|v| v.as_str())
.unwrap_or("");
+ tracing::debug!(
+ "[twitter] graphql media typename={} tweet_id={}",
+ typename,
+ tweet_id
+ );
match typename {
"TweetUnavailable" | "TweetTombstone" => {
@@ -303,6 +443,13 @@ impl TwitterDownloader {
.and_then(|v| v.as_str())
.unwrap_or("");
+ tracing::warn!(
+ "[twitter] graphql tombstone tweet_id={} reason='{}' tombstone_text='{}'",
+ tweet_id,
+ reason,
+ tombstone_text
+ );
+
if reason == "NsfwLoggedOut" || tombstone_text.starts_with("Age-restricted") {
return Err(anyhow!("Age-restricted content"));
}
@@ -310,29 +457,14 @@ impl TwitterDownloader {
Err(anyhow!("Post not available"))
}
"Tweet" | "TweetWithVisibilityResults" => {
- let base_tweet = if typename == "TweetWithVisibilityResults" {
- tweet_result.pointer("/tweet/legacy")
- } else {
- tweet_result.get("legacy")
- };
-
- let base_tweet = base_tweet.ok_or_else(|| anyhow!("Post not available"))?;
-
- let reposted_media = if typename == "TweetWithVisibilityResults" {
- tweet_result
- .pointer("/tweet/legacy/retweeted_status_result/result/tweet/legacy/extended_entities/media")
- } else {
- tweet_result.pointer(
- "/legacy/retweeted_status_result/result/legacy/extended_entities/media",
- )
- };
-
- let media = reposted_media
- .or_else(|| base_tweet.pointer("/extended_entities/media"))
- .and_then(|v| v.as_array())
+ let media = Self::media_arrays_from_tweet_result(tweet_result)
.ok_or_else(|| anyhow!("No media found in tweet"))?;
-
- Ok(media.clone())
+ tracing::debug!(
+ "[twitter] graphql extracted {} media entries for tweet_id={}",
+ media.len(),
+ tweet_id
+ );
+ Ok(media)
}
_ => Err(anyhow!("Post not available")),
}
@@ -341,53 +473,118 @@ impl TwitterDownloader {
fn extract_syndication_media(
json: &serde_json::Value,
) -> anyhow::Result<Vec<serde_json::Value>> {
- let media = json
- .get("mediaDetails")
- .and_then(|v| v.as_array())
+ let typename = json.get("__typename").and_then(|v| v.as_str()).unwrap_or("");
+ if typename == "TweetTombstone" || typename == "TweetUnavailable" {
+ tracing::warn!("[twitter] syndication tombstone typename={}", typename);
+ return Err(anyhow!("Post not available"));
+ }
+
+ let media = json.get("mediaDetails")
+ .and_then(Self::clone_media_array)
+ .or_else(|| Self::find_first_array_for_key(json, "mediaDetails"))
.ok_or_else(|| anyhow!("No media found in tweet"))?;
- Ok(media.clone())
+ tracing::debug!("[twitter] syndication extracted {} media entries", media.len());
+ Ok(media)
}
fn best_video_url(media_item: &serde_json::Value) -> Option<String> {
let variants = media_item
.pointer("/video_info/variants")
+ .or_else(|| media_item.pointer("/video/variants"))
.and_then(|v| v.as_array())?;
- variants
+ let best_mp4 = variants
.iter()
.filter(|v| v.get("content_type").and_then(|c| c.as_str()) == Some("video/mp4"))
.max_by_key(|v| v.get("bitrate").and_then(|b| b.as_u64()).unwrap_or(0))
.and_then(|v| v.get("url").and_then(|u| u.as_str()))
+ .map(|s| s.to_string());
+
+ if best_mp4.is_some() {
+ return best_mp4;
+ }
+
+ variants
+ .iter()
+ .filter_map(|v| v.get("url").and_then(|u| u.as_str()))
+ .find(|url| url.contains(".m3u8") || url.contains("mpegurl"))
+ .or_else(|| {
+ variants
+ .iter()
+ .filter_map(|v| v.get("url").and_then(|u| u.as_str()))
+ .next()
+ })
.map(|s| s.to_string())
}
+ fn best_photo_url(media_item: &serde_json::Value) -> Option<(String, String)> {
+ let base_url = media_item
+ .get("media_url_https")
+ .or_else(|| media_item.get("media_url"))
+ .and_then(|v| v.as_str())?;
+
+ let extension = url::Url::parse(base_url)
+ .ok()
+ .and_then(|u| {
+ u.path_segments()
+ .and_then(|segments| segments.last().map(|s| s.to_string()))
+ })
+ .and_then(|filename| filename.rsplit('.').next().map(|ext| ext.to_string()))
+ .filter(|ext| !ext.is_empty())
+ .unwrap_or_else(|| "jpg".to_string());
+
+ let url = if let Ok(mut parsed) = url::Url::parse(base_url) {
+ let existing: Vec<(String, String)> = parsed
+ .query_pairs()
+ .filter(|(key, _)| key != "name")
+ .map(|(key, value)| (key.into_owned(), value.into_owned()))
+ .collect();
+ parsed.set_query(None);
+ {
+ let mut qp = parsed.query_pairs_mut();
+ for (key, value) in existing {
+ qp.append_pair(&key, &value);
+ }
+ qp.append_pair("name", "orig");
+ }
+ parsed.to_string()
+ } else if base_url.contains('?') {
+ format!("{}&name=orig", base_url)
+ } else {
+ format!("{}?name=orig", base_url)
+ };
+
+ Some((url, extension))
+ }
+
fn parse_media_items(media: &[serde_json::Value]) -> anyhow::Result<TwitterMedia> {
let items: Vec<TwitterMediaItem> = media
.iter()
.filter_map(|m| {
- let media_type_str = m.get("type").and_then(|v| v.as_str()).unwrap_or("");
-
- match media_type_str {
- "photo" => {
- let base_url = m.get("media_url_https").and_then(|v| v.as_str())?;
- let url = format!("{}?name=4096x4096", base_url);
- let ext = base_url.rsplit('.').next().unwrap_or("jpg").to_string();
+ match Self::infer_media_type(m)? {
+ TwitterMediaType::Photo => {
+ let (url, ext) = Self::best_photo_url(m)?;
Some(TwitterMediaItem {
media_type: TwitterMediaType::Photo,
url,
extension: ext,
})
}
- "video" => {
+ TwitterMediaType::Video => {
let url = Self::best_video_url(m)?;
+ let extension = if url.contains(".m3u8") || url.contains("mpegurl") {
+ "ytdlp"
+ } else {
+ "mp4"
+ };
Some(TwitterMediaItem {
media_type: TwitterMediaType::Video,
url,
- extension: "mp4".to_string(),
+ extension: extension.to_string(),
})
}
- "animated_gif" => {
+ TwitterMediaType::AnimatedGif => {
let url = Self::best_video_url(m)?;
Some(TwitterMediaItem {
media_type: TwitterMediaType::AnimatedGif,
@@ -395,7 +592,6 @@ impl TwitterDownloader {
extension: "mp4".to_string(),
})
}
- _ => None,
}
})
.collect();
@@ -418,6 +614,54 @@ impl TwitterDownloader {
TwitterMediaType::AnimatedGif => MediaType::Gif,
}
}
+
+ fn media_info_from_twitter_media(filename_base: String, twitter_media: TwitterMedia) -> MediaInfo {
+ match twitter_media {
+ TwitterMedia::Single(item) => {
+ let media_type = Self::media_type_for_item(&item);
+ MediaInfo {
+ title: filename_base,
+ author: String::new(),
+ platform: "twitter".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "original".to_string(),
+ width: 0,
+ height: 0,
+ url: item.url,
+ format: item.extension,
+ }],
+ media_type,
+ file_size_bytes: None,
+ }
+ }
+ TwitterMedia::Multiple(items) => {
+ let qualities: Vec<VideoQuality> = items
+ .iter()
+ .enumerate()
+ .map(|(i, item)| VideoQuality {
+ label: format!("media_{}", i + 1),
+ width: 0,
+ height: 0,
+ url: item.url.clone(),
+ format: item.extension.clone(),
+ })
+ .collect();
+
+ MediaInfo {
+ title: filename_base,
+ author: String::new(),
+ platform: "twitter".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: qualities,
+ media_type: MediaType::Carousel,
+ file_size_bytes: None,
+ }
+ }
+ }
+ }
}
#[async_trait]
@@ -451,7 +695,20 @@ impl PlatformDownloader for TwitterDownloader {
"[twitter] native failed: {}, trying yt-dlp fallback",
native_err
);
- self.fallback_ytdlp(url).await.map_err(|_| native_err)
+ match self.fallback_ytdlp(url).await {
+ Ok(info) => Ok(info),
+ Err(fallback_err) => {
+ tracing::warn!(
+ "[twitter] yt-dlp fallback failed after native error: {}",
+ fallback_err
+ );
+ Err(anyhow!(
+ "Twitter extraction failed. native='{}'; ytdlp='{}'",
+ native_err,
+ fallback_err
+ ))
+ }
+ }
}
}
}
@@ -465,6 +722,11 @@ impl PlatformDownloader for TwitterDownloader {
if let Some(quality) = info.available_qualities.first() {
if quality.format == "ytdlp" {
let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;
+ let mut extra_flags = Vec::new();
+ if let Some(cookie) = Self::manual_cookie_string() {
+ extra_flags.push("--add-headers".to_string());
+ extra_flags.push(format!("Cookie:{}", cookie));
+ }
return crate::core::ytdlp::download_video(
&ytdlp_path,
&quality.url,
@@ -479,7 +741,7 @@ impl PlatformDownloader for TwitterDownloader {
None,
opts.concurrent_fragments,
false,
- &[],
+ &extra_flags,
)
.await;
}
@@ -487,6 +749,12 @@ impl PlatformDownloader for TwitterDownloader {
let count = info.available_qualities.len();
+ if count == 0 {
+ anyhow::bail!(
+ "No downloadable media found for this tweet (it may be text-only, protected, or deleted)"
+ );
+ }
+
if count == 1 {
let quality = info.available_qualities.first().unwrap();
let filename = format!(
@@ -554,19 +822,35 @@ impl PlatformDownloader for TwitterDownloader {
impl TwitterDownloader {
async fn fallback_ytdlp(&self, url: &str) -> anyhow::Result<MediaInfo> {
let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;
- let json = crate::core::ytdlp::get_video_info(&ytdlp_path, url, &[]).await?;
+ let mut extra_flags = vec![
+ "--referer".to_string(),
+ "https://x.com/".to_string(),
+ "--add-headers".to_string(),
+ "Referer:https://x.com/".to_string(),
+ ];
+ if let Some(cookie) = Self::manual_cookie_string() {
+ extra_flags.push("--add-headers".to_string());
+ extra_flags.push(format!("Cookie:{}", cookie));
+ }
+ let json = crate::core::ytdlp::get_video_info(&ytdlp_path, url, &extra_flags).await?;
crate::platforms::generic_ytdlp::GenericYtdlpDownloader::parse_video_info(&json)
}
async fn native_get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
let tweet_id =
Self::extract_tweet_id(url).ok_or_else(|| anyhow!("Could not extract tweet ID"))?;
+ tracing::debug!("[twitter] native_get_media_info tweet_id={} url={}", tweet_id, url);
let filename_base = format!("twitter_{}", tweet_id);
let media_items = match self.try_graphql(&tweet_id).await {
Ok(items) => items,
- Err(_) => {
+ Err(graphql_err) => {
+ tracing::warn!(
+ "[twitter] graphql lookup failed for tweet_id={}: {}",
+ tweet_id,
+ graphql_err
+ );
let syndication = self.request_syndication(&tweet_id).await?;
Self::extract_syndication_media(&syndication)?
}
@@ -574,64 +858,7 @@ impl TwitterDownloader {
let twitter_media = Self::parse_media_items(&media_items)?;
- match twitter_media {
- TwitterMedia::Single(item) => {
- let media_type = Self::media_type_for_item(&item);
- Ok(MediaInfo {
- title: filename_base,
- author: String::new(),
- platform: "twitter".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "original".to_string(),
- width: 0,
- height: 0,
- url: item.url,
- format: item.extension,
- }],
- media_type,
- file_size_bytes: None,
- })
- }
- TwitterMedia::Multiple(items) => {
- let has_video = items.iter().any(|i| {
- matches!(
- i.media_type,
- TwitterMediaType::Video | TwitterMediaType::AnimatedGif
- )
- });
-
- let media_type = if has_video {
- MediaType::Video
- } else {
- MediaType::Carousel
- };
-
- let qualities: Vec<VideoQuality> = items
- .iter()
- .enumerate()
- .map(|(i, item)| VideoQuality {
- label: format!("media_{}", i + 1),
- width: 0,
- height: 0,
- url: item.url.clone(),
- format: item.extension.clone(),
- })
- .collect();
-
- Ok(MediaInfo {
- title: filename_base,
- author: String::new(),
- platform: "twitter".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: qualities,
- media_type,
- file_size_bytes: None,
- })
- }
- }
+ Ok(Self::media_info_from_twitter_media(filename_base, twitter_media))
}
async fn try_graphql(&self, tweet_id: &str) -> anyhow::Result<Vec<serde_json::Value>> {
@@ -648,3 +875,6 @@ impl TwitterDownloader {
}
}
}
+
+#[cfg(test)]
+mod tests;
diff --git a/src/components/settings/SettingsDownloads.svelte b/src/components/settings/SettingsDownloads.svelte
index 4e6aa2f7..41de6791 100644
--- a/src/components/settings/SettingsDownloads.svelte
+++ b/src/components/settings/SettingsDownloads.svelte
@@ -384,6 +384,14 @@
</div>
<button class="toggle" class:on={settings.download.clipboard_detection} onclick={() => toggleBool("download", "clipboard_detection", settings.download.clipboard_detection)} role="switch" aria-checked={settings.download.clipboard_detection} aria-label={$t('settings.download.clipboard_detection') as string}><span class="toggle-knob"></span></button>
</div>
+ <div class="divider"></div>
+ <div class="setting-row">
+ <div class="setting-col">
+ <span class="setting-label">{$t('settings.download.auto_download_on_paste')}</span>
+ <span class="setting-path">{$t('settings.download.auto_download_on_paste_desc')}</span>
+ </div>
+ <button class="toggle" class:on={settings.download.auto_download_on_paste} onclick={() => toggleBool("download", "auto_download_on_paste", settings.download.auto_download_on_paste)} role="switch" aria-checked={settings.download.auto_download_on_paste} aria-label={$t('settings.download.auto_download_on_paste') as string}><span class="toggle-knob"></span></button>
+ </div>
</div>
</details>
diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.json
index b706f3df..93cf84af 100644
--- a/src/lib/i18n/el.json
+++ b/src/lib/i18n/el.json
@@ -97,6 +97,7 @@
"download_complete": "Ετοιμο! Το {{name}} ειναι στον φακελο σας",
"download_error": "Δεν μπορεσα να κατεβασω {{name}}. Θελετε να δοκιμασετε ξανα;",
"clipboard_url_detected": "Εντοπιστηκε συνδεσμος! Επικολληστε για ληψη",
+ "auto_download_started": "Αυτόματη λήψη ξεκίνησε",
"external_url_ready": "Το URL λήφθηκε και είναι έτοιμο για λήψη",
"external_url_queued": "Η λήψη προστέθηκε από την επέκταση Chrome",
"file_copied_to_clipboard": "Το αρχείο αντιγράφηκε στο πρόχειρο",
@@ -212,6 +213,8 @@
"embed_thumbnail_desc": "Ενσωματώστε το εξώφυλλο άλμπουμ σε αρχεία ήχου",
"clipboard_detection": "Ανίχνευση πρόχειρου",
"clipboard_detection_desc": "Αυτόματος εντοπισμός διευθύνσεων URL που αντιγράφηκαν στο πρόχειρο",
+ "auto_download_on_paste": "Αυτόματη λήψη κατά την επικόλληση",
+ "auto_download_on_paste_desc": "Ξεκινήστε αμέσως τη λήψη όταν εντοπιστεί URL στο πρόχειρο",
"organize_by_platform": "Οργάνωση ανά πλατφόρμα",
"organize_by_platform_desc": "Αποθηκεύστε αρχεία σε υποφακέλους με το όνομα της πλατφόρμας",
"download_subtitles": "Κατεβάστε υπότιτλους",
@@ -335,7 +338,9 @@
"torrent_listen_port": "Θύρα ακρόασης torrent",
"torrent_listen_port_desc": "Θύρα TCP για εισερχόμενες συνδέσεις BitTorrent",
"cookies_from_browser": "Cookies προγράμματος περιήγησης (προχωρημένο)",
- "cookies_from_browser_desc": "Ορίστε μόνο αν η επέκταση του προγράμματος περιήγησης δεν λειτουργεί. Οι περισσότεροι χρήστες πρέπει να το αφήσουν κενό."
+ "cookies_from_browser_desc": "Ορίστε μόνο αν η επέκταση του προγράμματος περιήγησης δεν λειτουργεί. Οι περισσότεροι χρήστες πρέπει να το αφήσουν κενό.",
+ "twitter_manual_cookie": "Χειροκίνητο cookie",
+ "twitter_manual_cookie_desc": "Αν μια λήψη αποτύχει, μπορείτε να επικολλήσετε εδώ μια χειροκίνητη κεφαλίδα Cookie και να δοκιμάσετε ξανά. Δεν περιορίζεται στο Twitter/X. Παράδειγμα: sessionid=...; csrftoken=...; auth_token=..."
},
"cat_appearance": "Appearance",
"cat_typography": "Τυπογραφία",
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index 3da085a6..e63dcf4b 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -97,6 +97,7 @@
"download_complete": "Done! {{name}} is in your folder",
"download_error": "Couldn't download {{name}}. Want to retry?",
"clipboard_url_detected": "Link detected! Paste to download",
+ "auto_download_started": "Auto-download started",
"external_url_ready": "URL received and ready to download",
"external_url_queued": "Download added from the Chrome extension",
"file_copied_to_clipboard": "File copied to clipboard",
@@ -212,6 +213,8 @@
"embed_thumbnail_desc": "Embed album art into audio files",
"clipboard_detection": "Clipboard detection",
"clipboard_detection_desc": "Auto-detect URLs copied to clipboard",
+ "auto_download_on_paste": "Auto-download on paste",
+ "auto_download_on_paste_desc": "Start downloading instantly when a URL is detected in the clipboard",
"organize_by_platform": "Organize by platform",
"organize_by_platform_desc": "Save files in subfolders named after the platform",
"download_subtitles": "Download subtitles",
@@ -335,7 +338,9 @@
"torrent_listen_port": "Torrent listen port",
"torrent_listen_port_desc": "TCP port for incoming BitTorrent connections",
"cookies_from_browser": "Read cookies directly from a browser profile (advanced)",
- "cookies_from_browser_desc": "Only set this if the browser extension isn't working. Most users should leave this empty."
+ "cookies_from_browser_desc": "Only set this if the browser extension isn't working. Most users should leave this empty.",
+ "twitter_manual_cookie": "Manual cookie",
+ "twitter_manual_cookie_desc": "If a download fails, you can paste a manual Cookie header here and try again. This is not limited to Twitter/X. Example: sessionid=...; csrftoken=...; auth_token=..."
},
"cat_appearance": "Appearance",
"cat_typography": "Typography",
diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.json
index b7bce7fe..fde223d8 100644
--- a/src/lib/i18n/fr.json
+++ b/src/lib/i18n/fr.json
@@ -97,6 +97,7 @@
"download_complete": "Fini ! {{name}} est dans votre dossier",
"download_error": "Impossible de telecharger {{name}}. Reessayer ?",
"clipboard_url_detected": "Lien detecte ! Collez pour telecharger",
+ "auto_download_started": "Téléchargement automatique lancé",
"external_url_ready": "URL reçue et prête à être téléchargée",
"external_url_queued": "Téléchargement ajouté depuis l'extension Chrome",
"file_copied_to_clipboard": "Fichier copié dans le presse-papiers",
@@ -212,6 +213,8 @@
"embed_thumbnail_desc": "Intégrer la pochette d'album dans les fichiers audio",
"clipboard_detection": "Détection du presse-papiers",
"clipboard_detection_desc": "Détecter automatiquement les URLs copiées dans le presse-papiers",
+ "auto_download_on_paste": "Téléchargement automatique au collage",
+ "auto_download_on_paste_desc": "Lancer immédiatement le téléchargement dès qu'une URL est détectée dans le presse-papiers",
"organize_by_platform": "Organiser par plateforme",
"organize_by_platform_desc": "Enregistrer les fichiers dans des sous-dossiers nommés d'après la plateforme",
"download_subtitles": "Télécharger les sous-titres",
@@ -335,7 +338,9 @@
"torrent_listen_port": "Port d’écoute torrent",
"torrent_listen_port_desc": "Port TCP pour les connexions BitTorrent entrantes",
"cookies_from_browser": "Cookies du navigateur (avancé)",
- "cookies_from_browser_desc": "À configurer uniquement si l'extension du navigateur ne fonctionne pas. La plupart des utilisateurs doivent laisser vide."
+ "cookies_from_browser_desc": "À configurer uniquement si l'extension du navigateur ne fonctionne pas. La plupart des utilisateurs doivent laisser vide.",
+ "twitter_manual_cookie": "Cookie manuel",
+ "twitter_manual_cookie_desc": "Si un téléchargement échoue, vous pouvez coller ici un en-tête Cookie manuel et réessayer. Ce n'est pas limité à Twitter/X. Exemple : sessionid=...; csrftoken=...; auth_token=..."
},
"cat_appearance": "Appearance",
"cat_typography": "Typographie",
diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.json
index 9f2d5a9f..c9876963 100644
--- a/src/lib/i18n/it.json
+++ b/src/lib/i18n/it.json
@@ -97,6 +97,7 @@
"download_complete": "Fatto! {{name}} e nella tua cartella",
"download_error": "Non riesco a scaricare {{name}}. Riprovare?",
"clipboard_url_detected": "Link rilevato! Incolla per scaricare",
+ "auto_download_started": "Download automatico avviato",
"external_url_ready": "URL ricevuto e pronto per il download",
"external_url_queued": "Download aggiunto dall'estensione Chrome",
"file_copied_to_clipboard": "File copiato negli appunti",
@@ -212,6 +213,8 @@
"embed_thumbnail_desc": "Incorpora copertina nei file audio",
"clipboard_detection": "Rilevamento appunti",
"clipboard_detection_desc": "Rileva automaticamente gli URL copiati negli appunti",
+ "auto_download_on_paste": "Download automatico all'incolla",
+ "auto_download_on_paste_desc": "Avvia il download immediatamente quando un URL viene rilevato negli appunti",
"organize_by_platform": "Organizza per piattaforma",
"organize_by_platform_desc": "Salva i file in sottocartelle con il nome della piattaforma",
"download_subtitles": "Scarica sottotitoli",
@@ -335,7 +338,9 @@
"torrent_listen_port": "Porta di ascolto torrent",
"torrent_listen_port_desc": "Porta TCP per le connessioni BitTorrent in entrata",
"cookies_from_browser": "Cookie del browser (avanzato)",
- "cookies_from_browser_desc": "Configura solo se l'estensione del browser non funziona. La maggior parte degli utenti dovrebbe lasciare vuoto."
+ "cookies_from_browser_desc": "Configura solo se l'estensione del browser non funziona. La maggior parte degli utenti dovrebbe lasciare vuoto.",
+ "twitter_manual_cookie": "Cookie manuale",
+ "twitter_manual_cookie_desc": "Se un download fallisce, puoi incollare qui un header Cookie manuale e riprovare. Non è limitato a Twitter/X. Esempio: sessionid=...; csrftoken=...; auth_token=..."
},
"cat_appearance": "Appearance",
"cat_typography": "Tipografia",
diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.json
index 9e49c5a1..9b0ef7dc 100644
--- a/src/lib/i18n/ja.json
+++ b/src/lib/i18n/ja.json
@@ -97,6 +97,7 @@
"download_complete": "完了!{{name}} はフォルダに保存されました",
"download_error": "{{name}} をダウンロードできませんでした。再試行しますか?",
"clipboard_url_detected": "リンクを検出!貼り付けてダウンロード",
+ "auto_download_started": "自動ダウンロードを開始しました",
"external_url_ready": "URLを受信し、ダウンロードの準備ができました",
"external_url_queued": "Chrome拡張機能からダウンロードを追加しました",
"file_copied_to_clipboard": "ファイルをクリップボードにコピーしました",
@@ -212,6 +213,8 @@
"embed_thumbnail_desc": "音声ファイルにアルバムアートを埋め込みます",
"clipboard_detection": "クリップボード検出",
"clipboard_detection_desc": "クリップボードにコピーされたURLを自動検出します",
+ "auto_download_on_paste": "貼り付けで自動ダウンロード",
+ "auto_download_on_paste_desc": "クリップボードでURLが検出されたらすぐにダウンロードを開始します",
"organize_by_platform": "プラットフォーム別に整理",
"organize_by_platform_desc": "プラットフォーム名のサブフォルダにファイルを保存します",
"download_subtitles": "字幕をダウンロード",
@@ -335,7 +338,9 @@
"torrent_listen_port": "Torrent待ち受けポート",
"torrent_listen_port_desc": "BitTorrent接続を受け付けるTCPポート",
"cookies_from_browser": "ブラウザのCookie(詳細)",
- "cookies_from_browser_desc": "ブラウザ拡張機能が動作しない場合のみ設定してください。通常は空のままにしてください。"
+ "cookies_from_browser_desc": "ブラウザ拡張機能が動作しない場合のみ設定してください。通常は空のままにしてください。",
+ "twitter_manual_cookie": "手動Cookie",
+ "twitter_manual_cookie_desc": "ダウンロードに失敗した場合、ここに手動のCookieヘッダーを貼り付けて再試行できます。Twitter/Xに限定されません。例: sessionid=...; csrftoken=...; auth_token=..."
},
"cat_appearance": "Appearance",
"cat_typography": "タイポグラフィ",
diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.ts
index ec9ac6c4..e614ab73 100644
--- a/src/lib/i18n/keys.ts
+++ b/src/lib/i18n/keys.ts
@@ -461,6 +461,8 @@ export type TranslationKeys =
| 'settings.advanced.title'
| 'settings.advanced.torrent_listen_port'
| 'settings.advanced.torrent_listen_port_desc'
+ | 'settings.advanced.twitter_manual_cookie'
+ | 'settings.advanced.twitter_manual_cookie_desc'
| 'settings.appearance.lang_el'
| 'settings.appearance.lang_en'
| 'settings.appearance.lang_es'
@@ -495,6 +497,8 @@ export type TranslationKeys =
| 'settings.dependencies.update'
| 'settings.dependencies.variant_aria'
| 'settings.download.always_ask_path'
+ | 'settings.download.auto_download_on_paste'
+ | 'settings.download.auto_download_on_paste_desc'
| 'settings.download.choose_folder'
| 'settings.download.clipboard_detection'
| 'settings.download.clipboard_detection_desc'
@@ -2294,6 +2298,7 @@ export type TranslationKeys =
| 'terms_note.agreement'
| 'terms_note.link'
+ | 'toast.auto_download_started'
| 'toast.clipboard_url_detected'
| 'toast.download_complete'
| 'toast.download_error'
diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.json
index dc089748..b571a198 100644
--- a/src/lib/i18n/pt.json
+++ b/src/lib/i18n/pt.json
@@ -97,6 +97,7 @@
"download_complete": "Pronto! {{name}} está na sua pasta",
"download_error": "Não consegui baixar {{name}}. Tente novamente?",
"clipboard_url_detected": "Link detectado! Cole para baixar",
+ "auto_download_started": "Download automático iniciado",
"external_url_ready": "URL recebida e pronta para download",
"external_url_queued": "Download adicionado pela extensão do Chrome",
"file_copied_to_clipboard": "Arquivo copiado para o clipboard",
@@ -212,6 +213,8 @@
"embed_thumbnail_desc": "Embutir capa de álbum em arquivos de áudio",
"clipboard_detection": "Detecção de clipboard",
"clipboard_detection_desc": "Detectar URLs copiadas automaticamente",
+ "auto_download_on_paste": "Download automático ao colar",
+ "auto_download_on_paste_desc": "Iniciar o download imediatamente quando um URL for detectado na área de transferência",
"organize_by_platform": "Organizar por plataforma",
"organize_by_platform_desc": "Salvar arquivos em subpastas com o nome da plataforma",
"download_subtitles": "Baixar legendas",
@@ -335,7 +338,9 @@
"torrent_listen_port": "Porta de escuta torrent",
"torrent_listen_port_desc": "Porta TCP para conexões BitTorrent de entrada",
"cookies_from_browser": "Ler cookies direto de um perfil do navegador (avançado)",
- "cookies_from_browser_desc": "Só configure se a extensão do navegador não funcionar. A maioria dos usuários deve deixar vazio."
+ "cookies_from_browser_desc": "Só configure se a extensão do navegador não funcionar. A maioria dos usuários deve deixar vazio.",
+ "twitter_manual_cookie": "Cookie manual",
+ "twitter_manual_cookie_desc": "Se um download falhar, você pode colar aqui um cabeçalho Cookie manual e tentar novamente. Não está limitado ao Twitter/X. Exemplo: sessionid=...; csrftoken=...; auth_token=..."
},
"cat_appearance": "Aparência",
"cat_typography": "Tipografia",
diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.json
index 674c9569..bcd29e8a 100644
--- a/src/lib/i18n/zh-TW.json
+++ b/src/lib/i18n/zh-TW.json
@@ -97,6 +97,7 @@
"download_complete": "下載完成: {{name}}",
"download_error": "下載失敗: {{name}}",
"clipboard_url_detected": "在剪貼簿中偵測到 URL",
+ "auto_download_started": "已啟動自動下載",
"external_url_ready": "已收到 URL,可以开始下载",
"external_url_queued": "已从 Chrome 扩展添加下载",
"file_copied_to_clipboard": "檔案已複製到剪貼簿",
@@ -212,6 +213,8 @@
"embed_thumbnail_desc": "將專輯封面嵌入音訊檔案",
"clipboard_detection": "剪貼簿偵測",
"clipboard_detection_desc": "自動偵測複製到剪貼簿的 URL",
+ "auto_download_on_paste": "貼上時自動下載",
+ "auto_download_on_paste_desc": "在剪貼簿中偵測到 URL 時立即開始下載",
"organize_by_platform": "依平台整理",
"organize_by_platform_desc": "依平台名稱將檔案儲存在子資料夾中",
"download_subtitles": "下載字幕",
@@ -335,7 +338,9 @@
"torrent_listen_port": "Torrent 監聽連接埠",
"torrent_listen_port_desc": "用於接收 BitTorrent 連線的 TCP 連接埠",
"cookies_from_browser": "浏览器 Cookie(高级)",
- "cookies_from_browser_desc": "仅在浏览器扩展无法工作时设置。大多数用户应保持为空。"
+ "cookies_from_browser_desc": "仅在浏览器扩展无法工作时设置。大多数用户应保持为空。",
+ "twitter_manual_cookie": "手動 Cookie",
+ "twitter_manual_cookie_desc": "如果下載失敗,您可以在此貼上手動的 Cookie 標頭並重試。不限於 Twitter/X。範例:sessionid=...; csrftoken=...; auth_token=..."
},
"cat_appearance": "Appearance",
"cat_typography": "排版",
diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.json
index 1efde4e1..a780497e 100644
--- a/src/lib/i18n/zh.json
+++ b/src/lib/i18n/zh.json
@@ -97,6 +97,7 @@
"download_complete": "完成!{{name}} 已保存到你的文件夹",
"download_error": "无法下载 {{name}}。要重试吗?",
"clipboard_url_detected": "检测到链接!粘贴即可下载",
+ "auto_download_started": "已启动自动下载",
"external_url_ready": "已收到 URL,可以开始下载",
"external_url_queued": "已从 Chrome 扩展添加下载",
"file_copied_to_clipboard": "文件已复制到剪贴板",
@@ -212,6 +213,8 @@
"embed_thumbnail_desc": "将专辑封面嵌入音频文件",
"clipboard_detection": "剪贴板检测",
"clipboard_detection_desc": "自动检测复制到剪贴板的链接",
+ "auto_download_on_paste": "粘贴时自动下载",
+ "auto_download_on_paste_desc": "检测到剪贴板中的 URL 时立即开始下载",
"organize_by_platform": "按平台整理",
"organize_by_platform_desc": "将文件保存到以平台命名的子文件夹中",
"download_subtitles": "下载字幕",
@@ -335,7 +338,9 @@
"torrent_listen_port": "Torrent 监听端口",
"torrent_listen_port_desc": "用于接收 BitTorrent 连接的 TCP 端口",
"cookies_from_browser": "浏览器 Cookie(高级)",
- "cookies_from_browser_desc": "仅在浏览器扩展无法工作时设置。大多数用户应保持为空。"
+ "cookies_from_browser_desc": "仅在浏览器扩展无法工作时设置。大多数用户应保持为空。",
+ "twitter_manual_cookie": "手动 Cookie",
+ "twitter_manual_cookie_desc": "如果下载失败,您可以在此粘贴手动的 Cookie 标头并重试。不限于 Twitter/X。示例:sessionid=...; csrftoken=...; auth_token=..."
},
"cat_appearance": "Appearance",
"cat_typography": "排版",
diff --git a/src/lib/stores/clipboard-monitor.ts b/src/lib/stores/clipboard-monitor.ts
index 217a45a2..96c8bc1f 100644
--- a/src/lib/stores/clipboard-monitor.ts
+++ b/src/lib/stores/clipboard-monitor.ts
@@ -1,3 +1,5 @@
+import { readText } from "@tauri-apps/plugin-clipboard-manager";
+
const POLL_INTERVAL = 2000;
const URL_PATTERN = /^(https?:\/\/|magnet:\?|p2p:).+/;
@@ -20,7 +22,7 @@ export function startClipboardMonitor() {
if (!enabled || !document.hasFocus()) return;
try {
- const text = await navigator.clipboard.readText();
+ const text = await readText();
const trimmed = text.trim().split(/[\s\n]/)[0];
if (
diff --git a/src/lib/stores/settings-store.svelte.ts b/src/lib/stores/settings-store.svelte.ts
index d49122ed..194faa67 100644
--- a/src/lib/stores/settings-store.svelte.ts
+++ b/src/lib/stores/settings-store.svelte.ts
@@ -16,6 +16,7 @@ export type AppSettings = {
embed_metadata: boolean;
embed_thumbnail: boolean;
clipboard_detection: boolean;
+ auto_download_on_paste: boolean;
filename_template: string;
organize_by_platform: boolean;
download_subtitles: boolean;
@@ -50,6 +51,7 @@ export type AppSettings = {
stagger_delay_ms: number;
torrent_listen_port: number;
cookies_from_browser: string;
+ twitter_manual_cookie: string;
};
telegram: {
concurrent_downloads: number;
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index 6a0e8e5c..e90a59ee 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -94,19 +94,52 @@
let p2pReceiveUrl = $state("");
let externalNotice = $state<ExternalUrlEvent | null>(null);
let lastExternalPrefillId = $state<number | null>(null);
+ let pendingAutoDownload = $state(false);
onMount(() => {
onClipboardUrl((detectedUrl) => {
if (omniState.kind === "preparing") return;
url = detectedUrl;
+ const settings = getSettings();
+ const autoDownload = !!(settings?.download.auto_download_on_paste && settings?.download.clipboard_detection);
+ pendingAutoDownload = autoDownload;
handleInput();
- showToast("info", $t("toast.clipboard_url_detected"));
+ showToast("info", $t(autoDownload ? "toast.auto_download_started" : "toast.clipboard_url_detected"));
});
return () => {
onClipboardUrl(null);
};
});
+ const AUTO_DOWNLOAD_DELAY_MS = 2000;
+
+ $effect(() => {
+ if (!pendingAutoDownload) return;
+ if (omniState.kind === "detected") {
+ const info = omniState.info;
+ if (info.platform === "hotmart" || info.platform === "p2p") {
+ pendingAutoDownload = false;
+ return;
+ }
+ pendingAutoDownload = false;
+ const snapshotUrl = url;
+ setTimeout(() => {
+ if (url === snapshotUrl && omniState.kind === "detected") {
+ handleAction();
+ }
+ }, AUTO_DOWNLOAD_DELAY_MS);
+ } else if (
+ omniState.kind === "unsupported" ||
+ omniState.kind === "error" ||
+ omniState.kind === "batch" ||
+ omniState.kind === "search-results" ||
+ omniState.kind === "search-empty" ||
+ omniState.kind === "idle"
+ ) {
+ pendingAutoDownload = false;
+ }
+ });
+
const STALL_THRESHOLD = 30_000;
let downloads = $derived(getDownloads());
let stallTick = $state(0);
@@ -148,7 +181,15 @@
lastExternalPrefillId = incoming.id;
clearPendingExternalPrefill(incoming.id);
externalNotice = incoming;
+
+ if (incoming.action !== "prefill") {
+ return;
+ }
+
url = incoming.url;
+ if (getSettings()?.download.auto_download_on_paste) {
+ pendingAutoDownload = true;
+ }
handleInput();
});
@@ -274,6 +315,9 @@
if (isUrl(trimmed)) {
omniState = { kind: "detecting" };
+ if (getSettings()?.download.auto_download_on_paste) {
+ pendingAutoDownload = true;
+ }
debounceTimer = setTimeout(() => {
detectPlatform(trimmed);
}, 500);
@@ -413,7 +457,7 @@
const settings = getSettings();
let outputDir = settings?.download.default_output_dir ?? "";
- if (settings?.download.always_ask_path || !outputDir) {
+ if ((settings?.download.always_ask_path && !settings?.download.auto_download_on_paste) || !outputDir) {
const selected = await open({
directory: true,
title: $t("settings.download.default_output_dir"),
@@ -456,7 +500,7 @@
const settings = getSettings();
let outputDir = settings?.download.default_output_dir ?? "";
- if (settings?.download.always_ask_path || !outputDir) {
+ if ((settings?.download.always_ask_path && !settings?.download.auto_download_on_paste) || !outputDir) {
const selected = await open({
directory: true,
title: $t("settings.download.default_output_dir"),
@@ -501,7 +545,7 @@
const settings = getSettings();
let outputDir = settings?.download.default_output_dir ?? "";
- if (settings?.download.always_ask_path || !outputDir) {
+ if ((settings?.download.always_ask_path && !settings?.download.auto_download_on_paste) || !outputDir) {
const selected = await open({
directory: true,
title: $t("settings.download.default_output_dir"),