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: Telegram Direct Uploader & Leech Bot, Dynamic Quality Picker, Merging Phase Badge & System Enhancements (#197)

Garvit Sharma9706fc6c8e6f
diff --git a/README.md b/README.md
index 36019c0a..6366e2c0 100644
--- a/README.md
+++ b/README.md
@@ -176,6 +176,12 @@ Things people search for, and OmniGet does:
- **Download only part of a video** by setting a start and end time.
- **Download subtitles** in any language, embed them, or generate them with Whisper when none exist.
- **Skip sponsors** with SponsorBlock, and auto embed metadata and thumbnails.
+- **Telegram Direct Uploader & Leech Bot**: Upload media directly to Telegram via User Session or Bot Token, supporting numeric Chat IDs, `@usernames`, custom thumbnails, custom filename & extension editing, **Send As** Video/Document/Audio modes, and 2GB (Free) / 4GB (Premium) auto-chunking.
+- **Dynamic YouTube Quality Picker**: View and select real available resolutions (`4K 2160p`, `2K 1440p`, `1080p`, `720p`, `Audio only`) extracted straight from yt-dlp metadata.
+- **Explicit Merging Phase & Smooth ETA**: Know exactly when audio and video are merging (`[Merger]`, `[ffmpeg]`) with live ETA estimations (`ETA ~3m 20s`).
+- **Header Bandwidth Limiter**: Throttle download speed on the fly directly from the Downloads header bar.
+- **Interactive Clipboard Detection Toast**: Auto-detect video URLs on clipboard with a single-click toast banner.
+- **System Dependency Detection**: Detect and use system-installed `yt-dlp`, `FFmpeg`, and `PDFium` binaries with source indicators (`PATH`, `Managed`, `Flatpak`).
- **Follow a channel** and auto download new uploads, with a tray notification.
- **Download Bilibili at maximum quality**, sign in once and unlock 4K, HDR, Hi-Res lossless audio and Dolby Atmos.
@@ -398,6 +404,12 @@ Found a bug or have a feature idea? [Open an issue](https://github.com/tonhowtf/
OmniGet is translated on [Weblate](https://hosted.weblate.org/engage/omniget/). Pick a language, translate in your browser, and Weblate opens a pull request automatically.
+### Contributors
+
+Thanks to all contributors who have participated in this project!
+
+[![Contributors](https://contrib.rocks/image?repo=tonhowtf/omniget)](https://github.com/tonhowtf/omniget/graphs/contributors)
+
### Developing plugins
OmniGet's Courses, Telegram, and Convert features are all plugins — Rust dynamic libraries built on [`omniget-plugin-sdk`](src-tauri/omniget-plugin-sdk) — and third-party plugins are welcome. The [Plugin Development Guide](docs/plugin-development.md) covers the architecture, a quick start from the [plugin template](https://github.com/tonhowtf/omniget-plugin-template), the manifest and host API, honest notes on ABI stability, and how to get listed in the [plugin registry](https://github.com/tonhowtf/omniget-plugins).
diff --git a/README.ru.md b/README.ru.md
index b0d1bc87..5b58bad8 100644
--- a/README.ru.md
+++ b/README.ru.md
@@ -390,6 +390,12 @@ omniget import-cookies cookies.txt # формат Netscape
OmniGet переводится на [Weblate](https://hosted.weblate.org/engage/omniget/). Выберите язык, переводите в браузере, и Weblate сам откроет pull request.
+### Участники
+
+Спасибо всем участникам, сделавшим вклад в этот проект!
+
+[![Участники](https://contrib.rocks/image?repo=tonhowtf/omniget)](https://github.com/tonhowtf/omniget/graphs/contributors)
+
## Уведомление для владельцев платформ
Если вы представляете указанную платформу и у вас есть вопросы, напишите на **[email protected]** с корпоративного адреса. Платформа будет убрана из списка сразу же.
diff --git a/README_zh_CN.md b/README_zh_CN.md
index f0958cfe..cbb0f108 100644
--- a/README_zh_CN.md
+++ b/README_zh_CN.md
@@ -390,6 +390,12 @@ omniget import-cookies cookies.txt # Netscape 格式
OmniGet 在 [Weblate](https://hosted.weblate.org/engage/omniget/) 上进行翻译。选择一种语言,在浏览器里翻译,Weblate 会自动开 PR。
+### 贡献者
+
+感谢所有为本项目做出贡献的开发者!
+
+[![贡献者](https://contrib.rocks/image?repo=tonhowtf/omniget)](https://github.com/tonhowtf/omniget/graphs/contributors)
+
## 致平台方
如果你代表某个被列出的平台并有顾虑,请用公司邮箱发邮件至 **[email protected]**。该平台会立即从列表中移除。
diff --git a/src-tauri/omniget-core/src/core/dependencies.rs b/src-tauri/omniget-core/src/core/dependencies.rs
index 30e30f2d..bdc11cbf 100644
--- a/src-tauri/omniget-core/src/core/dependencies.rs
+++ b/src-tauri/omniget-core/src/core/dependencies.rs
@@ -114,7 +114,12 @@ pub fn bin_name(tool: &str) -> String {
}
pub async fn find_tool(tool: &str) -> Option<PathBuf> {
- let _timer_start = std::time::Instant::now();
+ find_tool_with_source(tool).await.map(|(path, _)| path)
+}
+
+/// Like `find_tool` but also returns a source tag: "flatpak", "managed", or "system".
+/// Returns `None` if the tool is not found anywhere.
+pub async fn find_tool_with_source(tool: &str) -> Option<(PathBuf, &'static str)> {
let name = bin_name(tool);
let version_flag = version_flag_for(tool);
@@ -122,18 +127,12 @@ pub async fn find_tool(tool: &str) -> Option<PathBuf> {
{
let flatpak_path = PathBuf::from("/app/bin").join(&name);
if flatpak_path.exists() {
- tracing::debug!(
- "[perf] find_tool({}) took {:?}",
- tool,
- _timer_start.elapsed()
- );
- return Some(flatpak_path);
+ return Some((flatpak_path, "flatpak"));
}
}
- // Check managed bin dir first — managed binaries are known-good.
- let managed = managed_bin_dir().map(|d| d.join(&name));
- if let Some(ref managed_path) = managed {
+ // Check managed bin dir
+ if let Some(managed_path) = managed_bin_dir().map(|d| d.join(&name)) {
if managed_path.exists() {
let check = {
let managed = managed_path.clone();
@@ -151,30 +150,18 @@ pub async fn find_tool(tool: &str) -> Option<PathBuf> {
.ok()
.flatten()
};
-
if check.is_some() {
- tracing::debug!(
- "[perf] find_tool({}) took {:?}",
- tool,
- _timer_start.elapsed()
- );
- return Some(managed_path.clone());
+ return Some((managed_path, "managed"));
}
- tracing::warn!(
- "find_tool({}): binary exists at {} but failed to execute",
- tool,
- managed_path.display()
- );
}
}
- // Fall back to system PATH. Resolve to an absolute path so callers
- // (e.g. find_ffmpeg_location) can derive the parent directory.
+ // System PATH
let result = {
- let name = name.clone();
+ let name2 = name.clone();
let vf = version_flag.to_string();
tokio::task::spawn_blocking(move || {
- crate::core::process::std_command(&name)
+ crate::core::process::std_command(&name2)
.arg(&vf)
.stdout(Stdio::null())
.stderr(Stdio::null())
@@ -189,19 +176,9 @@ pub async fn find_tool(tool: &str) -> Option<PathBuf> {
if result.is_some() {
let abs = resolve_absolute_path(&name);
- tracing::debug!(
- "[perf] find_tool({}) took {:?}",
- tool,
- _timer_start.elapsed()
- );
- return Some(abs);
+ return Some((abs, "system"));
}
- tracing::debug!(
- "[perf] find_tool({}) took {:?}",
- tool,
- _timer_start.elapsed()
- );
None
}
@@ -238,47 +215,43 @@ fn version_flag_for(tool: &str) -> &'static str {
}
}
-pub async fn check_version(tool: &str) -> Option<String> {
- let _timer_start = std::time::Instant::now();
- let path = find_tool(tool).await?;
+/// Read the version string from a tool binary at a known path.
+/// This avoids re-running tool discovery when the path is already known.
+pub async fn check_version_at_path(path: &std::path::Path, tool: &str) -> Option<String> {
let version_flag = version_flag_for(tool);
- let output = {
- let path = path.clone();
- let vf = version_flag.to_string();
- tokio::task::spawn_blocking(move || {
- crate::core::process::std_command(&path)
- .arg(&vf)
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .output()
- })
- .await
- .ok()?
- .ok()?
- };
+ let path = path.to_path_buf();
+ let vf = version_flag.to_string();
+ let output = tokio::task::spawn_blocking(move || {
+ crate::core::process::std_command(&path)
+ .arg(&vf)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ })
+ .await
+ .ok()?
+ .ok()?;
if !output.status.success() {
- tracing::debug!(
- "[perf] check_version({}) took {:?}",
- tool,
- _timer_start.elapsed()
- );
return None;
}
let stdout = String::from_utf8_lossy(&output.stdout);
let first_line = stdout.lines().next().unwrap_or("");
- let result = if tool == "ffmpeg" || tool == "ffprobe" {
+ if tool == "ffmpeg" || tool == "ffprobe" {
first_line.split_whitespace().nth(2).map(|s| s.to_string())
- } else if tool == "yt-dlp" {
- Some(first_line.trim().to_string())
} else if tool == "aria2c" {
first_line.split_whitespace().nth(2).map(|s| s.to_string())
} else {
Some(first_line.trim().to_string())
- };
+ }
+}
+pub async fn check_version(tool: &str) -> Option<String> {
+ let _timer_start = std::time::Instant::now();
+ let path = find_tool(tool).await?;
+ let result = check_version_at_path(&path, tool).await;
tracing::debug!(
"[perf] check_version({}) took {:?}",
tool,
diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rs
index be8813dd..1c7a1f48 100644
--- a/src-tauri/omniget-core/src/core/ytdlp.rs
+++ b/src-tauri/omniget-core/src/core/ytdlp.rs
@@ -2545,15 +2545,17 @@ pub async fn download_video(
*guard = Some(dest_path);
}
}
- if line.contains("[Merger]") {
- let merging_progress = max_reported.max(95.0).min(98.0);
- if merging_progress > max_reported {
- max_reported = merging_progress;
- let _ = progress_tx
- .send(ProgressUpdate::percent(merging_progress))
- .await;
- last_send = std::time::Instant::now();
- }
+ if line.contains("[Merger]")
+ || line.contains("[FixupM3u8]")
+ || line.contains("[VideoConvertor]")
+ || (line.contains("[ffmpeg]") && line.to_lowercase().contains("merg"))
+ {
+ let merging_progress = max_reported.max(95.0).min(98.0).max(max_reported);
+ let _ = progress_tx
+ .send(ProgressUpdate::phase("merging", merging_progress))
+ .await;
+ max_reported = max_reported.max(merging_progress);
+ last_send = std::time::Instant::now();
continue;
}
if let Some(pct) = parse_progress_line(&line) {
diff --git a/src-tauri/omniget-core/src/models/progress.rs b/src-tauri/omniget-core/src/models/progress.rs
index 25420c07..c801aed0 100644
--- a/src-tauri/omniget-core/src/models/progress.rs
+++ b/src-tauri/omniget-core/src/models/progress.rs
@@ -5,6 +5,7 @@ pub struct ProgressUpdate {
pub total_bytes: Option<u64>,
pub speed_bps: Option<f64>,
pub eta_seconds: Option<u64>,
+ pub phase: Option<String>,
}
impl ProgressUpdate {
@@ -15,6 +16,14 @@ impl ProgressUpdate {
}
}
+ pub fn phase(phase: &str, percent: f64) -> Self {
+ Self {
+ percent,
+ phase: Some(phase.to_string()),
+ ..Default::default()
+ }
+ }
+
pub fn rich(
percent: f64,
downloaded_bytes: Option<u64>,
@@ -28,6 +37,7 @@ impl ProgressUpdate {
total_bytes,
speed_bps,
eta_seconds,
+ phase: None,
}
}
diff --git a/src-tauri/src/commands/dependencies.rs b/src-tauri/src/commands/dependencies.rs
index 038b3d3b..cab796e0 100644
--- a/src-tauri/src/commands/dependencies.rs
+++ b/src-tauri/src/commands/dependencies.rs
@@ -9,8 +9,12 @@ pub struct DependencyStatus {
pub name: String,
pub installed: bool,
pub version: Option<String>,
- /// `true` só quando a versão foi lida **e** é anterior ao piso conhecido.
- /// Versão ilegível não vira "desatualizado" — seria um alarme falso.
+ /// Where the binary was found: "managed" (downloaded by OmniGet),
+ /// "system" (found on the user's PATH), "flatpak", or "missing".
+ pub source: String,
+ /// Resolved absolute path to the binary, if found.
+ pub path: Option<String>,
+ /// `true` when version was read and is below supported floor.
pub outdated: bool,
}
@@ -23,9 +27,25 @@ pub struct DependencyVariantInfo {
#[tauri::command]
pub async fn check_dependencies() -> Result<Vec<DependencyStatus>, String> {
+ let (ytdlp_result, ffmpeg_result) = tokio::join!(
+ dependencies::find_tool_with_source("yt-dlp"),
+ dependencies::find_tool_with_source("ffmpeg"),
+ );
+
+ // Extract versions from the already-found paths — no second find required.
let (ytdlp_version, ffmpeg_version) = tokio::join!(
- dependencies::check_version("yt-dlp"),
- dependencies::check_version("ffmpeg"),
+ async {
+ match ytdlp_result.as_ref() {
+ Some((path, _)) => dependencies::check_version_at_path(path, "yt-dlp").await,
+ None => None,
+ }
+ },
+ async {
+ match ffmpeg_result.as_ref() {
+ Some((path, _)) => dependencies::check_version_at_path(path, "ffmpeg").await,
+ None => None,
+ }
+ },
);
let pdfium_installed = pdfium::is_installed();
@@ -35,6 +55,18 @@ pub async fn check_dependencies() -> Result<Vec<DependencyStatus>, String> {
None
};
+ let ytdlp_source = ytdlp_result
+ .as_ref()
+ .map(|(_, s)| s.to_string())
+ .unwrap_or_else(|| "missing".to_string());
+ let ytdlp_path = ytdlp_result.map(|(p, _)| p.to_string_lossy().to_string());
+
+ let ffmpeg_source = ffmpeg_result
+ .as_ref()
+ .map(|(_, s)| s.to_string())
+ .unwrap_or_else(|| "missing".to_string());
+ let ffmpeg_path = ffmpeg_result.map(|(p, _)| p.to_string_lossy().to_string());
+
let ytdlp_outdated = ytdlp_version
.as_deref()
.and_then(crate::core::ytdlp::ytdlp_version_is_supported)
@@ -46,18 +78,30 @@ pub async fn check_dependencies() -> Result<Vec<DependencyStatus>, String> {
name: "yt-dlp".into(),
installed: ytdlp_version.is_some(),
version: ytdlp_version,
+ source: ytdlp_source,
+ path: ytdlp_path,
outdated: ytdlp_outdated,
},
DependencyStatus {
name: "FFmpeg".into(),
installed: ffmpeg_version.is_some(),
version: ffmpeg_version,
+ source: ffmpeg_source,
+ path: ffmpeg_path,
outdated: false,
},
DependencyStatus {
name: "PDFium".into(),
installed: pdfium_installed,
version: pdfium_version,
+ source: if pdfium_installed {
+ "managed".into()
+ } else {
+ "missing".into()
+ },
+ path: pdfium::pdfium_target_dir()
+ .filter(|_| pdfium_installed)
+ .map(|p| p.to_string_lossy().to_string()),
outdated: false,
},
])
diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rs
index 312b417e..be485069 100644
--- a/src-tauri/src/core/queue.rs
+++ b/src-tauri/src/core/queue.rs
@@ -1,2088 +1,2092 @@
-use std::collections::HashMap;
-use std::path::PathBuf;
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::{Arc, OnceLock};
-
-static EMIT_COUNT: AtomicU64 = AtomicU64::new(0);
-
-pub fn now_ms() -> u64 {
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_millis() as u64)
- .unwrap_or(0)
-}
-
-fn append_download_log(app: &tauri::AppHandle, id: u64, line: impl AsRef<str>) {
- crate::core::download_log::push_line(id, line.as_ref());
- let _ = app.emit(
- "download-log-update",
- serde_json::json!({
- "id": id,
- }),
- );
-}
-
-use serde::Serialize;
-use tauri::{Emitter, Manager};
-use tokio::sync::mpsc;
-use tokio_util::sync::CancellationToken;
-
-fn shared_http_client() -> &'static reqwest::Client {
- static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
- CLIENT.get_or_init(|| {
- crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .build()
- .unwrap_or_default()
- })
-}
-
-use crate::core::ffmpeg::{self, MetadataEmbed};
-use crate::models::media::MediaInfo;
-use crate::platforms::traits::PlatformDownloader;
-use crate::storage::config;
-
-struct CachedInfo {
- info: MediaInfo,
- cached_at: std::time::Instant,
-}
-
-static INFO_CACHE: OnceLock<tokio::sync::Mutex<HashMap<String, CachedInfo>>> = OnceLock::new();
-
-fn info_cache() -> &'static tokio::sync::Mutex<HashMap<String, CachedInfo>> {
- INFO_CACHE.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))
-}
-
-const INFO_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(600);
-
-static IN_FLIGHT_FETCHES: OnceLock<
- tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
-> = OnceLock::new();
-
-fn in_flight_map() -> &'static tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>> {
- IN_FLIGHT_FETCHES.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))
-}
-
-#[derive(Debug, Clone, Serialize)]
-pub struct MediaPreviewEvent {
- pub url: String,
- pub title: String,
- pub author: String,
- pub thumbnail_url: Option<String>,
- pub duration_seconds: Option<f64>,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum QueueKind {
- Video,
- Audio,
- Image,
- Pdf,
- Book,
- Webpage,
- TelegramMedia,
- CourseLesson,
- Generic,
-}
-
-pub fn kind_from_platform(platform: &str) -> QueueKind {
- let p = platform.to_ascii_lowercase();
- match p.as_str() {
- "youtube" | "vimeo" | "twitch" | "bilibili" | "tiktok" | "twitter" | "x" | "instagram"
- | "reddit" | "bluesky" | "facebook" | "generic_ytdlp" => QueueKind::Video,
- "soundcloud" | "spotify" => QueueKind::Audio,
- "pinterest" => QueueKind::Image,
- "magnet" | "p2p" | "torrent" => QueueKind::Generic,
- "telegram" | "telegram_media" => QueueKind::TelegramMedia,
- "courses" | "course_lesson" => QueueKind::CourseLesson,
- "annas_archive" | "book" | "libgen" | "gutendex" => QueueKind::Book,
- "pdf" => QueueKind::Pdf,
- "webpage" | "embed" => QueueKind::Webpage,
- _ => QueueKind::Generic,
- }
-}
-
-#[derive(Debug, Clone, Serialize, PartialEq)]
-#[serde(tag = "type", content = "data")]
-pub enum QueueStatus {
- Queued,
- Active,
- Paused,
- Seeding,
- Complete { success: bool },
- Error { message: String, retryable: bool },
-}
-
-pub fn is_retryable_error_message(message: &str) -> bool {
- let lower = message.to_lowercase();
- if lower.contains("cancel") {
- return false;
- }
- let (category, _) = omniget_core::core::errors::classify_download_error(message);
- matches!(category, "unknown" | "rate_limited")
-}
-
-#[derive(Clone, Serialize)]
-pub struct QueueItemInfo {
- pub id: u64,
- pub url: String,
- pub platform: String,
- pub title: String,
- pub status: QueueStatus,
- pub percent: f64,
- pub speed_bytes_per_sec: f64,
- pub downloaded_bytes: u64,
- pub total_bytes: Option<u64>,
- pub file_path: Option<String>,
- pub file_size_bytes: Option<u64>,
- pub file_count: Option<u32>,
- pub thumbnail_url: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub kind: Option<QueueKind>,
- #[serde(default)]
- pub external: bool,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub eta_seconds: Option<u64>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub quality: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub download_mode: Option<String>,
-}
-
-pub struct QueueItem {
- pub id: u64,
- pub url: String,
- pub platform: String,
- pub title: String,
- pub status: QueueStatus,
- pub cancel_token: CancellationToken,
- pub output_dir: String,
- pub download_mode: Option<String>,
- pub quality: Option<String>,
- pub format_id: Option<String>,
- pub referer: Option<String>,
- pub extra_headers: Option<std::collections::HashMap<String, String>>,
- pub page_url: Option<String>,
- pub user_agent: Option<String>,
- pub percent: f64,
- pub speed_bytes_per_sec: f64,
- pub downloaded_bytes: u64,
- pub total_bytes: Option<u64>,
- pub file_path: Option<String>,
- pub file_size_bytes: Option<u64>,
- pub file_count: Option<u32>,
- pub media_info: Option<MediaInfo>,
- pub downloader: Arc<dyn PlatformDownloader>,
- pub ytdlp_path: Option<PathBuf>,
- pub from_hotkey: bool,
- pub torrent_id: Option<usize>,
- pub kind: Option<QueueKind>,
- pub external: bool,
- pub thumbnail_url_override: Option<String>,
- pub retry_count: u32,
- pub max_retries: u32,
- pub resume_state: Option<serde_json::Value>,
- pub concurrent_segments: Option<usize>,
- pub segment_size_bytes: Option<u64>,
- pub eta_seconds: Option<u64>,
- pub cookie_slug: Option<String>,
- pub custom_ytdlp_args: Option<Vec<String>>,
- pub torrent_files: Option<Vec<usize>>,
- pub scheduled_at_ms: Option<u64>,
- pub stop_at_ms: Option<u64>,
-}
-
-impl QueueItem {
- pub fn to_info(&self) -> QueueItemInfo {
- QueueItemInfo {
- id: self.id,
- url: self.url.clone(),
- platform: self.platform.clone(),
- title: self.title.clone(),
- status: self.status.clone(),
- percent: self.percent,
- speed_bytes_per_sec: self.speed_bytes_per_sec,
- downloaded_bytes: self.downloaded_bytes,
- total_bytes: self.total_bytes,
- file_path: self.file_path.clone(),
- file_size_bytes: self.file_size_bytes,
- file_count: self.file_count,
- thumbnail_url: self.thumbnail_url_override.clone().or_else(|| {
- self.media_info
- .as_ref()
- .and_then(|m| m.thumbnail_url.clone())
- }),
- kind: self.kind,
- external: self.external,
- eta_seconds: self.eta_seconds,
- quality: self.quality.clone(),
- download_mode: self.download_mode.clone(),
- }
- }
-}
-
-pub struct DownloadQueue {
- pub items: Vec<QueueItem>,
- pub max_concurrent: u32,
- pub stagger_delay_ms: u64,
- pub default_max_retries: u32,
-}
-
-impl DownloadQueue {
- pub fn new(max_concurrent: u32) -> Self {
- Self {
- items: Vec::new(),
- max_concurrent,
- stagger_delay_ms: 150,
- default_max_retries: 3,
- }
- }
-
- #[allow(clippy::too_many_arguments)]
- pub fn enqueue(
- &mut self,
- id: u64,
- url: String,
- platform: String,
- title: String,
- output_dir: String,
- download_mode: Option<String>,
- quality: Option<String>,
- format_id: Option<String>,
- referer: Option<String>,
- extra_headers: Option<std::collections::HashMap<String, String>>,
- page_url: Option<String>,
- user_agent: Option<String>,
- media_info: Option<MediaInfo>,
- total_bytes: Option<u64>,
- file_count: Option<u32>,
- downloader: Arc<dyn PlatformDownloader>,
- ytdlp_path: Option<PathBuf>,
- from_hotkey: bool,
- cookie_slug: Option<String>,
- custom_ytdlp_args: Option<Vec<String>>,
- torrent_files: Option<Vec<usize>>,
- scheduled_at_ms: Option<u64>,
- stop_at_ms: Option<u64>,
- ) {
- let computed_kind = Some(kind_from_platform(&platform));
- let item = QueueItem {
- id,
- url,
- platform,
- title,
- status: QueueStatus::Queued,
- cancel_token: CancellationToken::new(),
- output_dir,
- download_mode,
- quality,
- format_id,
- referer,
- extra_headers,
- page_url,
- user_agent,
- percent: 0.0,
- speed_bytes_per_sec: 0.0,
- downloaded_bytes: 0,
- total_bytes,
- file_path: None,
- file_size_bytes: None,
- file_count,
- media_info,
- downloader,
- ytdlp_path,
- from_hotkey,
- torrent_id: None,
- kind: computed_kind,
- external: false,
- thumbnail_url_override: None,
- retry_count: 0,
- max_retries: self.default_max_retries,
- resume_state: None,
- concurrent_segments: None,
- segment_size_bytes: None,
- eta_seconds: None,
- cookie_slug,
- custom_ytdlp_args,
- torrent_files,
- scheduled_at_ms,
- stop_at_ms,
- };
- crate::core::recovery::persist(crate::core::recovery::RecoveryItem {
- id: item.id,
- url: item.url.clone(),
- title: item.title.clone(),
- platform: item.platform.clone(),
- output_dir: item.output_dir.clone(),
- download_mode: item.download_mode.clone(),
- quality: item.quality.clone(),
- format_id: item.format_id.clone(),
- referer: item.referer.clone(),
- });
- self.items.push(item);
- }
-
- pub fn hydrate_from_history(&mut self) {
- let entries = crate::core::queue_history::list();
- if entries.is_empty() {
- return;
- }
- let placeholder: Arc<dyn PlatformDownloader> =
- Arc::new(crate::platforms::noop::NoopDownloader::new());
- for entry in entries.iter().rev() {
- if self.items.iter().any(|i| i.id == entry.id) {
- continue;
- }
- let status = if entry.success {
- QueueStatus::Complete { success: true }
- } else {
- let msg = entry.error.clone().unwrap_or_default();
- let retryable = is_retryable_error_message(&msg);
- QueueStatus::Error {
- message: msg,
- retryable,
- }
- };
- let percent = if entry.success { 100.0 } else { 0.0 };
- let item = QueueItem {
- id: entry.id,
- url: entry.url.clone(),
- platform: entry.platform.clone(),
- title: entry.title.clone(),
- status,
- cancel_token: CancellationToken::new(),
- output_dir: entry
- .file_path
- .as_ref()
- .and_then(|p| {
- std::path::Path::new(p)
- .parent()
- .map(|x| x.to_string_lossy().to_string())
- })
- .unwrap_or_default(),
- download_mode: None,
- quality: None,
- format_id: None,
- referer: None,
- extra_headers: None,
- page_url: None,
- user_agent: None,
- percent,
- speed_bytes_per_sec: 0.0,
- downloaded_bytes: entry.file_size_bytes.unwrap_or(0),
- total_bytes: entry.total_bytes,
- file_path: entry.file_path.clone(),
- file_size_bytes: entry.file_size_bytes,
- file_count: None,
- media_info: None,
- downloader: placeholder.clone(),
- ytdlp_path: None,
- from_hotkey: false,
- torrent_id: None,
- kind: entry.kind,
- external: false,
- thumbnail_url_override: entry.thumbnail_url.clone(),
- retry_count: 0,
- max_retries: 0,
- resume_state: None,
- concurrent_segments: None,
- segment_size_bytes: None,
- eta_seconds: None,
- cookie_slug: None,
- custom_ytdlp_args: None,
- torrent_files: None,
- scheduled_at_ms: None,
- stop_at_ms: None,
- };
- self.items.push(item);
- }
- }
-
- pub fn active_count(&self) -> u32 {
- self.items
- .iter()
- .filter(|i| i.status == QueueStatus::Active)
- .count() as u32
- }
-
- pub fn next_queued_ids(&self) -> Vec<u64> {
- let slots = self.max_concurrent.saturating_sub(self.active_count()) as usize;
- let now = now_ms();
- self.items
- .iter()
- .filter(|i| i.status == QueueStatus::Queued)
- .filter(|i| i.scheduled_at_ms.map(|t| now >= t).unwrap_or(true))
- .take(slots)
- .map(|i| i.id)
- .collect()
- }
-
- pub fn next_available_id(&self, preferred: u64) -> u64 {
- let mut id = preferred;
- while self.items.iter().any(|i| i.id == id) {
- id = id.saturating_add(1);
- }
- id
- }
-
- pub fn mark_active(&mut self, id: u64) {
- if let Some(item) = self
- .items
- .iter_mut()
- .find(|i| i.id == id && i.status == QueueStatus::Queued)
- {
- item.status = QueueStatus::Active;
- item.cancel_token = CancellationToken::new();
- }
- }
-
- pub fn mark_complete(
- &mut self,
- id: u64,
- success: bool,
- error: Option<String>,
- file_path: Option<String>,
- file_size_bytes: Option<u64>,
- ) {
- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
- let error_for_history = error.clone();
- if success {
- item.status = QueueStatus::Complete { success: true };
- item.percent = 100.0;
- } else {
- let msg = error.unwrap_or_default();
- let retryable = is_retryable_error_message(&msg);
- item.status = QueueStatus::Error {
- message: msg,
- retryable,
- };
- }
- item.file_path = file_path;
- item.file_size_bytes = file_size_bytes;
- item.speed_bytes_per_sec = 0.0;
- item.eta_seconds = None;
- crate::core::recovery::remove(id);
-
- if !item.external {
- let entry = crate::core::queue_history::HistoryEntry {
- id: item.id,
- url: item.url.clone(),
- platform: item.platform.clone(),
- title: item.title.clone(),
- file_path: item.file_path.clone(),
- file_size_bytes: item.file_size_bytes,
- total_bytes: item.total_bytes,
- success,
- error: if success { None } else { error_for_history },
- completed_at: crate::core::queue_history::now_unix_seconds(),
- thumbnail_url: item.thumbnail_url_override.clone().or_else(|| {
- item.media_info
- .as_ref()
- .and_then(|m| m.thumbnail_url.clone())
- }),
- kind: item.kind,
- };
- crate::core::queue_history::record(entry);
- }
- }
- }
-
- pub fn mark_seeding(
- &mut self,
- id: u64,
- file_path: Option<String>,
- file_size_bytes: Option<u64>,
- torrent_id: Option<usize>,
- ) {
- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
- item.status = QueueStatus::Seeding;
- item.percent = 100.0;
- item.file_path = file_path;
- item.file_size_bytes = file_size_bytes;
- item.speed_bytes_per_sec = 0.0;
- item.torrent_id = torrent_id;
- crate::core::recovery::remove(id);
- }
- }
-
- pub fn update_progress(
- &mut self,
- id: u64,
- percent: f64,
- speed: f64,
- downloaded: u64,
- total: Option<u64>,
- torrent_id: Option<usize>,
- eta_seconds: Option<u64>,
- ) {
- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
- if item.status != QueueStatus::Active {
- if torrent_id.is_some() && item.torrent_id.is_none() {
- item.torrent_id = torrent_id;
- }
- return;
- }
- item.percent = percent;
- item.speed_bytes_per_sec = speed;
- item.downloaded_bytes = downloaded;
- if let Some(t) = total {
- item.total_bytes = Some(t);
- }
- if torrent_id.is_some() && item.torrent_id.is_none() {
- item.torrent_id = torrent_id;
- }
- item.eta_seconds = eta_seconds;
- }
- }
-
- pub fn pause(&mut self, id: u64) -> bool {
- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
- if item.status == QueueStatus::Active {
- if item.platform != "magnet"
- && !omniget_core::core::ytdlp::pause_download_process(id)
- {
- return false;
- }
- item.status = QueueStatus::Paused;
- item.speed_bytes_per_sec = 0.0;
- item.eta_seconds = None;
- return true;
- }
- }
- false
- }
-
- pub fn resume(&mut self, id: u64) -> bool {
- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
- if item.status == QueueStatus::Paused {
- if item.platform != "magnet"
- && !omniget_core::core::ytdlp::resume_download_process(id)
- {
- return false;
- }
- item.status = QueueStatus::Active;
- return true;
- }
- }
- false
- }
-
- pub fn pause_all(&mut self) -> Vec<(u64, Option<usize>)> {
- let mut paused = Vec::new();
- for item in self.items.iter_mut() {
- if item.status == QueueStatus::Active {
- if item.platform != "magnet"
- && !omniget_core::core::ytdlp::pause_download_process(item.id)
- {
- continue;
- }
- item.status = QueueStatus::Paused;
- item.speed_bytes_per_sec = 0.0;
- item.eta_seconds = None;
- paused.push((item.id, item.torrent_id));
- }
- }
- paused
- }
-
- pub fn resume_all(&mut self) -> Vec<(u64, Option<usize>)> {
- let mut resumed = Vec::new();
- for item in self.items.iter_mut() {
- if item.status == QueueStatus::Paused {
- let tid = item.torrent_id;
- if item.platform != "magnet"
- && !omniget_core::core::ytdlp::resume_download_process(item.id)
- {
- continue;
- }
- item.status = QueueStatus::Active;
- resumed.push((item.id, tid));
- }
- }
- resumed
- }
-
- pub fn reorder(&mut self, ids_in_order: Vec<u64>) -> bool {
- let mut slots: Vec<Option<QueueItem>> = self.items.drain(..).map(Some).collect();
-
- let queued_slot_indices: Vec<usize> = slots
- .iter()
- .enumerate()
- .filter_map(|(idx, slot)| {
- slot.as_ref()
- .filter(|i| i.status == QueueStatus::Queued)
- .map(|_| idx)
- })
- .collect();
-
- if queued_slot_indices.is_empty() {
- self.items = slots.into_iter().flatten().collect();
- return false;
- }
-
- let queued_id_to_slot: std::collections::HashMap<u64, usize> = queued_slot_indices
- .iter()
- .map(|idx| (slots[*idx].as_ref().unwrap().id, *idx))
- .collect();
-
- let mut new_queued_order: Vec<QueueItem> = Vec::with_capacity(queued_slot_indices.len());
- let mut seen: std::collections::HashSet<u64> = std::collections::HashSet::new();
-
- for id in &ids_in_order {
- if seen.contains(id) {
- continue;
- }
- if let Some(slot_idx) = queued_id_to_slot.get(id) {
- if let Some(item) = slots[*slot_idx].take() {
- new_queued_order.push(item);
- seen.insert(*id);
- }
- }
- }
- for idx in &queued_slot_indices {
- if let Some(item) = slots[*idx].take() {
- new_queued_order.push(item);
- }
- }
-
- let mut iter = new_queued_order.into_iter();
- let mut rebuilt: Vec<QueueItem> = Vec::with_capacity(slots.len());
- for (idx, slot) in slots.into_iter().enumerate() {
- if queued_slot_indices.contains(&idx) {
- if let Some(item) = iter.next() {
- rebuilt.push(item);
- }
- } else if let Some(item) = slot {
- rebuilt.push(item);
- }
- }
- rebuilt.extend(iter);
- self.items = rebuilt;
- true
- }
-
- /// Cancel an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).
- pub fn cancel(&mut self, id: u64) -> (bool, Option<usize>) {
- let result = self.cancel_inner(id);
- if result.0 {
- crate::core::recovery::remove(id);
- }
- result
- }
-
- fn cancel_inner(&mut self, id: u64) -> (bool, Option<usize>) {
- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
- match &item.status {
- QueueStatus::Active => {
- item.cancel_token.cancel();
- item.status = QueueStatus::Error {
- message: "Cancelled".to_string(),
- retryable: false,
- };
- item.speed_bytes_per_sec = 0.0;
- return (true, None);
- }
- QueueStatus::Seeding => {
- let tid = item.torrent_id;
- item.status = QueueStatus::Error {
- message: "Cancelled".to_string(),
- retryable: false,
- };
- item.speed_bytes_per_sec = 0.0;
- return (true, tid);
- }
- QueueStatus::Paused => {
- // For magnet downloads, the cancel_token was not cancelled during pause,
- // so we must cancel it now to stop the background download loop.
- // Also return the torrent_id for session cleanup.
- item.cancel_token.cancel();
- let tid = if item.platform == "magnet" {
- item.torrent_id
- } else {
- None
- };
- item.status = QueueStatus::Error {
- message: "Cancelled".to_string(),
- retryable: false,
- };
- item.speed_bytes_per_sec = 0.0;
- return (true, tid);
- }
- QueueStatus::Queued => {
- item.status = QueueStatus::Error {
- message: "Cancelled".to_string(),
- retryable: false,
- };
- return (true, None);
- }
- _ => {}
- }
- }
- (false, None)
- }
-
- pub fn retry(&mut self, id: u64) -> bool {
- if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
- if matches!(item.status, QueueStatus::Error { .. }) {
- item.status = QueueStatus::Queued;
- item.cancel_token = CancellationToken::new();
- item.percent = 0.0;
- item.speed_bytes_per_sec = 0.0;
- item.downloaded_bytes = 0;
- item.file_path = None;
- item.file_size_bytes = None;
- item.retry_count = 0;
- return true;
- }
- }
- false
- }
-
- /// Remove an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).
- pub fn remove(&mut self, id: u64) -> Option<Option<usize>> {
- let result = self.remove_inner(id);
- if result.is_some() {
- crate::core::recovery::remove(id);
- crate::core::queue_history::remove(id);
- }
- result
- }
-
- fn remove_inner(&mut self, id: u64) -> Option<Option<usize>> {
- if let Some(pos) = self.items.iter().position(|i| i.id == id) {
- let item = &self.items[pos];
- if item.status == QueueStatus::Active {
- item.cancel_token.cancel();
- }
- // For paused magnet items, the cancel_token was not cancelled during pause
- if item.status == QueueStatus::Paused && item.platform == "magnet" {
- item.cancel_token.cancel();
- }
- let torrent_id = if item.status == QueueStatus::Seeding
- || (item.status == QueueStatus::Paused && item.platform == "magnet")
- {
- item.torrent_id
- } else {
- None
- };
- self.items.remove(pos);
- return Some(torrent_id);
- }
- None
- }
-
- pub fn clear_finished(&mut self) {
- let to_remove: Vec<u64> = self
- .items
- .iter()
- .filter(|i| matches!(i.status, QueueStatus::Complete { .. }))
- .map(|i| i.id)
- .collect();
- for id in &to_remove {
- crate::core::recovery::remove(*id);
- crate::core::queue_history::remove(*id);
- }
- self.items
- .retain(|i| !matches!(i.status, QueueStatus::Complete { .. }));
- }
-
- pub fn get_state(&self) -> Vec<QueueItemInfo> {
- self.items.iter().map(|i| i.to_info()).collect()
- }
-
- pub fn has_url(&self, url: &str) -> bool {
- self.items.iter().any(|i| {
- i.url == url
- && matches!(
- i.status,
- QueueStatus::Queued
- | QueueStatus::Active
- | QueueStatus::Paused
- | QueueStatus::Seeding
- )
- })
- }
-}
-
-pub struct ProgressThrottle {
- last_emit: std::time::Instant,
- min_interval: std::time::Duration,
-}
-
-impl ProgressThrottle {
- pub fn new(min_interval_ms: u64) -> Self {
- Self {
- last_emit: std::time::Instant::now() - std::time::Duration::from_secs(10),
- min_interval: std::time::Duration::from_millis(min_interval_ms),
- }
- }
-
- pub fn should_emit(&mut self) -> bool {
- let now = std::time::Instant::now();
- if now.duration_since(self.last_emit) >= self.min_interval {
- self.last_emit = now;
- true
- } else {
- false
- }
- }
-}
-
-#[derive(Clone, Serialize)]
-pub struct QueueItemProgress {
- pub id: u64,
- pub title: String,
- pub platform: String,
- pub percent: f64,
- pub speed_bytes_per_sec: f64,
- pub downloaded_bytes: u64,
- pub total_bytes: Option<u64>,
- pub phase: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub eta_seconds: Option<u64>,
-}
-
-pub fn emit_queue_state_from_state(app: &tauri::AppHandle, state: Vec<QueueItemInfo>) {
- let n = EMIT_COUNT.fetch_add(1, Ordering::Relaxed);
- if n.is_multiple_of(10) {
- tracing::debug!("[perf] emit_queue_state called {} times", n);
- }
- let _ = app.emit("queue-state-update", &state);
- let total = crate::tray::compute_total_active(app);
- crate::tray::update_active_count(app, total);
- crate::core::awake::sync(total > 0);
-
- let active_items: Vec<_> = state
- .iter()
- .filter(|i| i.status == QueueStatus::Active)
- .collect();
- let avg_percent = if !active_items.is_empty() {
- let sum: f64 = active_items.iter().map(|i| i.percent).sum();
- sum / active_items.len() as f64 / 100.0
- } else {
- 0.0
- };
- let total_speed: f64 = active_items.iter().map(|i| i.speed_bytes_per_sec).sum();
- crate::tray::update_speed_tooltip(app, total, total_speed);
- crate::tray::update_taskbar_badge(app, total, avg_percent);
-
- if let Some(window) = app.get_webview_window("main") {
- let title = if total > 0 {
- format!("({}) omniget", total)
- } else {
- "omniget".into()
- };
- let _ = window.set_title(&title);
- }
-}
-
-pub fn emit_queue_state(app: &tauri::AppHandle, queue: &DownloadQueue) {
- let state = queue.get_state();
- emit_queue_state_from_state(app, state);
-}
-
-/// RAII guard that ensures an Active queue item never leaks a slot.
-///
-/// If the download future panics or is dropped before reaching `mark_complete`
-/// / `mark_seeding`, the Drop impl spawns a task that transitions the item to
-/// Error("Download interrupted") and calls `try_start_next`, unblocking the
-/// queue.
-///
-/// When the download reaches a terminal state through the normal paths, the
-/// guard sees the item is no longer Active and does nothing (idempotent).
-struct ActiveJobSlot {
- app: tauri::AppHandle,
- queue: Arc<tokio::sync::Mutex<DownloadQueue>>,
- item_id: u64,
- armed: bool,
-}
-
-impl ActiveJobSlot {
- fn new(
- app: tauri::AppHandle,
- queue: Arc<tokio::sync::Mutex<DownloadQueue>>,
- item_id: u64,
- ) -> Self {
- Self {
- app,
- queue,
- item_id,
- armed: true,
- }
- }
-
- fn disarm(mut self) {
- self.armed = false;
- }
-}
-
-impl Drop for ActiveJobSlot {
- fn drop(&mut self) {
- if !self.armed {
- return;
- }
- let app = self.app.clone();
- let queue = self.queue.clone();
- let item_id = self.item_id;
- tokio::spawn(async move {
- let state = {
- let mut q = queue.lock().await;
- let still_active = q
- .items
- .iter()
- .find(|i| i.id == item_id)
- .map(|i| i.status == QueueStatus::Active)
- .unwrap_or(false);
- if !still_active {
- return;
- }
- tracing::warn!(
- "[queue] ActiveJobSlot guard firing for {} — download ended without clean release",
- item_id
- );
- q.mark_complete(
- item_id,
- false,
- Some("Download interrupted".to_string()),
- None,
- None,
- );
- q.get_state()
- };
- emit_queue_state_from_state(&app, state);
- try_start_next(app, queue).await;
- });
- }
-}
-
-pub fn spawn_download(
- app: tauri::AppHandle,
- queue: Arc<tokio::sync::Mutex<DownloadQueue>>,
- item_id: u64,
-) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
- Box::pin(async move {
- let _timer_start = std::time::Instant::now();
- let slot = ActiveJobSlot::new(app.clone(), queue.clone(), item_id);
- spawn_download_inner(app, queue, item_id).await;
- slot.disarm();
- tracing::debug!(
- "[perf] spawn_download {} took {:?}",
- item_id,
- _timer_start.elapsed()
- );
- })
-}
-
-async fn spawn_download_inner(
- app: tauri::AppHandle,
- queue: Arc<tokio::sync::Mutex<DownloadQueue>>,
- item_id: u64,
-) {
- tracing::info!("[queue] download {} started", item_id);
-
- let _ = app.emit(
- "queue-item-progress",
- &QueueItemProgress {
- id: item_id,
- title: "".to_string(),
- platform: "".to_string(),
- percent: 0.0,
- speed_bytes_per_sec: 0.0,
- downloaded_bytes: 0,
- total_bytes: None,
- phase: "preparing".to_string(),
- eta_seconds: None,
- },
- );
-
- let host_key = {
- let q = queue.lock().await;
- q.items
- .iter()
- .find(|i| i.id == item_id)
- .map(|i| crate::core::host_limiter::host_key_for_url(&i.url))
- };
- let _host_lease = match host_key {
- Some(key) => Some(crate::core::host_limiter::acquire(&key).await),
- None => None,
- };
-
- let (
- url,
- output_dir,
- download_mode,
- quality,
- format_id,
- referer,
- extra_headers,
- page_url,
- user_agent,
- cancel_token,
- media_info,
- platform_name,
- downloader,
- ytdlp_path,
- from_hotkey,
- cookie_slug,
- custom_ytdlp_args,
- torrent_files,
- ) = {
- let q = queue.lock().await;
- let item = match q.items.iter().find(|i| i.id == item_id) {
- Some(i) => i,
- None => return,
- };
- (
- item.url.clone(),
- item.output_dir.clone(),
- item.download_mode.clone(),
- item.quality.clone(),
- item.format_id.clone(),
- item.referer.clone(),
- item.extra_headers.clone(),
- item.page_url.clone(),
- item.user_agent.clone(),
- item.cancel_token.clone(),
- item.media_info.clone(),
- item.platform.clone(),
- item.downloader.clone(),
- item.ytdlp_path.clone(),
- item.from_hotkey,
- item.cookie_slug.clone(),
- item.custom_ytdlp_args.clone(),
- item.torrent_files.clone(),
- )
- };
-
- {
- let settings = crate::storage::config::load_settings(&app);
- let proxy = settings.proxy.clone();
- crate::core::http_client::init_proxy(proxy.clone());
- let proxy_status = if !proxy.enabled {
- "disabled; system/env proxy honored if set".to_string()
- } else if proxy.host.trim().is_empty() {
- "enabled but host is empty; falling back to system/env proxy".to_string()
- } else {
- format!(
- "enabled; {}://{}:{}",
- proxy.proxy_type, proxy.host, proxy.port
- )
- };
- append_download_log(
- &app,
- item_id,
- format!("[network] proxy setting: {}", proxy_status),
- );
- }
-
- let info_start = std::time::Instant::now();
- let info = match media_info {
- Some(i) if !i.available_qualities.is_empty() => {
- tracing::info!(
- "[queue] info for {} from cache/pre-fetched in {:?}",
- item_id,
- info_start.elapsed()
- );
- append_download_log(
- &app,
- item_id,
- format!(
- "[omniget] using cached video info: platform={} title=\"{}\"",
- platform_name, i.title
- ),
- );
- i
- }
- _ => {
- tracing::debug!(
- "[perf] spawn_download_inner {}: media_info is None, fetching info",
- item_id
- );
- append_download_log(
- &app,
- item_id,
- format!(
- "[omniget] fetching video info: platform={} url={}",
- platform_name, url
- ),
- );
- if let Some(slug) = cookie_slug.as_deref() {
- append_download_log(
- &app,
- item_id,
- format!("[cookies] selected managed cookie account: {}", slug),
- );
- }
- let _ = app.emit(
- "queue-item-progress",
- &QueueItemProgress {
- id: item_id,
- title: url.clone(),
- platform: platform_name.clone(),
- percent: 0.0,
- speed_bytes_per_sec: 0.0,
- downloaded_bytes: 0,
- total_bytes: None,
- phase: "fetching_info".to_string(),
- eta_seconds: None,
- },
- );
-
- let info_future =
- fetch_and_cache_info(&url, &*downloader, &platform_name, ytdlp_path.as_deref());
- let scoped_info_future = omniget_core::core::log_hook::CURRENT_COOKIE_SLUG.scope(
- cookie_slug.clone(),
- omniget_core::core::log_hook::CURRENT_DOWNLOAD_ID.scope(item_id, info_future),
- );
- let info_timeout_secs = if platform_name == "youtube"
- || url.to_ascii_lowercase().contains("youtube.com")
- || url.to_ascii_lowercase().contains("youtu.be")
- {
- omniget_core::core::ytdlp::YOUTUBE_VIDEO_INFO_TOTAL_TIMEOUT_SECS
- } else if platform_name == "douyin" {
- 30
- } else {
- omniget_core::core::ytdlp::DEFAULT_VIDEO_INFO_TOTAL_TIMEOUT_SECS
- };
- let info_result = tokio::time::timeout(
- std::time::Duration::from_secs(info_timeout_secs),
- scoped_info_future,
- )
- .await;
-
- match info_result {
- Ok(Ok(i)) => {
- append_download_log(
- &app,
- item_id,
- format!(
- "[omniget] video info fetched in {:.1}s: title=\"{}\"",
- info_start.elapsed().as_secs_f64(),
- i.title
- ),
- );
- i
- }
- Ok(Err(e)) => {
- append_download_log(
- &app,
- item_id,
- format!(
- "[omniget] failed fetching video info after {:.1}s: {}",
- info_start.elapsed().as_secs_f64(),
- e
- ),
- );
- let state = {
- let mut q = queue.lock().await;
- q.mark_complete(item_id, false, Some(e.to_string()), None, None);
- q.get_state()
- };
- emit_queue_state_from_state(&app, state);
- try_start_next(app, queue).await;
- return;
- }
- Err(_) => {
- tracing::warn!(
- "[queue] info fetch timed out for {} after {}s",
- item_id,
- info_timeout_secs
- );
- append_download_log(
- &app,
- item_id,
- format!(
- "[omniget] video info timed out after {}s",
- info_timeout_secs
- ),
- );
- let state = {
- let mut q = queue.lock().await;
- q.mark_complete(
- item_id,
- false,
- Some("Timed out fetching video info".to_string()),
- None,
- None,
- );
- q.get_state()
- };
- emit_queue_state_from_state(&app, state);
- try_start_next(app, queue).await;
- return;
- }
- }
- }
- };
- tracing::info!(
- "[queue] info fetch for {} took {:?}",
- item_id,
- info_start.elapsed()
- );
-
- let mut info = info;
- if is_generic_title(&info.title) {
- let pokemon = omniget_core::core::pokemon_names::random_pokemon_name();
- info.title = format!("video_{}", pokemon);
- }
-
- let state = {
- let mut q = queue.lock().await;
- if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {
- item.title = info.title.clone();
- item.total_bytes = info.file_size_bytes;
- let fc = if info.media_type == crate::models::media::MediaType::Carousel
- || info.media_type == crate::models::media::MediaType::Playlist
- {
- info.available_qualities.len() as u32
- } else {
- 1
- };
- item.file_count = Some(fc);
- item.media_info = Some(info.clone());
- }
- q.get_state()
- };
- emit_queue_state_from_state(&app, state);
-
- let _ = app.emit(
- "queue-item-progress",
- &QueueItemProgress {
- id: item_id,
- title: info.title.clone(),
- platform: platform_name.clone(),
- percent: 0.5,
- speed_bytes_per_sec: 0.0,
- downloaded_bytes: 0,
- total_bytes: info.file_size_bytes,
- phase: "starting".to_string(),
- eta_seconds: None,
- },
- );
-
- let settings = config::load_settings(&app);
- let tmpl = settings.download.filename_template.clone();
- let mut final_output_dir = std::path::PathBuf::from(&output_dir);
- if settings.download.organize_by_platform {
- final_output_dir = final_output_dir.join(&platform_name);
- }
- let torrent_id_slot = Arc::new(tokio::sync::Mutex::new(None));
- let audio_format = if download_mode.as_deref() == Some("audio") {
- Some(settings.download.music_audio_format.clone())
- } else {
- None
- };
- let custom_ytdlp_args = {
- let mut args = custom_ytdlp_args.clone();
- if settings.download.skip_existing {
- let flags = args.get_or_insert_with(Vec::new);
- if !flags.iter().any(|f| f == "--no-overwrites") {
- flags.push("--no-overwrites".to_string());
- }
- }
- args
- };
- let opts = crate::models::media::DownloadOptions {
- quality: quality.or_else(|| Some(settings.download.video_quality.clone())),
- output_dir: final_output_dir,
- filename_template: Some(tmpl),
- download_subtitles: settings.download.download_subtitles,
- include_auto_subtitles: settings.download.include_auto_subtitles,
- download_mode,
- audio_format,
- format_id,
- referer,
- extra_headers,
- page_url,
- user_agent,
- cancel_token: cancel_token.clone(),
- concurrent_fragments: settings.advanced.concurrent_fragments,
- ytdlp_path,
- torrent_listen_port: Some(settings.advanced.torrent_listen_port),
- torrent_id_slot: Some(torrent_id_slot.clone()),
- custom_ytdlp_args: custom_ytdlp_args.clone(),
- torrent_files: torrent_files.clone(),
- torrent_auto_trackers: settings.advanced.torrent_auto_trackers,
- torrent_upnp: settings.advanced.torrent_upnp,
- };
-
- let total_bytes = info.file_size_bytes;
- let item_title = info.title.clone();
- let log_title = item_title.clone();
- let item_platform = platform_name.clone();
- let (tx, mut rx) = mpsc::channel::<omniget_core::models::progress::ProgressUpdate>(32);
-
- let app_progress = app.clone();
- let queue_progress = queue.clone();
- let torrent_id_slot_progress = torrent_id_slot.clone();
- let progress_forwarder = tokio::spawn(async move {
- const STALL_AFTER: std::time::Duration = std::time::Duration::from_secs(6);
-
- let mut last_bytes: u64 = 0;
- let mut last_time = std::time::Instant::now();
- let mut throttle = ProgressThrottle::new(250);
- let mut current_speed: f64 = 0.0;
- let mut last_percent: f64 = 0.0;
- let mut last_advance = std::time::Instant::now();
- let mut stalled = false;
-
- loop {
- let update = tokio::select! {
- msg = rx.recv() => match msg {
- Some(u) => u,
- None => break,
- },
- _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {
- if !stalled && last_advance.elapsed() >= STALL_AFTER {
- stalled = true;
- current_speed = 0.0;
- {
- let mut q = queue_progress.lock().await;
- let tid = { *torrent_id_slot_progress.lock().await };
- q.update_progress(
- item_id, last_percent, 0.0, last_bytes, total_bytes, tid, None,
- );
- }
- let _ = app_progress.emit(
- "queue-item-progress",
- &QueueItemProgress {
- id: item_id,
- title: item_title.clone(),
- platform: item_platform.clone(),
- percent: last_percent,
- speed_bytes_per_sec: 0.0,
- downloaded_bytes: last_bytes,
- total_bytes,
- phase: "stalled".to_string(),
- eta_seconds: None,
- },
- );
- }
- continue;
- }
- };
-
- let percent = update.percent;
- if !throttle.should_emit() && percent < 100.0 && !update.has_real_metrics() {
- continue;
- }
-
- let now = std::time::Instant::now();
- let resolved_total = update.total_bytes.or(total_bytes);
- let mut clamped = percent.clamp(0.0, 100.0);
- if percent >= 0.0 && percent < 100.0 {
- if clamped < last_percent {
- clamped = last_percent;
- }
-
- let metric_percent = update.downloaded_bytes.and_then(|downloaded| {
- resolved_total
- .filter(|total| *total > 0)
- .map(|total| (downloaded as f64 / total as f64 * 100.0).clamp(0.0, 100.0))
- });
-
- if let Some(metric) = metric_percent {
- let metric_ceiling = (metric + 15.0).max(last_percent);
- if clamped > metric_ceiling {
- clamped = metric_ceiling;
- }
- } else {
- let max_step = if update.has_real_metrics() { 12.0 } else { 6.0 };
- let ceiling = (last_percent + max_step).min(99.0);
- if clamped > ceiling {
- clamped = ceiling;
- }
- }
- }
-
- let mut downloaded_bytes = update.downloaded_bytes.unwrap_or_else(|| {
- resolved_total
- .map(|total| (clamped / 100.0 * total as f64) as u64)
- .unwrap_or(last_bytes)
- });
- if downloaded_bytes < last_bytes && percent < 100.0 {
- downloaded_bytes = last_bytes;
- }
-
- if let Some(real) = update.speed_bps {
- current_speed = real;
- } else if downloaded_bytes > last_bytes {
- let dt = now.duration_since(last_time).as_secs_f64();
- if dt > 0.1 {
- let instant_speed = (downloaded_bytes - last_bytes) as f64 / dt;
- current_speed = if current_speed > 0.0 {
- current_speed * 0.7 + instant_speed * 0.3
- } else {
- instant_speed
- };
- }
- }
-
- if downloaded_bytes > last_bytes || clamped > last_percent || update.speed_bps.is_some()
- {
- last_advance = now;
- stalled = false;
- }
- last_bytes = downloaded_bytes;
- last_time = now;
- last_percent = clamped;
-
- let phase_value = if percent < 0.0 { percent } else { clamped };
- let phase = match phase_value {
- p if p < -1.5 => "connecting",
- p if p < -0.5 => "starting",
- p if p > 99.5 => "finalizing",
- p if p > 0.0 => "downloading",
- _ => "starting",
- };
-
- let eta_seconds = update
- .eta_seconds
- .or_else(|| omniget_core::core::ytdlp::get_eta(item_id))
- .or_else(|| {
- if current_speed > 0.0 {
- resolved_total.and_then(|total| {
- (total > downloaded_bytes)
- .then(|| ((total - downloaded_bytes) as f64 / current_speed) as u64)
- })
- } else {
- None
- }
- });
-
- {
- let mut q = queue_progress.lock().await;
- let tid = { *torrent_id_slot_progress.lock().await };
- q.update_progress(
- item_id,
- clamped,
- current_speed,
- downloaded_bytes,
- resolved_total,
- tid,
- eta_seconds,
- );
- }
-
- let _ = app_progress.emit(
- "queue-item-progress",
- &QueueItemProgress {
- id: item_id,
- title: item_title.clone(),
- platform: item_platform.clone(),
- percent: clamped,
- speed_bytes_per_sec: current_speed,
- downloaded_bytes,
- total_bytes: resolved_total,
- phase: phase.to_string(),
- eta_seconds,
- },
- );
- }
- omniget_core::core::ytdlp::clear_eta(item_id);
- });
-
- if let Some(ua) = opts.user_agent.clone() {
- omniget_core::core::ytdlp::register_ext_user_agent(url.clone(), ua);
- }
- if let Some(hdrs) = opts.extra_headers.clone() {
- omniget_core::core::ytdlp::register_ext_headers(url.clone(), hdrs);
- }
-
- let dl_start = std::time::Instant::now();
- append_download_log(
- &app,
- item_id,
- format!(
- "[omniget] starting download: platform={} title=\"{}\" url={}",
- platform_name, log_title, url
- ),
- );
- let dl_future = async {
- tokio::select! {
- r = downloader.download(&info, &opts, tx) => r,
- _ = cancel_token.cancelled() => {
- Err(anyhow::anyhow!("Download cancelado"))
- }
- }
- };
- let result = omniget_core::core::log_hook::CURRENT_COOKIE_SLUG
- .scope(
- cookie_slug.clone(),
- omniget_core::core::log_hook::CURRENT_DOWNLOAD_ID.scope(item_id, dl_future),
- )
- .await;
- omniget_core::core::ytdlp::clear_ext_user_agent(&url);
- omniget_core::core::ytdlp::clear_ext_headers(&url);
- tracing::info!(
- "[queue] download {} completed in {:?}",
- item_id,
- dl_start.elapsed()
- );
-
- let _ = progress_forwarder.await;
-
- let was_paused = {
- let q = queue.lock().await;
- q.items
- .iter()
- .find(|i| i.id == item_id)
- .map(|i| i.status == QueueStatus::Paused)
- .unwrap_or(false)
- };
-
- if was_paused {
- let state = {
- let q = queue.lock().await;
- q.get_state()
- };
- emit_queue_state_from_state(&app, state);
- try_start_next(app, queue).await;
- return;
- }
-
- match result {
- Ok(dl) => {
- append_download_log(
- &app,
- item_id,
- format!(
- "[omniget] download finished: path={} size={} bytes",
- dl.file_path.to_string_lossy(),
- dl.file_size_bytes
- ),
- );
- let is_seeding = platform_name == "magnet" && dl.torrent_id.is_some();
- if !is_seeding {
- if let Err(msg) = validate_download_output(&dl.file_path).await {
- tracing::error!(
- "[queue] download {} reported success but output is missing or empty: {:?}",
- item_id,
- dl.file_path
- );
- append_download_log(
- &app,
- item_id,
- format!(
- "[omniget] download reported success but output missing or empty: {}",
- dl.file_path.to_string_lossy()
- ),
- );
- let state = {
- let mut q = queue.lock().await;
- q.mark_complete(item_id, false, Some(msg), None, None);
- q.get_state()
- };
- emit_queue_state_from_state(&app, state);
- try_start_next(app, queue).await;
- return;
- }
- }
-
- if settings.download.embed_metadata
- && platform_name != "magnet"
- && ffmpeg::is_ffmpeg_available().await
- {
- let metadata = MetadataEmbed {
- title: Some(info.title.clone()),
- artist: Some(info.author.clone()),
- thumbnail_url: info.thumbnail_url.clone(),
- ..Default::default()
- };
- if let Err(e) = ffmpeg::embed_metadata(
- &dl.file_path,
- &metadata,
- settings.download.embed_thumbnail,
- shared_http_client(),
- )
- .await
- {
- tracing::warn!("Metadata embed failed for '{}': {}", info.title, e);
- }
- }
-
- if from_hotkey && settings.download.copy_to_clipboard_on_hotkey {
- #[cfg(not(target_os = "android"))]
- {
- match crate::core::clipboard::copy_file_to_clipboard(&dl.file_path).await {
- Ok(()) => {
- let _ = app.emit(
- "file-copied-to-clipboard",
- serde_json::json!({
- "path": dl.file_path.to_string_lossy(),
- }),
- );
- }
- Err(e) => {
- tracing::warn!("[clipboard] failed to copy file: {}", e);
- }
- }
- }
- }
-
- let state = {
- let mut q = queue.lock().await;
- if platform_name == "magnet" && dl.torrent_id.is_some() {
- q.mark_seeding(
- item_id,
- Some(dl.file_path.to_string_lossy().to_string()),
- Some(dl.file_size_bytes),
- dl.torrent_id,
- );
- } else {
- q.mark_complete(
- item_id,
- true,
- None,
- Some(dl.file_path.to_string_lossy().to_string()),
- Some(dl.file_size_bytes),
- );
- }
- q.get_state()
- };
- emit_queue_state_from_state(&app, state);
- }
- Err(e) => {
- let raw_err = e.to_string();
- append_download_log(
- &app,
- item_id,
- format!("[omniget] download failed: {}", raw_err),
- );
- let (category, hint) = omniget_core::core::errors::classify_download_error(&raw_err);
- let user_msg = if category != "unknown" {
- format!("{} ({})", hint, raw_err)
- } else {
- raw_err.clone()
- };
- tracing::error!(
- "Download error '{}' [{}]: {}",
- platform_name,
- category,
- raw_err
- );
-
- let retry_decision = {
- let mut q = queue.lock().await;
- if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {
- if item.downloaded_bytes > 5 * 1024 * 1024 {
- item.retry_count = 0;
- }
- let retryable = is_retryable_category(category);
- let attempt = item.retry_count;
- let max = item.max_retries;
- if retryable && attempt < max {
- item.retry_count = attempt + 1;
- Some((attempt + 1, max))
- } else {
- None
- }
- } else {
- None
- }
- };
-
- if let Some((next_attempt, max)) = retry_decision {
- let delay_secs = (1u64 << (next_attempt - 1).min(5)).min(30);
- tracing::warn!(
- "[queue] retry {}/{} for {} in {}s (category={})",
- next_attempt,
- max,
- item_id,
- delay_secs,
- category
- );
- let state = {
- let mut q = queue.lock().await;
- if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {
- item.status = QueueStatus::Queued;
- item.cancel_token = CancellationToken::new();
- item.percent = 0.0;
- item.speed_bytes_per_sec = 0.0;
- item.downloaded_bytes = 0;
- }
- q.get_state()
- };
- emit_queue_state_from_state(&app, state);
- let app_for_retry = app.clone();
- let queue_for_retry = queue.clone();
- tokio::spawn(async move {
- tokio::time::sleep(std::time::Duration::from_secs(delay_secs)).await;
- try_start_next(app_for_retry, queue_for_retry).await;
- });
- return;
- }
-
- let state = {
- let mut q = queue.lock().await;
- q.mark_complete(item_id, false, Some(user_msg), None, None);
- q.get_state()
- };
- emit_queue_state_from_state(&app, state);
- }
- }
-
- try_start_next(app, queue).await;
-}
-
-fn is_retryable_category(category: &str) -> bool {
- matches!(category, "unknown" | "rate_limited")
-}
-
-const OUTPUT_MISSING_ERROR: &str =
- "Download reported success but the file is missing or empty. Check disk space and antivirus exclusions, then retry.";
-
-async fn validate_download_output(path: &std::path::Path) -> Result<(), String> {
- if path.as_os_str().is_empty() {
- return Err(OUTPUT_MISSING_ERROR.to_string());
- }
- let meta = match tokio::fs::metadata(path).await {
- Ok(m) => m,
- Err(_) => return Err(OUTPUT_MISSING_ERROR.to_string()),
- };
- if meta.is_dir() {
- let mut entries = match tokio::fs::read_dir(path).await {
- Ok(e) => e,
- Err(_) => return Err(OUTPUT_MISSING_ERROR.to_string()),
- };
- match entries.next_entry().await {
- Ok(Some(_)) => Ok(()),
- _ => Err(OUTPUT_MISSING_ERROR.to_string()),
- }
- } else if meta.len() > 0 {
- Ok(())
- } else {
- Err(OUTPUT_MISSING_ERROR.to_string())
- }
-}
-
-async fn fetch_and_cache_info(
- url: &str,
- downloader: &dyn PlatformDownloader,
- platform: &str,
- ytdlp_path: Option<&std::path::Path>,
-) -> anyhow::Result<MediaInfo> {
- {
- let cache = info_cache().lock().await;
- if let Some(entry) = cache.get(url) {
- if entry.cached_at.elapsed() < INFO_CACHE_TTL {
- tracing::debug!("[perf] fetch_and_cache_info: cache hit for {}", platform);
- return Ok(entry.info.clone());
- }
- }
- }
-
- let url_lock = {
- let mut map = in_flight_map().lock().await;
- map.entry(url.to_string())
- .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
- .clone()
- };
- let _guard = url_lock.lock().await;
-
- {
- let cache = info_cache().lock().await;
- if let Some(entry) = cache.get(url) {
- if entry.cached_at.elapsed() < INFO_CACHE_TTL {
- tracing::debug!(
- "[perf] fetch_and_cache_info: dedup cache hit for {}",
- platform
- );
- return Ok(entry.info.clone());
- }
- }
- }
-
- tracing::debug!("[perf] fetch_and_cache_info: fetching for {}", platform);
- let info = if let Some(ytdlp) = ytdlp_path {
- match platform {
- "youtube" => {
- omniget_core::platforms::YouTubeDownloader::fetch_with_ytdlp(url, ytdlp).await?
- }
- "generic" => {
- if crate::platforms::generic_ytdlp::is_direct_media_url(url).is_some() {
- downloader.get_media_info(url).await?
- } else {
- let json = crate::core::ytdlp::get_video_info(ytdlp, url, &[]).await?;
- crate::platforms::generic_ytdlp::GenericYtdlpDownloader::parse_video_info(
- &json,
- )?
- }
- }
- _ => downloader.get_media_info(url).await?,
- }
- } else {
- downloader.get_media_info(url).await?
- };
-
- let mut cache = info_cache().lock().await;
- cache.insert(
- url.to_string(),
- CachedInfo {
- info: info.clone(),
- cached_at: std::time::Instant::now(),
- },
- );
- if cache.len() > 50 {
- cache.retain(|_, v| v.cached_at.elapsed() < INFO_CACHE_TTL);
- }
- Ok(info)
-}
-
-pub async fn try_get_cached_info(url: &str) -> Option<MediaInfo> {
- let cache = info_cache().lock().await;
- cache
- .get(url)
- .filter(|entry| entry.cached_at.elapsed() < INFO_CACHE_TTL)
- .map(|entry| entry.info.clone())
-}
-
-pub async fn prefetch_info(
- url: &str,
- downloader: &dyn PlatformDownloader,
- platform: &str,
- ytdlp_path: Option<&std::path::Path>,
-) {
- prefetch_info_with_emit(url, downloader, platform, ytdlp_path, None).await;
-}
-
-pub async fn prefetch_info_with_emit(
- url: &str,
- downloader: &dyn PlatformDownloader,
- platform: &str,
- ytdlp_path: Option<&std::path::Path>,
- app: Option<tauri::AppHandle>,
-) {
- let _timer_start = std::time::Instant::now();
- tracing::debug!("[perf] prefetch_info: started");
- let result = tokio::time::timeout(
- std::time::Duration::from_secs(15),
- fetch_and_cache_info(url, downloader, platform, ytdlp_path),
- )
- .await;
- match result {
- Ok(Ok(info)) => {
- tracing::debug!(
- "[perf] prefetch_info: completed in {:?} — {}",
- _timer_start.elapsed(),
- info.title
- );
- if let Some(app) = app {
- let preview = MediaPreviewEvent {
- url: url.to_string(),
- title: info.title.clone(),
- author: info.author.clone(),
- thumbnail_url: info.thumbnail_url.clone(),
- duration_seconds: info.duration_seconds,
- };
- let _ = app.emit("media-info-preview", preview);
- }
- }
- Ok(Err(e)) => tracing::warn!(
- "[perf] prefetch_info: failed in {:?} — {}",
- _timer_start.elapsed(),
- e
- ),
- Err(_) => tracing::warn!(
- "[perf] prefetch_info: timed out after {:?}",
- _timer_start.elapsed()
- ),
- }
-}
-
-pub async fn try_start_next(app: tauri::AppHandle, queue: Arc<tokio::sync::Mutex<DownloadQueue>>) {
- let _timer_start = std::time::Instant::now();
- let (next_ids, stagger, state_to_emit) = {
- let mut q = queue.lock().await;
- let ids = q.next_queued_ids();
- for nid in &ids {
- q.mark_active(*nid);
- }
- let state = if !ids.is_empty() {
- Some(q.get_state())
- } else {
- None
- };
- (ids, q.stagger_delay_ms, state)
- };
-
- if let Some(state) = state_to_emit {
- emit_queue_state_from_state(&app, state);
- }
-
- let batch_size = next_ids.len();
- for (i, nid) in next_ids.into_iter().enumerate() {
- let _ = app.emit(
- "queue-item-progress",
- &QueueItemProgress {
- id: nid,
- title: String::new(),
- platform: String::new(),
- percent: 0.0,
- speed_bytes_per_sec: 0.0,
- downloaded_bytes: 0,
- total_bytes: None,
- phase: "queued_starting".to_string(),
- eta_seconds: None,
- },
- );
-
- if i > 0 {
- let item_platform = {
- let q = queue.lock().await;
- q.items
- .iter()
- .find(|item| item.id == nid)
- .map(|item| item.platform.clone())
- };
- let delay_ms = if item_platform.as_deref() == Some("youtube") {
- 2000
- } else if batch_size > 3 {
- stagger.max(1000)
- } else {
- stagger
- };
- if delay_ms > 0 {
- tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
- }
- }
- let app_c = app.clone();
- let queue_c = queue.clone();
- tokio::spawn(async move {
- spawn_download(app_c, queue_c, nid).await;
- });
- }
- tracing::debug!("[perf] try_start_next took {:?}", _timer_start.elapsed());
-}
-
-// Periodic tick so a future-scheduled download still starts when its time
-// arrives even if the queue is otherwise idle, and so a download with a
-// stop time is cancelled when that time passes.
-pub fn start_scheduler(app: tauri::AppHandle) {
- tauri::async_runtime::spawn(async move {
- tokio::time::sleep(std::time::Duration::from_secs(15)).await;
- loop {
- let state = app.state::<crate::AppState>();
- let queue = state.download_queue.clone();
- let (has_due, stopped_any) = {
- let q = queue.lock().await;
- let now = now_ms();
- let mut stopped = false;
- for item in &q.items {
- if item.status == QueueStatus::Active {
- if let Some(stop) = item.stop_at_ms {
- if now >= stop {
- item.cancel_token.cancel();
- stopped = true;
- }
- }
- }
- }
- let due = q.items.iter().any(|i| {
- i.status == QueueStatus::Queued
- && i.scheduled_at_ms.map(|t| now >= t).unwrap_or(false)
- });
- (due, stopped)
- };
- if has_due || stopped_any {
- try_start_next(app.clone(), queue.clone()).await;
- }
- tokio::time::sleep(std::time::Duration::from_secs(15)).await;
- }
- });
-}
-
-fn is_generic_title(title: &str) -> bool {
- let t = title.to_lowercase();
- let t = t.trim();
- t.is_empty()
- || t == "video"
- || t == "media"
- || t == "untitled"
- || t == "unknown"
- || t.starts_with("video [video]")
- || t.starts_with("media [media]")
-}
-
-#[cfg(test)]
-mod kind_tests {
- use super::{kind_from_platform, QueueKind};
-
- #[test]
- fn youtube_and_video_platforms_map_to_video() {
- assert_eq!(kind_from_platform("youtube"), QueueKind::Video);
- assert_eq!(kind_from_platform("vimeo"), QueueKind::Video);
- assert_eq!(kind_from_platform("twitch"), QueueKind::Video);
- assert_eq!(kind_from_platform("bilibili"), QueueKind::Video);
- assert_eq!(kind_from_platform("tiktok"), QueueKind::Video);
- assert_eq!(kind_from_platform("instagram"), QueueKind::Video);
- assert_eq!(kind_from_platform("reddit"), QueueKind::Video);
- assert_eq!(kind_from_platform("bluesky"), QueueKind::Video);
- assert_eq!(kind_from_platform("generic_ytdlp"), QueueKind::Video);
- }
-
- #[test]
- fn audio_platforms() {
- assert_eq!(kind_from_platform("soundcloud"), QueueKind::Audio);
- assert_eq!(kind_from_platform("spotify"), QueueKind::Audio);
- }
-
- #[test]
- fn pinterest_is_image() {
- assert_eq!(kind_from_platform("pinterest"), QueueKind::Image);
- }
-
- #[test]
- fn pdf_kind() {
- assert_eq!(kind_from_platform("pdf"), QueueKind::Pdf);
- }
-
- #[test]
- fn book_platforms() {
- assert_eq!(kind_from_platform("annas_archive"), QueueKind::Book);
- assert_eq!(kind_from_platform("libgen"), QueueKind::Book);
- assert_eq!(kind_from_platform("gutendex"), QueueKind::Book);
- assert_eq!(kind_from_platform("book"), QueueKind::Book);
- }
-
- #[test]
- fn webpage_kind() {
- assert_eq!(kind_from_platform("webpage"), QueueKind::Webpage);
- assert_eq!(kind_from_platform("embed"), QueueKind::Webpage);
- }
-
- #[test]
- fn telegram_kind() {
- assert_eq!(kind_from_platform("telegram"), QueueKind::TelegramMedia);
- assert_eq!(
- kind_from_platform("telegram_media"),
- QueueKind::TelegramMedia
- );
- }
-
- #[test]
- fn course_lesson_kind() {
- assert_eq!(kind_from_platform("courses"), QueueKind::CourseLesson);
- assert_eq!(kind_from_platform("course_lesson"), QueueKind::CourseLesson);
- }
-
- #[test]
- fn generic_for_torrents_and_p2p() {
- assert_eq!(kind_from_platform("magnet"), QueueKind::Generic);
- assert_eq!(kind_from_platform("p2p"), QueueKind::Generic);
- assert_eq!(kind_from_platform("torrent"), QueueKind::Generic);
- }
-
- #[test]
- fn unknown_platform_falls_back_to_generic() {
- assert_eq!(kind_from_platform(""), QueueKind::Generic);
- assert_eq!(kind_from_platform("totally-unknown"), QueueKind::Generic);
- assert_eq!(kind_from_platform("xyz123"), QueueKind::Generic);
- }
-
- #[test]
- fn case_insensitive() {
- assert_eq!(kind_from_platform("YouTube"), QueueKind::Video);
- assert_eq!(kind_from_platform("TELEGRAM"), QueueKind::TelegramMedia);
- }
-}
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, OnceLock};
+
+static EMIT_COUNT: AtomicU64 = AtomicU64::new(0);
+
+pub fn now_ms() -> u64 {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+fn append_download_log(app: &tauri::AppHandle, id: u64, line: impl AsRef<str>) {
+ crate::core::download_log::push_line(id, line.as_ref());
+ let _ = app.emit(
+ "download-log-update",
+ serde_json::json!({
+ "id": id,
+ }),
+ );
+}
+
+use serde::Serialize;
+use tauri::{Emitter, Manager};
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+fn shared_http_client() -> &'static reqwest::Client {
+ static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
+ CLIENT.get_or_init(|| {
+ crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .build()
+ .unwrap_or_default()
+ })
+}
+
+use crate::core::ffmpeg::{self, MetadataEmbed};
+use crate::models::media::MediaInfo;
+use crate::platforms::traits::PlatformDownloader;
+use crate::storage::config;
+
+struct CachedInfo {
+ info: MediaInfo,
+ cached_at: std::time::Instant,
+}
+
+static INFO_CACHE: OnceLock<tokio::sync::Mutex<HashMap<String, CachedInfo>>> = OnceLock::new();
+
+fn info_cache() -> &'static tokio::sync::Mutex<HashMap<String, CachedInfo>> {
+ INFO_CACHE.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))
+}
+
+const INFO_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(600);
+
+static IN_FLIGHT_FETCHES: OnceLock<
+ tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
+> = OnceLock::new();
+
+fn in_flight_map() -> &'static tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>> {
+ IN_FLIGHT_FETCHES.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct MediaPreviewEvent {
+ pub url: String,
+ pub title: String,
+ pub author: String,
+ pub thumbnail_url: Option<String>,
+ pub duration_seconds: Option<f64>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum QueueKind {
+ Video,
+ Audio,
+ Image,
+ Pdf,
+ Book,
+ Webpage,
+ TelegramMedia,
+ CourseLesson,
+ Generic,
+}
+
+pub fn kind_from_platform(platform: &str) -> QueueKind {
+ let p = platform.to_ascii_lowercase();
+ match p.as_str() {
+ "youtube" | "vimeo" | "twitch" | "bilibili" | "tiktok" | "twitter" | "x" | "instagram"
+ | "reddit" | "bluesky" | "facebook" | "generic_ytdlp" => QueueKind::Video,
+ "soundcloud" | "spotify" => QueueKind::Audio,
+ "pinterest" => QueueKind::Image,
+ "magnet" | "p2p" | "torrent" => QueueKind::Generic,
+ "telegram" | "telegram_media" => QueueKind::TelegramMedia,
+ "courses" | "course_lesson" => QueueKind::CourseLesson,
+ "annas_archive" | "book" | "libgen" | "gutendex" => QueueKind::Book,
+ "pdf" => QueueKind::Pdf,
+ "webpage" | "embed" => QueueKind::Webpage,
+ _ => QueueKind::Generic,
+ }
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(tag = "type", content = "data")]
+pub enum QueueStatus {
+ Queued,
+ Active,
+ Paused,
+ Seeding,
+ Complete { success: bool },
+ Error { message: String, retryable: bool },
+}
+
+pub fn is_retryable_error_message(message: &str) -> bool {
+ let lower = message.to_lowercase();
+ if lower.contains("cancel") {
+ return false;
+ }
+ let (category, _) = omniget_core::core::errors::classify_download_error(message);
+ matches!(category, "unknown" | "rate_limited")
+}
+
+#[derive(Clone, Serialize)]
+pub struct QueueItemInfo {
+ pub id: u64,
+ pub url: String,
+ pub platform: String,
+ pub title: String,
+ pub status: QueueStatus,
+ pub percent: f64,
+ pub speed_bytes_per_sec: f64,
+ pub downloaded_bytes: u64,
+ pub total_bytes: Option<u64>,
+ pub file_path: Option<String>,
+ pub file_size_bytes: Option<u64>,
+ pub file_count: Option<u32>,
+ pub thumbnail_url: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub kind: Option<QueueKind>,
+ #[serde(default)]
+ pub external: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub eta_seconds: Option<u64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub quality: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub download_mode: Option<String>,
+}
+
+pub struct QueueItem {
+ pub id: u64,
+ pub url: String,
+ pub platform: String,
+ pub title: String,
+ pub status: QueueStatus,
+ pub cancel_token: CancellationToken,
+ pub output_dir: String,
+ pub download_mode: Option<String>,
+ pub quality: Option<String>,
+ pub format_id: Option<String>,
+ pub referer: Option<String>,
+ pub extra_headers: Option<std::collections::HashMap<String, String>>,
+ pub page_url: Option<String>,
+ pub user_agent: Option<String>,
+ pub percent: f64,
+ pub speed_bytes_per_sec: f64,
+ pub downloaded_bytes: u64,
+ pub total_bytes: Option<u64>,
+ pub file_path: Option<String>,
+ pub file_size_bytes: Option<u64>,
+ pub file_count: Option<u32>,
+ pub media_info: Option<MediaInfo>,
+ pub downloader: Arc<dyn PlatformDownloader>,
+ pub ytdlp_path: Option<PathBuf>,
+ pub from_hotkey: bool,
+ pub torrent_id: Option<usize>,
+ pub kind: Option<QueueKind>,
+ pub external: bool,
+ pub thumbnail_url_override: Option<String>,
+ pub retry_count: u32,
+ pub max_retries: u32,
+ pub resume_state: Option<serde_json::Value>,
+ pub concurrent_segments: Option<usize>,
+ pub segment_size_bytes: Option<u64>,
+ pub eta_seconds: Option<u64>,
+ pub cookie_slug: Option<String>,
+ pub custom_ytdlp_args: Option<Vec<String>>,
+ pub torrent_files: Option<Vec<usize>>,
+ pub scheduled_at_ms: Option<u64>,
+ pub stop_at_ms: Option<u64>,
+}
+
+impl QueueItem {
+ pub fn to_info(&self) -> QueueItemInfo {
+ QueueItemInfo {
+ id: self.id,
+ url: self.url.clone(),
+ platform: self.platform.clone(),
+ title: self.title.clone(),
+ status: self.status.clone(),
+ percent: self.percent,
+ speed_bytes_per_sec: self.speed_bytes_per_sec,
+ downloaded_bytes: self.downloaded_bytes,
+ total_bytes: self.total_bytes,
+ file_path: self.file_path.clone(),
+ file_size_bytes: self.file_size_bytes,
+ file_count: self.file_count,
+ thumbnail_url: self.thumbnail_url_override.clone().or_else(|| {
+ self.media_info
+ .as_ref()
+ .and_then(|m| m.thumbnail_url.clone())
+ }),
+ kind: self.kind,
+ external: self.external,
+ eta_seconds: self.eta_seconds,
+ quality: self.quality.clone(),
+ download_mode: self.download_mode.clone(),
+ }
+ }
+}
+
+pub struct DownloadQueue {
+ pub items: Vec<QueueItem>,
+ pub max_concurrent: u32,
+ pub stagger_delay_ms: u64,
+ pub default_max_retries: u32,
+}
+
+impl DownloadQueue {
+ pub fn new(max_concurrent: u32) -> Self {
+ Self {
+ items: Vec::new(),
+ max_concurrent,
+ stagger_delay_ms: 150,
+ default_max_retries: 3,
+ }
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub fn enqueue(
+ &mut self,
+ id: u64,
+ url: String,
+ platform: String,
+ title: String,
+ output_dir: String,
+ download_mode: Option<String>,
+ quality: Option<String>,
+ format_id: Option<String>,
+ referer: Option<String>,
+ extra_headers: Option<std::collections::HashMap<String, String>>,
+ page_url: Option<String>,
+ user_agent: Option<String>,
+ media_info: Option<MediaInfo>,
+ total_bytes: Option<u64>,
+ file_count: Option<u32>,
+ downloader: Arc<dyn PlatformDownloader>,
+ ytdlp_path: Option<PathBuf>,
+ from_hotkey: bool,
+ cookie_slug: Option<String>,
+ custom_ytdlp_args: Option<Vec<String>>,
+ torrent_files: Option<Vec<usize>>,
+ scheduled_at_ms: Option<u64>,
+ stop_at_ms: Option<u64>,
+ ) {
+ let computed_kind = Some(kind_from_platform(&platform));
+ let item = QueueItem {
+ id,
+ url,
+ platform,
+ title,
+ status: QueueStatus::Queued,
+ cancel_token: CancellationToken::new(),
+ output_dir,
+ download_mode,
+ quality,
+ format_id,
+ referer,
+ extra_headers,
+ page_url,
+ user_agent,
+ percent: 0.0,
+ speed_bytes_per_sec: 0.0,
+ downloaded_bytes: 0,
+ total_bytes,
+ file_path: None,
+ file_size_bytes: None,
+ file_count,
+ media_info,
+ downloader,
+ ytdlp_path,
+ from_hotkey,
+ torrent_id: None,
+ kind: computed_kind,
+ external: false,
+ thumbnail_url_override: None,
+ retry_count: 0,
+ max_retries: self.default_max_retries,
+ resume_state: None,
+ concurrent_segments: None,
+ segment_size_bytes: None,
+ eta_seconds: None,
+ cookie_slug,
+ custom_ytdlp_args,
+ torrent_files,
+ scheduled_at_ms,
+ stop_at_ms,
+ };
+ crate::core::recovery::persist(crate::core::recovery::RecoveryItem {
+ id: item.id,
+ url: item.url.clone(),
+ title: item.title.clone(),
+ platform: item.platform.clone(),
+ output_dir: item.output_dir.clone(),
+ download_mode: item.download_mode.clone(),
+ quality: item.quality.clone(),
+ format_id: item.format_id.clone(),
+ referer: item.referer.clone(),
+ });
+ self.items.push(item);
+ }
+
+ pub fn hydrate_from_history(&mut self) {
+ let entries = crate::core::queue_history::list();
+ if entries.is_empty() {
+ return;
+ }
+ let placeholder: Arc<dyn PlatformDownloader> =
+ Arc::new(crate::platforms::noop::NoopDownloader::new());
+ for entry in entries.iter().rev() {
+ if self.items.iter().any(|i| i.id == entry.id) {
+ continue;
+ }
+ let status = if entry.success {
+ QueueStatus::Complete { success: true }
+ } else {
+ let msg = entry.error.clone().unwrap_or_default();
+ let retryable = is_retryable_error_message(&msg);
+ QueueStatus::Error {
+ message: msg,
+ retryable,
+ }
+ };
+ let percent = if entry.success { 100.0 } else { 0.0 };
+ let item = QueueItem {
+ id: entry.id,
+ url: entry.url.clone(),
+ platform: entry.platform.clone(),
+ title: entry.title.clone(),
+ status,
+ cancel_token: CancellationToken::new(),
+ output_dir: entry
+ .file_path
+ .as_ref()
+ .and_then(|p| {
+ std::path::Path::new(p)
+ .parent()
+ .map(|x| x.to_string_lossy().to_string())
+ })
+ .unwrap_or_default(),
+ download_mode: None,
+ quality: None,
+ format_id: None,
+ referer: None,
+ extra_headers: None,
+ page_url: None,
+ user_agent: None,
+ percent,
+ speed_bytes_per_sec: 0.0,
+ downloaded_bytes: entry.file_size_bytes.unwrap_or(0),
+ total_bytes: entry.total_bytes,
+ file_path: entry.file_path.clone(),
+ file_size_bytes: entry.file_size_bytes,
+ file_count: None,
+ media_info: None,
+ downloader: placeholder.clone(),
+ ytdlp_path: None,
+ from_hotkey: false,
+ torrent_id: None,
+ kind: entry.kind,
+ external: false,
+ thumbnail_url_override: entry.thumbnail_url.clone(),
+ retry_count: 0,
+ max_retries: 0,
+ resume_state: None,
+ concurrent_segments: None,
+ segment_size_bytes: None,
+ eta_seconds: None,
+ cookie_slug: None,
+ custom_ytdlp_args: None,
+ torrent_files: None,
+ scheduled_at_ms: None,
+ stop_at_ms: None,
+ };
+ self.items.push(item);
+ }
+ }
+
+ pub fn active_count(&self) -> u32 {
+ self.items
+ .iter()
+ .filter(|i| i.status == QueueStatus::Active)
+ .count() as u32
+ }
+
+ pub fn next_queued_ids(&self) -> Vec<u64> {
+ let slots = self.max_concurrent.saturating_sub(self.active_count()) as usize;
+ let now = now_ms();
+ self.items
+ .iter()
+ .filter(|i| i.status == QueueStatus::Queued)
+ .filter(|i| i.scheduled_at_ms.map(|t| now >= t).unwrap_or(true))
+ .take(slots)
+ .map(|i| i.id)
+ .collect()
+ }
+
+ pub fn next_available_id(&self, preferred: u64) -> u64 {
+ let mut id = preferred;
+ while self.items.iter().any(|i| i.id == id) {
+ id = id.saturating_add(1);
+ }
+ id
+ }
+
+ pub fn mark_active(&mut self, id: u64) {
+ if let Some(item) = self
+ .items
+ .iter_mut()
+ .find(|i| i.id == id && i.status == QueueStatus::Queued)
+ {
+ item.status = QueueStatus::Active;
+ item.cancel_token = CancellationToken::new();
+ }
+ }
+
+ pub fn mark_complete(
+ &mut self,
+ id: u64,
+ success: bool,
+ error: Option<String>,
+ file_path: Option<String>,
+ file_size_bytes: Option<u64>,
+ ) {
+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
+ let error_for_history = error.clone();
+ if success {
+ item.status = QueueStatus::Complete { success: true };
+ item.percent = 100.0;
+ } else {
+ let msg = error.unwrap_or_default();
+ let retryable = is_retryable_error_message(&msg);
+ item.status = QueueStatus::Error {
+ message: msg,
+ retryable,
+ };
+ }
+ item.file_path = file_path;
+ item.file_size_bytes = file_size_bytes;
+ item.speed_bytes_per_sec = 0.0;
+ item.eta_seconds = None;
+ crate::core::recovery::remove(id);
+
+ if !item.external {
+ let entry = crate::core::queue_history::HistoryEntry {
+ id: item.id,
+ url: item.url.clone(),
+ platform: item.platform.clone(),
+ title: item.title.clone(),
+ file_path: item.file_path.clone(),
+ file_size_bytes: item.file_size_bytes,
+ total_bytes: item.total_bytes,
+ success,
+ error: if success { None } else { error_for_history },
+ completed_at: crate::core::queue_history::now_unix_seconds(),
+ thumbnail_url: item.thumbnail_url_override.clone().or_else(|| {
+ item.media_info
+ .as_ref()
+ .and_then(|m| m.thumbnail_url.clone())
+ }),
+ kind: item.kind,
+ };
+ crate::core::queue_history::record(entry);
+ }
+ }
+ }
+
+ pub fn mark_seeding(
+ &mut self,
+ id: u64,
+ file_path: Option<String>,
+ file_size_bytes: Option<u64>,
+ torrent_id: Option<usize>,
+ ) {
+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
+ item.status = QueueStatus::Seeding;
+ item.percent = 100.0;
+ item.file_path = file_path;
+ item.file_size_bytes = file_size_bytes;
+ item.speed_bytes_per_sec = 0.0;
+ item.torrent_id = torrent_id;
+ crate::core::recovery::remove(id);
+ }
+ }
+
+ pub fn update_progress(
+ &mut self,
+ id: u64,
+ percent: f64,
+ speed: f64,
+ downloaded: u64,
+ total: Option<u64>,
+ torrent_id: Option<usize>,
+ eta_seconds: Option<u64>,
+ ) {
+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
+ if item.status != QueueStatus::Active {
+ if torrent_id.is_some() && item.torrent_id.is_none() {
+ item.torrent_id = torrent_id;
+ }
+ return;
+ }
+ item.percent = percent;
+ item.speed_bytes_per_sec = speed;
+ item.downloaded_bytes = downloaded;
+ if let Some(t) = total {
+ item.total_bytes = Some(t);
+ }
+ if torrent_id.is_some() && item.torrent_id.is_none() {
+ item.torrent_id = torrent_id;
+ }
+ item.eta_seconds = eta_seconds;
+ }
+ }
+
+ pub fn pause(&mut self, id: u64) -> bool {
+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
+ if item.status == QueueStatus::Active {
+ if item.platform != "magnet"
+ && !omniget_core::core::ytdlp::pause_download_process(id)
+ {
+ return false;
+ }
+ item.status = QueueStatus::Paused;
+ item.speed_bytes_per_sec = 0.0;
+ item.eta_seconds = None;
+ return true;
+ }
+ }
+ false
+ }
+
+ pub fn resume(&mut self, id: u64) -> bool {
+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
+ if item.status == QueueStatus::Paused {
+ if item.platform != "magnet"
+ && !omniget_core::core::ytdlp::resume_download_process(id)
+ {
+ return false;
+ }
+ item.status = QueueStatus::Active;
+ return true;
+ }
+ }
+ false
+ }
+
+ pub fn pause_all(&mut self) -> Vec<(u64, Option<usize>)> {
+ let mut paused = Vec::new();
+ for item in self.items.iter_mut() {
+ if item.status == QueueStatus::Active {
+ if item.platform != "magnet"
+ && !omniget_core::core::ytdlp::pause_download_process(item.id)
+ {
+ continue;
+ }
+ item.status = QueueStatus::Paused;
+ item.speed_bytes_per_sec = 0.0;
+ item.eta_seconds = None;
+ paused.push((item.id, item.torrent_id));
+ }
+ }
+ paused
+ }
+
+ pub fn resume_all(&mut self) -> Vec<(u64, Option<usize>)> {
+ let mut resumed = Vec::new();
+ for item in self.items.iter_mut() {
+ if item.status == QueueStatus::Paused {
+ let tid = item.torrent_id;
+ if item.platform != "magnet"
+ && !omniget_core::core::ytdlp::resume_download_process(item.id)
+ {
+ continue;
+ }
+ item.status = QueueStatus::Active;
+ resumed.push((item.id, tid));
+ }
+ }
+ resumed
+ }
+
+ pub fn reorder(&mut self, ids_in_order: Vec<u64>) -> bool {
+ let mut slots: Vec<Option<QueueItem>> = self.items.drain(..).map(Some).collect();
+
+ let queued_slot_indices: Vec<usize> = slots
+ .iter()
+ .enumerate()
+ .filter_map(|(idx, slot)| {
+ slot.as_ref()
+ .filter(|i| i.status == QueueStatus::Queued)
+ .map(|_| idx)
+ })
+ .collect();
+
+ if queued_slot_indices.is_empty() {
+ self.items = slots.into_iter().flatten().collect();
+ return false;
+ }
+
+ let queued_id_to_slot: std::collections::HashMap<u64, usize> = queued_slot_indices
+ .iter()
+ .map(|idx| (slots[*idx].as_ref().unwrap().id, *idx))
+ .collect();
+
+ let mut new_queued_order: Vec<QueueItem> = Vec::with_capacity(queued_slot_indices.len());
+ let mut seen: std::collections::HashSet<u64> = std::collections::HashSet::new();
+
+ for id in &ids_in_order {
+ if seen.contains(id) {
+ continue;
+ }
+ if let Some(slot_idx) = queued_id_to_slot.get(id) {
+ if let Some(item) = slots[*slot_idx].take() {
+ new_queued_order.push(item);
+ seen.insert(*id);
+ }
+ }
+ }
+ for idx in &queued_slot_indices {
+ if let Some(item) = slots[*idx].take() {
+ new_queued_order.push(item);
+ }
+ }
+
+ let mut iter = new_queued_order.into_iter();
+ let mut rebuilt: Vec<QueueItem> = Vec::with_capacity(slots.len());
+ for (idx, slot) in slots.into_iter().enumerate() {
+ if queued_slot_indices.contains(&idx) {
+ if let Some(item) = iter.next() {
+ rebuilt.push(item);
+ }
+ } else if let Some(item) = slot {
+ rebuilt.push(item);
+ }
+ }
+ rebuilt.extend(iter);
+ self.items = rebuilt;
+ true
+ }
+
+ /// Cancel an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).
+ pub fn cancel(&mut self, id: u64) -> (bool, Option<usize>) {
+ let result = self.cancel_inner(id);
+ if result.0 {
+ crate::core::recovery::remove(id);
+ }
+ result
+ }
+
+ fn cancel_inner(&mut self, id: u64) -> (bool, Option<usize>) {
+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
+ match &item.status {
+ QueueStatus::Active => {
+ item.cancel_token.cancel();
+ item.status = QueueStatus::Error {
+ message: "Cancelled".to_string(),
+ retryable: false,
+ };
+ item.speed_bytes_per_sec = 0.0;
+ return (true, None);
+ }
+ QueueStatus::Seeding => {
+ let tid = item.torrent_id;
+ item.status = QueueStatus::Error {
+ message: "Cancelled".to_string(),
+ retryable: false,
+ };
+ item.speed_bytes_per_sec = 0.0;
+ return (true, tid);
+ }
+ QueueStatus::Paused => {
+ // For magnet downloads, the cancel_token was not cancelled during pause,
+ // so we must cancel it now to stop the background download loop.
+ // Also return the torrent_id for session cleanup.
+ item.cancel_token.cancel();
+ let tid = if item.platform == "magnet" {
+ item.torrent_id
+ } else {
+ None
+ };
+ item.status = QueueStatus::Error {
+ message: "Cancelled".to_string(),
+ retryable: false,
+ };
+ item.speed_bytes_per_sec = 0.0;
+ return (true, tid);
+ }
+ QueueStatus::Queued => {
+ item.status = QueueStatus::Error {
+ message: "Cancelled".to_string(),
+ retryable: false,
+ };
+ return (true, None);
+ }
+ _ => {}
+ }
+ }
+ (false, None)
+ }
+
+ pub fn retry(&mut self, id: u64) -> bool {
+ if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
+ if matches!(item.status, QueueStatus::Error { .. }) {
+ item.status = QueueStatus::Queued;
+ item.cancel_token = CancellationToken::new();
+ item.percent = 0.0;
+ item.speed_bytes_per_sec = 0.0;
+ item.downloaded_bytes = 0;
+ item.file_path = None;
+ item.file_size_bytes = None;
+ item.retry_count = 0;
+ return true;
+ }
+ }
+ false
+ }
+
+ /// Remove an item. Returns the torrent_id if the item needs torrent cleanup (caller should delete from session).
+ pub fn remove(&mut self, id: u64) -> Option<Option<usize>> {
+ let result = self.remove_inner(id);
+ if result.is_some() {
+ crate::core::recovery::remove(id);
+ crate::core::queue_history::remove(id);
+ }
+ result
+ }
+
+ fn remove_inner(&mut self, id: u64) -> Option<Option<usize>> {
+ if let Some(pos) = self.items.iter().position(|i| i.id == id) {
+ let item = &self.items[pos];
+ if item.status == QueueStatus::Active {
+ item.cancel_token.cancel();
+ }
+ // For paused magnet items, the cancel_token was not cancelled during pause
+ if item.status == QueueStatus::Paused && item.platform == "magnet" {
+ item.cancel_token.cancel();
+ }
+ let torrent_id = if item.status == QueueStatus::Seeding
+ || (item.status == QueueStatus::Paused && item.platform == "magnet")
+ {
+ item.torrent_id
+ } else {
+ None
+ };
+ self.items.remove(pos);
+ return Some(torrent_id);
+ }
+ None
+ }
+
+ pub fn clear_finished(&mut self) {
+ let to_remove: Vec<u64> = self
+ .items
+ .iter()
+ .filter(|i| matches!(i.status, QueueStatus::Complete { .. }))
+ .map(|i| i.id)
+ .collect();
+ for id in &to_remove {
+ crate::core::recovery::remove(*id);
+ crate::core::queue_history::remove(*id);
+ }
+ self.items
+ .retain(|i| !matches!(i.status, QueueStatus::Complete { .. }));
+ }
+
+ pub fn get_state(&self) -> Vec<QueueItemInfo> {
+ self.items.iter().map(|i| i.to_info()).collect()
+ }
+
+ pub fn has_url(&self, url: &str) -> bool {
+ self.items.iter().any(|i| {
+ i.url == url
+ && matches!(
+ i.status,
+ QueueStatus::Queued
+ | QueueStatus::Active
+ | QueueStatus::Paused
+ | QueueStatus::Seeding
+ )
+ })
+ }
+}
+
+pub struct ProgressThrottle {
+ last_emit: std::time::Instant,
+ min_interval: std::time::Duration,
+}
+
+impl ProgressThrottle {
+ pub fn new(min_interval_ms: u64) -> Self {
+ Self {
+ last_emit: std::time::Instant::now() - std::time::Duration::from_secs(10),
+ min_interval: std::time::Duration::from_millis(min_interval_ms),
+ }
+ }
+
+ pub fn should_emit(&mut self) -> bool {
+ let now = std::time::Instant::now();
+ if now.duration_since(self.last_emit) >= self.min_interval {
+ self.last_emit = now;
+ true
+ } else {
+ false
+ }
+ }
+}
+
+#[derive(Clone, Serialize)]
+pub struct QueueItemProgress {
+ pub id: u64,
+ pub title: String,
+ pub platform: String,
+ pub percent: f64,
+ pub speed_bytes_per_sec: f64,
+ pub downloaded_bytes: u64,
+ pub total_bytes: Option<u64>,
+ pub phase: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub eta_seconds: Option<u64>,
+}
+
+pub fn emit_queue_state_from_state(app: &tauri::AppHandle, state: Vec<QueueItemInfo>) {
+ let n = EMIT_COUNT.fetch_add(1, Ordering::Relaxed);
+ if n.is_multiple_of(10) {
+ tracing::debug!("[perf] emit_queue_state called {} times", n);
+ }
+ let _ = app.emit("queue-state-update", &state);
+ let total = crate::tray::compute_total_active(app);
+ crate::tray::update_active_count(app, total);
+ crate::core::awake::sync(total > 0);
+
+ let active_items: Vec<_> = state
+ .iter()
+ .filter(|i| i.status == QueueStatus::Active)
+ .collect();
+ let avg_percent = if !active_items.is_empty() {
+ let sum: f64 = active_items.iter().map(|i| i.percent).sum();
+ sum / active_items.len() as f64 / 100.0
+ } else {
+ 0.0
+ };
+ let total_speed: f64 = active_items.iter().map(|i| i.speed_bytes_per_sec).sum();
+ crate::tray::update_speed_tooltip(app, total, total_speed);
+ crate::tray::update_taskbar_badge(app, total, avg_percent);
+
+ if let Some(window) = app.get_webview_window("main") {
+ let title = if total > 0 {
+ format!("({}) omniget", total)
+ } else {
+ "omniget".into()
+ };
+ let _ = window.set_title(&title);
+ }
+}
+
+pub fn emit_queue_state(app: &tauri::AppHandle, queue: &DownloadQueue) {
+ let state = queue.get_state();
+ emit_queue_state_from_state(app, state);
+}
+
+/// RAII guard that ensures an Active queue item never leaks a slot.
+///
+/// If the download future panics or is dropped before reaching `mark_complete`
+/// / `mark_seeding`, the Drop impl spawns a task that transitions the item to
+/// Error("Download interrupted") and calls `try_start_next`, unblocking the
+/// queue.
+///
+/// When the download reaches a terminal state through the normal paths, the
+/// guard sees the item is no longer Active and does nothing (idempotent).
+struct ActiveJobSlot {
+ app: tauri::AppHandle,
+ queue: Arc<tokio::sync::Mutex<DownloadQueue>>,
+ item_id: u64,
+ armed: bool,
+}
+
+impl ActiveJobSlot {
+ fn new(
+ app: tauri::AppHandle,
+ queue: Arc<tokio::sync::Mutex<DownloadQueue>>,
+ item_id: u64,
+ ) -> Self {
+ Self {
+ app,
+ queue,
+ item_id,
+ armed: true,
+ }
+ }
+
+ fn disarm(mut self) {
+ self.armed = false;
+ }
+}
+
+impl Drop for ActiveJobSlot {
+ fn drop(&mut self) {
+ if !self.armed {
+ return;
+ }
+ let app = self.app.clone();
+ let queue = self.queue.clone();
+ let item_id = self.item_id;
+ tokio::spawn(async move {
+ let state = {
+ let mut q = queue.lock().await;
+ let still_active = q
+ .items
+ .iter()
+ .find(|i| i.id == item_id)
+ .map(|i| i.status == QueueStatus::Active)
+ .unwrap_or(false);
+ if !still_active {
+ return;
+ }
+ tracing::warn!(
+ "[queue] ActiveJobSlot guard firing for {} — download ended without clean release",
+ item_id
+ );
+ q.mark_complete(
+ item_id,
+ false,
+ Some("Download interrupted".to_string()),
+ None,
+ None,
+ );
+ q.get_state()
+ };
+ emit_queue_state_from_state(&app, state);
+ try_start_next(app, queue).await;
+ });
+ }
+}
+
+pub fn spawn_download(
+ app: tauri::AppHandle,
+ queue: Arc<tokio::sync::Mutex<DownloadQueue>>,
+ item_id: u64,
+) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
+ Box::pin(async move {
+ let _timer_start = std::time::Instant::now();
+ let slot = ActiveJobSlot::new(app.clone(), queue.clone(), item_id);
+ spawn_download_inner(app, queue, item_id).await;
+ slot.disarm();
+ tracing::debug!(
+ "[perf] spawn_download {} took {:?}",
+ item_id,
+ _timer_start.elapsed()
+ );
+ })
+}
+
+async fn spawn_download_inner(
+ app: tauri::AppHandle,
+ queue: Arc<tokio::sync::Mutex<DownloadQueue>>,
+ item_id: u64,
+) {
+ tracing::info!("[queue] download {} started", item_id);
+
+ let _ = app.emit(
+ "queue-item-progress",
+ &QueueItemProgress {
+ id: item_id,
+ title: "".to_string(),
+ platform: "".to_string(),
+ percent: 0.0,
+ speed_bytes_per_sec: 0.0,
+ downloaded_bytes: 0,
+ total_bytes: None,
+ phase: "preparing".to_string(),
+ eta_seconds: None,
+ },
+ );
+
+ let host_key = {
+ let q = queue.lock().await;
+ q.items
+ .iter()
+ .find(|i| i.id == item_id)
+ .map(|i| crate::core::host_limiter::host_key_for_url(&i.url))
+ };
+ let _host_lease = match host_key {
+ Some(key) => Some(crate::core::host_limiter::acquire(&key).await),
+ None => None,
+ };
+
+ let (
+ url,
+ output_dir,
+ download_mode,
+ quality,
+ format_id,
+ referer,
+ extra_headers,
+ page_url,
+ user_agent,
+ cancel_token,
+ media_info,
+ platform_name,
+ downloader,
+ ytdlp_path,
+ from_hotkey,
+ cookie_slug,
+ custom_ytdlp_args,
+ torrent_files,
+ ) = {
+ let q = queue.lock().await;
+ let item = match q.items.iter().find(|i| i.id == item_id) {
+ Some(i) => i,
+ None => return,
+ };
+ (
+ item.url.clone(),
+ item.output_dir.clone(),
+ item.download_mode.clone(),
+ item.quality.clone(),
+ item.format_id.clone(),
+ item.referer.clone(),
+ item.extra_headers.clone(),
+ item.page_url.clone(),
+ item.user_agent.clone(),
+ item.cancel_token.clone(),
+ item.media_info.clone(),
+ item.platform.clone(),
+ item.downloader.clone(),
+ item.ytdlp_path.clone(),
+ item.from_hotkey,
+ item.cookie_slug.clone(),
+ item.custom_ytdlp_args.clone(),
+ item.torrent_files.clone(),
+ )
+ };
+
+ {
+ let settings = crate::storage::config::load_settings(&app);
+ let proxy = settings.proxy.clone();
+ crate::core::http_client::init_proxy(proxy.clone());
+ let proxy_status = if !proxy.enabled {
+ "disabled; system/env proxy honored if set".to_string()
+ } else if proxy.host.trim().is_empty() {
+ "enabled but host is empty; falling back to system/env proxy".to_string()
+ } else {
+ format!(
+ "enabled; {}://{}:{}",
+ proxy.proxy_type, proxy.host, proxy.port
+ )
+ };
+ append_download_log(
+ &app,
+ item_id,
+ format!("[network] proxy setting: {}", proxy_status),
+ );
+ }
+
+ let info_start = std::time::Instant::now();
+ let info = match media_info {
+ Some(i) if !i.available_qualities.is_empty() => {
+ tracing::info!(
+ "[queue] info for {} from cache/pre-fetched in {:?}",
+ item_id,
+ info_start.elapsed()
+ );
+ append_download_log(
+ &app,
+ item_id,
+ format!(
+ "[omniget] using cached video info: platform={} title=\"{}\"",
+ platform_name, i.title
+ ),
+ );
+ i
+ }
+ _ => {
+ tracing::debug!(
+ "[perf] spawn_download_inner {}: media_info is None, fetching info",
+ item_id
+ );
+ append_download_log(
+ &app,
+ item_id,
+ format!(
+ "[omniget] fetching video info: platform={} url={}",
+ platform_name, url
+ ),
+ );
+ if let Some(slug) = cookie_slug.as_deref() {
+ append_download_log(
+ &app,
+ item_id,
+ format!("[cookies] selected managed cookie account: {}", slug),
+ );
+ }
+ let _ = app.emit(
+ "queue-item-progress",
+ &QueueItemProgress {
+ id: item_id,
+ title: url.clone(),
+ platform: platform_name.clone(),
+ percent: 0.0,
+ speed_bytes_per_sec: 0.0,
+ downloaded_bytes: 0,
+ total_bytes: None,
+ phase: "fetching_info".to_string(),
+ eta_seconds: None,
+ },
+ );
+
+ let info_future =
+ fetch_and_cache_info(&url, &*downloader, &platform_name, ytdlp_path.as_deref());
+ let scoped_info_future = omniget_core::core::log_hook::CURRENT_COOKIE_SLUG.scope(
+ cookie_slug.clone(),
+ omniget_core::core::log_hook::CURRENT_DOWNLOAD_ID.scope(item_id, info_future),
+ );
+ let info_timeout_secs = if platform_name == "youtube"
+ || url.to_ascii_lowercase().contains("youtube.com")
+ || url.to_ascii_lowercase().contains("youtu.be")
+ {
+ omniget_core::core::ytdlp::YOUTUBE_VIDEO_INFO_TOTAL_TIMEOUT_SECS
+ } else if platform_name == "douyin" {
+ 30
+ } else {
+ omniget_core::core::ytdlp::DEFAULT_VIDEO_INFO_TOTAL_TIMEOUT_SECS
+ };
+ let info_result = tokio::time::timeout(
+ std::time::Duration::from_secs(info_timeout_secs),
+ scoped_info_future,
+ )
+ .await;
+
+ match info_result {
+ Ok(Ok(i)) => {
+ append_download_log(
+ &app,
+ item_id,
+ format!(
+ "[omniget] video info fetched in {:.1}s: title=\"{}\"",
+ info_start.elapsed().as_secs_f64(),
+ i.title
+ ),
+ );
+ i
+ }
+ Ok(Err(e)) => {
+ append_download_log(
+ &app,
+ item_id,
+ format!(
+ "[omniget] failed fetching video info after {:.1}s: {}",
+ info_start.elapsed().as_secs_f64(),
+ e
+ ),
+ );
+ let state = {
+ let mut q = queue.lock().await;
+ q.mark_complete(item_id, false, Some(e.to_string()), None, None);
+ q.get_state()
+ };
+ emit_queue_state_from_state(&app, state);
+ try_start_next(app, queue).await;
+ return;
+ }
+ Err(_) => {
+ tracing::warn!(
+ "[queue] info fetch timed out for {} after {}s",
+ item_id,
+ info_timeout_secs
+ );
+ append_download_log(
+ &app,
+ item_id,
+ format!(
+ "[omniget] video info timed out after {}s",
+ info_timeout_secs
+ ),
+ );
+ let state = {
+ let mut q = queue.lock().await;
+ q.mark_complete(
+ item_id,
+ false,
+ Some("Timed out fetching video info".to_string()),
+ None,
+ None,
+ );
+ q.get_state()
+ };
+ emit_queue_state_from_state(&app, state);
+ try_start_next(app, queue).await;
+ return;
+ }
+ }
+ }
+ };
+ tracing::info!(
+ "[queue] info fetch for {} took {:?}",
+ item_id,
+ info_start.elapsed()
+ );
+
+ let mut info = info;
+ if is_generic_title(&info.title) {
+ let pokemon = omniget_core::core::pokemon_names::random_pokemon_name();
+ info.title = format!("video_{}", pokemon);
+ }
+
+ let state = {
+ let mut q = queue.lock().await;
+ if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {
+ item.title = info.title.clone();
+ item.total_bytes = info.file_size_bytes;
+ let fc = if info.media_type == crate::models::media::MediaType::Carousel
+ || info.media_type == crate::models::media::MediaType::Playlist
+ {
+ info.available_qualities.len() as u32
+ } else {
+ 1
+ };
+ item.file_count = Some(fc);
+ item.media_info = Some(info.clone());
+ }
+ q.get_state()
+ };
+ emit_queue_state_from_state(&app, state);
+
+ let _ = app.emit(
+ "queue-item-progress",
+ &QueueItemProgress {
+ id: item_id,
+ title: info.title.clone(),
+ platform: platform_name.clone(),
+ percent: 0.5,
+ speed_bytes_per_sec: 0.0,
+ downloaded_bytes: 0,
+ total_bytes: info.file_size_bytes,
+ phase: "starting".to_string(),
+ eta_seconds: None,
+ },
+ );
+
+ let settings = config::load_settings(&app);
+ let tmpl = settings.download.filename_template.clone();
+ let mut final_output_dir = std::path::PathBuf::from(&output_dir);
+ if settings.download.organize_by_platform {
+ final_output_dir = final_output_dir.join(&platform_name);
+ }
+ let torrent_id_slot = Arc::new(tokio::sync::Mutex::new(None));
+ let audio_format = if download_mode.as_deref() == Some("audio") {
+ Some(settings.download.music_audio_format.clone())
+ } else {
+ None
+ };
+ let custom_ytdlp_args = {
+ let mut args = custom_ytdlp_args.clone();
+ if settings.download.skip_existing {
+ let flags = args.get_or_insert_with(Vec::new);
+ if !flags.iter().any(|f| f == "--no-overwrites") {
+ flags.push("--no-overwrites".to_string());
+ }
+ }
+ args
+ };
+ let opts = crate::models::media::DownloadOptions {
+ quality: quality.or_else(|| Some(settings.download.video_quality.clone())),
+ output_dir: final_output_dir,
+ filename_template: Some(tmpl),
+ download_subtitles: settings.download.download_subtitles,
+ include_auto_subtitles: settings.download.include_auto_subtitles,
+ download_mode,
+ audio_format,
+ format_id,
+ referer,
+ extra_headers,
+ page_url,
+ user_agent,
+ cancel_token: cancel_token.clone(),
+ concurrent_fragments: settings.advanced.concurrent_fragments,
+ ytdlp_path,
+ torrent_listen_port: Some(settings.advanced.torrent_listen_port),
+ torrent_id_slot: Some(torrent_id_slot.clone()),
+ custom_ytdlp_args: custom_ytdlp_args.clone(),
+ torrent_files: torrent_files.clone(),
+ torrent_auto_trackers: settings.advanced.torrent_auto_trackers,
+ torrent_upnp: settings.advanced.torrent_upnp,
+ };
+
+ let total_bytes = info.file_size_bytes;
+ let item_title = info.title.clone();
+ let log_title = item_title.clone();
+ let item_platform = platform_name.clone();
+ let (tx, mut rx) = mpsc::channel::<omniget_core::models::progress::ProgressUpdate>(32);
+
+ let app_progress = app.clone();
+ let queue_progress = queue.clone();
+ let torrent_id_slot_progress = torrent_id_slot.clone();
+ let progress_forwarder = tokio::spawn(async move {
+ const STALL_AFTER: std::time::Duration = std::time::Duration::from_secs(6);
+
+ let mut last_bytes: u64 = 0;
+ let mut last_time = std::time::Instant::now();
+ let mut throttle = ProgressThrottle::new(250);
+ let mut current_speed: f64 = 0.0;
+ let mut last_percent: f64 = 0.0;
+ let mut last_advance = std::time::Instant::now();
+ let mut stalled = false;
+
+ loop {
+ let update = tokio::select! {
+ msg = rx.recv() => match msg {
+ Some(u) => u,
+ None => break,
+ },
+ _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {
+ if !stalled && last_advance.elapsed() >= STALL_AFTER {
+ stalled = true;
+ current_speed = 0.0;
+ {
+ let mut q = queue_progress.lock().await;
+ let tid = { *torrent_id_slot_progress.lock().await };
+ q.update_progress(
+ item_id, last_percent, 0.0, last_bytes, total_bytes, tid, None,
+ );
+ }
+ let _ = app_progress.emit(
+ "queue-item-progress",
+ &QueueItemProgress {
+ id: item_id,
+ title: item_title.clone(),
+ platform: item_platform.clone(),
+ percent: last_percent,
+ speed_bytes_per_sec: 0.0,
+ downloaded_bytes: last_bytes,
+ total_bytes,
+ phase: "stalled".to_string(),
+ eta_seconds: None,
+ },
+ );
+ }
+ continue;
+ }
+ };
+
+ let percent = update.percent;
+ if !throttle.should_emit() && percent < 100.0 && !update.has_real_metrics() {
+ continue;
+ }
+
+ let now = std::time::Instant::now();
+ let resolved_total = update.total_bytes.or(total_bytes);
+ let mut clamped = percent.clamp(0.0, 100.0);
+ if percent >= 0.0 && percent < 100.0 {
+ if clamped < last_percent {
+ clamped = last_percent;
+ }
+
+ let metric_percent = update.downloaded_bytes.and_then(|downloaded| {
+ resolved_total
+ .filter(|total| *total > 0)
+ .map(|total| (downloaded as f64 / total as f64 * 100.0).clamp(0.0, 100.0))
+ });
+
+ if let Some(metric) = metric_percent {
+ let metric_ceiling = (metric + 15.0).max(last_percent);
+ if clamped > metric_ceiling {
+ clamped = metric_ceiling;
+ }
+ } else {
+ let max_step = if update.has_real_metrics() { 12.0 } else { 6.0 };
+ let ceiling = (last_percent + max_step).min(99.0);
+ if clamped > ceiling {
+ clamped = ceiling;
+ }
+ }
+ }
+
+ let mut downloaded_bytes = update.downloaded_bytes.unwrap_or_else(|| {
+ resolved_total
+ .map(|total| (clamped / 100.0 * total as f64) as u64)
+ .unwrap_or(last_bytes)
+ });
+ if downloaded_bytes < last_bytes && percent < 100.0 {
+ downloaded_bytes = last_bytes;
+ }
+
+ if let Some(real) = update.speed_bps {
+ current_speed = real;
+ } else if downloaded_bytes > last_bytes {
+ let dt = now.duration_since(last_time).as_secs_f64();
+ if dt > 0.1 {
+ let instant_speed = (downloaded_bytes - last_bytes) as f64 / dt;
+ current_speed = if current_speed > 0.0 {
+ current_speed * 0.7 + instant_speed * 0.3
+ } else {
+ instant_speed
+ };
+ }
+ }
+
+ if downloaded_bytes > last_bytes || clamped > last_percent || update.speed_bps.is_some()
+ {
+ last_advance = now;
+ stalled = false;
+ }
+ last_bytes = downloaded_bytes;
+ last_time = now;
+ last_percent = clamped;
+
+ let phase_value = if percent < 0.0 { percent } else { clamped };
+ let phase = if let Some(ref custom_phase) = update.phase {
+ custom_phase.as_str()
+ } else {
+ match phase_value {
+ p if p < -1.5 => "connecting",
+ p if p < -0.5 => "starting",
+ p if p > 99.5 => "finalizing",
+ p if p > 0.0 => "downloading",
+ _ => "starting",
+ }
+ };
+
+ let eta_seconds = update
+ .eta_seconds
+ .or_else(|| omniget_core::core::ytdlp::get_eta(item_id))
+ .or_else(|| {
+ if current_speed > 0.0 {
+ resolved_total.and_then(|total| {
+ (total > downloaded_bytes)
+ .then(|| ((total - downloaded_bytes) as f64 / current_speed) as u64)
+ })
+ } else {
+ None
+ }
+ });
+
+ {
+ let mut q = queue_progress.lock().await;
+ let tid = { *torrent_id_slot_progress.lock().await };
+ q.update_progress(
+ item_id,
+ clamped,
+ current_speed,
+ downloaded_bytes,
+ resolved_total,
+ tid,
+ eta_seconds,
+ );
+ }
+
+ let _ = app_progress.emit(
+ "queue-item-progress",
+ &QueueItemProgress {
+ id: item_id,
+ title: item_title.clone(),
+ platform: item_platform.clone(),
+ percent: clamped,
+ speed_bytes_per_sec: current_speed,
+ downloaded_bytes,
+ total_bytes: resolved_total,
+ phase: phase.to_string(),
+ eta_seconds,
+ },
+ );
+ }
+ omniget_core::core::ytdlp::clear_eta(item_id);
+ });
+
+ if let Some(ua) = opts.user_agent.clone() {
+ omniget_core::core::ytdlp::register_ext_user_agent(url.clone(), ua);
+ }
+ if let Some(hdrs) = opts.extra_headers.clone() {
+ omniget_core::core::ytdlp::register_ext_headers(url.clone(), hdrs);
+ }
+
+ let dl_start = std::time::Instant::now();
+ append_download_log(
+ &app,
+ item_id,
+ format!(
+ "[omniget] starting download: platform={} title=\"{}\" url={}",
+ platform_name, log_title, url
+ ),
+ );
+ let dl_future = async {
+ tokio::select! {
+ r = downloader.download(&info, &opts, tx) => r,
+ _ = cancel_token.cancelled() => {
+ Err(anyhow::anyhow!("Download cancelado"))
+ }
+ }
+ };
+ let result = omniget_core::core::log_hook::CURRENT_COOKIE_SLUG
+ .scope(
+ cookie_slug.clone(),
+ omniget_core::core::log_hook::CURRENT_DOWNLOAD_ID.scope(item_id, dl_future),
+ )
+ .await;
+ omniget_core::core::ytdlp::clear_ext_user_agent(&url);
+ omniget_core::core::ytdlp::clear_ext_headers(&url);
+ tracing::info!(
+ "[queue] download {} completed in {:?}",
+ item_id,
+ dl_start.elapsed()
+ );
+
+ let _ = progress_forwarder.await;
+
+ let was_paused = {
+ let q = queue.lock().await;
+ q.items
+ .iter()
+ .find(|i| i.id == item_id)
+ .map(|i| i.status == QueueStatus::Paused)
+ .unwrap_or(false)
+ };
+
+ if was_paused {
+ let state = {
+ let q = queue.lock().await;
+ q.get_state()
+ };
+ emit_queue_state_from_state(&app, state);
+ try_start_next(app, queue).await;
+ return;
+ }
+
+ match result {
+ Ok(dl) => {
+ append_download_log(
+ &app,
+ item_id,
+ format!(
+ "[omniget] download finished: path={} size={} bytes",
+ dl.file_path.to_string_lossy(),
+ dl.file_size_bytes
+ ),
+ );
+ let is_seeding = platform_name == "magnet" && dl.torrent_id.is_some();
+ if !is_seeding {
+ if let Err(msg) = validate_download_output(&dl.file_path).await {
+ tracing::error!(
+ "[queue] download {} reported success but output is missing or empty: {:?}",
+ item_id,
+ dl.file_path
+ );
+ append_download_log(
+ &app,
+ item_id,
+ format!(
+ "[omniget] download reported success but output missing or empty: {}",
+ dl.file_path.to_string_lossy()
+ ),
+ );
+ let state = {
+ let mut q = queue.lock().await;
+ q.mark_complete(item_id, false, Some(msg), None, None);
+ q.get_state()
+ };
+ emit_queue_state_from_state(&app, state);
+ try_start_next(app, queue).await;
+ return;
+ }
+ }
+
+ if settings.download.embed_metadata
+ && platform_name != "magnet"
+ && ffmpeg::is_ffmpeg_available().await
+ {
+ let metadata = MetadataEmbed {
+ title: Some(info.title.clone()),
+ artist: Some(info.author.clone()),
+ thumbnail_url: info.thumbnail_url.clone(),
+ ..Default::default()
+ };
+ if let Err(e) = ffmpeg::embed_metadata(
+ &dl.file_path,
+ &metadata,
+ settings.download.embed_thumbnail,
+ shared_http_client(),
+ )
+ .await
+ {
+ tracing::warn!("Metadata embed failed for '{}': {}", info.title, e);
+ }
+ }
+
+ if from_hotkey && settings.download.copy_to_clipboard_on_hotkey {
+ #[cfg(not(target_os = "android"))]
+ {
+ match crate::core::clipboard::copy_file_to_clipboard(&dl.file_path).await {
+ Ok(()) => {
+ let _ = app.emit(
+ "file-copied-to-clipboard",
+ serde_json::json!({
+ "path": dl.file_path.to_string_lossy(),
+ }),
+ );
+ }
+ Err(e) => {
+ tracing::warn!("[clipboard] failed to copy file: {}", e);
+ }
+ }
+ }
+ }
+
+ let state = {
+ let mut q = queue.lock().await;
+ if platform_name == "magnet" && dl.torrent_id.is_some() {
+ q.mark_seeding(
+ item_id,
+ Some(dl.file_path.to_string_lossy().to_string()),
+ Some(dl.file_size_bytes),
+ dl.torrent_id,
+ );
+ } else {
+ q.mark_complete(
+ item_id,
+ true,
+ None,
+ Some(dl.file_path.to_string_lossy().to_string()),
+ Some(dl.file_size_bytes),
+ );
+ }
+ q.get_state()
+ };
+ emit_queue_state_from_state(&app, state);
+ }
+ Err(e) => {
+ let raw_err = e.to_string();
+ append_download_log(
+ &app,
+ item_id,
+ format!("[omniget] download failed: {}", raw_err),
+ );
+ let (category, hint) = omniget_core::core::errors::classify_download_error(&raw_err);
+ let user_msg = if category != "unknown" {
+ format!("{} ({})", hint, raw_err)
+ } else {
+ raw_err.clone()
+ };
+ tracing::error!(
+ "Download error '{}' [{}]: {}",
+ platform_name,
+ category,
+ raw_err
+ );
+
+ let retry_decision = {
+ let mut q = queue.lock().await;
+ if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {
+ if item.downloaded_bytes > 5 * 1024 * 1024 {
+ item.retry_count = 0;
+ }
+ let retryable = is_retryable_category(category);
+ let attempt = item.retry_count;
+ let max = item.max_retries;
+ if retryable && attempt < max {
+ item.retry_count = attempt + 1;
+ Some((attempt + 1, max))
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ };
+
+ if let Some((next_attempt, max)) = retry_decision {
+ let delay_secs = (1u64 << (next_attempt - 1).min(5)).min(30);
+ tracing::warn!(
+ "[queue] retry {}/{} for {} in {}s (category={})",
+ next_attempt,
+ max,
+ item_id,
+ delay_secs,
+ category
+ );
+ let state = {
+ let mut q = queue.lock().await;
+ if let Some(item) = q.items.iter_mut().find(|i| i.id == item_id) {
+ item.status = QueueStatus::Queued;
+ item.cancel_token = CancellationToken::new();
+ item.percent = 0.0;
+ item.speed_bytes_per_sec = 0.0;
+ item.downloaded_bytes = 0;
+ }
+ q.get_state()
+ };
+ emit_queue_state_from_state(&app, state);
+ let app_for_retry = app.clone();
+ let queue_for_retry = queue.clone();
+ tokio::spawn(async move {
+ tokio::time::sleep(std::time::Duration::from_secs(delay_secs)).await;
+ try_start_next(app_for_retry, queue_for_retry).await;
+ });
+ return;
+ }
+
+ let state = {
+ let mut q = queue.lock().await;
+ q.mark_complete(item_id, false, Some(user_msg), None, None);
+ q.get_state()
+ };
+ emit_queue_state_from_state(&app, state);
+ }
+ }
+
+ try_start_next(app, queue).await;
+}
+
+fn is_retryable_category(category: &str) -> bool {
+ matches!(category, "unknown" | "rate_limited")
+}
+
+const OUTPUT_MISSING_ERROR: &str =
+ "Download reported success but the file is missing or empty. Check disk space and antivirus exclusions, then retry.";
+
+async fn validate_download_output(path: &std::path::Path) -> Result<(), String> {
+ if path.as_os_str().is_empty() {
+ return Err(OUTPUT_MISSING_ERROR.to_string());
+ }
+ let meta = match tokio::fs::metadata(path).await {
+ Ok(m) => m,
+ Err(_) => return Err(OUTPUT_MISSING_ERROR.to_string()),
+ };
+ if meta.is_dir() {
+ let mut entries = match tokio::fs::read_dir(path).await {
+ Ok(e) => e,
+ Err(_) => return Err(OUTPUT_MISSING_ERROR.to_string()),
+ };
+ match entries.next_entry().await {
+ Ok(Some(_)) => Ok(()),
+ _ => Err(OUTPUT_MISSING_ERROR.to_string()),
+ }
+ } else if meta.len() > 0 {
+ Ok(())
+ } else {
+ Err(OUTPUT_MISSING_ERROR.to_string())
+ }
+}
+
+async fn fetch_and_cache_info(
+ url: &str,
+ downloader: &dyn PlatformDownloader,
+ platform: &str,
+ ytdlp_path: Option<&std::path::Path>,
+) -> anyhow::Result<MediaInfo> {
+ {
+ let cache = info_cache().lock().await;
+ if let Some(entry) = cache.get(url) {
+ if entry.cached_at.elapsed() < INFO_CACHE_TTL {
+ tracing::debug!("[perf] fetch_and_cache_info: cache hit for {}", platform);
+ return Ok(entry.info.clone());
+ }
+ }
+ }
+
+ let url_lock = {
+ let mut map = in_flight_map().lock().await;
+ map.entry(url.to_string())
+ .or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
+ .clone()
+ };
+ let _guard = url_lock.lock().await;
+
+ {
+ let cache = info_cache().lock().await;
+ if let Some(entry) = cache.get(url) {
+ if entry.cached_at.elapsed() < INFO_CACHE_TTL {
+ tracing::debug!(
+ "[perf] fetch_and_cache_info: dedup cache hit for {}",
+ platform
+ );
+ return Ok(entry.info.clone());
+ }
+ }
+ }
+
+ tracing::debug!("[perf] fetch_and_cache_info: fetching for {}", platform);
+ let info = if let Some(ytdlp) = ytdlp_path {
+ match platform {
+ "youtube" => {
+ omniget_core::platforms::YouTubeDownloader::fetch_with_ytdlp(url, ytdlp).await?
+ }
+ "generic" => {
+ if crate::platforms::generic_ytdlp::is_direct_media_url(url).is_some() {
+ downloader.get_media_info(url).await?
+ } else {
+ let json = crate::core::ytdlp::get_video_info(ytdlp, url, &[]).await?;
+ crate::platforms::generic_ytdlp::GenericYtdlpDownloader::parse_video_info(
+ &json,
+ )?
+ }
+ }
+ _ => downloader.get_media_info(url).await?,
+ }
+ } else {
+ downloader.get_media_info(url).await?
+ };
+
+ let mut cache = info_cache().lock().await;
+ cache.insert(
+ url.to_string(),
+ CachedInfo {
+ info: info.clone(),
+ cached_at: std::time::Instant::now(),
+ },
+ );
+ if cache.len() > 50 {
+ cache.retain(|_, v| v.cached_at.elapsed() < INFO_CACHE_TTL);
+ }
+ Ok(info)
+}
+
+pub async fn try_get_cached_info(url: &str) -> Option<MediaInfo> {
+ let cache = info_cache().lock().await;
+ cache
+ .get(url)
+ .filter(|entry| entry.cached_at.elapsed() < INFO_CACHE_TTL)
+ .map(|entry| entry.info.clone())
+}
+
+pub async fn prefetch_info(
+ url: &str,
+ downloader: &dyn PlatformDownloader,
+ platform: &str,
+ ytdlp_path: Option<&std::path::Path>,
+) {
+ prefetch_info_with_emit(url, downloader, platform, ytdlp_path, None).await;
+}
+
+pub async fn prefetch_info_with_emit(
+ url: &str,
+ downloader: &dyn PlatformDownloader,
+ platform: &str,
+ ytdlp_path: Option<&std::path::Path>,
+ app: Option<tauri::AppHandle>,
+) {
+ let _timer_start = std::time::Instant::now();
+ tracing::debug!("[perf] prefetch_info: started");
+ let result = tokio::time::timeout(
+ std::time::Duration::from_secs(15),
+ fetch_and_cache_info(url, downloader, platform, ytdlp_path),
+ )
+ .await;
+ match result {
+ Ok(Ok(info)) => {
+ tracing::debug!(
+ "[perf] prefetch_info: completed in {:?} — {}",
+ _timer_start.elapsed(),
+ info.title
+ );
+ if let Some(app) = app {
+ let preview = MediaPreviewEvent {
+ url: url.to_string(),
+ title: info.title.clone(),
+ author: info.author.clone(),
+ thumbnail_url: info.thumbnail_url.clone(),
+ duration_seconds: info.duration_seconds,
+ };
+ let _ = app.emit("media-info-preview", preview);
+ }
+ }
+ Ok(Err(e)) => tracing::warn!(
+ "[perf] prefetch_info: failed in {:?} — {}",
+ _timer_start.elapsed(),
+ e
+ ),
+ Err(_) => tracing::warn!(
+ "[perf] prefetch_info: timed out after {:?}",
+ _timer_start.elapsed()
+ ),
+ }
+}
+
+pub async fn try_start_next(app: tauri::AppHandle, queue: Arc<tokio::sync::Mutex<DownloadQueue>>) {
+ let _timer_start = std::time::Instant::now();
+ let (next_ids, stagger, state_to_emit) = {
+ let mut q = queue.lock().await;
+ let ids = q.next_queued_ids();
+ for nid in &ids {
+ q.mark_active(*nid);
+ }
+ let state = if !ids.is_empty() {
+ Some(q.get_state())
+ } else {
+ None
+ };
+ (ids, q.stagger_delay_ms, state)
+ };
+
+ if let Some(state) = state_to_emit {
+ emit_queue_state_from_state(&app, state);
+ }
+
+ let batch_size = next_ids.len();
+ for (i, nid) in next_ids.into_iter().enumerate() {
+ let _ = app.emit(
+ "queue-item-progress",
+ &QueueItemProgress {
+ id: nid,
+ title: String::new(),
+ platform: String::new(),
+ percent: 0.0,
+ speed_bytes_per_sec: 0.0,
+ downloaded_bytes: 0,
+ total_bytes: None,
+ phase: "queued_starting".to_string(),
+ eta_seconds: None,
+ },
+ );
+
+ if i > 0 {
+ let item_platform = {
+ let q = queue.lock().await;
+ q.items
+ .iter()
+ .find(|item| item.id == nid)
+ .map(|item| item.platform.clone())
+ };
+ let delay_ms = if item_platform.as_deref() == Some("youtube") {
+ 2000
+ } else if batch_size > 3 {
+ stagger.max(1000)
+ } else {
+ stagger
+ };
+ if delay_ms > 0 {
+ tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
+ }
+ }
+ let app_c = app.clone();
+ let queue_c = queue.clone();
+ tokio::spawn(async move {
+ spawn_download(app_c, queue_c, nid).await;
+ });
+ }
+ tracing::debug!("[perf] try_start_next took {:?}", _timer_start.elapsed());
+}
+
+// Periodic tick so a future-scheduled download still starts when its time
+// arrives even if the queue is otherwise idle, and so a download with a
+// stop time is cancelled when that time passes.
+pub fn start_scheduler(app: tauri::AppHandle) {
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(std::time::Duration::from_secs(15)).await;
+ loop {
+ let state = app.state::<crate::AppState>();
+ let queue = state.download_queue.clone();
+ let (has_due, stopped_any) = {
+ let q = queue.lock().await;
+ let now = now_ms();
+ let mut stopped = false;
+ for item in &q.items {
+ if item.status == QueueStatus::Active {
+ if let Some(stop) = item.stop_at_ms {
+ if now >= stop {
+ item.cancel_token.cancel();
+ stopped = true;
+ }
+ }
+ }
+ }
+ let due = q.items.iter().any(|i| {
+ i.status == QueueStatus::Queued
+ && i.scheduled_at_ms.map(|t| now >= t).unwrap_or(false)
+ });
+ (due, stopped)
+ };
+ if has_due || stopped_any {
+ try_start_next(app.clone(), queue.clone()).await;
+ }
+ tokio::time::sleep(std::time::Duration::from_secs(15)).await;
+ }
+ });
+}
+
+fn is_generic_title(title: &str) -> bool {
+ let t = title.to_lowercase();
+ let t = t.trim();
+ t.is_empty()
+ || t == "video"
+ || t == "media"
+ || t == "untitled"
+ || t == "unknown"
+ || t.starts_with("video [video]")
+ || t.starts_with("media [media]")
+}
+
+#[cfg(test)]
+mod kind_tests {
+ use super::{kind_from_platform, QueueKind};
+
+ #[test]
+ fn youtube_and_video_platforms_map_to_video() {
+ assert_eq!(kind_from_platform("youtube"), QueueKind::Video);
+ assert_eq!(kind_from_platform("vimeo"), QueueKind::Video);
+ assert_eq!(kind_from_platform("twitch"), QueueKind::Video);
+ assert_eq!(kind_from_platform("bilibili"), QueueKind::Video);
+ assert_eq!(kind_from_platform("tiktok"), QueueKind::Video);
+ assert_eq!(kind_from_platform("instagram"), QueueKind::Video);
+ assert_eq!(kind_from_platform("reddit"), QueueKind::Video);
+ assert_eq!(kind_from_platform("bluesky"), QueueKind::Video);
+ assert_eq!(kind_from_platform("generic_ytdlp"), QueueKind::Video);
+ }
+
+ #[test]
+ fn audio_platforms() {
+ assert_eq!(kind_from_platform("soundcloud"), QueueKind::Audio);
+ assert_eq!(kind_from_platform("spotify"), QueueKind::Audio);
+ }
+
+ #[test]
+ fn pinterest_is_image() {
+ assert_eq!(kind_from_platform("pinterest"), QueueKind::Image);
+ }
+
+ #[test]
+ fn pdf_kind() {
+ assert_eq!(kind_from_platform("pdf"), QueueKind::Pdf);
+ }
+
+ #[test]
+ fn book_platforms() {
+ assert_eq!(kind_from_platform("annas_archive"), QueueKind::Book);
+ assert_eq!(kind_from_platform("libgen"), QueueKind::Book);
+ assert_eq!(kind_from_platform("gutendex"), QueueKind::Book);
+ assert_eq!(kind_from_platform("book"), QueueKind::Book);
+ }
+
+ #[test]
+ fn webpage_kind() {
+ assert_eq!(kind_from_platform("webpage"), QueueKind::Webpage);
+ assert_eq!(kind_from_platform("embed"), QueueKind::Webpage);
+ }
+
+ #[test]
+ fn telegram_kind() {
+ assert_eq!(kind_from_platform("telegram"), QueueKind::TelegramMedia);
+ assert_eq!(
+ kind_from_platform("telegram_media"),
+ QueueKind::TelegramMedia
+ );
+ }
+
+ #[test]
+ fn course_lesson_kind() {
+ assert_eq!(kind_from_platform("courses"), QueueKind::CourseLesson);
+ assert_eq!(kind_from_platform("course_lesson"), QueueKind::CourseLesson);
+ }
+
+ #[test]
+ fn generic_for_torrents_and_p2p() {
+ assert_eq!(kind_from_platform("magnet"), QueueKind::Generic);
+ assert_eq!(kind_from_platform("p2p"), QueueKind::Generic);
+ assert_eq!(kind_from_platform("torrent"), QueueKind::Generic);
+ }
+
+ #[test]
+ fn unknown_platform_falls_back_to_generic() {
+ assert_eq!(kind_from_platform(""), QueueKind::Generic);
+ assert_eq!(kind_from_platform("totally-unknown"), QueueKind::Generic);
+ assert_eq!(kind_from_platform("xyz123"), QueueKind::Generic);
+ }
+
+ #[test]
+ fn case_insensitive() {
+ assert_eq!(kind_from_platform("YouTube"), QueueKind::Video);
+ assert_eq!(kind_from_platform("TELEGRAM"), QueueKind::TelegramMedia);
+ }
+}
diff --git a/src/components/celebrate/Confetti.svelte b/src/components/celebrate/Confetti.svelte
index a988d592..6e204791 100644
--- a/src/components/celebrate/Confetti.svelte
+++ b/src/components/celebrate/Confetti.svelte
@@ -58,7 +58,7 @@
{#each particles as p (p.id)}
<span
class="particle"
- style="--tx: {p.x}px; --ty: {p.y}px; --rot: {p.rot}deg; --color: {p.color}; --delay: {p.delay}ms;"
+ style:--tx="{p.x}px" style:--ty="{p.y}px" style:--rot="{p.rot}deg" style:--color="{p.color}" style:--delay="{p.delay}ms"
></span>
{/each}
{/if}
diff --git a/src/components/dialog/TelegramUploadModal.svelte b/src/components/dialog/TelegramUploadModal.svelte
new file mode 100644
index 00000000..851753cf
--- /dev/null
+++ b/src/components/dialog/TelegramUploadModal.svelte
@@ -0,0 +1,627 @@
+<script lang="ts">
+ import { open as openFileDialog } from "@tauri-apps/plugin-dialog";
+ import { t } from "$lib/i18n";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import { formatBytes } from "$lib/stores/download-store.svelte";
+ import {
+ telegramUploadFile,
+ calculateTelegramChunks,
+ translateTelegramError,
+ type TelegramUploadTier,
+ type TelegramSendAsMode,
+ type TelegramChat,
+ telegramGetChats,
+ } from "$lib/study-telegram-bridge";
+ import { onMount } from "svelte";
+
+ let {
+ open = false,
+ filePath = "",
+ fileSize = 0,
+ defaultName = "",
+ defaultThumb = null as string | null,
+ onClose = () => {},
+ }: {
+ open?: boolean;
+ filePath?: string;
+ fileSize?: number;
+ defaultName?: string;
+ defaultThumb?: string | null;
+ onClose?: () => void;
+ } = $props();
+
+ type AuthMode = "user_session" | "bot_token";
+ let authMode = $state<AuthMode>("user_session");
+
+ let botToken = $state("");
+ let destChatId = $state("");
+ let customFileName = $state("");
+ let customThumbPath = $state<string | null>(null);
+ let caption = $state("");
+ let tier = $state<TelegramUploadTier>("free");
+ let sendAs = $state<TelegramSendAsMode>("video");
+
+ let chats = $state<TelegramChat[]>([]);
+ let loadingChats = $state(false);
+ let selectedChatId = $state<number | null>(null);
+
+ let uploading = $state(false);
+ let uploadSuccess = $state(false);
+ let uploadError = $state<string | null>(null);
+
+ function autoDetectSendAs(fileNameOrPath: string): TelegramSendAsMode {
+ const ext = fileNameOrPath.split(".").pop()?.toLowerCase() ?? "";
+ if (["mp4", "mkv", "avi", "mov", "webm", "flv", "m4v"].includes(ext)) return "video";
+ if (["mp3", "m4a", "flac", "aac", "ogg", "wav", "opus"].includes(ext)) return "audio";
+ return "document";
+ }
+
+ function onKeydown(e: KeyboardEvent) {
+ if (open && e.key === "Escape" && !uploading) {
+ e.preventDefault();
+ onClose();
+ }
+ }
+
+ onMount(() => {
+ window.addEventListener("keydown", onKeydown);
+ return () => window.removeEventListener("keydown", onKeydown);
+ });
+
+ $effect(() => {
+ if (open) {
+ customFileName = defaultName || filePath.split(/[/\\]/).pop() || "";
+ customThumbPath = defaultThumb || null;
+ sendAs = autoDetectSendAs(customFileName || filePath);
+ uploading = false;
+ uploadSuccess = false;
+ uploadError = null;
+ if (authMode === "user_session" && chats.length === 0) {
+ loadUserChats();
+ }
+ }
+ });
+
+ async function loadUserChats() {
+ loadingChats = true;
+ try {
+ chats = await telegramGetChats();
+ if (chats.length > 0) {
+ selectedChatId = chats[0].id;
+ }
+ } catch {
+ // User session might not be logged in
+ } finally {
+ loadingChats = false;
+ }
+ }
+
+ let chunkAnalysis = $derived(calculateTelegramChunks(fileSize, tier));
+
+ async function pickThumbnail() {
+ try {
+ const selected = await openFileDialog({
+ title: $t("telegram.pick_thumbnail") as string,
+ filters: [{ name: "Images", extensions: ["jpg", "jpeg", "png", "webp"] }],
+ multiple: false,
+ });
+ if (selected && typeof selected === "string") {
+ customThumbPath = selected;
+ }
+ } catch (e) {
+ console.warn("pick thumbnail error", e);
+ }
+ }
+
+ function clearThumbnail() {
+ customThumbPath = null;
+ }
+
+ function normalizeTargetChat(input: string): string {
+ let trimmed = input.trim();
+ if (trimmed.startsWith("https://t.me/")) {
+ const parts = trimmed.replace("https://t.me/", "").split("/");
+ return "@" + parts[0];
+ }
+ if (trimmed.startsWith("t.me/")) {
+ const parts = trimmed.replace("t.me/", "").split("/");
+ return "@" + parts[0];
+ }
+ return trimmed;
+ }
+
+ function validateBotToken(token: string): boolean {
+ return /^\d+:[A-Za-z0-9_-]+$/.test(token.trim());
+ }
+
+ async function handleUpload() {
+ if (!filePath.trim()) {
+ uploadError = $t("telegram.error_no_file") as string;
+ return;
+ }
+
+ const rawTarget = authMode === "bot_token"
+ ? destChatId
+ : (selectedChatId ? String(selectedChatId) : destChatId);
+
+ const targetChat = normalizeTargetChat(rawTarget);
+
+ if (!targetChat) {
+ uploadError = $t("telegram.error_no_chat") as string;
+ return;
+ }
+ if (authMode === "bot_token") {
+ if (!botToken.trim()) {
+ uploadError = $t("telegram.error_no_bot_token") as string;
+ return;
+ }
+ if (!validateBotToken(botToken)) {
+ uploadError = $t("telegram.error_invalid_bot_token") as string;
+ return;
+ }
+ }
+
+ uploading = true;
+ uploadError = null;
+ uploadSuccess = false;
+
+ try {
+ const res = await telegramUploadFile({
+ filePath,
+ destChatId: targetChat,
+ customFileName: customFileName.trim() || undefined,
+ customThumbnailPath: customThumbPath || undefined,
+ caption: caption.trim() || undefined,
+ botToken: authMode === "bot_token" ? botToken.trim() : undefined,
+ tier,
+ sendAs,
+ });
+
+ if (res.success || res.messageId) {
+ uploadSuccess = true;
+ showToast("success", $t("telegram.upload_success") as string);
+ setTimeout(() => {
+ onClose();
+ }, 1200);
+ } else {
+ uploadError = $t("telegram.upload_failed") as string;
+ }
+ } catch (e: any) {
+ const rawErr = typeof e === "string" ? e : e.message ?? ($t("telegram.upload_failed") as string);
+ uploadError = translateTelegramError(rawErr, (key) => $t(key) as string);
+ showToast("error", uploadError);
+ } finally {
+ uploading = false;
+ }
+ }
+</script>
+
+{#if open}
+ <div class="overlay" role="presentation" onclick={(e) => { if (e.target === e.currentTarget && !uploading) onClose(); }}>
+ <div class="dialog" role="dialog" aria-modal="true" aria-labelledby="tg-upload-title">
+ <header class="head">
+ <h3 id="tg-upload-title">{$t('telegram.upload_title')}</h3>
+ <button class="close" onclick={onClose} disabled={uploading} aria-label={$t('common.close')}>×</button>
+ </header>
+
+ <div class="body">
+ <div class="auth-tabs" role="tablist">
+ <button
+ class="tab-btn"
+ class:active={authMode === "user_session"}
+ onclick={() => { authMode = "user_session"; if (chats.length === 0) loadUserChats(); }}
+ role="tab"
+ aria-selected={authMode === "user_session"}
+ >
+ {$t('telegram.auth_user_session')}
+ </button>
+ <button
+ class="tab-btn"
+ class:active={authMode === "bot_token"}
+ onclick={() => { authMode = "bot_token"; }}
+ role="tab"
+ aria-selected={authMode === "bot_token"}
+ >
+ {$t('telegram.auth_bot_token')}
+ </button>
+ </div>
+
+ {#if authMode === "user_session"}
+ <div class="field-group">
+ <label class="field-label" for="tg-chat-select">{$t('telegram.destination_chat')}</label>
+ {#if loadingChats}
+ <div class="field-hint">{$t('common.loading')}</div>
+ {:else if chats.length > 0}
+ <select id="tg-chat-select" class="select-full" bind:value={selectedChatId}>
+ {#each chats as chat (chat.id)}
+ <option value={chat.id}>{chat.title} ({chat.chat_type})</option>
+ {/each}
+ </select>
+ {:else}
+ <input
+ id="tg-chat-select"
+ type="text"
+ class="input-full"
+ placeholder={$t('telegram.dest_placeholder')}
+ bind:value={destChatId}
+ />
+ <span class="field-hint">{$t('telegram.user_session_hint')}</span>
+ {/if}
+ </div>
+ {:else}
+ <div class="field-group">
+ <label class="field-label" for="tg-bot-token">{$t('telegram.bot_token_label')}</label>
+ <input
+ id="tg-bot-token"
+ type="password"
+ class="input-full"
+ placeholder="123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ"
+ bind:value={botToken}
+ />
+ </div>
+ <div class="field-group">
+ <label class="field-label" for="tg-bot-chat">{$t('telegram.bot_chat_id_label')}</label>
+ <input
+ id="tg-bot-chat"
+ type="text"
+ class="input-full"
+ placeholder="@channel_username, chat_id or -100123456789"
+ bind:value={destChatId}
+ />
+ </div>
+ {/if}
+
+ <div class="field-group">
+ <label class="field-label">{$t('telegram.send_as_label')}</label>
+ <div class="send-as-pills">
+ <button
+ class="send-as-pill"
+ class:active={sendAs === "video"}
+ onclick={() => { sendAs = "video"; }}
+ >
+ 🎬 {$t('telegram.send_as_video')}
+ </button>
+ <button
+ class="send-as-pill"
+ class:active={sendAs === "document"}
+ onclick={() => { sendAs = "document"; }}
+ >
+ 📄 {$t('telegram.send_as_document')}
+ </button>
+ <button
+ class="send-as-pill"
+ class:active={sendAs === "audio"}
+ onclick={() => { sendAs = "audio"; }}
+ >
+ 🎵 {$t('telegram.send_as_audio')}
+ </button>
+ </div>
+ </div>
+
+ <div class="field-group">
+ <label class="field-label" for="tg-filename">{$t('telegram.custom_filename_label')}</label>
+ <input
+ id="tg-filename"
+ type="text"
+ class="input-full"
+ bind:value={customFileName}
+ placeholder="video_name.mp4"
+ />
+ <span class="field-hint">{$t('telegram.custom_filename_hint')}</span>
+ </div>
+
+ <div class="field-group">
+ <label class="field-label" for="tg-thumb-btn">{$t('telegram.custom_thumbnail_label')}</label>
+ <div class="thumb-row">
+ {#if customThumbPath}
+ <span class="thumb-path" title={customThumbPath}>{customThumbPath.split(/[/\\]/).pop()}</span>
+ <button class="button button-small" onclick={clearThumbnail}>{$t('common.remove')}</button>
+ {:else}
+ <button id="tg-thumb-btn" class="button" onclick={pickThumbnail}>{$t('telegram.pick_thumbnail')}</button>
+ {/if}
+ </div>
+ </div>
+
+ <div class="field-group">
+ <label class="field-label" for="tg-caption">{$t('telegram.caption_label')}</label>
+ <textarea
+ id="tg-caption"
+ class="textarea-full"
+ rows="2"
+ bind:value={caption}
+ placeholder={$t('telegram.caption_placeholder') as string}
+ ></textarea>
+ </div>
+
+ <div class="field-group">
+ <label class="field-label">{$t('telegram.tier_limit_label')}</label>
+ <div class="tier-pills">
+ <button
+ class="tier-pill"
+ class:active={tier === "free"}
+ onclick={() => { tier = "free"; }}
+ >
+ {$t('telegram.tier_free')} (2.0 GB)
+ </button>
+ <button
+ class="tier-pill"
+ class:active={tier === "premium"}
+ onclick={() => { tier = "premium"; }}
+ >
+ {$t('telegram.tier_premium')} (4.0 GB)
+ </button>
+ </div>
+ </div>
+
+ {#if chunkAnalysis.requiresSplit}
+ <div class="split-warning">
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z" />
+ <line x1="12" y1="9" x2="12" y2="13" />
+ <line x1="12" y1="17" x2="12.01" y2="17" />
+ </svg>
+ <span>
+ {$t('telegram.split_warning', {
+ size: formatBytes(fileSize),
+ limit: formatBytes(chunkAnalysis.limitBytes),
+ parts: String(chunkAnalysis.partCount),
+ })}
+ </span>
+ </div>
+ {/if}
+
+ {#if uploadError}
+ <div class="error-banner">{uploadError}</div>
+ {/if}
+ </div>
+
+ <footer class="foot">
+ <button class="button" onclick={onClose} disabled={uploading}>{$t('common.cancel')}</button>
+ <button class="button action-btn" onclick={handleUpload} disabled={uploading}>
+ {#if uploading}
+ <span class="spinner"></span> {$t('telegram.uploading')}
+ {:else if uploadSuccess}
+ ✓ {$t('telegram.upload_success')}
+ {:else}
+ {$t('telegram.start_upload')}
+ {/if}
+ </button>
+ </footer>
+ </div>
+ </div>
+{/if}
+
+<style>
+ .overlay {
+ position: fixed;
+ inset: 0;
+ background: var(--dialog-backdrop, rgba(0, 0, 0, 0.5));
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 1000;
+ }
+
+ .dialog {
+ background: var(--popup-bg, #1a1a1a);
+ border: 1px solid var(--content-border, rgba(255, 255, 255, 0.1));
+ border-radius: var(--border-radius, 12px);
+ width: 490px;
+ max-width: 90vw;
+ display: flex;
+ flex-direction: column;
+ box-shadow: 0 16px 40px rgba(0, 0, 0, 0.4);
+ overflow: hidden;
+ }
+
+ .head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 18px;
+ border-bottom: 1px solid var(--content-border);
+ }
+
+ .head h3 {
+ font-size: 15px;
+ font-weight: 600;
+ margin: 0;
+ }
+
+ .close {
+ background: none;
+ border: none;
+ font-size: 20px;
+ color: var(--gray);
+ cursor: pointer;
+ }
+
+ .body {
+ padding: 16px 18px;
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ max-height: 70vh;
+ overflow-y: auto;
+ }
+
+ .auth-tabs {
+ display: flex;
+ gap: 4px;
+ background: var(--button);
+ padding: 3px;
+ border-radius: 8px;
+ }
+
+ .tab-btn {
+ flex: 1;
+ padding: 6px 10px;
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--gray);
+ background: transparent;
+ border: none;
+ border-radius: 6px;
+ cursor: pointer;
+ }
+
+ .tab-btn.active {
+ background: var(--button-elevated);
+ color: var(--text);
+ }
+
+ .field-group {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+
+ .field-label {
+ font-size: 12.5px;
+ font-weight: 500;
+ color: var(--gray);
+ }
+
+ .field-hint {
+ font-size: 11px;
+ color: var(--gray);
+ opacity: 0.8;
+ }
+
+ .input-full,
+ .select-full,
+ .textarea-full {
+ width: 100%;
+ padding: 8px 12px;
+ font-size: 13px;
+ background: var(--input-bg, rgba(0, 0, 0, 0.2));
+ border: 1px solid var(--input-border, rgba(255, 255, 255, 0.15));
+ border-radius: 8px;
+ color: var(--text);
+ box-sizing: border-box;
+ }
+
+ .send-as-pills,
+ .tier-pills {
+ display: flex;
+ gap: 8px;
+ }
+
+ .send-as-pill,
+ .tier-pill {
+ flex: 1;
+ padding: 6px 10px;
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--gray);
+ background: var(--button);
+ border: 1px solid transparent;
+ border-radius: 6px;
+ cursor: pointer;
+ text-align: center;
+ }
+
+ .send-as-pill.active,
+ .tier-pill.active {
+ background: var(--button-elevated);
+ color: var(--accent);
+ border-color: var(--accent);
+ }
+
+ .thumb-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+
+ .thumb-path {
+ font-size: 12px;
+ font-family: var(--font-mono);
+ color: var(--accent);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ max-width: 250px;
+ }
+
+ .split-warning {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 12px;
+ background: color-mix(in srgb, #f59e0b 15%, transparent);
+ color: #f59e0b;
+ border-radius: 8px;
+ font-size: 12px;
+ line-height: 1.4;
+ }
+
+ .error-banner {
+ padding: 8px 12px;
+ background: color-mix(in srgb, var(--error, #ef4444) 15%, transparent);
+ color: var(--error, #ef4444);
+ border-radius: 8px;
+ font-size: 12px;
+ }
+
+ .foot {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 10px;
+ padding: 12px 18px;
+ border-top: 1px solid var(--content-border);
+ }
+
+ .action-btn {
+ background: var(--accent);
+ color: #fff;
+ border: none;
+ font-weight: 600;
+ }
+
+ .button-small {
+ padding: 4px 8px;
+ font-size: 11px;
+ }
+
+ .spinner {
+ display: inline-block;
+ width: 12px;
+ height: 12px;
+ border: 2px solid rgba(255, 255, 255, 0.3);
+ border-radius: 50%;
+ border-top-color: #fff;
+ animation: spin 0.8s linear infinite;
+ }
+
+ .input-full:focus-visible,
+ .select-full:focus-visible,
+ .textarea-full:focus-visible,
+ .tab-btn:focus-visible,
+ .send-as-pill:focus-visible,
+ .tier-pill:focus-visible,
+ .button:focus-visible,
+ .close:focus-visible {
+ outline: 2px solid var(--accent, #3b82f6);
+ outline-offset: 2px;
+ }
+
+ @media (max-width: 535px) {
+ .dialog {
+ width: 100vw;
+ max-width: 100vw;
+ border-radius: 0;
+ height: 100vh;
+ max-height: 100vh;
+ }
+ .send-as-pills,
+ .tier-pills {
+ flex-direction: column;
+ }
+ }
+
+ @keyframes spin {
+ to { transform: rotate(360deg); }
+ }
+</style>
diff --git a/src/components/download/DownloadSpeedGraph.svelte b/src/components/download/DownloadSpeedGraph.svelte
index 002f0f8d..d6646e9d 100644
--- a/src/components/download/DownloadSpeedGraph.svelte
+++ b/src/components/download/DownloadSpeedGraph.svelte
@@ -75,7 +75,7 @@
<div
class="speed-graph"
- style="width: {width}px; height: {height}px"
+ style:width="{width}px" style:height="{height}px"
title="Now: {formatSpeed(currentBps)} • Peak: {formatSpeed(peakBps)}"
aria-hidden="true"
>
diff --git a/src/components/downloads/SubtitleWorkshop.svelte b/src/components/downloads/SubtitleWorkshop.svelte
index 2a598990..5690972e 100644
--- a/src/components/downloads/SubtitleWorkshop.svelte
+++ b/src/components/downloads/SubtitleWorkshop.svelte
@@ -286,10 +286,10 @@
{#if peaks.length}
<div class="wave" aria-hidden="true">
{#each peaks as p, idx (idx)}
- <span class="bar" style="height:{Math.max(2, p * 100)}%"></span>
+ <span class="bar" style:height="{Math.max(2, p * 100)}%"></span>
{/each}
{#each shots as sec (sec)}
- <span class="shot" style="left:{durationMs ? (sec * 1000 / durationMs) * 100 : 0}%"></span>
+ <span class="shot" style:left="{durationMs ? (sec * 1000 / durationMs) * 100 : 0}%"></span>
{/each}
</div>
{/if}
diff --git a/src/components/hotmart/CourseCard.svelte b/src/components/hotmart/CourseCard.svelte
index 0bd31874..a5e1eb8c 100644
--- a/src/components/hotmart/CourseCard.svelte
+++ b/src/components/hotmart/CourseCard.svelte
@@ -88,7 +88,7 @@
<div class="mini-progress-track">
<div
class="mini-progress-fill"
- style="width: {downloadPercent.toFixed(1)}%"
+ style:width="{downloadPercent.toFixed(1)}%"
></div>
</div>
{:else if downloadStatus === "complete"}
diff --git a/src/components/omnibox/QualityPicker.svelte b/src/components/omnibox/QualityPicker.svelte
index faa2dcc1..67c4a4de 100644
--- a/src/components/omnibox/QualityPicker.svelte
+++ b/src/components/omnibox/QualityPicker.svelte
@@ -1,31 +1,73 @@
<script lang="ts">
import { t } from "$lib/i18n";
- let { selectedQuality = $bindable("best"), selectedFormatId } = $props();
+ let {
+ selectedQuality = $bindable("best"),
+ selectedFormatId,
+ availableHeights = null as number[] | null,
+ hasAudioOnly = false,
+ } = $props();
- const qualities = [
- { value: "best", key: "omnibox.quality_best" },
- { value: "1080p", key: "omnibox.quality_1080p" },
- { value: "720p", key: "omnibox.quality_720p" },
- { value: "480p", key: "omnibox.quality_480p" },
- { value: "360p", key: "omnibox.quality_360p" },
+ // Full ordered list of resolution options (label, yt-dlp quality value, height for filtering)
+ const RESOLUTION_OPTIONS = [
+ { value: "best", key: "omnibox.quality_best", height: Infinity },
+ { value: "2160p", key: "omnibox.quality_2160p", height: 2160 },
+ { value: "1440p", key: "omnibox.quality_1440p", height: 1440 },
+ { value: "1080p", key: "omnibox.quality_1080p", height: 1080 },
+ { value: "720p", key: "omnibox.quality_720p", height: 720 },
+ { value: "480p", key: "omnibox.quality_480p", height: 480 },
+ { value: "360p", key: "omnibox.quality_360p", height: 360 },
];
+
+ // Derive which resolution pills to show.
+ // Before formats load: show standard set (Best + 1080p + 720p + 480p + 360p).
+ // After formats load: show only resolutions actually available, plus Best always.
+ let visibleOptions = $derived.by(() => {
+ if (!availableHeights) {
+ // Pre-fetch fallback: strip 2K / 4K from hardcoded list to keep UI tidy
+ return RESOLUTION_OPTIONS.filter(o => o.height === Infinity || o.height <= 1080);
+ }
+ return RESOLUTION_OPTIONS.filter(o => {
+ if (o.height === Infinity) return true; // "Best" always shown
+ return availableHeights!.some(h => h === o.height);
+ });
+ });
+
+ // i18n keys that may not exist yet — provide a fallback label
+ function qualityLabel(value: string, key: string): string {
+ const translated = $t(key);
+ // If no translation key exists (e.g. 2160p, 1440p), build a label from value
+ if (translated === key) return value;
+ return translated;
+ }
</script>
{#if !selectedFormatId}
<div class="quality-group">
<span class="quality-label">{$t('omnibox.quality')}</span>
<div class="quality-pills">
- {#each qualities as q}
+ {#each visibleOptions as q (q.value)}
<button
class="quality-pill"
class:active={selectedQuality === q.value}
onclick={() => { selectedQuality = q.value; }}
>
- {$t(q.key)}
+ {qualityLabel(q.value, q.key)}
</button>
{/each}
+ {#if hasAudioOnly}
+ <button
+ class="quality-pill quality-pill--audio"
+ class:active={selectedQuality === "audio"}
+ onclick={() => { selectedQuality = "audio"; }}
+ >
+ {$t('omnibox.quality_audio')}
+ </button>
+ {/if}
</div>
+ {#if availableHeights}
+ <span class="quality-hint">{$t('omnibox.quality_from_formats')}</span>
+ {/if}
</div>
{/if}
@@ -67,6 +109,16 @@
border-color: var(--cta);
}
+ .quality-pill--audio {
+ border-style: dashed;
+ border-color: var(--content-border);
+ }
+
+ .quality-pill--audio.active {
+ border-style: solid;
+ border-color: var(--cta);
+ }
+
@media (hover: hover) {
.quality-pill:not(.active):hover {
background: var(--button-hover);
@@ -78,4 +130,10 @@
outline: var(--focus-ring);
outline-offset: var(--focus-ring-offset);
}
+
+ .quality-hint {
+ font-size: 10.5px;
+ color: var(--gray);
+ opacity: 0.7;
+ }
</style>
diff --git a/src/components/p2p/P2pSendDialog.svelte b/src/components/p2p/P2pSendDialog.svelte
index 61de3d66..65adeafa 100644
--- a/src/components/p2p/P2pSendDialog.svelte
+++ b/src/components/p2p/P2pSendDialog.svelte
@@ -202,7 +202,7 @@
<div
class="progress-bar-inner"
class:paused-bar={sendState.paused}
- style="width: {Math.min(sendState.progress, 100)}%"
+ style:width="{Math.min(sendState.progress, 100)}%"
></div>
</div>
<span class="progress-text">{sendState.progress.toFixed(1)}%</span>
diff --git a/src/components/settings/DependencyRow.svelte b/src/components/settings/DependencyRow.svelte
index 0a56bdc3..aa807c39 100644
--- a/src/components/settings/DependencyRow.svelte
+++ b/src/components/settings/DependencyRow.svelte
@@ -14,13 +14,16 @@
name: string;
installed: boolean;
version: string | null;
+ source?: string;
+ /** Absolute path where the binary was found */
+ path?: string | null;
outdated?: boolean;
busy: boolean;
onInstall: (variant: string | null) => void | Promise<void>;
onAfterCustomFile?: () => void | Promise<void>;
};
- let { name, installed, version, outdated = false, busy, onInstall, onAfterCustomFile }: Props =
+ let { name, installed, version, source = "missing", path = null, outdated = false, busy, onInstall, onAfterCustomFile }: Props =
$props();
let variants = $state<DependencyVariantInfo[]>([]);
@@ -143,15 +146,24 @@
{/if}
</td>
<td class="deps-cell-status">
- {#if installed && outdated}
- <span class="deps-status deps-status-outdated" title={$t("settings.dependencies.outdated_hint") as string}>
- {$t("settings.dependencies.status_outdated")}
- </span>
- {:else if installed}
- <span class="deps-status deps-status-ok">{$t("settings.dependencies.status_installed")}</span>
- {:else}
- <span class="deps-status deps-status-missing">{$t("settings.dependencies.status_missing")}</span>
- {/if}
+ <div class="deps-status-group">
+ {#if installed && outdated}
+ <span class="deps-status deps-status-outdated" title={$t("settings.dependencies.outdated_hint") as string}>
+ {$t("settings.dependencies.status_outdated")}
+ </span>
+ {:else if installed}
+ <span class="deps-status deps-status-ok">{$t("settings.dependencies.status_installed")}</span>
+ {:else}
+ <span class="deps-status deps-status-missing">{$t("settings.dependencies.status_missing")}</span>
+ {/if}
+ {#if source === "system"}
+ <span class="deps-source deps-source-system" title={path ?? ""}>PATH</span>
+ {:else if source === "managed"}
+ <span class="deps-source deps-source-managed">{$t("settings.dependencies.source_managed")}</span>
+ {:else if source === "flatpak"}
+ <span class="deps-source deps-source-flatpak">Flatpak</span>
+ {/if}
+ </div>
</td>
<td class="deps-cell-action">
<div class="deps-actions">
@@ -176,7 +188,7 @@
{:else}
<button class="button dep-btn" onclick={handleInstall}>
{#if installed}
- {$t("settings.dependencies.update")}
+ {source === "system" ? $t("settings.dependencies.download_managed") : $t("settings.dependencies.update")}
{:else}
{$t("settings.dependencies.install")}
{/if}
@@ -211,7 +223,11 @@
>
{$t("settings.dependencies.show_folder")}
</button>
- {#if installDir}
+ {#if path}
+ <div class="menu-path" title={path}>
+ <code>{path}</code>
+ </div>
+ {:else if installDir}
<div class="menu-path" title={installDir}>
<code>{installDir}</code>
</div>
@@ -244,6 +260,12 @@
font-size: 11px;
font-weight: 600;
}
+ .deps-status-group {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ align-items: flex-start;
+ }
.deps-status-ok {
background: color-mix(in srgb, var(--success, #16a34a) 18%, transparent);
color: var(--success, #16a34a);
@@ -256,6 +278,26 @@
background: color-mix(in srgb, var(--text) 8%, transparent);
color: var(--text-dim, var(--gray));
}
+ .deps-source {
+ display: inline-flex;
+ padding: 1px 6px;
+ border-radius: 999px;
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ }
+ .deps-source-system {
+ background: color-mix(in srgb, #3b82f6 15%, transparent);
+ color: #3b82f6;
+ }
+ .deps-source-managed {
+ background: color-mix(in srgb, var(--accent) 15%, transparent);
+ color: var(--accent);
+ }
+ .deps-source-flatpak {
+ background: color-mix(in srgb, var(--warning, #f59e0b) 15%, transparent);
+ color: var(--warning, #f59e0b);
+ }
.deps-actions {
display: flex;
align-items: center;
diff --git a/src/components/settings/SettingsAppearance.svelte b/src/components/settings/SettingsAppearance.svelte
index a28e3a9f..760fdbea 100644
--- a/src/components/settings/SettingsAppearance.svelte
+++ b/src/components/settings/SettingsAppearance.svelte
@@ -85,9 +85,9 @@
>
{#if theme.colors}
<div class="theme-preview">
- <div class="preview-bg" style="background: {theme.colors[0]}">
- <div class="preview-text" style="color: {theme.colors[1]}">Aa</div>
- <div class="preview-accent" style="background: {theme.colors[2]}"></div>
+ <div class="preview-bg" style:background="{theme.colors[0]}">
+ <div class="preview-text" style:color="{theme.colors[1]}">Aa</div>
+ <div class="preview-accent" style:background="{theme.colors[2]}"></div>
</div>
</div>
{:else}
@@ -113,9 +113,9 @@
onclick={() => changeTheme(theme.id)}
>
<div class="theme-preview">
- <div class="preview-bg" style="background: {theme.colors[0]}">
- <div class="preview-text" style="color: {theme.colors[1]}">Aa</div>
- <div class="preview-accent" style="background: {theme.colors[2]}"></div>
+ <div class="preview-bg" style:background="{theme.colors[0]}">
+ <div class="preview-text" style:color="{theme.colors[1]}">Aa</div>
+ <div class="preview-accent" style:background="{theme.colors[2]}"></div>
</div>
</div>
<span class="theme-name">{theme.label}</span>
diff --git a/src/components/settings/SettingsPlugins.svelte b/src/components/settings/SettingsPlugins.svelte
index 80b71913..4b80b7b5 100644
--- a/src/components/settings/SettingsPlugins.svelte
+++ b/src/components/settings/SettingsPlugins.svelte
@@ -134,6 +134,8 @@
name={dep.name}
installed={dep.installed}
version={dep.version}
+ source={dep.source}
+ path={dep.path}
outdated={dep.outdated}
busy={installingDep === dep.name}
onInstall={(variant) => onInstallDep(dep.name, variant)}
diff --git a/src/components/settings/SettingsTypography.svelte b/src/components/settings/SettingsTypography.svelte
index 8521f661..73238572 100644
--- a/src/components/settings/SettingsTypography.svelte
+++ b/src/components/settings/SettingsTypography.svelte
@@ -214,7 +214,7 @@
</div>
<span
class="preset-sample"
- style="font-family: {previewFontStack({ value: preset.values.font_display, label: '', family: 'display', bundled: true })};"
+ style:font-family="{previewFontStack({ value: preset.values.font_display, label: '', family: 'display', bundled: true })}"
>
Aa Bb 123
</span>
@@ -248,7 +248,7 @@
</label>
<span
class="font-sample"
- style="font-family: {previewFontStack({ value: typo.font_display, label: '', family: 'display', bundled: true })};"
+ style:font-family="{previewFontStack({ value: typo.font_display, label: '', family: 'display', bundled: true })}"
>
Aa Bb 123
</span>
@@ -265,7 +265,7 @@
</label>
<span
class="font-sample"
- style="font-family: {previewFontStack({ value: typo.font_body, label: '', family: 'body', bundled: true })};"
+ style:font-family="{previewFontStack({ value: typo.font_body, label: '', family: 'body', bundled: true })}"
>
{$t("settings.typography.body_sample")}
</span>
@@ -282,7 +282,7 @@
</label>
<span
class="font-sample mono"
- style="font-family: {previewFontStack({ value: typo.font_mono, label: '', family: 'mono', bundled: true })};"
+ style:font-family="{previewFontStack({ value: typo.font_mono, label: '', family: 'mono', bundled: true })}"
>
{`const x = 42;`}
</span>
diff --git a/src/components/settings/settings-helpers.ts b/src/components/settings/settings-helpers.ts
index 0b48e2fa..2103147a 100644
--- a/src/components/settings/settings-helpers.ts
+++ b/src/components/settings/settings-helpers.ts
@@ -63,6 +63,9 @@ export type DependencyStatus = {
name: string;
installed: boolean;
version: string | null;
+ /** "managed" | "system" | "flatpak" | "missing" */
+ source: string;
+ path: string | null;
outdated: boolean;
};
diff --git a/src/components/shell/AppSidebar.svelte b/src/components/shell/AppSidebar.svelte
index 9ae6fe41..f1c2640a 100644
--- a/src/components/shell/AppSidebar.svelte
+++ b/src/components/shell/AppSidebar.svelte
@@ -4,19 +4,21 @@
import NavIcon from "$components/shell/NavIcon.svelte";
import type { NavItem } from "$lib/nav-config";
+ interface Props {
+ primaryNav?: NavItem[];
+ appNav?: NavItem[];
+ pluginNav?: NavItem[];
+ badgeLabel?: string;
+ badgeCount?: number;
+ }
+
let {
- primaryNav,
- appNav,
- pluginNav,
- badgeLabel,
- badgeCount,
- }: {
- primaryNav: NavItem[];
- appNav: NavItem[];
- pluginNav: NavItem[];
- badgeLabel: string;
- badgeCount: number;
- } = $props();
+ primaryNav = [],
+ appNav = [],
+ pluginNav = [],
+ badgeLabel = "",
+ badgeCount = 0,
+ }: Props = $props();
let pluginsExpanded = $state(true);
diff --git a/src/lib/components/cookies/PlatformLogo.svelte b/src/lib/components/cookies/PlatformLogo.svelte
index 598d54d4..1b0efa0e 100644
--- a/src/lib/components/cookies/PlatformLogo.svelte
+++ b/src/lib/components/cookies/PlatformLogo.svelte
@@ -41,7 +41,7 @@
let genericBg = $derived(genericGradient(domain || "x"));
</script>
-<div class="logo" style="width: {size}px; height: {size}px;" data-kind={kind}>
+<div class="logo" style:width="{size}px" style:height="{size}px" data-kind={kind}>
{#if kind === "youtube"}
<div class="bg yt">
<svg viewBox="0 0 24 24" width="60%" height="60%" fill="white" aria-hidden="true">
@@ -137,7 +137,7 @@
</svg>
</div>
{:else}
- <div class="bg generic" style="background: {genericBg};">
+ <div class="bg generic" style:background="{genericBg}">
<span class="initial">{genericInitial}</span>
</div>
{/if}
diff --git a/src/lib/i18n/el.json b/src/lib/i18n/el.json
index 49ca6a64..fda39801 100644
--- a/src/lib/i18n/el.json
+++ b/src/lib/i18n/el.json
@@ -334,6 +334,7 @@
"phase_starting": "Εκκίνηση μηχανισμού μεταφόρτωσης...",
"phase_connecting": "Σύνδεση στον εξυπηρετητή...",
"phase_preparing": "Προετοιμασία μεταφόρτωσης...",
+ "phase_merging": "Merging audio & video...",
"cancel": "Ακύρωση",
"clear_finished": "Εκκαθάριση των ολοκληρωμένων",
"clear_confirm": "Clear all finished downloads?",
@@ -482,71 +483,43 @@
"toast_replaced": "Αντικαταστάθηκε το αρχικό. Εξοικονομήθηκαν {{saved}} ({{pct}}%) με {{encoder}}"
},
"telegram": {
- "title": "Πλατφόρμα Telegram",
- "checking_session": "Έλεγχος συνεδρίας...",
- "login": "Είσοδος",
- "logout": "Έξοδος",
- "logged_as": "Έγινε είσοδος ως {{phone}}",
- "phone_label": "Αριθμός τηλεφώνου",
- "phone_placeholder": "+30 690 123 4567",
- "phone_hint": "Συμπεριλάβετε τον κωδικό χώρας",
- "send_code": "Αποστολή κωδικού",
- "sending_code": "Αποστολή...",
- "code_label": "Κωδικός επαλήθευσης",
- "code_placeholder": "00000",
- "code_hint": "Στείλαμε κωδικό στην εφαρμογή Telegram",
- "verify": "Επαλήθευση",
- "verifying": "Γίνεται η επαλήθευση...",
- "invalid_code": "Μη έγκυρος κωδικός. Δοκιμάστε ξανά.",
- "password_label": "Κωδικός πρόσβασης δύο παραγόντων",
- "password_placeholder": "Ο κωδικός σας δύο παραγόντων",
- "password_hint": "Υπόδειξη: {{hint}}",
- "password_submit": "Επιβεβαίωση",
- "password_verifying": "Επαλήθευση...",
- "invalid_password": "Μη έγκυρος κωδικός. Δοκιμάστε ξανά.",
- "chats_title": "Οι συνομιλίες σας",
- "loading_chats": "Φόρτωση συνομιλίων...",
- "chats_error": "Αποτυχία φόρτωσης συνομιλίων",
- "no_chats": "Δεν βρέθηκαν συνομιλίες.",
- "chat_count": "{{count}} συνομιλίες",
- "chat_count_one": "{{count}} συνομιλία",
- "chat_type_private": "Ιδιωτική",
- "chat_type_group": "Ομάδα",
- "chat_type_channel": "Κανάλι",
- "media_title": "Μέσα",
- "loading_media": "Φόρτωση μέσων...",
- "no_media": "Δεν βρέθηκαν μέσα σε αυτήν την συνομιλία.",
- "media_error": "Αποτυχία φόρτωσης μέσων",
- "filter_all": "Όλα",
- "filter_photo": "Φωτογραφίες",
- "filter_video": "Βίντεο",
- "filter_document": "Αρχεία",
- "filter_audio": "Ηχητικά",
- "search_files": "Αναζήτηση αρχείων...",
- "searching": "Αναζήτηση...",
- "back_to_chats": "Πίσω στις συνομιλίες",
- "download_btn": "Λήψη",
- "downloading": "Μεταφόρτωση...",
- "downloaded": "Ολοκληρωμένα",
- "choose_folder": "Επιλογή φακέλου μεταφορτώσεων",
- "unknown_error": "Άγνωστο σφάλμα",
- "download_all": "Λήψη όλων",
- "batch_progress": "{{done}} από {{total}} αρχεία",
- "batch_cancelled": "Διαδοχική μεταφόρτωση ακυρώθηκε",
- "batch_complete": "Όλα τα αρχεία έχουν μεταφορτωθεί",
- "load_more": "Φόρτωση επιπλέον",
- "status_waiting": "Αναμονή",
- "status_skipped": "Παραλήφθηκε",
- "status_error": "Σφάλμα",
- "file_count": "{{count}} αντικείμενα",
- "cancel_batch": "Ακύρωση",
- "qr_title": "Σαρώστε για είσοδο",
- "qr_instruction": "Ανοίξτε το Telegram στο τηλέφωνο σας, και πηγαίντε Ρυθμίσεις > Συσκευές > Σύνδεση συσκευής desktop",
- "qr_loading": "Δημιουργία κωδικού QR...",
- "qr_error": "Αποτυχία δημιουργίας κωδικού QR",
- "or_separator": "ή",
- "use_phone": "Κάνε χρήση αριθμού τηλεφώνου",
- "back_to_qr": "Πίσω στον κωδικό QR"
+ "upload_title": "Upload to Telegram / Leech Bot",
+ "auth_user_session": "User Session",
+ "auth_bot_token": "Bot Token",
+ "destination_chat": "Destination Chat / Channel",
+ "dest_placeholder": "@channel_name, chat_id or -100123456789",
+ "user_session_hint": "Select from your chat list or type a Chat ID / @channel_username",
+ "bot_token_label": "Bot Token",
+ "bot_chat_id_label": "Target Chat ID / Username",
+ "custom_filename_label": "Custom Filename & Extension",
+ "custom_filename_hint": "Rename file or change extension before uploading to Telegram",
+ "custom_thumbnail_label": "Custom Thumbnail",
+ "pick_thumbnail": "Pick image from disk…",
+ "caption_label": "Upload Caption (Optional)",
+ "caption_placeholder": "Add a caption or notes for Telegram media post...",
+ "tier_limit_label": "Telegram File Limit Mode",
+ "tier_free": "Free Tier",
+ "tier_premium": "Premium Tier",
+ "split_warning": "File size ({{size}}) exceeds {{limit}} Telegram limit. Will auto-split into {{parts}} parts.",
+ "start_upload": "Start Telegram Upload",
+ "uploading": "Uploading to Telegram...",
+ "upload_success": "Uploaded to Telegram successfully!",
+ "upload_failed": "Telegram upload failed.",
+ "error_no_chat": "Please select or enter a destination chat ID or @username.",
+ "error_no_bot_token": "Please enter a valid Bot Token.",
+ "error_invalid_bot_token": "Invalid Bot Token format. Expected format: 123456789:ABCdef...",
+ "error_no_file": "No source file provided for upload.",
+ "send_as_label": "Send Media As",
+ "send_as_video": "Video (Streamable)",
+ "send_as_document": "Document / File",
+ "send_as_audio": "Audio Track",
+ "send_to_telegram": "Upload to Telegram",
+ "err_bot_not_started": "Bot not started by user. Open Telegram, search your bot, and press /start first.",
+ "err_bot_not_member": "Bot is not in the destination chat. Add your bot as Administrator with 'Post Messages' permission.",
+ "err_chat_not_found": "Destination chat not found. Verify the @username or numeric Chat ID (-100...).",
+ "err_unauthorized": "Invalid Bot Token. Check token from @BotFather.",
+ "err_bot_file_too_large": "File exceeds Telegram Bot API limit (50MB). Switch to 'User Session' mode for files up to 2GB/4GB.",
+ "err_rate_limit": "Telegram rate limit reached. Please wait a moment before retrying."
},
"settings": {
"title": "Ρυθμίσεις",
@@ -724,6 +697,8 @@
"status_outdated": "Παρωχημένο",
"outdated_hint": "Αυτή η έκδοση δεν έχει τις δημοσιευμένες διορθώσεις ασφαλείας. Χρησιμοποιήστε την Ενημέρωση για την τρέχουσα.",
"status_missing": "Missing",
+ "source_managed": "Managed",
+ "download_managed": "Get Managed",
"not_found": "δεν βρέθηκε",
"install": "Εγκατάσταση",
"update": "Ενημέρωση",
@@ -1084,12 +1059,15 @@
"mode_mute": "Χωρις ηχο",
"quality": "Ποιότητα",
"quality_best": "Καλυτερη ποιοτητα",
+ "quality_2160p": "4K (2160p)",
+ "quality_1440p": "2K (1440p)",
"quality_1080p": "Full HD (1080p)",
"quality_720p": "HD (720p) — ελαφρυτερο",
"quality_480p": "Μεσαιο (480p) — γρηγορο",
"quality_360p": "Χαμηλο (360p) — πολυ ελαφρυ",
"quality_best_short": "Καλύτερο",
"quality_audio": "Ήχος",
+ "quality_from_formats": "Showing resolutions available for this video",
"view_formats": "Προβολή μορφών",
"hide_formats": "Απόκρυψη μορφών",
"no_formats": "Δεν υπάρχουν διαθέσιμες μορφές για αυτό το βίντεο",
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index 9319e761..29d654a6 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -334,6 +334,7 @@
"phase_starting": "Starting download engine...",
"phase_connecting": "Connecting to server...",
"phase_preparing": "Preparing download...",
+ "phase_merging": "Merging audio & video...",
"cancel": "Cancel",
"clear_finished": "Clear finished",
"clear_confirm": "Clear all finished downloads?",
@@ -724,6 +725,8 @@
"status_outdated": "Outdated",
"outdated_hint": "This version is missing published security fixes. Use Update to get the current one.",
"status_missing": "Missing",
+ "source_managed": "Managed",
+ "download_managed": "Get Managed",
"not_found": "not found",
"install": "Install",
"update": "Update",
@@ -1084,12 +1087,15 @@
"mode_mute": "No Sound",
"quality": "Quality",
"quality_best": "Best quality",
+ "quality_2160p": "4K (2160p)",
+ "quality_1440p": "2K (1440p)",
"quality_1080p": "Full HD (1080p)",
"quality_720p": "HD (720p) — lighter",
"quality_480p": "Medium (480p) — fast",
"quality_360p": "Low (360p) — very light",
"quality_best_short": "Best",
"quality_audio": "Audio",
+ "quality_from_formats": "Showing resolutions available for this video",
"view_formats": "View formats",
"hide_formats": "Hide formats",
"no_formats": "No formats available for this video",
@@ -3905,5 +3911,44 @@
"test_title": "Tracking notifications are working",
"test_body": "You will see notifications like this when your packages move."
}
+ },
+ "telegram": {
+ "upload_title": "Upload to Telegram / Leech Bot",
+ "auth_user_session": "User Session",
+ "auth_bot_token": "Bot Token",
+ "destination_chat": "Destination Chat / Channel",
+ "dest_placeholder": "@channel_name, chat_id or -100123456789",
+ "user_session_hint": "Select from your chat list or type a Chat ID / @channel_username",
+ "bot_token_label": "Bot Token",
+ "bot_chat_id_label": "Target Chat ID / Username",
+ "custom_filename_label": "Custom Filename & Extension",
+ "custom_filename_hint": "Rename file or change extension before uploading to Telegram",
+ "custom_thumbnail_label": "Custom Thumbnail",
+ "pick_thumbnail": "Pick image from disk…",
+ "caption_label": "Upload Caption (Optional)",
+ "caption_placeholder": "Add a caption or notes for Telegram media post...",
+ "tier_limit_label": "Telegram File Limit Mode",
+ "tier_free": "Free Tier",
+ "tier_premium": "Premium Tier",
+ "split_warning": "File size ({{size}}) exceeds {{limit}} Telegram limit. Will auto-split into {{parts}} parts.",
+ "start_upload": "Start Telegram Upload",
+ "uploading": "Uploading to Telegram...",
+ "upload_success": "Uploaded to Telegram successfully!",
+ "upload_failed": "Telegram upload failed.",
+ "error_no_chat": "Please select or enter a destination chat ID or @username.",
+ "error_no_bot_token": "Please enter a valid Bot Token.",
+ "error_invalid_bot_token": "Invalid Bot Token format. Expected format: 123456789:ABCdef...",
+ "error_no_file": "No source file provided for upload.",
+ "send_as_label": "Send Media As",
+ "send_as_video": "Video (Streamable)",
+ "send_as_document": "Document / File",
+ "send_as_audio": "Audio Track",
+ "send_to_telegram": "Upload to Telegram",
+ "err_bot_not_started": "Bot not started by user. Open Telegram, search your bot, and press /start first.",
+ "err_bot_not_member": "Bot is not in the destination chat. Add your bot as Administrator with 'Post Messages' permission.",
+ "err_chat_not_found": "Destination chat not found. Verify the @username or numeric Chat ID (-100...).",
+ "err_unauthorized": "Invalid Bot Token. Check token from @BotFather.",
+ "err_bot_file_too_large": "File exceeds Telegram Bot API limit (50MB). Switch to 'User Session' mode for files up to 2GB/4GB.",
+ "err_rate_limit": "Telegram rate limit reached. Please wait a moment before retrying."
}
}
diff --git a/src/lib/i18n/es.json b/src/lib/i18n/es.json
index 52ded7a2..e7fbcde5 100644
--- a/src/lib/i18n/es.json
+++ b/src/lib/i18n/es.json
@@ -334,6 +334,7 @@
"phase_starting": "Iniciando motor de descarga...",
"phase_connecting": "Conectando al servidor...",
"phase_preparing": "Preparando descarga...",
+ "phase_merging": "Merging audio & video...",
"cancel": "Cancelar",
"clear_finished": "Limpiar terminadas",
"clear_confirm": "¿Limpiar todas las descargas terminadas?",
@@ -482,71 +483,43 @@
"toast_replaced": "Original sustituido. Ahorrado {{saved}} ({{pct}}%) con {{encoder}}"
},
"telegram": {
- "title": "Telegram",
- "checking_session": "Comprobando sesión...",
- "login": "Iniciar sesión",
- "logout": "Cerrar sesión",
- "logged_as": "Sesión iniciada como {{phone}}",
- "phone_label": "Número de teléfono",
- "phone_placeholder": "+34 600 000 000",
- "phone_hint": "Incluye el código de país",
- "send_code": "Enviar código",
- "sending_code": "Enviando...",
- "code_label": "Código de verificación",
- "code_placeholder": "00000",
- "code_hint": "Enviamos un código a tu app de Telegram",
- "verify": "Verificar",
- "verifying": "Verificando...",
- "invalid_code": "Código no válido. Inténtalo de nuevo.",
- "password_label": "Contraseña de dos factores",
- "password_placeholder": "Tu contraseña 2FA",
- "password_hint": "Pista: {{hint}}",
- "password_submit": "Confirmar",
- "password_verifying": "Verificando...",
- "invalid_password": "Contraseña no válida. Inténtalo de nuevo.",
- "chats_title": "Tus chats",
- "loading_chats": "Cargando chats...",
- "chats_error": "Error al cargar chats",
- "no_chats": "No hay chats.",
- "chat_count": "{{count}} chats",
- "chat_count_one": "{{count}} chat",
- "chat_type_private": "Privado",
- "chat_type_group": "Grupo",
- "chat_type_channel": "Canal",
- "media_title": "Multimedia",
- "loading_media": "Cargando multimedia...",
- "no_media": "No se encontró multimedia en este chat.",
- "media_error": "Error al cargar multimedia",
- "filter_all": "Todo",
- "filter_photo": "Fotos",
- "filter_video": "Vídeos",
- "filter_document": "Archivos",
- "filter_audio": "Audio",
- "search_files": "Buscar archivos...",
- "searching": "Buscando...",
- "back_to_chats": "Volver a chats",
- "download_btn": "Descargar",
- "downloading": "Descargando...",
- "downloaded": "Descargado",
- "choose_folder": "Elegir carpeta de descarga",
- "unknown_error": "Error desconocido",
- "download_all": "Descargar todo",
- "batch_progress": "{{done}} de {{total}} archivos",
- "batch_cancelled": "Descarga en lote cancelada",
- "batch_complete": "Todos los archivos descargados",
- "load_more": "Cargar más",
- "status_waiting": "Esperando",
- "status_skipped": "Omitido",
- "status_error": "Error",
- "file_count": "{{count}} elementos",
- "cancel_batch": "Cancelar",
- "qr_title": "Escanea para iniciar sesión",
- "qr_instruction": "Abre Telegram en tu teléfono y ve a Ajustes > Dispositivos > Vincular dispositivo de escritorio",
- "qr_loading": "Generando código QR...",
- "qr_error": "Error al generar código QR",
- "or_separator": "o",
- "use_phone": "Usar número de teléfono",
- "back_to_qr": "Volver al código QR"
+ "upload_title": "Upload to Telegram / Leech Bot",
+ "auth_user_session": "User Session",
+ "auth_bot_token": "Bot Token",
+ "destination_chat": "Destination Chat / Channel",
+ "dest_placeholder": "@channel_name, chat_id or -100123456789",
+ "user_session_hint": "Select from your chat list or type a Chat ID / @channel_username",
+ "bot_token_label": "Bot Token",
+ "bot_chat_id_label": "Target Chat ID / Username",
+ "custom_filename_label": "Custom Filename & Extension",
+ "custom_filename_hint": "Rename file or change extension before uploading to Telegram",
+ "custom_thumbnail_label": "Custom Thumbnail",
+ "pick_thumbnail": "Pick image from disk…",
+ "caption_label": "Upload Caption (Optional)",
+ "caption_placeholder": "Add a caption or notes for Telegram media post...",
+ "tier_limit_label": "Telegram File Limit Mode",
+ "tier_free": "Free Tier",
+ "tier_premium": "Premium Tier",
+ "split_warning": "File size ({{size}}) exceeds {{limit}} Telegram limit. Will auto-split into {{parts}} parts.",
+ "start_upload": "Start Telegram Upload",
+ "uploading": "Uploading to Telegram...",
+ "upload_success": "Uploaded to Telegram successfully!",
+ "upload_failed": "Telegram upload failed.",
+ "error_no_chat": "Please select or enter a destination chat ID or @username.",
+ "error_no_bot_token": "Please enter a valid Bot Token.",
+ "error_invalid_bot_token": "Invalid Bot Token format. Expected format: 123456789:ABCdef...",
+ "error_no_file": "No source file provided for upload.",
+ "send_as_label": "Send Media As",
+ "send_as_video": "Video (Streamable)",
+ "send_as_document": "Document / File",
+ "send_as_audio": "Audio Track",
+ "send_to_telegram": "Upload to Telegram",
+ "err_bot_not_started": "Bot not started by user. Open Telegram, search your bot, and press /start first.",
+ "err_bot_not_member": "Bot is not in the destination chat. Add your bot as Administrator with 'Post Messages' permission.",
+ "err_chat_not_found": "Destination chat not found. Verify the @username or numeric Chat ID (-100...).",
+ "err_unauthorized": "Invalid Bot Token. Check token from @BotFather.",
+ "err_bot_file_too_large": "File exceeds Telegram Bot API limit (50MB). Switch to 'User Session' mode for files up to 2GB/4GB.",
+ "err_rate_limit": "Telegram rate limit reached. Please wait a moment before retrying."
},
"settings": {
"title": "Configuración",
@@ -724,6 +697,8 @@
"status_outdated": "Desactualizado",
"outdated_hint": "Esta versión no incluye correcciones de seguridad ya publicadas. Usa Actualizar para obtener la actual.",
"status_missing": "Missing",
+ "source_managed": "Managed",
+ "download_managed": "Get Managed",
"not_found": "no encontrado",
"install": "Instalar",
"update": "Actualizar",
@@ -1084,12 +1059,15 @@
"mode_mute": "Sin sonido",
"quality": "Calidad",
"quality_best": "Mejor calidad",
+ "quality_2160p": "4K (2160p)",
+ "quality_1440p": "2K (1440p)",
"quality_1080p": "Full HD (1080p)",
"quality_720p": "HD (720p) — más ligero",
"quality_480p": "Media (480p) — rápida",
"quality_360p": "Baja (360p) — muy ligera",
"quality_best_short": "Mejor",
"quality_audio": "Audio",
+ "quality_from_formats": "Showing resolutions available for this video",
"view_formats": "Ver formatos",
"hide_formats": "Ocultar formatos",
"no_formats": "No hay formatos disponibles para este vídeo",
diff --git a/src/lib/i18n/fr.json b/src/lib/i18n/fr.json
index 81de36bc..61e6b0f3 100644
--- a/src/lib/i18n/fr.json
+++ b/src/lib/i18n/fr.json
@@ -334,6 +334,7 @@
"phase_starting": "Démarrage du moteur de téléchargement...",
"phase_connecting": "Connexion au serveur...",
"phase_preparing": "Préparation du téléchargement...",
+ "phase_merging": "Merging audio & video...",
"cancel": "Annuler",
"clear_finished": "Effacer les terminés",
"clear_confirm": "Clear all finished downloads?",
@@ -482,71 +483,43 @@
"toast_replaced": "Original remplacé. Économisé {{saved}} ({{pct}}%) avec {{encoder}}"
},
"telegram": {
- "title": "Telegram",
- "checking_session": "Vérification de la session...",
- "login": "Se connecter",
- "logout": "Se déconnecter",
- "logged_as": "Connecté en tant que {{phone}}",
- "phone_label": "Numéro de téléphone",
- "phone_placeholder": "+33 6 12 34 56 78",
- "phone_hint": "Incluez l'indicatif du pays",
- "send_code": "Envoyer le code",
- "sending_code": "Envoi...",
- "code_label": "Code de vérification",
- "code_placeholder": "00000",
- "code_hint": "Nous avons envoyé un code à votre application Telegram",
- "verify": "Vérifier",
- "verifying": "Vérification...",
- "invalid_code": "Code invalide. Veuillez réessayer.",
- "password_label": "Mot de passe à deux facteurs",
- "password_placeholder": "Votre mot de passe 2FA",
- "password_hint": "Indice : {{hint}}",
- "password_submit": "Confirmer",
- "password_verifying": "Vérification...",
- "invalid_password": "Mot de passe invalide. Veuillez réessayer.",
- "chats_title": "Vos discussions",
- "loading_chats": "Chargement des discussions...",
- "chats_error": "Échec du chargement des discussions",
- "no_chats": "Aucune discussion trouvée.",
- "chat_count": "{{count}} discussions",
- "chat_count_one": "{{count}} discussion",
- "chat_type_private": "Privé",
- "chat_type_group": "Groupe",
- "chat_type_channel": "Canal",
- "media_title": "Médias",
- "loading_media": "Chargement des médias...",
- "no_media": "Aucun média trouvé dans cette discussion.",
- "media_error": "Échec du chargement des médias",
- "filter_all": "Tout",
- "filter_photo": "Photos",
- "filter_video": "Vidéos",
- "filter_document": "Fichiers",
- "filter_audio": "Audio",
- "search_files": "Rechercher des fichiers...",
- "searching": "Recherche...",
- "back_to_chats": "Retour aux discussions",
- "download_btn": "Télécharger",
- "downloading": "Téléchargement...",
- "downloaded": "Téléchargé",
- "choose_folder": "Choisir le dossier de téléchargement",
- "unknown_error": "Erreur inconnue",
- "download_all": "Tout télécharger",
- "batch_progress": "{{done}} sur {{total}} fichiers",
- "batch_cancelled": "Téléchargement groupé annulé",
- "batch_complete": "Tous les fichiers téléchargés",
- "load_more": "Charger plus",
- "status_waiting": "En attente",
- "status_skipped": "Ignoré",
- "status_error": "Erreur",
- "file_count": "{{count}} éléments",
- "cancel_batch": "Annuler",
- "qr_title": "Scannez pour vous connecter",
- "qr_instruction": "Ouvrez Telegram sur votre téléphone, allez dans Paramètres > Appareils > Associer un appareil",
- "qr_loading": "Génération du QR code...",
- "qr_error": "Échec de la génération du QR code",
- "or_separator": "ou",
- "use_phone": "Utiliser un numéro de téléphone",
- "back_to_qr": "Retour au QR code"
+ "upload_title": "Upload to Telegram / Leech Bot",
+ "auth_user_session": "User Session",
+ "auth_bot_token": "Bot Token",
+ "destination_chat": "Destination Chat / Channel",
+ "dest_placeholder": "@channel_name, chat_id or -100123456789",
+ "user_session_hint": "Select from your chat list or type a Chat ID / @channel_username",
+ "bot_token_label": "Bot Token",
+ "bot_chat_id_label": "Target Chat ID / Username",
+ "custom_filename_label": "Custom Filename & Extension",
+ "custom_filename_hint": "Rename file or change extension before uploading to Telegram",
+ "custom_thumbnail_label": "Custom Thumbnail",
+ "pick_thumbnail": "Pick image from disk…",
+ "caption_label": "Upload Caption (Optional)",
+ "caption_placeholder": "Add a caption or notes for Telegram media post...",
+ "tier_limit_label": "Telegram File Limit Mode",
+ "tier_free": "Free Tier",
+ "tier_premium": "Premium Tier",
+ "split_warning": "File size ({{size}}) exceeds {{limit}} Telegram limit. Will auto-split into {{parts}} parts.",
+ "start_upload": "Start Telegram Upload",
+ "uploading": "Uploading to Telegram...",
+ "upload_success": "Uploaded to Telegram successfully!",
+ "upload_failed": "Telegram upload failed.",
+ "error_no_chat": "Please select or enter a destination chat ID or @username.",
+ "error_no_bot_token": "Please enter a valid Bot Token.",
+ "error_invalid_bot_token": "Invalid Bot Token format. Expected format: 123456789:ABCdef...",
+ "error_no_file": "No source file provided for upload.",
+ "send_as_label": "Send Media As",
+ "send_as_video": "Video (Streamable)",
+ "send_as_document": "Document / File",
+ "send_as_audio": "Audio Track",
+ "send_to_telegram": "Upload to Telegram",
+ "err_bot_not_started": "Bot not started by user. Open Telegram, search your bot, and press /start first.",
+ "err_bot_not_member": "Bot is not in the destination chat. Add your bot as Administrator with 'Post Messages' permission.",
+ "err_chat_not_found": "Destination chat not found. Verify the @username or numeric Chat ID (-100...).",
+ "err_unauthorized": "Invalid Bot Token. Check token from @BotFather.",
+ "err_bot_file_too_large": "File exceeds Telegram Bot API limit (50MB). Switch to 'User Session' mode for files up to 2GB/4GB.",
+ "err_rate_limit": "Telegram rate limit reached. Please wait a moment before retrying."
},
"settings": {
"title": "Paramètres",
@@ -724,6 +697,8 @@
"status_outdated": "Obsolète",
"outdated_hint": "Cette version n'a pas les correctifs de sécurité déjà publiés. Utilisez Mettre à jour pour obtenir la version actuelle.",
"status_missing": "Missing",
+ "source_managed": "Managed",
+ "download_managed": "Get Managed",
"not_found": "non trouvé",
"install": "Installer",
"update": "Mettre à jour",
@@ -1084,12 +1059,15 @@
"mode_mute": "Sans son",
"quality": "Qualité",
"quality_best": "Meilleure qualite",
+ "quality_2160p": "4K (2160p)",
+ "quality_1440p": "2K (1440p)",
"quality_1080p": "Full HD (1080p)",
"quality_720p": "HD (720p) — plus leger",
"quality_480p": "Moyen (480p) — rapide",
"quality_360p": "Bas (360p) — tres leger",
"quality_best_short": "Meilleur",
"quality_audio": "Audio",
+ "quality_from_formats": "Showing resolutions available for this video",
"view_formats": "Voir les formats",
"hide_formats": "Masquer les formats",
"no_formats": "Aucun format disponible pour cette vidéo",
diff --git a/src/lib/i18n/it.json b/src/lib/i18n/it.json
index 21343982..fc72ed71 100644
--- a/src/lib/i18n/it.json
+++ b/src/lib/i18n/it.json
@@ -334,6 +334,7 @@
"phase_starting": "Avvio motore di download...",
"phase_connecting": "Connessione al server...",
"phase_preparing": "Preparazione download...",
+ "phase_merging": "Merging audio & video...",
"cancel": "Annulla",
"clear_finished": "Cancella completati",
"clear_confirm": "Clear all finished downloads?",
@@ -482,71 +483,43 @@
"toast_replaced": "Originale sostituito. Risparmiato {{saved}} ({{pct}}%) con {{encoder}}"
},
"telegram": {
- "title": "Telegram",
- "checking_session": "Verifica sessione...",
- "login": "Accedi",
- "logout": "Esci",
- "logged_as": "Connesso come {{phone}}",
- "phone_label": "Numero di telefono",
- "phone_placeholder": "+39 333 123 4567",
- "phone_hint": "Includi il prefisso internazionale",
- "send_code": "Invia codice",
- "sending_code": "Invio in corso...",
- "code_label": "Codice di verifica",
- "code_placeholder": "00000",
- "code_hint": "Abbiamo inviato un codice alla tua app Telegram",
- "verify": "Verifica",
- "verifying": "Verifica in corso...",
- "invalid_code": "Codice non valido. Riprova.",
- "password_label": "Password a due fattori",
- "password_placeholder": "La tua password 2FA",
- "password_hint": "Suggerimento: {{hint}}",
- "password_submit": "Conferma",
- "password_verifying": "Verifica in corso...",
- "invalid_password": "Password non valida. Riprova.",
- "chats_title": "Le tue chat",
- "loading_chats": "Caricamento chat...",
- "chats_error": "Impossibile caricare le chat",
- "no_chats": "Nessuna chat trovata.",
- "chat_count": "{{count}} chat",
- "chat_count_one": "{{count}} chat",
- "chat_type_private": "Privata",
- "chat_type_group": "Gruppo",
- "chat_type_channel": "Canale",
- "media_title": "Media",
- "loading_media": "Caricamento media...",
- "no_media": "Nessun media trovato in questa chat.",
- "media_error": "Impossibile caricare i media",
- "filter_all": "Tutti",
- "filter_photo": "Foto",
- "filter_video": "Video",
- "filter_document": "File",
- "filter_audio": "Audio",
- "search_files": "Cerca file...",
- "searching": "Ricerca in corso...",
- "back_to_chats": "Torna alle chat",
- "download_btn": "Scarica",
- "downloading": "Download in corso...",
- "downloaded": "Scaricato",
- "choose_folder": "Scegli cartella di download",
- "unknown_error": "Errore sconosciuto",
- "download_all": "Scarica tutto",
- "batch_progress": "{{done}} di {{total}} file",
- "batch_cancelled": "Download in blocco annullato",
- "batch_complete": "Tutti i file scaricati",
- "load_more": "Carica altri",
- "status_waiting": "In attesa",
- "status_skipped": "Saltato",
- "status_error": "Errore",
- "file_count": "{{count}} elementi",
- "cancel_batch": "Annulla",
- "qr_title": "Scansiona per accedere",
- "qr_instruction": "Apri Telegram sul telefono, vai su Impostazioni > Dispositivi > Collega dispositivo desktop",
- "qr_loading": "Generazione codice QR...",
- "qr_error": "Impossibile generare il codice QR",
- "or_separator": "oppure",
- "use_phone": "Usa il numero di telefono",
- "back_to_qr": "Torna al codice QR"
+ "upload_title": "Upload to Telegram / Leech Bot",
+ "auth_user_session": "User Session",
+ "auth_bot_token": "Bot Token",
+ "destination_chat": "Destination Chat / Channel",
+ "dest_placeholder": "@channel_name, chat_id or -100123456789",
+ "user_session_hint": "Select from your chat list or type a Chat ID / @channel_username",
+ "bot_token_label": "Bot Token",
+ "bot_chat_id_label": "Target Chat ID / Username",
+ "custom_filename_label": "Custom Filename & Extension",
+ "custom_filename_hint": "Rename file or change extension before uploading to Telegram",
+ "custom_thumbnail_label": "Custom Thumbnail",
+ "pick_thumbnail": "Pick image from disk…",
+ "caption_label": "Upload Caption (Optional)",
+ "caption_placeholder": "Add a caption or notes for Telegram media post...",
+ "tier_limit_label": "Telegram File Limit Mode",
+ "tier_free": "Free Tier",
+ "tier_premium": "Premium Tier",
+ "split_warning": "File size ({{size}}) exceeds {{limit}} Telegram limit. Will auto-split into {{parts}} parts.",
+ "start_upload": "Start Telegram Upload",
+ "uploading": "Uploading to Telegram...",
+ "upload_success": "Uploaded to Telegram successfully!",
+ "upload_failed": "Telegram upload failed.",
+ "error_no_chat": "Please select or enter a destination chat ID or @username.",
+ "error_no_bot_token": "Please enter a valid Bot Token.",
+ "error_invalid_bot_token": "Invalid Bot Token format. Expected format: 123456789:ABCdef...",
+ "error_no_file": "No source file provided for upload.",
+ "send_as_label": "Send Media As",
+ "send_as_video": "Video (Streamable)",
+ "send_as_document": "Document / File",
+ "send_as_audio": "Audio Track",
+ "send_to_telegram": "Upload to Telegram",
+ "err_bot_not_started": "Bot not started by user. Open Telegram, search your bot, and press /start first.",
+ "err_bot_not_member": "Bot is not in the destination chat. Add your bot as Administrator with 'Post Messages' permission.",
+ "err_chat_not_found": "Destination chat not found. Verify the @username or numeric Chat ID (-100...).",
+ "err_unauthorized": "Invalid Bot Token. Check token from @BotFather.",
+ "err_bot_file_too_large": "File exceeds Telegram Bot API limit (50MB). Switch to 'User Session' mode for files up to 2GB/4GB.",
+ "err_rate_limit": "Telegram rate limit reached. Please wait a moment before retrying."
},
"settings": {
"title": "Impostazioni",
@@ -724,6 +697,8 @@
"status_outdated": "Non aggiornato",
"outdated_hint": "Questa versione non ha le correzioni di sicurezza già pubblicate. Usa Aggiorna per ottenere quella attuale.",
"status_missing": "Missing",
+ "source_managed": "Managed",
+ "download_managed": "Get Managed",
"not_found": "non trovato",
"install": "Installa",
"update": "Aggiorna",
@@ -1084,12 +1059,15 @@
"mode_mute": "Senza audio",
"quality": "Qualità",
"quality_best": "Migliore qualita",
+ "quality_2160p": "4K (2160p)",
+ "quality_1440p": "2K (1440p)",
"quality_1080p": "Full HD (1080p)",
"quality_720p": "HD (720p) — leggero",
"quality_480p": "Medio (480p) — veloce",
"quality_360p": "Basso (360p) — molto leggero",
"quality_best_short": "Migliore",
"quality_audio": "Audio",
+ "quality_from_formats": "Showing resolutions available for this video",
"view_formats": "Mostra formati",
"hide_formats": "Nascondi formati",
"no_formats": "Nessun formato disponibile per questo video",
diff --git a/src/lib/i18n/ja.json b/src/lib/i18n/ja.json
index edf00b4b..a5b1cc5f 100644
--- a/src/lib/i18n/ja.json
+++ b/src/lib/i18n/ja.json
@@ -334,6 +334,7 @@
"phase_starting": "ダウンロードエンジンを起動中...",
"phase_connecting": "サーバーに接続中...",
"phase_preparing": "ダウンロードを準備中...",
+ "phase_merging": "Merging audio & video...",
"cancel": "キャンセル",
"clear_finished": "完了済みをクリア",
"clear_confirm": "Clear all finished downloads?",
@@ -482,71 +483,43 @@
"toast_replaced": "元のファイルを置き換えました。{{encoder}} で {{saved}}({{pct}}%)節約しました"
},
"telegram": {
- "title": "Telegram",
- "checking_session": "セッションを確認中...",
- "login": "ログイン",
- "logout": "ログアウト",
- "logged_as": "{{phone}} でログイン中",
- "phone_label": "電話番号",
- "phone_placeholder": "+81 90 1234 5678",
- "phone_hint": "国番号を含めてください",
- "send_code": "コードを送信",
- "sending_code": "送信中...",
- "code_label": "認証コード",
- "code_placeholder": "00000",
- "code_hint": "Telegramアプリにコードを送信しました",
- "verify": "確認",
- "verifying": "確認中...",
- "invalid_code": "無効なコードです。もう一度お試しください。",
- "password_label": "二段階認証パスワード",
- "password_placeholder": "2FAパスワードを入力",
- "password_hint": "ヒント: {{hint}}",
- "password_submit": "確認",
- "password_verifying": "確認中...",
- "invalid_password": "無効なパスワードです。もう一度お試しください。",
- "chats_title": "あなたのチャット",
- "loading_chats": "チャットを読み込み中...",
- "chats_error": "チャットの読み込みに失敗しました",
- "no_chats": "チャットが見つかりません。",
- "chat_count": "{{count}} チャット",
- "chat_count_one": "{{count}} チャット",
- "chat_type_private": "プライベート",
- "chat_type_group": "グループ",
- "chat_type_channel": "チャンネル",
- "media_title": "メディア",
- "loading_media": "メディアを読み込み中...",
- "no_media": "このチャットにメディアが見つかりません。",
- "media_error": "メディアの読み込みに失敗しました",
- "filter_all": "すべて",
- "filter_photo": "写真",
- "filter_video": "動画",
- "filter_document": "ファイル",
- "filter_audio": "音声",
- "search_files": "ファイルを検索...",
- "searching": "検索中...",
- "back_to_chats": "チャット一覧に戻る",
- "download_btn": "ダウンロード",
- "downloading": "ダウンロード中...",
- "downloaded": "ダウンロード済み",
- "choose_folder": "ダウンロードフォルダを選択",
- "unknown_error": "不明なエラー",
- "download_all": "すべてダウンロード",
- "batch_progress": "{{done}} / {{total}} ファイル",
- "batch_cancelled": "一括ダウンロードがキャンセルされました",
- "batch_complete": "すべてのファイルをダウンロードしました",
- "load_more": "さらに読み込む",
- "status_waiting": "待機中",
- "status_skipped": "スキップ",
- "status_error": "エラー",
- "file_count": "{{count}} 件",
- "cancel_batch": "キャンセル",
- "qr_title": "スキャンしてログイン",
- "qr_instruction": "スマートフォンでTelegramを開き、設定 > デバイス > デスクトップデバイスをリンク に進んでください",
- "qr_loading": "QRコードを生成中...",
- "qr_error": "QRコードの生成に失敗しました",
- "or_separator": "または",
- "use_phone": "電話番号でログイン",
- "back_to_qr": "QRコードに戻る"
+ "upload_title": "Upload to Telegram / Leech Bot",
+ "auth_user_session": "User Session",
+ "auth_bot_token": "Bot Token",
+ "destination_chat": "Destination Chat / Channel",
+ "dest_placeholder": "@channel_name, chat_id or -100123456789",
+ "user_session_hint": "Select from your chat list or type a Chat ID / @channel_username",
+ "bot_token_label": "Bot Token",
+ "bot_chat_id_label": "Target Chat ID / Username",
+ "custom_filename_label": "Custom Filename & Extension",
+ "custom_filename_hint": "Rename file or change extension before uploading to Telegram",
+ "custom_thumbnail_label": "Custom Thumbnail",
+ "pick_thumbnail": "Pick image from disk…",
+ "caption_label": "Upload Caption (Optional)",
+ "caption_placeholder": "Add a caption or notes for Telegram media post...",
+ "tier_limit_label": "Telegram File Limit Mode",
+ "tier_free": "Free Tier",
+ "tier_premium": "Premium Tier",
+ "split_warning": "File size ({{size}}) exceeds {{limit}} Telegram limit. Will auto-split into {{parts}} parts.",
+ "start_upload": "Start Telegram Upload",
+ "uploading": "Uploading to Telegram...",
+ "upload_success": "Uploaded to Telegram successfully!",
+ "upload_failed": "Telegram upload failed.",
+ "error_no_chat": "Please select or enter a destination chat ID or @username.",
+ "error_no_bot_token": "Please enter a valid Bot Token.",
+ "error_invalid_bot_token": "Invalid Bot Token format. Expected format: 123456789:ABCdef...",
+ "error_no_file": "No source file provided for upload.",
+ "send_as_label": "Send Media As",
+ "send_as_video": "Video (Streamable)",
+ "send_as_document": "Document / File",
+ "send_as_audio": "Audio Track",
+ "send_to_telegram": "Upload to Telegram",
+ "err_bot_not_started": "Bot not started by user. Open Telegram, search your bot, and press /start first.",
+ "err_bot_not_member": "Bot is not in the destination chat. Add your bot as Administrator with 'Post Messages' permission.",
+ "err_chat_not_found": "Destination chat not found. Verify the @username or numeric Chat ID (-100...).",
+ "err_unauthorized": "Invalid Bot Token. Check token from @BotFather.",
+ "err_bot_file_too_large": "File exceeds Telegram Bot API limit (50MB). Switch to 'User Session' mode for files up to 2GB/4GB.",
+ "err_rate_limit": "Telegram rate limit reached. Please wait a moment before retrying."
},
"settings": {
"title": "設定",
@@ -724,6 +697,8 @@
"status_outdated": "更新が必要",
"outdated_hint": "このバージョンには公開済みのセキュリティ修正が含まれていません。「更新」で最新版を取得してください。",
"status_missing": "Missing",
+ "source_managed": "Managed",
+ "download_managed": "Get Managed",
"not_found": "見つかりません",
"install": "インストール",
"update": "更新",
@@ -1084,12 +1059,15 @@
"mode_mute": "音声なし",
"quality": "画質",
"quality_best": "最高画質",
+ "quality_2160p": "4K (2160p)",
+ "quality_1440p": "2K (1440p)",
"quality_1080p": "フルHD (1080p)",
"quality_720p": "HD (720p) — 軽量",
"quality_480p": "中画質 (480p) — 高速",
"quality_360p": "低画質 (360p) — 超軽量",
"quality_best_short": "最高",
"quality_audio": "音声",
+ "quality_from_formats": "Showing resolutions available for this video",
"view_formats": "フォーマットを表示",
"hide_formats": "フォーマットを隠す",
"no_formats": "この動画で利用可能なフォーマットはありません",
diff --git a/src/lib/i18n/keys.ts b/src/lib/i18n/keys.ts
index a618c557..db1c083f 100644
--- a/src/lib/i18n/keys.ts
+++ b/src/lib/i18n/keys.ts
@@ -213,6 +213,7 @@ export type TranslationKeys =
| 'downloads.pause_all'
| 'downloads.phase_connecting'
| 'downloads.phase_fetching_info'
+ | 'downloads.phase_merging'
| 'downloads.phase_preparing'
| 'downloads.phase_starting'
| 'downloads.quality_hint'
@@ -761,12 +762,15 @@ export type TranslationKeys =
| 'omnibox.preset_music'
| 'omnibox.quality'
| 'omnibox.quality_1080p'
+ | 'omnibox.quality_1440p'
+ | 'omnibox.quality_2160p'
| 'omnibox.quality_360p'
| 'omnibox.quality_480p'
| 'omnibox.quality_720p'
| 'omnibox.quality_audio'
| 'omnibox.quality_best'
| 'omnibox.quality_best_short'
+ | 'omnibox.quality_from_formats'
| 'omnibox.referer_label'
| 'omnibox.referer_placeholder'
| 'omnibox.retry'
@@ -1182,6 +1186,7 @@ export type TranslationKeys =
| 'settings.dependencies.col_name'
| 'settings.dependencies.col_status'
| 'settings.dependencies.col_version'
+ | 'settings.dependencies.download_managed'
| 'settings.dependencies.filter_all_files'
| 'settings.dependencies.filter_pdfium'
| 'settings.dependencies.install'
@@ -1194,6 +1199,7 @@ export type TranslationKeys =
| 'settings.dependencies.pick_dialog_title'
| 'settings.dependencies.set_file_failed'
| 'settings.dependencies.show_folder'
+ | 'settings.dependencies.source_managed'
| 'settings.dependencies.status_installed'
| 'settings.dependencies.status_missing'
| 'settings.dependencies.status_outdated'
@@ -3387,71 +3393,43 @@ export type TranslationKeys =
| 'study.subjects.unarchive'
| 'study.subjects.weekly_minutes'
- | 'telegram.back_to_chats'
- | 'telegram.back_to_qr'
- | 'telegram.batch_cancelled'
- | 'telegram.batch_complete'
- | 'telegram.batch_progress'
- | 'telegram.cancel_batch'
- | 'telegram.chat_count'
- | 'telegram.chat_count_one'
- | 'telegram.chat_type_channel'
- | 'telegram.chat_type_group'
- | 'telegram.chat_type_private'
- | 'telegram.chats_error'
- | 'telegram.chats_title'
- | 'telegram.checking_session'
- | 'telegram.choose_folder'
- | 'telegram.code_hint'
- | 'telegram.code_label'
- | 'telegram.code_placeholder'
- | 'telegram.download_all'
- | 'telegram.download_btn'
- | 'telegram.downloaded'
- | 'telegram.downloading'
- | 'telegram.file_count'
- | 'telegram.filter_all'
- | 'telegram.filter_audio'
- | 'telegram.filter_document'
- | 'telegram.filter_photo'
- | 'telegram.filter_video'
- | 'telegram.invalid_code'
- | 'telegram.invalid_password'
- | 'telegram.load_more'
- | 'telegram.loading_chats'
- | 'telegram.loading_media'
- | 'telegram.logged_as'
- | 'telegram.login'
- | 'telegram.logout'
- | 'telegram.media_error'
- | 'telegram.media_title'
- | 'telegram.no_chats'
- | 'telegram.no_media'
- | 'telegram.or_separator'
- | 'telegram.password_hint'
- | 'telegram.password_label'
- | 'telegram.password_placeholder'
- | 'telegram.password_submit'
- | 'telegram.password_verifying'
- | 'telegram.phone_hint'
- | 'telegram.phone_label'
- | 'telegram.phone_placeholder'
- | 'telegram.qr_error'
- | 'telegram.qr_instruction'
- | 'telegram.qr_loading'
- | 'telegram.qr_title'
- | 'telegram.search_files'
- | 'telegram.searching'
- | 'telegram.send_code'
- | 'telegram.sending_code'
- | 'telegram.status_error'
- | 'telegram.status_skipped'
- | 'telegram.status_waiting'
- | 'telegram.title'
- | 'telegram.unknown_error'
- | 'telegram.use_phone'
- | 'telegram.verify'
- | 'telegram.verifying'
+ | 'telegram.auth_bot_token'
+ | 'telegram.auth_user_session'
+ | 'telegram.bot_chat_id_label'
+ | 'telegram.bot_token_label'
+ | 'telegram.caption_label'
+ | 'telegram.caption_placeholder'
+ | 'telegram.custom_filename_hint'
+ | 'telegram.custom_filename_label'
+ | 'telegram.custom_thumbnail_label'
+ | 'telegram.dest_placeholder'
+ | 'telegram.destination_chat'
+ | 'telegram.err_bot_file_too_large'
+ | 'telegram.err_bot_not_member'
+ | 'telegram.err_bot_not_started'
+ | 'telegram.err_chat_not_found'
+ | 'telegram.err_rate_limit'
+ | 'telegram.err_unauthorized'
+ | 'telegram.error_invalid_bot_token'
+ | 'telegram.error_no_bot_token'
+ | 'telegram.error_no_chat'
+ | 'telegram.error_no_file'
+ | 'telegram.pick_thumbnail'
+ | 'telegram.send_as_audio'
+ | 'telegram.send_as_document'
+ | 'telegram.send_as_label'
+ | 'telegram.send_as_video'
+ | 'telegram.send_to_telegram'
+ | 'telegram.split_warning'
+ | 'telegram.start_upload'
+ | 'telegram.tier_free'
+ | 'telegram.tier_limit_label'
+ | 'telegram.tier_premium'
+ | 'telegram.upload_failed'
+ | 'telegram.upload_success'
+ | 'telegram.upload_title'
+ | 'telegram.uploading'
+ | 'telegram.user_session_hint'
| 'terms_note.agreement'
| 'terms_note.link'
diff --git a/src/lib/i18n/pt.json b/src/lib/i18n/pt.json
index aab6c5d5..bfe8f6b8 100644
--- a/src/lib/i18n/pt.json
+++ b/src/lib/i18n/pt.json
@@ -334,6 +334,7 @@
"phase_starting": "Iniciando download...",
"phase_connecting": "Conectando ao servidor...",
"phase_preparing": "Preparando download...",
+ "phase_merging": "Merging audio & video...",
"cancel": "Cancelar",
"clear_finished": "Limpar finalizados",
"clear_confirm": "Limpar todos os downloads finalizados?",
@@ -482,71 +483,43 @@
"toast_replaced": "Substituiu o original. Economizou {{saved}} ({{pct}}%) usando {{encoder}}"
},
"telegram": {
- "title": "Telegram",
- "checking_session": "Verificando sessão...",
- "login": "Entrar",
- "logout": "Sair",
- "logged_as": "Logado como {{phone}}",
- "phone_label": "Número de telefone",
- "phone_placeholder": "+55 11 91234 5678",
- "phone_hint": "Inclua o código do país",
- "send_code": "Enviar código",
- "sending_code": "Enviando...",
- "code_label": "Código de verificação",
- "code_placeholder": "00000",
- "code_hint": "Enviamos um código para o seu Telegram",
- "verify": "Verificar",
- "verifying": "Verificando...",
- "invalid_code": "Código inválido. Tente novamente.",
- "password_label": "Senha de dois fatores",
- "password_placeholder": "Sua senha 2FA",
- "password_hint": "Dica: {{hint}}",
- "password_submit": "Confirmar",
- "password_verifying": "Verificando...",
- "invalid_password": "Senha inválida. Tente novamente.",
- "chats_title": "Seus Chats",
- "loading_chats": "Carregando chats...",
- "chats_error": "Erro ao carregar chats",
- "no_chats": "Nenhum chat encontrado.",
- "chat_count": "{{count}} chats",
- "chat_count_one": "{{count}} chat",
- "chat_type_private": "Privado",
- "chat_type_group": "Grupo",
- "chat_type_channel": "Canal",
- "media_title": "Mídia",
- "loading_media": "Carregando mídia...",
- "no_media": "Nenhuma mídia encontrada neste chat.",
- "media_error": "Erro ao carregar mídia",
- "filter_all": "Tudo",
- "filter_photo": "Fotos",
- "filter_video": "Vídeos",
- "filter_document": "Arquivos",
- "filter_audio": "Áudio",
- "search_files": "Buscar arquivos...",
- "searching": "Buscando...",
- "back_to_chats": "Voltar aos chats",
- "download_btn": "Baixar",
- "downloading": "Baixando...",
- "downloaded": "Baixado",
- "choose_folder": "Escolher pasta de download",
- "unknown_error": "Erro desconhecido",
- "download_all": "Baixar tudo",
- "batch_progress": "{{done}} de {{total}} arquivos",
- "batch_cancelled": "Download em lote cancelado",
- "batch_complete": "Todos os arquivos baixados",
- "load_more": "Carregar mais",
- "status_waiting": "Aguardando",
- "status_skipped": "Pulado",
- "status_error": "Erro",
- "file_count": "{{count}} itens",
- "cancel_batch": "Cancelar",
- "qr_title": "Escaneie para entrar",
- "qr_instruction": "Abra o Telegram no celular, vá em Configurações > Dispositivos > Conectar dispositivo",
- "qr_loading": "Gerando QR code...",
- "qr_error": "Falha ao gerar QR code",
- "or_separator": "ou",
- "use_phone": "Usar número de telefone",
- "back_to_qr": "Voltar ao QR code"
+ "upload_title": "Upload to Telegram / Leech Bot",
+ "auth_user_session": "User Session",
+ "auth_bot_token": "Bot Token",
+ "destination_chat": "Destination Chat / Channel",
+ "dest_placeholder": "@channel_name, chat_id or -100123456789",
+ "user_session_hint": "Select from your chat list or type a Chat ID / @channel_username",
+ "bot_token_label": "Bot Token",
+ "bot_chat_id_label": "Target Chat ID / Username",
+ "custom_filename_label": "Custom Filename & Extension",
+ "custom_filename_hint": "Rename file or change extension before uploading to Telegram",
+ "custom_thumbnail_label": "Custom Thumbnail",
+ "pick_thumbnail": "Pick image from disk…",
+ "caption_label": "Upload Caption (Optional)",
+ "caption_placeholder": "Add a caption or notes for Telegram media post...",
+ "tier_limit_label": "Telegram File Limit Mode",
+ "tier_free": "Free Tier",
+ "tier_premium": "Premium Tier",
+ "split_warning": "File size ({{size}}) exceeds {{limit}} Telegram limit. Will auto-split into {{parts}} parts.",
+ "start_upload": "Start Telegram Upload",
+ "uploading": "Uploading to Telegram...",
+ "upload_success": "Uploaded to Telegram successfully!",
+ "upload_failed": "Telegram upload failed.",
+ "error_no_chat": "Please select or enter a destination chat ID or @username.",
+ "error_no_bot_token": "Please enter a valid Bot Token.",
+ "error_invalid_bot_token": "Invalid Bot Token format. Expected format: 123456789:ABCdef...",
+ "error_no_file": "No source file provided for upload.",
+ "send_as_label": "Send Media As",
+ "send_as_video": "Video (Streamable)",
+ "send_as_document": "Document / File",
+ "send_as_audio": "Audio Track",
+ "send_to_telegram": "Upload to Telegram",
+ "err_bot_not_started": "Bot not started by user. Open Telegram, search your bot, and press /start first.",
+ "err_bot_not_member": "Bot is not in the destination chat. Add your bot as Administrator with 'Post Messages' permission.",
+ "err_chat_not_found": "Destination chat not found. Verify the @username or numeric Chat ID (-100...).",
+ "err_unauthorized": "Invalid Bot Token. Check token from @BotFather.",
+ "err_bot_file_too_large": "File exceeds Telegram Bot API limit (50MB). Switch to 'User Session' mode for files up to 2GB/4GB.",
+ "err_rate_limit": "Telegram rate limit reached. Please wait a moment before retrying."
},
"settings": {
"title": "Configurações",
@@ -724,6 +697,8 @@
"status_outdated": "Desatualizado",
"outdated_hint": "Esta versão não tem correções de segurança já publicadas. Use Atualizar para pegar a atual.",
"status_missing": "Missing",
+ "source_managed": "Managed",
+ "download_managed": "Get Managed",
"not_found": "não encontrado",
"install": "Instalar",
"update": "Atualizar",
@@ -1084,12 +1059,15 @@
"mode_mute": "Sem Som",
"quality": "Qualidade",
"quality_best": "Melhor qualidade",
+ "quality_2160p": "4K (2160p)",
+ "quality_1440p": "2K (1440p)",
"quality_1080p": "Full HD (1080p)",
"quality_720p": "HD (720p) — leve",
"quality_480p": "Médio (480p) — rápido",
"quality_360p": "Baixo (360p) — muito leve",
"quality_best_short": "Melhor",
"quality_audio": "Áudio",
+ "quality_from_formats": "Showing resolutions available for this video",
"view_formats": "Ver formatos",
"hide_formats": "Ocultar formatos",
"no_formats": "Nenhum formato disponível para este vídeo",
diff --git a/src/lib/i18n/ru.json b/src/lib/i18n/ru.json
index 2d75285e..4b2a88e2 100644
--- a/src/lib/i18n/ru.json
+++ b/src/lib/i18n/ru.json
@@ -334,6 +334,7 @@
"phase_starting": "Запуск движка скачивания…",
"phase_connecting": "Подключение к серверу…",
"phase_preparing": "Подготовка к скачиванию…",
+ "phase_merging": "Merging audio & video...",
"cancel": "Отмена",
"clear_finished": "Очистить завершённые",
"clear_confirm": "Очистить все завершённые загрузки?",
@@ -482,71 +483,43 @@
"toast_replaced": "Исходный файл заменён. Сэкономлено {{saved}} ({{pct}}%) с помощью {{encoder}}"
},
"telegram": {
- "title": "Telegram",
- "checking_session": "Проверка сеанса…",
- "login": "Войти",
- "logout": "Выйти",
- "logged_as": "Вошли как {{phone}}",
- "phone_label": "Номер телефона",
- "phone_placeholder": "+7 123 456 7890",
- "phone_hint": "Укажите номер вместе с кодом страны",
- "send_code": "Отправить код",
- "sending_code": "Отправка…",
- "code_label": "Код подтверждения",
- "code_placeholder": "00000",
- "code_hint": "Мы отправили код в ваше приложение Telegram",
- "verify": "Подтвердить",
- "verifying": "Проверка…",
- "invalid_code": "Неверный код. Попробуйте ещё раз.",
- "password_label": "Пароль двухфакторной аутентификации",
- "password_placeholder": "Ваш 2FA пароль",
- "password_hint": "Подсказка: {{hint}}",
- "password_submit": "Подтвердить",
- "password_verifying": "Проверка…",
- "invalid_password": "Неверный пароль. Попробуйте ещё раз.",
- "chats_title": "Ваши чаты",
- "loading_chats": "Загрузка чатов…",
- "chats_error": "Не удалось загрузить чаты",
- "no_chats": "Чаты не найдены.",
- "chat_count": "Чатов: {{count}}",
- "chat_count_one": "{{count}} чат",
- "chat_type_private": "Личный",
- "chat_type_group": "Группа",
- "chat_type_channel": "Канал",
- "media_title": "Медиа",
- "loading_media": "Загрузка медиа…",
- "no_media": "В этом чате медиа не найдены.",
- "media_error": "Не удалось загрузить медиа",
- "filter_all": "Все",
- "filter_photo": "Фото",
- "filter_video": "Видео",
- "filter_document": "Файлы",
- "filter_audio": "Аудио",
- "search_files": "Поиск файлов…",
- "searching": "Поиск…",
- "back_to_chats": "Назад к чатам",
- "download_btn": "Скачать",
- "downloading": "Скачивание…",
- "downloaded": "Скачано",
- "choose_folder": "Выберите папку загрузок",
- "unknown_error": "Неизвестная ошибка",
- "download_all": "Скачать всё",
- "batch_progress": "{{done}} из {{total}} файлов",
- "batch_cancelled": "Пакетное скачивание отменено",
- "batch_complete": "Все файлы скачаны",
- "load_more": "Загрузить ещё",
- "status_waiting": "Ожидание",
- "status_skipped": "Пропущено",
- "status_error": "Ошибка",
- "file_count": "Элементов: {{count}}",
- "cancel_batch": "Отмена",
- "qr_title": "Сканируйте QR-код для входа",
- "qr_instruction": "Откройте Telegram на телефоне, перейдите в Настройки → Устройства → Подключить устройство",
- "qr_loading": "Генерация QR-кода…",
- "qr_error": "Не удалось создать QR-код",
- "or_separator": "или",
- "use_phone": "Использовать номер телефона",
- "back_to_qr": "Назад к QR-коду"
+ "upload_title": "Upload to Telegram / Leech Bot",
+ "auth_user_session": "User Session",
+ "auth_bot_token": "Bot Token",
+ "destination_chat": "Destination Chat / Channel",
+ "dest_placeholder": "@channel_name, chat_id or -100123456789",
+ "user_session_hint": "Select from your chat list or type a Chat ID / @channel_username",
+ "bot_token_label": "Bot Token",
+ "bot_chat_id_label": "Target Chat ID / Username",
+ "custom_filename_label": "Custom Filename & Extension",
+ "custom_filename_hint": "Rename file or change extension before uploading to Telegram",
+ "custom_thumbnail_label": "Custom Thumbnail",
+ "pick_thumbnail": "Pick image from disk…",
+ "caption_label": "Upload Caption (Optional)",
+ "caption_placeholder": "Add a caption or notes for Telegram media post...",
+ "tier_limit_label": "Telegram File Limit Mode",
+ "tier_free": "Free Tier",
+ "tier_premium": "Premium Tier",
+ "split_warning": "File size ({{size}}) exceeds {{limit}} Telegram limit. Will auto-split into {{parts}} parts.",
+ "start_upload": "Start Telegram Upload",
+ "uploading": "Uploading to Telegram...",
+ "upload_success": "Uploaded to Telegram successfully!",
+ "upload_failed": "Telegram upload failed.",
+ "error_no_chat": "Please select or enter a destination chat ID or @username.",
+ "error_no_bot_token": "Please enter a valid Bot Token.",
+ "error_invalid_bot_token": "Invalid Bot Token format. Expected format: 123456789:ABCdef...",
+ "error_no_file": "No source file provided for upload.",
+ "send_as_label": "Send Media As",
+ "send_as_video": "Video (Streamable)",
+ "send_as_document": "Document / File",
+ "send_as_audio": "Audio Track",
+ "send_to_telegram": "Upload to Telegram",
+ "err_bot_not_started": "Bot not started by user. Open Telegram, search your bot, and press /start first.",
+ "err_bot_not_member": "Bot is not in the destination chat. Add your bot as Administrator with 'Post Messages' permission.",
+ "err_chat_not_found": "Destination chat not found. Verify the @username or numeric Chat ID (-100...).",
+ "err_unauthorized": "Invalid Bot Token. Check token from @BotFather.",
+ "err_bot_file_too_large": "File exceeds Telegram Bot API limit (50MB). Switch to 'User Session' mode for files up to 2GB/4GB.",
+ "err_rate_limit": "Telegram rate limit reached. Please wait a moment before retrying."
},
"settings": {
"title": "Настройки",
@@ -724,6 +697,8 @@
"status_outdated": "Устарело",
"outdated_hint": "В этой версии нет уже опубликованных исправлений безопасности. Нажмите «Обновить», чтобы получить актуальную.",
"status_missing": "Отсутствует",
+ "source_managed": "Managed",
+ "download_managed": "Get Managed",
"not_found": "не найдено",
"install": "Установить",
"update": "Обновить",
@@ -1084,12 +1059,15 @@
"mode_mute": "Без звука",
"quality": "Качество",
"quality_best": "Лучшее качество",
+ "quality_2160p": "4K (2160p)",
+ "quality_1440p": "2K (1440p)",
"quality_1080p": "Full HD (1080p)",
"quality_720p": "HD (720p) — легче",
"quality_480p": "Среднее (480p) — быстро",
"quality_360p": "Низкое (360p) — минимальный размер",
"quality_best_short": "Лучшее",
"quality_audio": "Аудио",
+ "quality_from_formats": "Showing resolutions available for this video",
"view_formats": "Посмотреть форматы",
"hide_formats": "Скрыть форматы",
"no_formats": "Для этого видео нет доступных форматов",
diff --git a/src/lib/i18n/zh-TW.json b/src/lib/i18n/zh-TW.json
index 81f32172..7553958b 100644
--- a/src/lib/i18n/zh-TW.json
+++ b/src/lib/i18n/zh-TW.json
@@ -334,6 +334,7 @@
"phase_starting": "正在啟動下載引擎...",
"phase_connecting": "正在連線到伺服器...",
"phase_preparing": "正在準備下載...",
+ "phase_merging": "Merging audio & video...",
"cancel": "取消",
"clear_finished": "清除已完成項目",
"clear_confirm": "Clear all finished downloads?",
@@ -482,71 +483,43 @@
"toast_replaced": "已取代原始檔案。使用 {{encoder}} 節省 {{saved}}({{pct}}%)"
},
"telegram": {
- "title": "Telegram",
- "checking_session": "正在檢查登入狀態...",
- "login": "登入",
- "logout": "登出",
- "logged_as": "已登入為 {{phone}}",
- "phone_label": "電話號碼",
- "phone_placeholder": "+1 234 567 8900",
- "phone_hint": "請包含國碼",
- "send_code": "傳送驗證碼",
- "sending_code": "傳送中...",
- "code_label": "驗證碼",
- "code_placeholder": "00000",
- "code_hint": "系統已將驗證碼傳送到您的 Telegram 應用程式",
- "verify": "驗證",
- "verifying": "驗證中...",
- "invalid_code": "驗證碼無效。請再試一次。",
- "password_label": "雙重驗證密碼",
- "password_placeholder": "您的 2FA 密碼",
- "password_hint": "提示: {{hint}}",
- "password_submit": "確認",
- "password_verifying": "驗證中...",
- "invalid_password": "密碼無效。請再試一次。",
- "chats_title": "您的聊天",
- "loading_chats": "正在載入聊天...",
- "chats_error": "載入聊天失敗",
- "no_chats": "找不到任何聊天。",
- "chat_count": "{{count}} 個聊天",
- "chat_count_one": "{{count}} 個聊天",
- "chat_type_private": "私人",
- "chat_type_group": "群組",
- "chat_type_channel": "頻道",
- "media_title": "媒體",
- "loading_media": "正在載入媒體...",
- "no_media": "此聊天沒有任何媒體。",
- "media_error": "載入媒體失敗",
- "filter_all": "全部",
- "filter_photo": "照片",
- "filter_video": "影片",
- "filter_document": "檔案",
- "filter_audio": "音訊",
- "search_files": "搜尋檔案...",
- "searching": "搜尋中...",
- "back_to_chats": "返回聊天",
- "download_btn": "下載",
- "downloading": "下載中...",
- "downloaded": "已下載",
- "choose_folder": "選擇下載資料夾",
- "unknown_error": "未知錯誤",
- "download_all": "全部下載",
- "batch_progress": "{{done}} / {{total}} 個檔案",
- "batch_cancelled": "大量下載已取消",
- "batch_complete": "所有檔案已下載",
- "load_more": "載入更多",
- "status_waiting": "等待中",
- "status_skipped": "已略過",
- "status_error": "錯誤",
- "file_count": "{{count}} 個項目",
- "cancel_batch": "取消",
- "qr_title": "掃描以登入",
- "qr_instruction": "在手機開啟 Telegram,前往 設定 > 裝置 > 連結桌面裝置",
- "qr_loading": "正在產生 QR Code...",
- "qr_error": "產生 QR Code 失敗",
- "or_separator": "或",
- "use_phone": "改用電話號碼",
- "back_to_qr": "返回 QR Code"
+ "upload_title": "Upload to Telegram / Leech Bot",
+ "auth_user_session": "User Session",
+ "auth_bot_token": "Bot Token",
+ "destination_chat": "Destination Chat / Channel",
+ "dest_placeholder": "@channel_name, chat_id or -100123456789",
+ "user_session_hint": "Select from your chat list or type a Chat ID / @channel_username",
+ "bot_token_label": "Bot Token",
+ "bot_chat_id_label": "Target Chat ID / Username",
+ "custom_filename_label": "Custom Filename & Extension",
+ "custom_filename_hint": "Rename file or change extension before uploading to Telegram",
+ "custom_thumbnail_label": "Custom Thumbnail",
+ "pick_thumbnail": "Pick image from disk…",
+ "caption_label": "Upload Caption (Optional)",
+ "caption_placeholder": "Add a caption or notes for Telegram media post...",
+ "tier_limit_label": "Telegram File Limit Mode",
+ "tier_free": "Free Tier",
+ "tier_premium": "Premium Tier",
+ "split_warning": "File size ({{size}}) exceeds {{limit}} Telegram limit. Will auto-split into {{parts}} parts.",
+ "start_upload": "Start Telegram Upload",
+ "uploading": "Uploading to Telegram...",
+ "upload_success": "Uploaded to Telegram successfully!",
+ "upload_failed": "Telegram upload failed.",
+ "error_no_chat": "Please select or enter a destination chat ID or @username.",
+ "error_no_bot_token": "Please enter a valid Bot Token.",
+ "error_invalid_bot_token": "Invalid Bot Token format. Expected format: 123456789:ABCdef...",
+ "error_no_file": "No source file provided for upload.",
+ "send_as_label": "Send Media As",
+ "send_as_video": "Video (Streamable)",
+ "send_as_document": "Document / File",
+ "send_as_audio": "Audio Track",
+ "send_to_telegram": "Upload to Telegram",
+ "err_bot_not_started": "Bot not started by user. Open Telegram, search your bot, and press /start first.",
+ "err_bot_not_member": "Bot is not in the destination chat. Add your bot as Administrator with 'Post Messages' permission.",
+ "err_chat_not_found": "Destination chat not found. Verify the @username or numeric Chat ID (-100...).",
+ "err_unauthorized": "Invalid Bot Token. Check token from @BotFather.",
+ "err_bot_file_too_large": "File exceeds Telegram Bot API limit (50MB). Switch to 'User Session' mode for files up to 2GB/4GB.",
+ "err_rate_limit": "Telegram rate limit reached. Please wait a moment before retrying."
},
"settings": {
"title": "設定",
@@ -724,6 +697,8 @@
"status_outdated": "已過時",
"outdated_hint": "此版本缺少已發布的安全修復。請點選「更新」取得目前版本。",
"status_missing": "Missing",
+ "source_managed": "Managed",
+ "download_managed": "Get Managed",
"not_found": "找不到",
"install": "安裝",
"update": "更新",
@@ -1084,12 +1059,15 @@
"mode_mute": "靜音",
"quality": "畫質",
"quality_best": "最佳畫質",
+ "quality_2160p": "4K (2160p)",
+ "quality_1440p": "2K (1440p)",
"quality_1080p": "1080p",
"quality_720p": "720p",
"quality_480p": "480p",
"quality_360p": "360p",
"quality_best_short": "最佳",
"quality_audio": "音訊",
+ "quality_from_formats": "Showing resolutions available for this video",
"view_formats": "檢視格式",
"hide_formats": "隱藏格式",
"no_formats": "此影片沒有可用格式",
diff --git a/src/lib/i18n/zh.json b/src/lib/i18n/zh.json
index c720037e..3538fcec 100644
--- a/src/lib/i18n/zh.json
+++ b/src/lib/i18n/zh.json
@@ -334,6 +334,7 @@
"phase_starting": "正在启动下载引擎...",
"phase_connecting": "正在连接服务器...",
"phase_preparing": "正在准备下载...",
+ "phase_merging": "Merging audio & video...",
"cancel": "取消",
"clear_finished": "清除已完成",
"clear_confirm": "清除所有已完成下载?",
@@ -482,71 +483,43 @@
"toast_replaced": "已替换原始文件。使用 {{encoder}} 节省 {{saved}}({{pct}}%)"
},
"telegram": {
- "title": "Telegram",
- "checking_session": "正在检查登录状态...",
- "login": "登录",
- "logout": "退出登录",
- "logged_as": "已登录为 {{phone}}",
- "phone_label": "手机号",
- "phone_placeholder": "+86 138 0000 0000",
- "phone_hint": "请包含国家区号",
- "send_code": "发送验证码",
- "sending_code": "正在发送...",
- "code_label": "验证码",
- "code_placeholder": "00000",
- "code_hint": "验证码已发送到您的 Telegram 应用",
- "verify": "验证",
- "verifying": "正在验证...",
- "invalid_code": "验证码无效,请重试。",
- "password_label": "两步验证密码",
- "password_placeholder": "您的 2FA 密码",
- "password_hint": "提示:{{hint}}",
- "password_submit": "确认",
- "password_verifying": "正在验证...",
- "invalid_password": "密码错误,请重试。",
- "chats_title": "我的对话",
- "loading_chats": "正在加载对话...",
- "chats_error": "加载对话失败",
- "no_chats": "未找到对话。",
- "chat_count": "{{count}} 个对话",
- "chat_count_one": "{{count}} 个对话",
- "chat_type_private": "私聊",
- "chat_type_group": "群组",
- "chat_type_channel": "频道",
- "media_title": "媒体",
- "loading_media": "正在加载媒体...",
- "no_media": "该对话中未找到媒体文件。",
- "media_error": "加载媒体失败",
- "filter_all": "全部",
- "filter_photo": "图片",
- "filter_video": "视频",
- "filter_document": "文件",
- "filter_audio": "音频",
- "search_files": "搜索文件...",
- "searching": "搜索中...",
- "back_to_chats": "返回对话列表",
- "download_btn": "下载",
- "downloading": "下载中...",
- "downloaded": "已下载",
- "choose_folder": "选择下载文件夹",
- "unknown_error": "未知错误",
- "download_all": "全部下载",
- "batch_progress": "{{done}}/{{total}} 个文件",
- "batch_cancelled": "批量下载已取消",
- "batch_complete": "全部文件下载完成",
- "load_more": "加载更多",
- "status_waiting": "等待中",
- "status_skipped": "已跳过",
- "status_error": "错误",
- "file_count": "{{count}} 项",
- "cancel_batch": "取消",
- "qr_title": "扫码登录",
- "qr_instruction": "打开手机上的 Telegram,前往 设置 > 设备 > 关联桌面设备",
- "qr_loading": "正在生成二维码...",
- "qr_error": "生成二维码失败",
- "or_separator": "或",
- "use_phone": "使用手机号登录",
- "back_to_qr": "返回二维码"
+ "upload_title": "Upload to Telegram / Leech Bot",
+ "auth_user_session": "User Session",
+ "auth_bot_token": "Bot Token",
+ "destination_chat": "Destination Chat / Channel",
+ "dest_placeholder": "@channel_name, chat_id or -100123456789",
+ "user_session_hint": "Select from your chat list or type a Chat ID / @channel_username",
+ "bot_token_label": "Bot Token",
+ "bot_chat_id_label": "Target Chat ID / Username",
+ "custom_filename_label": "Custom Filename & Extension",
+ "custom_filename_hint": "Rename file or change extension before uploading to Telegram",
+ "custom_thumbnail_label": "Custom Thumbnail",
+ "pick_thumbnail": "Pick image from disk…",
+ "caption_label": "Upload Caption (Optional)",
+ "caption_placeholder": "Add a caption or notes for Telegram media post...",
+ "tier_limit_label": "Telegram File Limit Mode",
+ "tier_free": "Free Tier",
+ "tier_premium": "Premium Tier",
+ "split_warning": "File size ({{size}}) exceeds {{limit}} Telegram limit. Will auto-split into {{parts}} parts.",
+ "start_upload": "Start Telegram Upload",
+ "uploading": "Uploading to Telegram...",
+ "upload_success": "Uploaded to Telegram successfully!",
+ "upload_failed": "Telegram upload failed.",
+ "error_no_chat": "Please select or enter a destination chat ID or @username.",
+ "error_no_bot_token": "Please enter a valid Bot Token.",
+ "error_invalid_bot_token": "Invalid Bot Token format. Expected format: 123456789:ABCdef...",
+ "error_no_file": "No source file provided for upload.",
+ "send_as_label": "Send Media As",
+ "send_as_video": "Video (Streamable)",
+ "send_as_document": "Document / File",
+ "send_as_audio": "Audio Track",
+ "send_to_telegram": "Upload to Telegram",
+ "err_bot_not_started": "Bot not started by user. Open Telegram, search your bot, and press /start first.",
+ "err_bot_not_member": "Bot is not in the destination chat. Add your bot as Administrator with 'Post Messages' permission.",
+ "err_chat_not_found": "Destination chat not found. Verify the @username or numeric Chat ID (-100...).",
+ "err_unauthorized": "Invalid Bot Token. Check token from @BotFather.",
+ "err_bot_file_too_large": "File exceeds Telegram Bot API limit (50MB). Switch to 'User Session' mode for files up to 2GB/4GB.",
+ "err_rate_limit": "Telegram rate limit reached. Please wait a moment before retrying."
},
"settings": {
"title": "设置",
@@ -724,6 +697,8 @@
"status_outdated": "已过时",
"outdated_hint": "此版本缺少已发布的安全修复。请点击“更新”获取当前版本。",
"status_missing": "Missing",
+ "source_managed": "Managed",
+ "download_managed": "Get Managed",
"not_found": "未找到",
"install": "安装",
"update": "更新",
@@ -1084,12 +1059,15 @@
"mode_mute": "无声",
"quality": "质量",
"quality_best": "最佳质量",
+ "quality_2160p": "4K (2160p)",
+ "quality_1440p": "2K (1440p)",
"quality_1080p": "全高清 (1080p)",
"quality_720p": "高清 (720p) — 较小",
"quality_480p": "中等 (480p) — 快速",
"quality_360p": "低清 (360p) — 极小",
"quality_best_short": "最佳",
"quality_audio": "音频",
+ "quality_from_formats": "Showing resolutions available for this video",
"view_formats": "查看格式",
"hide_formats": "隐藏格式",
"no_formats": "该视频没有可用格式",
diff --git a/src/lib/reader-components/ReaderThemeMenu.svelte b/src/lib/reader-components/ReaderThemeMenu.svelte
index dd34a408..75ddaba6 100644
--- a/src/lib/reader-components/ReaderThemeMenu.svelte
+++ b/src/lib/reader-components/ReaderThemeMenu.svelte
@@ -34,7 +34,7 @@
class:selected={theme === opt.id}
onclick={() => pick(opt.id)}
>
- <span class="swatch" style="background: {opt.swatch};"></span>
+ <span class="swatch" style:background="{opt.swatch}"></span>
<span class="name">{opt.label}</span>
</button>
{/each}
diff --git a/src/lib/reader-components/ReaderTypographyMenu.svelte b/src/lib/reader-components/ReaderTypographyMenu.svelte
index 0200fb5a..aa77e4dc 100644
--- a/src/lib/reader-components/ReaderTypographyMenu.svelte
+++ b/src/lib/reader-components/ReaderTypographyMenu.svelte
@@ -39,7 +39,7 @@
class="font-pick"
class:selected={typography.font_family === opt.key}
onclick={() => (typography = { ...typography, font_family: opt.key })}
- style="font-family: {opt.key === 'serif' ? "'Charter', Georgia, serif" : opt.key === 'mono' ? "'IBM Plex Mono', monospace" : opt.key === 'sans' ? 'system-ui, sans-serif' : "'DM Sans', sans-serif"};"
+ style:font-family="{opt.key === 'serif' ?"'Charter', Georgia, serif" : opt.key === 'mono' ? "'IBM Plex Mono', monospace" : opt.key === 'sans' ? 'system-ui, sans-serif' : "'DM Sans', sans-serif"};"
title={opt.label}
>
Aa
diff --git a/src/lib/stores/settings-store.svelte.ts b/src/lib/stores/settings-store.svelte.ts
index dc3a1d3b..d60a4d6e 100644
--- a/src/lib/stores/settings-store.svelte.ts
+++ b/src/lib/stores/settings-store.svelte.ts
@@ -113,6 +113,11 @@ export type AppSettings = {
mode?: "auto" | "audio" | "mute" | null;
quality?: string | null;
};
+ accessibility?: {
+ reduce_motion?: boolean;
+ reduce_transparency?: boolean;
+ disable_haptics?: boolean;
+ };
typography?: TypographySettings;
};
diff --git a/src/lib/study-components/ProgressRing.svelte b/src/lib/study-components/ProgressRing.svelte
index f00e520f..53182fa6 100644
--- a/src/lib/study-components/ProgressRing.svelte
+++ b/src/lib/study-components/ProgressRing.svelte
@@ -31,7 +31,7 @@
const labelSize = $derived(Math.max(10, Math.round(size * 0.22)));
</script>
-<div class="ring" style="width: {size}px; height: {size}px;">
+<div class="ring" style:width="{size}px" style:height="{size}px">
<svg width={size} height={size} viewBox="0 0 {size} {size}" aria-hidden="true">
<circle
cx={size / 2}
@@ -59,7 +59,7 @@
<div class="center">{@render center()}</div>
{:else if label}
<div class="center">
- <span class="label" style="font-size: {labelSize}px;">{label}</span>
+ <span class="label" style:font-size="{labelSize}px">{label}</span>
</div>
{/if}
</div>
diff --git a/src/lib/study-components/TelegramCloneWizard.svelte b/src/lib/study-components/TelegramCloneWizard.svelte
index b4f4a353..697eec09 100644
--- a/src/lib/study-components/TelegramCloneWizard.svelte
+++ b/src/lib/study-components/TelegramCloneWizard.svelte
@@ -378,7 +378,7 @@
class="progress-inner"
class:status-error={s.status === "error"}
class:status-completed={s.status === "completed"}
- style="width: {pct(s)}%"
+ style:width="{pct(s)}%"
></div>
</div>
<div class="session-meta">
diff --git a/src/lib/study-components/TelegramPerfPanel.svelte b/src/lib/study-components/TelegramPerfPanel.svelte
index 61937598..47aacdb2 100644
--- a/src/lib/study-components/TelegramPerfPanel.svelte
+++ b/src/lib/study-components/TelegramPerfPanel.svelte
@@ -225,7 +225,7 @@
<div class="bw-bar-outer">
<div
class="bw-bar-inner"
- style="width: {Math.min(100, bw.percentage)}%"
+ style:width="{Math.min(100, bw.percentage)}%"
class:warn={bw.percentage > 80}
></div>
</div>
diff --git a/src/lib/study-components/TelegramTransferPanel.svelte b/src/lib/study-components/TelegramTransferPanel.svelte
index cbcd075f..dede4b3a 100644
--- a/src/lib/study-components/TelegramTransferPanel.svelte
+++ b/src/lib/study-components/TelegramTransferPanel.svelte
@@ -76,7 +76,7 @@
<span class="transfer-meta">{fmtSize(t.sizeBytes)} · {Math.round(t.percent)}%</span>
</div>
<div class="progress-outer">
- <div class="progress-inner" style="width: {Math.max(2, Math.min(100, t.percent))}%"></div>
+ <div class="progress-inner" style:width="{Math.max(2, Math.min(100, t.percent))}%"></div>
</div>
</li>
{/each}
diff --git a/src/lib/study-components/notes/shell/NbTabContextMenu.svelte b/src/lib/study-components/notes/shell/NbTabContextMenu.svelte
index f864b028..07a5053b 100644
--- a/src/lib/study-components/notes/shell/NbTabContextMenu.svelte
+++ b/src/lib/study-components/notes/shell/NbTabContextMenu.svelte
@@ -53,7 +53,7 @@
<div
class="nb-tab-context-menu"
data-nb-context-menu="true"
- style="left: {x}px; top: {y}px;"
+ style:left="{x}px" style:top="{y}px"
role="menu"
>
<button class="item" role="menuitem" onclick={close}>
diff --git a/src/lib/study-music-components/ContextMenu.svelte b/src/lib/study-music-components/ContextMenu.svelte
index 30e28be3..bf88f2c6 100644
--- a/src/lib/study-music-components/ContextMenu.svelte
+++ b/src/lib/study-music-components/ContextMenu.svelte
@@ -63,7 +63,7 @@
<div
bind:this={menuEl}
class="ctx-menu"
- style="left: {adjustedPos.left}px; top: {adjustedPos.top}px;"
+ style:left="{adjustedPos.left}px" style:top="{adjustedPos.top}px"
role="menu"
tabindex="-1"
>
diff --git a/src/lib/study-music-components/SoundCloudDownloadButton.svelte b/src/lib/study-music-components/SoundCloudDownloadButton.svelte
index 52c0d057..fa022e7b 100644
--- a/src/lib/study-music-components/SoundCloudDownloadButton.svelte
+++ b/src/lib/study-music-components/SoundCloudDownloadButton.svelte
@@ -25,7 +25,7 @@
aria-label={`Baixando — ${pct}%`}
title={`Baixando — ${pct}%`}
>
- <span class="ring" style="--pct: {pct}">
+ <span class="ring" style:--pct="{pct}">
<span class="pct">{pct < 1 ? "" : pct}</span>
</span>
</button>
diff --git a/src/lib/study-music-youtube-components/YoutubeShelf.svelte b/src/lib/study-music-youtube-components/YoutubeShelf.svelte
index cf6831a4..9f5dc633 100644
--- a/src/lib/study-music-youtube-components/YoutubeShelf.svelte
+++ b/src/lib/study-music-youtube-components/YoutubeShelf.svelte
@@ -16,7 +16,7 @@
{#if title}
<h3 class="title">{title}</h3>
{/if}
- <div class="grid" style="--min-card: {minCard}px">
+ <div class="grid" style:--min-card="{minCard}px">
{#each items as item, idx (idx)}
<YoutubeItem item={item} {onPlay} {onPlaylistOpen} />
{/each}
diff --git a/src/lib/study-telegram-bridge.ts b/src/lib/study-telegram-bridge.ts
index be155266..4b20e334 100644
--- a/src/lib/study-telegram-bridge.ts
+++ b/src/lib/study-telegram-bridge.ts
@@ -330,6 +330,8 @@ export async function telegramListChats(force = false): Promise<TelegramChat[]>
return items;
}
+export const telegramGetChats = telegramListChats;
+
export function invalidateChatsCache() {
chatsCache = null;
}
@@ -1345,3 +1347,100 @@ export async function enqueueTelegramDownloadBatch(args: {
}
return { batchId, studyIds };
}
+
+export const TELEGRAM_FREE_LIMIT_BYTES = 2 * 1024 * 1024 * 1024; // 2.0 GB
+export const TELEGRAM_PREMIUM_LIMIT_BYTES = 4 * 1024 * 1024 * 1024; // 4.0 GB
+
+export type TelegramUploadTier = "free" | "premium";
+export type TelegramSendAsMode = "video" | "document" | "audio";
+
+export type TelegramUploadArgs = {
+ filePath: string;
+ destChatId: string | number;
+ customFileName?: string;
+ customThumbnailPath?: string;
+ caption?: string;
+ botToken?: string;
+ tier?: TelegramUploadTier;
+ sendAs?: TelegramSendAsMode;
+};
+
+export function calculateTelegramChunks(
+ fileSize: number,
+ tier: TelegramUploadTier = "free",
+): { requiresSplit: boolean; limitBytes: number; partCount: number; partSize: number } {
+ const limitBytes = tier === "premium" ? TELEGRAM_PREMIUM_LIMIT_BYTES : TELEGRAM_FREE_LIMIT_BYTES;
+ if (fileSize <= limitBytes) {
+ return { requiresSplit: false, limitBytes, partCount: 1, partSize: fileSize };
+ }
+ const partCount = Math.ceil(fileSize / limitBytes);
+ const partSize = Math.ceil(fileSize / partCount);
+ return { requiresSplit: true, limitBytes, partCount, partSize };
+}
+
+export function translateTelegramError(errorString: string, tr?: (key: string) => string): string {
+ const lower = errorString.toLowerCase();
+ const t = tr ?? ((k) => k);
+
+ if (lower.includes("blocked by the user") || lower.includes("can't initiate conversation") || lower.includes("bot was blocked")) {
+ return t("telegram.err_bot_not_started");
+ }
+ if (lower.includes("not a member") || lower.includes("not an admin") || lower.includes("kicked") || lower.includes("rights to send") || lower.includes("not enough rights")) {
+ return t("telegram.err_bot_not_member");
+ }
+ if (lower.includes("chat not found") || lower.includes("chat_invalid")) {
+ return t("telegram.err_chat_not_found");
+ }
+ if (lower.includes("unauthorized") || lower.includes("invalid token")) {
+ return t("telegram.err_unauthorized");
+ }
+ if (lower.includes("file_too_large") || lower.includes("entity too large") || lower.includes("file is too big")) {
+ return t("telegram.err_bot_file_too_large");
+ }
+ if (lower.includes("too many requests") || lower.includes("retry after")) {
+ return t("telegram.err_rate_limit");
+ }
+ return errorString;
+}
+
+export async function telegramUploadFile(args: TelegramUploadArgs): Promise<{ success: boolean; messageId?: number }> {
+ const sendAs = args.sendAs ?? "video";
+ if (args.botToken) {
+ return pluginInvoke<{ success: boolean; messageId?: number }>("telegram", "telegram_bot_upload_file", {
+ botToken: args.botToken,
+ chatId: String(args.destChatId),
+ filePath: args.filePath,
+ customFileName: args.customFileName ?? null,
+ customThumbnailPath: args.customThumbnailPath ?? null,
+ caption: args.caption ?? null,
+ sendAs,
+ }).catch(async () => {
+ return invoke<{ success: boolean; messageId?: number }>("telegram_bot_upload_file", {
+ botToken: args.botToken,
+ chatId: String(args.destChatId),
+ filePath: args.filePath,
+ customFileName: args.customFileName ?? null,
+ customThumbnailPath: args.customThumbnailPath ?? null,
+ caption: args.caption ?? null,
+ sendAs,
+ });
+ });
+ }
+ return pluginInvoke<{ success: boolean; messageId?: number }>("telegram", "telegram_user_upload_file", {
+ chatId: args.destChatId,
+ filePath: args.filePath,
+ customFileName: args.customFileName ?? null,
+ customThumbnailPath: args.customThumbnailPath ?? null,
+ caption: args.caption ?? null,
+ sendAs,
+ }).catch(async () => {
+ return invoke<{ success: boolean; messageId?: number }>("telegram_user_upload_file", {
+ chatId: args.destChatId,
+ filePath: args.filePath,
+ customFileName: args.customFileName ?? null,
+ customThumbnailPath: args.customThumbnailPath ?? null,
+ caption: args.caption ?? null,
+ sendAs,
+ });
+ });
+}
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index cadd1f4a..90f8dca4 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -16,7 +16,7 @@
import CommandPalette from "$components/shell/CommandPalette.svelte";
import { setCommandPaletteItems } from "$lib/stores/command-palette-store.svelte";
import { refreshUpdateInfo } from "$lib/stores/update-store.svelte";
- import { startClipboardMonitor, stopClipboardMonitor } from "$lib/stores/clipboard-monitor";
+ import { startClipboardMonitor, stopClipboardMonitor, onClipboardUrl } from "$lib/stores/clipboard-monitor";
import { initChangelog } from "$lib/stores/changelog-store.svelte";
import { needsOnboarding } from "$lib/stores/onboarding-store.svelte";
import { isYtdlpAvailable, isDepsChecked, refreshYtdlpStatus } from "$lib/stores/dependency-store.svelte";
@@ -65,16 +65,13 @@
page.url.pathname.startsWith("/about"),
);
- let DebugPanel = $state<Component | null>(null);
- let OnboardingWizard = $state<Component | null>(null);
- let BandwidthPill = $state<Component | null>(null);
- let NotificationBell = $state<Component | null>(null);
- let ChangelogDialog = $state<Component | null>(null);
- let ConfirmCloseDialog = $state<Component | null>(null);
- let ShortcutsDialog = $state<Component | null>(null);
- let LegalDialog = $state<Component | null>(null);
- let RecoveryDialog = $state<Component | null>(null);
- let BilibiliSessionExpiredBanner = $state<Component | null>(null);
+ let DebugPanel = $state<any>(null);
+ let OnboardingWizard = $state<any>(null);
+ let ChangelogDialog = $state<any>(null);
+ let ConfirmCloseDialog = $state<any>(null);
+ let ShortcutsDialog = $state<any>(null);
+ let LegalDialog = $state<any>(null);
+ let RecoveryDialog = $state<any>(null);
function handleExternalUrlEvent(event: Omit<ExternalUrlEvent, "id">) {
if (event.action === "prefill") {
@@ -119,24 +116,107 @@
.catch(() => {});
}
- function buildCommandPaletteItems() {
- const navItems = [...CORE_NAV_ITEMS, ...pluginNavItems].map((item) => ({
- id: `nav-${item.href}`,
- label: item.label || (item.labelKey ? get(t)(item.labelKey) : item.href),
- group: get(t)("command_palette.group_nav"),
- keywords: item.href,
- action: () => goto(item.href),
- }));
+ onMount(() => {
+ initDownloadListener();
+
+ if (import.meta.env.DEV) {
+ import("$components/debug/DebugPanel.svelte").then((m) => {
+ DebugPanel = m.default;
+ });
+ }
+
+ import("$components/onboarding/OnboardingWizard.svelte").then((m) => {
+ OnboardingWizard = m.default;
+ });
+ import("$components/dialog/ChangelogDialog.svelte").then((m) => {
+ ChangelogDialog = m.default;
+ });
+ import("$components/dialog/ConfirmCloseDialog.svelte").then((m) => {
+ ConfirmCloseDialog = m.default;
+ });
+ import("$components/dialog/ShortcutsDialog.svelte").then((m) => {
+ ShortcutsDialog = m.default;
+ });
+ import("$components/dialog/LegalDialog.svelte").then((m) => {
+ LegalDialog = m.default;
+ });
+ import("$components/dialog/RecoveryDialog.svelte").then((m) => {
+ RecoveryDialog = m.default;
+ });
+
+ refreshYtdlpStatus();
+ refreshUpdateInfo();
+ initChangelog();
+ ensureTrackerNotifications();
+ reloadPluginNav();
+
+ let unlistenExternalUrl: (() => void) | null = null;
+ let unlistenPlugins: (() => void) | null = null;
+
+ listen<Omit<ExternalUrlEvent, "id">>("external-url-event", (event) => {
+ handleExternalUrlEvent(event.payload);
+ }).then((un) => {
+ unlistenExternalUrl = un;
+ });
+
+ listen("plugins-changed", () => {
+ reloadPluginNav();
+ }).then((un) => {
+ unlistenPlugins = un;
+ });
+ return () => {
+ if (unlistenExternalUrl) unlistenExternalUrl();
+ if (unlistenPlugins) unlistenPlugins();
+ };
+ });
+
+ function buildCommandPaletteItems() {
setCommandPaletteItems([
- ...navItems,
{
- id: "action-paste",
- label: get(t)("command_palette.action_paste"),
- group: get(t)("command_palette.group_action"),
- keywords: "clipboard url paste",
+ id: "nav-home",
+ label: get(t)("command_palette.nav_home"),
+ group: get(t)("command_palette.group_nav"),
+ keywords: "index main prefill",
action: () => goto("/"),
},
+ {
+ id: "nav-downloads",
+ label: get(t)("command_palette.nav_downloads"),
+ group: get(t)("command_palette.group_nav"),
+ keywords: "queue active history",
+ action: () => goto("/downloads"),
+ },
+ {
+ id: "nav-settings",
+ label: get(t)("command_palette.nav_settings"),
+ group: get(t)("command_palette.group_nav"),
+ keywords: "preferences options config",
+ action: () => goto("/settings"),
+ },
+ {
+ id: "nav-marketplace",
+ label: get(t)("command_palette.nav_marketplace"),
+ group: get(t)("command_palette.group_nav"),
+ keywords: "plugins extensions store",
+ action: () => goto("/marketplace"),
+ },
+ {
+ id: "nav-about",
+ label: get(t)("command_palette.nav_about"),
+ group: get(t)("command_palette.group_nav"),
+ keywords: "info version changelog project",
+ action: () => goto("/about"),
+ },
+ {
+ id: "action-prefill",
+ label: get(t)("command_palette.action_prefill"),
+ group: get(t)("command_palette.group_action"),
+ keywords: "url link add download",
+ action: () => {
+ goto("/");
+ },
+ },
{
id: "action-downloads",
label: get(t)("command_palette.action_downloads"),
@@ -156,11 +236,20 @@
$effect(() => {
if (settings?.download.clipboard_detection) {
+ onClipboardUrl((clipboardUrl) => {
+ queueExternalPrefill({ action: "prefill", url: clipboardUrl, source: "clipboard" });
+ showToast("info", $t("toast.clipboard_detected") as string);
+ if (page.url.pathname !== "/") {
+ goto("/");
+ }
+ });
startClipboardMonitor();
} else {
+ onClipboardUrl(null);
stopClipboardMonitor();
}
return () => {
+ onClipboardUrl(null);
stopClipboardMonitor();
};
});
@@ -177,257 +266,171 @@
async function checkAutoVacuum() {
try {
- const { studySettingsGet, studyLibraryVacuum } = await import("$lib/study-bridge");
- const studySettings = await studySettingsGet();
- const enabled = studySettings.library?.auto_vacuum ?? true;
- if (!enabled) return;
- const intervalDays = studySettings.library?.auto_vacuum_interval_days ?? 30;
- const intervalMs = intervalDays * 86400 * 1000;
- const last = Number(localStorage.getItem(VACUUM_LAST_RUN_KEY) ?? "0");
const now = Date.now();
- if (now - last < intervalMs) return;
- const result = await studyLibraryVacuum();
- localStorage.setItem(VACUUM_LAST_RUN_KEY, String(now));
- const total =
- (result.seek_logs_deleted ?? 0)
- + (result.notifications_deleted ?? 0)
- + (result.recents_deleted ?? 0);
- if (total > 0) {
- console.info(`[study] auto-vacuum: ${total} items cleaned`, result);
+ const lastRunStr = localStorage.getItem(VACUUM_LAST_RUN_KEY);
+ const lastRun = lastRunStr ? parseInt(lastRunStr, 10) : 0;
+
+ if (now - lastRun > 7 * 24 * 60 * 60 * 1000) {
+ await invoke("db_vacuum");
+ localStorage.setItem(VACUUM_LAST_RUN_KEY, String(now));
}
- } catch (e) {
- console.warn("auto-vacuum failed", e);
- }
+ } catch {}
}
onMount(() => {
- let cleanup: (() => void) | undefined;
- let unlistenExternal: (() => void) | undefined;
- let unlistenChannels: (() => void) | undefined;
- initDownloadListener().then((fn) => (cleanup = fn));
- setTimeout(() => void checkAutoVacuum(), 5000);
- void ensureTrackerNotifications();
- import("$lib/rpc").then(({ rpcSyncIdleStats }) => rpcSyncIdleStats());
-
- void import("$components/dialog/ChangelogDialog.svelte").then((m) => { ChangelogDialog = m.default; });
- void import("$components/dialog/ConfirmCloseDialog.svelte").then((m) => { ConfirmCloseDialog = m.default; });
- void import("$components/dialog/ShortcutsDialog.svelte").then((m) => { ShortcutsDialog = m.default; });
- void import("$components/dialog/LegalDialog.svelte").then((m) => { LegalDialog = m.default; });
- void import("$components/dialog/RecoveryDialog.svelte").then((m) => { RecoveryDialog = m.default; });
- void import("$lib/components/BilibiliSessionExpiredBanner.svelte").then((m) => { BilibiliSessionExpiredBanner = m.default; });
- if (showOnboarding) {
- void import("$components/onboarding/OnboardingWizard.svelte").then((m) => { OnboardingWizard = m.default; });
- }
- void import("$components/debug/DebugPanel.svelte").then((m) => { DebugPanel = m.default; });
-
- reloadPluginNav();
- listen("plugins-changed", () => { reloadPluginNav(); });
- listen<{ outcome: string; url: string | null }>("hotkey-download-result", (event) => {
- const outcome = event.payload.outcome;
- if (outcome === "queued") {
- showToast("success", $t("toast.hotkey_queued"));
- } else if (outcome === "already_queued") {
- showToast("info", $t("toast.hotkey_already_queued"));
- } else if (outcome === "not_a_url") {
- showToast("info", $t("toast.hotkey_not_a_url"));
- } else if (outcome === "unsupported") {
- showToast("error", $t("toast.hotkey_unsupported"));
- } else {
- showToast("error", $t("toast.hotkey_clipboard_error"));
- }
- });
- listen<Omit<ExternalUrlEvent, "id">>("external-url", (event) => {
- handleExternalUrlEvent(event.payload);
- }).then((fn) => {
- unlistenExternal = fn;
- invoke<Omit<ExternalUrlEvent, "id">[]>("register_external_frontend")
- .then((events) => {
- for (const event of events) {
- handleExternalUrlEvent(event);
- }
- })
- .catch(() => {});
- });
- listen<{ channel_title: string; auto_download: boolean; videos: unknown[] }>(
- "channel-new-videos",
- (event) => {
- const p = event.payload;
- const count = p.videos?.length ?? 0;
- if (count <= 0) return;
- showToast(
- "info",
- $t(
- p.auto_download
- ? "toast.channel_new_auto"
- : "toast.channel_new",
- { channel: p.channel_title, count },
- ) as string,
- );
- },
- ).then((fn) => {
- unlistenChannels = fn;
- });
- refreshUpdateInfo();
- initChangelog();
- refreshYtdlpStatus();
-
- const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
- const handleChange = () => {
- const s = getSettings();
- if (s?.appearance.theme === "system") {
- document.documentElement.setAttribute("data-theme", mediaQuery.matches ? "dark" : "light");
- }
- };
- mediaQuery.addEventListener("change", handleChange);
-
- return () => {
- cleanup?.();
- unlistenExternal?.();
- unlistenChannels?.();
- mediaQuery.removeEventListener("change", handleChange);
- };
- });
-
- $effect(() => {
- if (isStudyRoute) {
- void import("$lib/study-components/BandwidthPill.svelte").then((m) => { BandwidthPill = m.default; });
- void import("$lib/study-components/shelves/NotificationBell.svelte").then((m) => { NotificationBell = m.default; });
- } else {
- BandwidthPill = null;
- NotificationBell = null;
- }
+ void checkAutoVacuum();
});
</script>
-<div class="mac-shell">
- <AppToolbar />
- <div class="mac-shell-body">
- <AppSidebar
- {primaryNav}
- {appNav}
- {pluginNav}
- {badgeLabel}
- badgeCount={counts.badge}
- />
- <main
- class="mac-content"
- class:mac-content--home={page.url.pathname === "/"}
- class:mac-content--pane={
- page.url.pathname.startsWith("/settings") ||
- page.url.pathname.startsWith("/downloads")
- }
- >
- {#if ytdlpMissing && !ytdlpDismissed && isCoreRoute}
- <div class="ytdlp-banner">
- <span class="ytdlp-banner-text">{$t('common.ytdlp_missing')}</span>
- <button class="button ytdlp-banner-link" onclick={() => goto('/settings#dependencies')}>
- {$t('common.go_to_settings')}
- </button>
- <button class="ytdlp-banner-close" onclick={() => ytdlpDismissed = true} aria-label={$t('common.close')}>
- <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
- <path d="M18 6L6 18M6 6l12 12" />
- </svg>
+<div class="shell" data-reduce-motion={settings?.accessibility?.reduce_motion}>
+ <AppSidebar {primaryNav} {appNav} {pluginNav} {badgeLabel} />
+
+ <div class="shell-body">
+ <AppToolbar />
+
+ {#if ytdlpMissing && !ytdlpDismissed}
+ <div class="ytdlp-banner" role="alert">
+ <span class="ytdlp-banner-text">
+ {$t("ytdlp_missing_banner.text")}
+ </span>
+ <div class="ytdlp-banner-actions">
+ <a href="/settings#dependencies" class="button ytdlp-banner-link">
+ {$t("ytdlp_missing_banner.open_settings")}
+ </a>
+ <button
+ type="button"
+ class="ytdlp-banner-close"
+ onclick={() => (ytdlpDismissed = true)}
+ aria-label={$t("ytdlp_missing_banner.dismiss") as string}
+ >
+ ✕
</button>
</div>
+ </div>
+ {/if}
+
+ <main id="main-content" class="content">
+ {#if isStudyRoute}
+ <div class="study-shell">
+ {@render children()}
+ </div>
+ {:else if isCoreRoute}
+ <div class="core-shell">
+ {@render children()}
+ </div>
+ {:else}
+ {@render children()}
{/if}
- {@render children()}
</main>
</div>
</div>
+<Toast />
<CommandPalette />
-{#if isStudyRoute && BandwidthPill}
- <div class="bandwidth-pill-mount">
- <BandwidthPill />
- </div>
-{/if}
-
-{#if isStudyRoute && NotificationBell}
- <div class="notification-bell-mount">
- <NotificationBell />
- </div>
+{#if showOnboarding && OnboardingWizard}
+ <OnboardingWizard />
{/if}
-<Toast />
{#if DebugPanel}
<DebugPanel />
{/if}
-{#if BilibiliSessionExpiredBanner}
- <BilibiliSessionExpiredBanner />
-{/if}
+
{#if ChangelogDialog}
<ChangelogDialog />
{/if}
+
{#if ConfirmCloseDialog}
<ConfirmCloseDialog />
{/if}
+
{#if ShortcutsDialog}
<ShortcutsDialog />
{/if}
+
{#if LegalDialog}
<LegalDialog />
{/if}
+
{#if RecoveryDialog}
<RecoveryDialog />
{/if}
-{#if showOnboarding && OnboardingWizard}
- <OnboardingWizard />
-{/if}
<style>
- .bandwidth-pill-mount {
- position: fixed;
- bottom: 12px;
- right: 12px;
- z-index: 50;
- pointer-events: none;
+ .shell {
+ display: flex;
+ width: 100vw;
+ height: 100vh;
+ overflow: hidden;
+ background: var(--bg);
+ color: var(--text);
}
- .notification-bell-mount {
- position: fixed;
- top: calc(var(--titlebar-height) + 8px);
- right: 16px;
- z-index: 60;
+ .shell-body {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ height: 100vh;
+ overflow: hidden;
}
- .ytdlp-banner {
+ .content {
+ flex: 1;
+ overflow-y: auto;
+ min-height: 0;
display: flex;
- align-items: center;
- gap: 10px;
- padding: 10px 14px;
- margin-bottom: var(--padding);
- background: color-mix(in srgb, var(--warning) 18%, var(--surface));
- color: color-mix(in srgb, var(--warning) 82%, var(--text));
- border: 1px solid color-mix(in srgb, var(--warning) 34%, var(--border));
- border-radius: var(--border-radius);
- font-size: var(--text-sm);
- font-weight: 500;
+ flex-direction: column;
}
- :global([data-theme="light"]) .ytdlp-banner,
- :global([data-theme="catppuccin-latte"]) .ytdlp-banner,
- :global([data-theme="eink-day"]) .ytdlp-banner,
- :global([data-theme="eink-sepia"]) .ytdlp-banner,
- :global([data-theme="nyxvamp-radiance"]) .ytdlp-banner {
- color: var(--on-warning);
+ .core-shell {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ max-width: 1200px;
+ width: 100%;
+ margin: 0 auto;
+ padding: var(--padding);
+ }
+
+ .study-shell {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ }
+
+ .ytdlp-banner {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 8px 16px;
+ background: var(--warning);
+ color: var(--on-warning, black);
+ font-size: 13px;
+ gap: 12px;
}
.ytdlp-banner-text {
flex: 1;
+ font-weight: 500;
+ }
+
+ .ytdlp-banner-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
}
.ytdlp-banner-link {
+ font-size: 12px;
+ padding: 4px 10px;
+ border-radius: var(--radius-sm);
background: var(--cta);
color: var(--on-cta);
- border: none;
- font-size: var(--text-sm);
+ text-decoration: none;
font-weight: 500;
- padding: 4px 10px;
- border-radius: var(--radius-sm);
- cursor: pointer;
- white-space: nowrap;
- box-shadow: none;
}
@media (hover: hover) {
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index 4ed2ed72..86414f9e 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -1,1940 +1,1930 @@
-<script lang="ts">
- import { invoke } from "@tauri-apps/api/core";
- import { open } from "@tauri-apps/plugin-dialog";
- import { goto } from "$app/navigation";
- import { onMount } from "svelte";
- import SupportedServices from "$components/services/SupportedServices.svelte";
- import BilibiliPreviewExtras from "$components/omnibox/BilibiliPreviewExtras.svelte";
- import DownloadModeSelector from "$components/omnibox/DownloadModeSelector.svelte";
- import QualityPicker from "$components/omnibox/QualityPicker.svelte";
- import FormatSelector from "$components/omnibox/FormatSelector.svelte";
- import CookieAccountPicker from "$components/omnibox/CookieAccountPicker.svelte";
- import OmniboxAdvanced from "$components/omnibox/OmniboxAdvanced.svelte";
- import MediaPreview from "$components/omnibox/MediaPreview.svelte";
- import BatchDownload from "$components/omnibox/BatchDownload.svelte";
- import SearchResults from "$components/omnibox/SearchResults.svelte";
- import P2pSendDialog from "$components/p2p/P2pSendDialog.svelte";
- import P2pReceiveDialog from "$components/p2p/P2pReceiveDialog.svelte";
- import HomeHero from "$components/home/HomeHero.svelte";
- import HomeUrlBar from "$components/home/HomeUrlBar.svelte";
- import HomeInspector from "$components/home/HomeInspector.svelte";
- import {
- type OmniState,
- type PlatformInfo,
- type SearchResult,
- type HomeInputMode,
- showInspectorForState,
- showOmniboxForState,
- isUrl,
- } from "$lib/home/omnibox-controller";
- import { getDownloads, formatBytes } from "$lib/stores/download-store.svelte";
- import { getSettings, updateSettings } from "$lib/stores/settings-store.svelte";
- import { showToast } from "$lib/stores/toast-store.svelte";
- import { onClipboardUrl } from "$lib/stores/clipboard-monitor";
- import { getMediaPreview, clearMediaPreview } from "$lib/stores/media-preview-store.svelte";
- import { clearPendingExternalPrefill, getPendingExternalPrefill, type ExternalUrlEvent } from "$lib/stores/external-url-store.svelte";
- import { getOmniboxDraftUrl, setOmniboxDraftUrl } from "$lib/stores/omnibox-draft-store.svelte";
- import { t } from "$lib/i18n";
- import { translateBackendError } from "$lib/error-translate";
- import { platformDisplayName } from "$lib/platform-display-names";
- import { STUDY_MAINTENANCE_NOTICE } from "$lib/study-feature-flags";
-
- type DownloadStarted = {
- id: number;
- title: string;
- };
-
- type FormatInfo = {
- format_id: string;
- ext: string;
- resolution: string | null;
- width: number | null;
- height: number | null;
- fps: number | null;
- vcodec: string | null;
- acodec: string | null;
- filesize: number | null;
- tbr: number | null;
- has_video: boolean;
- has_audio: boolean;
- format_note: string | null;
- };
-
- // Platforms whose content is downloaded via the Courses page (courses
- // plugin + logged-in account), not from a pasted URL.
- const COURSE_PLATFORMS = new Set(["hotmart", "udemy"]);
-
- let url = $state(getOmniboxDraftUrl());
- let homeInputMode = $state<HomeInputMode>("url");
- let omniState = $state<OmniState>({ kind: "idle" });
- let debounceTimer = $state<ReturnType<typeof setTimeout> | null>(null);
- let downloadMode = $state<"auto" | "audio" | "mute">("auto");
- let selectedQuality = $state("best");
- let clipStart = $state("");
- let clipEnd = $state("");
- let scheduleAt = $state("");
- let scheduleStop = $state("");
- let playlistEntries = $state<{ index: number; title: string; url: string }[]>([]);
- let selectedPlaylistItems = $state<Set<number>>(new Set());
- let playlistLoading = $state(false);
- let torrentEntries = $state<{ index: number; path: string; size_bytes: number }[]>([]);
- let selectedTorrentFiles = $state<Set<number>>(new Set());
- let torrentLoading = $state(false);
- let selectedFormatId = $state<string | null>(null);
- let formats = $state<FormatInfo[]>([]);
- let loadingFormats = $state(false);
- let formatError = $state<string | null>(null);
- let formatFetchGeneration = $state(0);
- let referer = $state("");
-
- type CookieAccount = {
- slug: string;
- alias: string;
- captured_at_ms: number;
- cookie_count: number;
- last_used_at_ms: number | null;
- };
- let cookieAccounts = $state<CookieAccount[]>([]);
- let selectedCookieSlug = $state<string | null>(null);
- let cookieHint = $state<"stale" | "expired" | null>(null);
- let advancedMode = $state(false);
- const STUDY_NOTICE_DISMISS_KEY = "omniget.study_maintenance_notice_dismissed_v1";
- let studyNoticeDismissed = $state(
- typeof localStorage !== "undefined"
- && localStorage.getItem(STUDY_NOTICE_DISMISS_KEY) === "1"
- );
- function dismissStudyNotice() {
- studyNoticeDismissed = true;
- try { localStorage.setItem(STUDY_NOTICE_DISMISS_KEY, "1"); } catch {}
- }
- let mediaPreview = $derived(getMediaPreview());
- let pendingExternalPrefill = $derived(getPendingExternalPrefill());
- let previewImageLoading = $state(true);
- let showP2pSendDialog = $state(false);
- let p2pReceiveCode = $state<string | null>(null);
- 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(autoDownload ? "toast.auto_download_started" : "toast.clipboard_url_detected"));
- });
- if (url.trim()) {
- queueMicrotask(() => handleInput());
- }
- return () => {
- onClipboardUrl(null);
- };
- });
-
- $effect(() => {
- setOmniboxDraftUrl(url);
- });
-
- const AUTO_DOWNLOAD_DELAY_MS = 2000;
-
- $effect(() => {
- if (!pendingAutoDownload) return;
- if (omniState.kind === "detected") {
- const info = omniState.info;
- if (COURSE_PLATFORMS.has(info.platform) || 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);
- let lastCompletionAt = $state(0);
- let firstCompletionOfSession = $state(false);
- let completionSeenIds = new Set<string | number>();
-
- $effect(() => {
- for (const [id, item] of downloads.entries()) {
- if (item.status === "complete" && !completionSeenIds.has(id)) {
- completionSeenIds.add(id);
- lastCompletionAt = Date.now();
- if (!firstCompletionOfSession) {
- firstCompletionOfSession = true;
- }
- break;
- }
- }
- });
-
- $effect(() => {
- const interval = setInterval(() => { stallTick++; }, 5000);
- return () => clearInterval(interval);
- });
-
-
- $effect(() => {
- if (mediaPreview) {
- previewImageLoading = true;
- }
- });
-
- $effect(() => {
- const incoming = pendingExternalPrefill;
- if (!incoming || incoming.id === lastExternalPrefillId) {
- return;
- }
-
- 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();
- });
-
- let mascotEmotion = $derived.by((): "idle" | "downloading" | "error" | "stalled" | "queue" | "complete" | "amazed" => {
- void stallTick;
-
- if (lastCompletionAt > 0 && Date.now() - lastCompletionAt < 5000) {
- return firstCompletionOfSession && completionSeenIds.size === 1 ? "amazed" : "complete";
- }
-
- if (omniState.kind === "preparing") return "downloading";
- if (omniState.kind === "error") return "error";
-
- let hasActiveDownloading = false;
- let hasActiveStalled = false;
- let hasItems = false;
- for (const item of downloads.values()) {
- hasItems = true;
- if (item.status === "downloading") {
- hasActiveDownloading = true;
- const elapsed = Date.now() - item.lastUpdateAt;
- if (elapsed > STALL_THRESHOLD) {
- hasActiveStalled = true;
- }
- }
- }
-
- if (hasActiveStalled) return "stalled";
- if (hasActiveDownloading) return "downloading";
- if (hasItems) return "queue";
- return "idle";
- });
-
- let mascotCompact = $derived(omniState.kind !== "idle");
-
- function pickRandom(raw: string): string {
- if (raw.includes("|")) {
- const opts = raw.split("|");
- return opts[Math.floor(Math.random() * opts.length)];
- }
- return raw;
- }
-
- let lastBubbleKey = $state("");
- let bubbleText = $state("");
-
- $effect(() => {
- let key: string;
- if (mascotEmotion === "amazed") key = "amazed";
- else if (mascotEmotion === "complete") key = "complete";
- else if (mascotEmotion === "queue") key = "queue";
- else if (mascotEmotion === "downloading") key = "downloading";
- else if (mascotEmotion === "stalled") key = "stalled";
- else {
- switch (omniState.kind) {
- case "idle": key = "idle"; break;
- case "detecting": key = "detecting"; break;
- case "detected": key = "detected"; break;
- case "preparing": key = "preparing"; break;
- case "searching":
- case "search-results": key = "search"; break;
- case "error": key = "error"; break;
- default: key = ""; break;
- }
- }
- if (key && key !== lastBubbleKey) {
- lastBubbleKey = key;
- bubbleText = pickRandom($t(`mascot.${key}`));
- } else if (!key) {
- lastBubbleKey = "";
- bubbleText = "";
- }
- });
-
- let showLoopIcon = $derived(
- omniState.kind === "detected" ||
- omniState.kind === "preparing" ||
- omniState.kind === "batch"
- );
-
- let showOmnibox = $derived(showOmniboxForState(omniState));
- let showInspector = $derived(showInspectorForState(omniState));
-
- function isValidTimeBound(v: string): boolean {
- return /^(\d+:)?\d{1,2}:\d{1,2}(\.\d+)?$|^\d+(\.\d+)?$/.test(v.trim());
- }
-
- function buildTimeRange(): string | null {
- const s = clipStart.trim();
- const e = clipEnd.trim();
- if (!s && !e) return null;
- if (s && !isValidTimeBound(s)) return null;
- if (e && !isValidTimeBound(e)) return null;
- return `${s || "0"}-${e || "inf"}`;
- }
-
- function toEpochMs(v: string): number | null {
- if (!v) return null;
- const ms = new Date(v.includes("T") ? v : `${v}T00:00`).getTime();
- if (Number.isNaN(ms)) return null;
- return ms;
- }
-
- function schedulePart(v: string, part: "date" | "time"): string {
- if (!v) return "";
- const [date, time = ""] = v.split("T");
- return part === "date" ? date : time;
- }
-
- function withSchedulePart(current: string, part: "date" | "time", value: string): string {
- const pad = (n: number) => String(n).padStart(2, "0");
- let [date, time = ""] = current ? current.split("T") : ["", ""];
- if (part === "date") date = value;
- else time = value;
- if (!date && !time) return "";
- if (!date) {
- const now = new Date();
- date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
- }
- if (!time) time = "00:00";
- return `${date}T${time}`;
- }
-
- function setSchedulePreset(kind: "1h" | "tonight" | "1d") {
- const d = new Date();
- if (kind === "1h") d.setHours(d.getHours() + 1);
- else if (kind === "1d") d.setDate(d.getDate() + 1);
- else {
- d.setHours(22, 0, 0, 0);
- if (d.getTime() < Date.now()) d.setDate(d.getDate() + 1);
- }
- const pad = (n: number) => String(n).padStart(2, "0");
- scheduleAt = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
- }
-
- function handleInput() {
- if (debounceTimer) clearTimeout(debounceTimer);
- clearMediaPreview();
- clipStart = "";
- clipEnd = "";
- scheduleAt = "";
- scheduleStop = "";
- cookieHint = null;
- playlistEntries = [];
- selectedPlaylistItems = new Set();
- playlistLoading = false;
- torrentEntries = [];
- selectedTorrentFiles = new Set();
- torrentLoading = false;
- const currentSettings = getSettings();
- const saved = currentSettings?.last_download_options;
- const savedMode = saved?.mode;
- const settingsQuality = currentSettings?.download.video_quality;
- selectedQuality = settingsQuality && typeof settingsQuality === "string"
- ? settingsQuality
- : "best";
- downloadMode = savedMode === "audio" || savedMode === "mute" ? savedMode : "auto";
- selectedFormatId = null;
- formats = [];
- loadingFormats = false;
- formatError = null;
- formatFetchGeneration++;
- referer = "";
-
- const trimmed = url.trim();
- if (!trimmed) {
- omniState = { kind: "idle" };
- return;
- }
-
- const urls = trimmed.split(/[\s\n]+/).filter(isUrl);
-
- if (urls.length > 1) {
- omniState = { kind: "batch", urls };
- return;
- }
-
- if (isUrl(trimmed)) {
- omniState = { kind: "detecting" };
- if (getSettings()?.download.auto_download_on_paste) {
- pendingAutoDownload = true;
- }
- debounceTimer = setTimeout(() => {
- detectPlatform(trimmed);
- }, 500);
- return;
- }
-
- if (trimmed.length >= 2) {
- omniState = { kind: "searching" };
- debounceTimer = setTimeout(() => {
- performSearch(trimmed);
- }, 600);
- } else {
- omniState = { kind: "idle" };
- }
- }
-
- async function detectPlatform(value: string) {
- try {
- const result = await invoke<PlatformInfo>("detect_platform", { url: value });
- if (result.supported) {
- omniState = { kind: "detected", info: result };
- if (!COURSE_PLATFORMS.has(result.platform)) {
- invoke("prefetch_media_info", { url: value }).catch(() => {});
- }
- loadCookieAccounts(value);
- if (result.content_type === "playlist") {
- loadPlaylistEntries(value);
- }
- if (isTorrentUrl(value)) {
- loadTorrentContents(value);
- }
- } else {
- omniState = { kind: "unsupported" };
- }
- } catch {
- omniState = { kind: "unsupported" };
- }
- }
-
- async function loadPlaylistEntries(targetUrl: string) {
- playlistEntries = [];
- selectedPlaylistItems = new Set();
- playlistLoading = true;
- try {
- const entries = await invoke<{ index: number; title: string; url: string }[]>(
- "playlist_entries",
- { url: targetUrl }
- );
- playlistEntries = entries;
- selectedPlaylistItems = new Set(entries.map((e) => e.index));
- } catch {
- playlistEntries = [];
- } finally {
- playlistLoading = false;
- }
- }
-
- function togglePlaylistItem(idx: number) {
- const next = new Set(selectedPlaylistItems);
- if (next.has(idx)) next.delete(idx);
- else next.add(idx);
- selectedPlaylistItems = next;
- }
-
- function selectAllPlaylist() {
- selectedPlaylistItems = new Set(playlistEntries.map((e) => e.index));
- }
-
- function selectNonePlaylist() {
- selectedPlaylistItems = new Set();
- }
-
- function isTorrentUrl(value: string): boolean {
- const v = value.trim().toLowerCase();
- return v.startsWith("magnet:") || v.endsWith(".torrent");
- }
-
- async function loadTorrentContents(targetUrl: string) {
- torrentEntries = [];
- selectedTorrentFiles = new Set();
- torrentLoading = true;
- try {
- const entries = await invoke<{ index: number; path: string; size_bytes: number }[]>(
- "torrent_contents",
- { url: targetUrl }
- );
- torrentEntries = entries;
- selectedTorrentFiles = new Set(entries.map((e) => e.index));
- } catch {
- torrentEntries = [];
- } finally {
- torrentLoading = false;
- }
- }
-
- function toggleTorrentFile(idx: number) {
- const next = new Set(selectedTorrentFiles);
- if (next.has(idx)) next.delete(idx);
- else next.add(idx);
- selectedTorrentFiles = next;
- }
-
- function selectAllTorrent() {
- selectedTorrentFiles = new Set(torrentEntries.map((e) => e.index));
- }
-
- function selectNoneTorrent() {
- selectedTorrentFiles = new Set();
- }
-
- async function loadCookieAccounts(targetUrl: string) {
- try {
- const result = await invoke<{ domain: string; accounts: CookieAccount[] }>(
- "cookies_accounts_for_url",
- { url: targetUrl }
- );
- const accounts = result.accounts.slice().sort((a, b) => {
- const lhs = a.last_used_at_ms ?? a.captured_at_ms;
- const rhs = b.last_used_at_ms ?? b.captured_at_ms;
- return rhs - lhs;
- });
- cookieAccounts = accounts;
- selectedCookieSlug = accounts[0]?.slug ?? null;
- cookieHint = null;
- if (accounts.length > 0) {
- try {
- const h = await invoke<{ items: { domain: string; slug: string; status: string }[] }>(
- "cookies_health"
- );
- const slug = selectedCookieSlug ?? "_default";
- const item =
- h.items.find((it) => it.domain === result.domain && it.slug === slug) ??
- h.items.find((it) => it.domain === result.domain);
- if (item && item.status !== "fresh") {
- cookieHint = item.status === "expired" ? "expired" : "stale";
- }
- } catch {}
- }
- } catch {
- cookieAccounts = [];
- selectedCookieSlug = null;
- cookieHint = null;
- }
- }
-
- async function performSearch(query: string) {
- try {
- const results = await invoke<SearchResult[]>("search_videos", {
- query,
- platform: "youtube",
- maxResults: 6,
- });
- if (url.trim() !== query) return;
- if (results.length > 0) {
- omniState = { kind: "search-results", results };
- } else {
- omniState = { kind: "search-empty" };
- }
- } catch {
- if (url.trim() === query) {
- omniState = { kind: "search-empty" };
- }
- }
- }
-
- function selectSearchResult(result: SearchResult) {
- url = result.url;
- omniState = { kind: "detecting" };
- detectPlatform(result.url);
- }
-
- function getContentTypeLabel(contentType: string | null): string {
- if (!contentType) return $t("omnibox.content_type.unknown");
- const key = `omnibox.content_type.${contentType}`;
- const result = $t(key);
- if (result === key) return $t("omnibox.content_type.unknown");
- return result;
- }
-
-
- async function loadFormats() {
- if (loadingFormats) return;
- if (formats.length > 0) {
- formats = [];
- selectedFormatId = null;
- formatError = null;
- return;
- }
- const targetUrl = url.trim();
- if (!targetUrl) {
- formatError = $t("omnibox.formats_error");
- return;
- }
- loadingFormats = true;
- formatError = null;
- const gen = ++formatFetchGeneration;
- try {
- const result = await invoke<FormatInfo[]>("get_media_formats", { url: targetUrl });
- if (gen !== formatFetchGeneration) return;
- formats = result;
- if (result.length === 0) {
- formatError = $t("omnibox.no_formats");
- }
- } catch (e: any) {
- if (gen !== formatFetchGeneration) return;
- formats = [];
- const msg = typeof e === "string" ? e : e.message ?? "";
- formatError = msg ? translateBackendError(msg, $t) : $t("omnibox.formats_error");
- } finally {
- loadingFormats = false;
- }
- }
-
- function selectFormat(formatId: string) {
- selectedFormatId = formatId;
- }
-
- function clearFormatSelection() {
- selectedFormatId = null;
- }
-
- function presetBest() {
- selectedFormatId = null;
- downloadMode = "auto";
- selectedQuality = "best";
- }
-
- function presetMusic() {
- selectedFormatId = null;
- downloadMode = "audio";
- }
-
- function persistLastDownloadOptions() {
- const saved = getSettings()?.last_download_options;
- const nextMode = downloadMode;
- if (saved?.mode === nextMode) return;
- updateSettings({
- last_download_options: {
- mode: nextMode,
- quality: saved?.quality ?? "best",
- },
- }).catch(() => {});
- }
-
- async function handleAction() {
- if (omniState.kind !== "detected") return;
- const info = omniState.info;
-
- if (COURSE_PLATFORMS.has(info.platform)) {
- goto(`/courses/${encodeURIComponent(info.platform)}`);
- return;
- }
-
- if (info.platform === "p2p") {
- const trimmed = url.trim();
- const code = trimmed.replace(/^p2p:/, "");
- p2pReceiveUrl = trimmed;
- p2pReceiveCode = code;
- return;
- }
-
- const isPlaylist = info.content_type === "playlist" && playlistEntries.length > 0;
- if (isPlaylist && selectedPlaylistItems.size === 0) {
- showToast("error", $t("omnibox.playlist_none_selected") as string);
- return;
- }
-
- const isTorrent = torrentEntries.length > 0;
- if (isTorrent && selectedTorrentFiles.size === 0) {
- showToast("error", $t("omnibox.torrent_none_selected") as string);
- return;
- }
-
- const settings = getSettings();
- let outputDir = settings?.download.default_output_dir ?? "";
-
- 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"),
- });
- if (!selected) return;
- outputDir = selected;
- }
-
- const currentUrl = url.trim();
- const platform = info.platform;
- omniState = { kind: "preparing", platform };
- url = "";
-
- try {
- await invoke<DownloadStarted>("download_from_url", {
- url: currentUrl,
- outputDir,
- downloadMode: downloadMode === "auto" ? null : downloadMode,
- quality: selectedQuality,
- formatId: selectedFormatId,
- referer: referer.trim() || null,
- cookieSlug: selectedCookieSlug,
- timeRange: buildTimeRange(),
- playlistItems: isPlaylist ? [...selectedPlaylistItems] : null,
- torrentFiles: isTorrent ? [...selectedTorrentFiles] : null,
- scheduledAt: toEpochMs(scheduleAt),
- stopAt: toEpochMs(scheduleStop),
- });
- persistLastDownloadOptions();
- omniState = { kind: "idle" };
- } catch (e: any) {
- const msg = typeof e === "string" ? e : e.message ?? $t("omnibox.error");
- omniState = {
- kind: "error",
- message: msg,
- originalUrl: currentUrl,
- platform,
- };
- }
- }
-
- async function handleBatchDownload() {
- if (omniState.kind !== "batch") return;
- const batchUrls = omniState.urls;
-
- const settings = getSettings();
- let outputDir = settings?.download.default_output_dir ?? "";
-
- 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"),
- });
- if (!selected) return;
- outputDir = selected;
- }
-
- omniState = { kind: "idle" };
- url = "";
-
- const results = await Promise.allSettled(
- batchUrls.map(u => invoke<DownloadStarted>("download_from_url", {
- url: u,
- outputDir,
- downloadMode: downloadMode === "auto" ? null : downloadMode,
- quality: selectedQuality,
- formatId: null,
- referer: null,
- cookieSlug: null,
- }))
- );
-
- const queued = results.filter(r => r.status === "fulfilled").length;
- if (queued > 0) {
- showToast("info", $t("omnibox.batch_queued", { count: queued }));
- persistLastDownloadOptions();
- }
- }
-
- function handleRetry() {
- if (omniState.kind !== "error") return;
- url = omniState.originalUrl;
- omniState = { kind: "detecting" };
- detectPlatform(url.trim());
- }
-
- async function handleP2pAccept() {
- const currentUrl = p2pReceiveUrl;
- p2pReceiveCode = null;
- p2pReceiveUrl = "";
-
- const settings = getSettings();
- let outputDir = settings?.download.default_output_dir ?? "";
-
- 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"),
- });
- if (!selected) return;
- outputDir = selected;
- }
-
- omniState = { kind: "preparing", platform: "p2p" };
- url = "";
-
- try {
- await invoke("download_from_url", {
- url: currentUrl,
- outputDir,
- downloadMode: null,
- quality: "best",
- formatId: null,
- referer: null,
- cookieSlug: null,
- });
- omniState = { kind: "idle" };
- } catch (e: any) {
- const msg = typeof e === "string" ? e : e.message ?? $t("omnibox.error");
- omniState = { kind: "error", message: msg, originalUrl: currentUrl, platform: "p2p" };
- }
- }
-
- function handleP2pReject() {
- p2pReceiveCode = null;
- p2pReceiveUrl = "";
- }
-
- async function openTorrentFile() {
- const selected = await open({
- title: "Select .torrent file",
- filters: [{ name: "Torrent", extensions: ["torrent"] }],
- multiple: false,
- });
- if (selected && typeof selected === "string") {
- url = selected;
- handleInput();
- }
- }
-
- async function openBatchFile() {
- const selected = await open({
- title: $t("omnibox.batch_file_title"),
- filters: [{ name: "Text", extensions: ["txt"] }],
- multiple: false,
- });
- if (!selected || typeof selected !== "string") return;
- try {
- const urls = await invoke<string[]>("parse_batch_file", { path: selected });
- if (urls.length === 0) {
- showToast("info", $t("omnibox.batch_file_empty"));
- return;
- }
- if (urls.length === 1) {
- url = urls[0];
- handleInput();
- return;
- }
- url = urls.join("\n");
- omniState = { kind: "batch", urls };
- } catch (e: any) {
- const msg = typeof e === "string" ? e : e.message ?? $t("omnibox.error");
- showToast("error", msg);
- }
- }
-
- function handleHomeModeChange(mode: HomeInputMode) {
- // batch/torrent/p2p are momentary actions, not persistent input modes:
- // return to "url" so the tab bar never strands on an empty state when
- // the picker/dialog is cancelled
- if (mode === "p2p") {
- showP2pSendDialog = true;
- homeInputMode = "url";
- } else if (mode === "torrent") {
- void openTorrentFile().finally(() => {
- homeInputMode = "url";
- });
- } else if (mode === "batch") {
- void openBatchFile().finally(() => {
- homeInputMode = "url";
- });
- }
- }
-
- function handleDismiss() {
- clearMediaPreview();
- omniState = { kind: "idle" };
- url = "";
- }
-</script>
-
-<div class="home-mac">
- {#if STUDY_MAINTENANCE_NOTICE && !studyNoticeDismissed}
- <div class="study-maintenance-banner" role="status">
- <div class="study-maintenance-text">
- <strong>{$t("study.maintenance.home_banner_title")}</strong>
- <span>{$t("study.maintenance.home_banner_body")}</span>
- </div>
- <button
- type="button"
- class="study-maintenance-dismiss"
- onclick={dismissStudyNotice}
- aria-label={$t('common.close')}
- >
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
- <path d="M18 6L6 18M6 6l12 12" />
- </svg>
- </button>
- </div>
- {/if}
-
- <div class="home-mac-workspace">
- <div class="home-mac-hero">
- <HomeHero
- emotion={mascotEmotion}
- compact={mascotCompact}
- bubbleText={bubbleText || undefined}
- celebrate={mascotEmotion === "amazed"}
- />
- </div>
- <div class="home-mac-main">
- <div class="mode-toggle-row">
- <button
- type="button"
- class="mode-toggle-btn"
- class:active={!advancedMode}
- onclick={() => { advancedMode = false; }}
- >
- {$t('omnibox.mode_normal')}
- </button>
- <button
- type="button"
- class="mode-toggle-btn"
- class:active={advancedMode}
- onclick={() => { advancedMode = true; }}
- >
- {$t('omnibox.mode_advanced')}
- </button>
- </div>
-
- {#if advancedMode}
- <OmniboxAdvanced />
- {:else}
- {#if externalNotice}
- <div class="feedback-card feedback-enter external-url-card">
- <div class="card-row">
- <svg class="card-status-icon" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <path d="M12 5v14" />
- <path d="M5 12h14" />
- </svg>
- <span class="card-title">{$t('omnibox.external_url_ready')}</span>
- <button class="dismiss-btn" onclick={() => { externalNotice = null; }} aria-label={$t('common.close')}>
- <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <path d="M18 6L6 18M6 6l12 12" />
- </svg>
- </button>
- </div>
- <div class="card-row">
- <span class="card-subtext external-url-text">{externalNotice.url}</span>
- </div>
- </div>
- {/if}
-
- {#if showLoopIcon}
- <img
- src="/loop.png"
- alt=""
- width="40"
- height="40"
- class="loop-icon"
- class:loop-bounce={omniState.kind === "detected" || omniState.kind === "batch"}
- class:loop-pulse={omniState.kind === "preparing"}
- />
- {/if}
-
- {#if omniState.kind === "detecting"}
- <div class="feedback feedback-enter">
- <span class="feedback-spinner"></span>
- </div>
-
- {:else if omniState.kind === "detected"}
- <div class="feedback feedback-enter" data-supported="true">
- <span class="feedback-text">
- {platformDisplayName(omniState.info.platform)}
- {#if omniState.info.content_type}
- <span class="feedback-sep">&middot;</span>
- {getContentTypeLabel(omniState.info.content_type)}
- {/if}
- </span>
- </div>
- {/if}
-
- {#if showOmnibox}
- <HomeUrlBar bind:url bind:mode={homeInputMode} onInput={handleInput} onModeChange={handleHomeModeChange} />
- {/if}
-
- {#if omniState.kind === "batch"}
- <div class="batch-options">
- <DownloadModeSelector bind:downloadMode />
- <BatchDownload count={omniState.urls.length} onDownload={handleBatchDownload} />
- </div>
-
- {:else if omniState.kind === "searching"}
- <div class="feedback feedback-enter">
- <span class="feedback-spinner"></span>
- <span class="feedback-text search-hint">{$t('omnibox.searching')}</span>
- </div>
-
- {:else if omniState.kind === "search-results"}
- <SearchResults results={omniState.results} onSelect={selectSearchResult} />
-
- {:else if omniState.kind === "search-empty"}
- <div class="feedback feedback-enter" data-supported="false">
- <svg class="feedback-icon" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <circle cx="11" cy="11" r="8" />
- <path d="M21 21l-4.35-4.35" />
- </svg>
- <span class="feedback-text">{$t('omnibox.search_empty')}</span>
- </div>
-
- {:else if omniState.kind === "unsupported"}
- <div class="feedback feedback-enter" data-supported="false">
- <svg class="feedback-icon" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
- <circle cx="12" cy="12" r="10" />
- <path d="M12 8v4m0 4h.01" />
- </svg>
- <span class="feedback-text">{$t('omnibox.unsupported')}</span>
- </div>
- {/if}
- {/if}
-
- {#if omniState.kind === "idle"}
- <SupportedServices />
- {/if}
- </div>
-
- <HomeInspector open={showInspector} title={$t('home.inspector_title')}>
- {#if omniState.kind === "detected"}
- <MediaPreview bind:mediaPreview bind:imageLoading={previewImageLoading} />
- {#if omniState.info.content_type === "playlist"}
- <div class="playlist-picker">
- <div class="playlist-head">
- <span class="playlist-count">
- {$t('omnibox.playlist_selected', { selected: selectedPlaylistItems.size, total: playlistEntries.length })}
- </span>
- {#if !playlistLoading && playlistEntries.length > 0}
- <div class="playlist-bulk">
- <button type="button" class="playlist-link" onclick={selectAllPlaylist}>{$t('omnibox.playlist_all')}</button>
- <button type="button" class="playlist-link" onclick={selectNonePlaylist}>{$t('omnibox.playlist_none')}</button>
- </div>
- {/if}
- </div>
- {#if playlistLoading}
- <div class="playlist-status"><span class="feedback-spinner"></span> {$t('omnibox.playlist_loading')}</div>
- {:else if playlistEntries.length === 0}
- <span class="playlist-status">{$t('omnibox.playlist_empty')}</span>
- {:else}
- <ul class="playlist-list">
- {#each playlistEntries as entry (entry.index)}
- <li>
- <label class="playlist-item">
- <input type="checkbox" checked={selectedPlaylistItems.has(entry.index)} onchange={() => togglePlaylistItem(entry.index)} />
- <span class="playlist-idx">{entry.index}.</span>
- <span class="playlist-title">{entry.title}</span>
- </label>
- </li>
- {/each}
- </ul>
- {/if}
- </div>
- {/if}
- {#if torrentLoading || torrentEntries.length > 0}
- <div class="playlist-picker">
- <div class="playlist-head">
- <span class="playlist-count">
- {$t('omnibox.torrent_selected', { selected: selectedTorrentFiles.size, total: torrentEntries.length })}
- </span>
- {#if !torrentLoading && torrentEntries.length > 0}
- <div class="playlist-bulk">
- <button type="button" class="playlist-link" onclick={selectAllTorrent}>{$t('omnibox.playlist_all')}</button>
- <button type="button" class="playlist-link" onclick={selectNoneTorrent}>{$t('omnibox.playlist_none')}</button>
- </div>
- {/if}
- </div>
- {#if torrentLoading}
- <div class="playlist-status"><span class="feedback-spinner"></span> {$t('omnibox.torrent_loading')}</div>
- {:else}
- <ul class="playlist-list">
- {#each torrentEntries as entry (entry.index)}
- <li>
- <label class="playlist-item">
- <input type="checkbox" checked={selectedTorrentFiles.has(entry.index)} onchange={() => toggleTorrentFile(entry.index)} />
- <span class="playlist-title">{entry.path}</span>
- <span class="torrent-size">{formatBytes(entry.size_bytes)}</span>
- </label>
- </li>
- {/each}
- </ul>
- {/if}
- </div>
- {/if}
- {#if cookieHint}
- <p class="cookie-hint" class:expired={cookieHint === "expired"} role="status">
- <span>{cookieHint === "expired" ? $t("omnibox.cookie_hint_expired") : $t("omnibox.cookie_hint_stale")}</span>
- <button type="button" class="cookie-hint-link" onclick={() => goto("/settings?tab=cookies")}>{$t("omnibox.cookie_hint_action")}</button>
- </p>
- {/if}
- {#if COURSE_PLATFORMS.has(omniState.info.platform)}
- <button class="button action-btn" onclick={handleAction}>{$t(omniState.info.platform === "udemy" ? 'omnibox.go_to_udemy' : 'omnibox.go_to_hotmart')}</button>
- {:else}
- {@const playlistBlocked = omniState.info.content_type === "playlist" && playlistEntries.length > 0 && selectedPlaylistItems.size === 0}
- {@const torrentBlocked = torrentEntries.length > 0 && selectedTorrentFiles.size === 0}
- {#if omniState.info.platform === "bilibili"}
- <BilibiliPreviewExtras {url} accountSlug={selectedCookieSlug && selectedCookieSlug !== "_anonymous" ? selectedCookieSlug : null} />
- {/if}
- <button class="download-primary-btn" disabled={playlistBlocked || torrentBlocked} onclick={handleAction}>{$t('omnibox.download')}</button>
- {#if omniState.info.platform !== "direct_file"}
- <details class="options-panel">
- <summary class="options-toggle">{$t('omnibox.options')}</summary>
- <div class="options-content">
- <DownloadModeSelector bind:downloadMode onChange={() => { selectedFormatId = null; }} />
- <QualityPicker bind:selectedQuality selectedFormatId />
- {#if cookieAccounts.length > 1}
- <CookieAccountPicker accounts={cookieAccounts} bind:selectedSlug={selectedCookieSlug} />
- {/if}
- <details class="options-panel">
- <summary class="options-toggle">{$t('omnibox.advanced')}</summary>
- <div class="options-content">
- {#if omniState.info.platform === "vimeo" || omniState.info.platform === "generic"}
- <div class="referer-input-wrapper">
- <label class="referer-label" for="referer-input">{$t('omnibox.referer_label')}</label>
- <input id="referer-input" class="referer-input" type="text" placeholder={$t('omnibox.referer_placeholder')} bind:value={referer} spellcheck="false" />
- </div>
- {/if}
- {#if omniState.info.content_type !== "playlist"}
- <div class="timerange-wrapper">
- <span class="timerange-label">{$t('omnibox.timerange_label')}</span>
- <div class="timerange-inputs">
- <input class="timerange-input" type="text" placeholder={$t('omnibox.timerange_start')} bind:value={clipStart} spellcheck="false" inputmode="numeric" aria-label={$t('omnibox.timerange_start') as string} />
- <span class="timerange-sep" aria-hidden="true">—</span>
- <input class="timerange-input" type="text" placeholder={$t('omnibox.timerange_end')} bind:value={clipEnd} spellcheck="false" inputmode="numeric" aria-label={$t('omnibox.timerange_end') as string} />
- </div>
- <span class="timerange-hint">{$t('omnibox.timerange_hint')}</span>
- </div>
- {/if}
- <div class="timerange-wrapper">
- <span class="timerange-label">{$t('omnibox.schedule_label')}</span>
- <div class="schedule-presets">
- <button type="button" class="schedule-preset" onclick={() => setSchedulePreset('1h')}>{$t('omnibox.schedule_1h')}</button>
- <button type="button" class="schedule-preset" onclick={() => setSchedulePreset('tonight')}>{$t('omnibox.schedule_tonight')}</button>
- <button type="button" class="schedule-preset" onclick={() => setSchedulePreset('1d')}>{$t('omnibox.schedule_1d')}</button>
- {#if scheduleAt || scheduleStop}
- <button type="button" class="schedule-preset" onclick={() => { scheduleAt = ""; scheduleStop = ""; }}>{$t('omnibox.schedule_clear')}</button>
- {/if}
- </div>
- <div class="timerange-inputs schedule-row">
- <input class="timerange-input schedule-date" type="date" value={schedulePart(scheduleAt, "date")} oninput={(e) => { scheduleAt = withSchedulePart(scheduleAt, "date", e.currentTarget.value); }} aria-label={$t('omnibox.schedule_start') as string} />
- <input class="timerange-input schedule-time" type="time" step="60" value={schedulePart(scheduleAt, "time")} oninput={(e) => { scheduleAt = withSchedulePart(scheduleAt, "time", e.currentTarget.value); }} aria-label={$t('omnibox.schedule_start') as string} />
- <span class="timerange-sep" aria-hidden="true">—</span>
- <input class="timerange-input schedule-date" type="date" value={schedulePart(scheduleStop, "date")} oninput={(e) => { scheduleStop = withSchedulePart(scheduleStop, "date", e.currentTarget.value); }} aria-label={$t('omnibox.schedule_stop') as string} />
- <input class="timerange-input schedule-time" type="time" step="60" value={schedulePart(scheduleStop, "time")} oninput={(e) => { scheduleStop = withSchedulePart(scheduleStop, "time", e.currentTarget.value); }} aria-label={$t('omnibox.schedule_stop') as string} />
- </div>
- <span class="timerange-hint">{$t('omnibox.schedule_hint')}</span>
- </div>
- <FormatSelector
- platform={omniState.info.platform}
- isPlaylist={omniState.info.content_type === "playlist"}
- bind:formats
- bind:selectedFormatId
- {loadingFormats}
- {formatError}
- onLoadFormats={loadFormats}
- onSelectFormat={selectFormat}
- onClearFormat={clearFormatSelection}
- onPresetBest={presetBest}
- onPresetMusic={presetMusic}
- />
- </div>
- </details>
- </div>
- </details>
- {/if}
- {/if}
- {:else if omniState.kind === "preparing"}
- <div class="feedback-card feedback-enter">
- <div class="card-row">
- <span class="feedback-spinner"></span>
- <span class="card-text">{$t('omnibox.preparing')}</span>
- </div>
- </div>
- {:else if omniState.kind === "error"}
- <div class="feedback-card feedback-enter" data-status="error">
- <div class="card-row">
- <span class="card-title card-error-text">{omniState.message}</span>
- </div>
- <div class="card-row card-actions">
- <button class="button card-action-btn" onclick={handleRetry}>{$t('omnibox.retry')}</button>
- </div>
- </div>
- {/if}
- </HomeInspector>
- </div>
-
- {#if showP2pSendDialog}
- <P2pSendDialog onClose={() => { showP2pSendDialog = false; }} />
- {/if}
-
- {#if p2pReceiveCode}
- <P2pReceiveDialog
- code={p2pReceiveCode}
- onAccept={handleP2pAccept}
- onReject={handleP2pReject}
- />
- {/if}
-
- <div class="terms-note">
- {$t('terms_note.agreement')}
- <a href="/about/terms" class="terms-link">{$t('terms_note.link')}</a>
- </div>
-</div>
-
-<style>
- .home-mac {
- width: 100%;
- }
-
- .study-maintenance-banner {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- width: 100%;
- max-width: 640px;
- padding: 8px 12px;
- background: color-mix(in oklab, var(--secondary) 8%, transparent);
- border: 1px solid color-mix(in oklab, var(--secondary) 18%, transparent);
- border-radius: var(--border-radius);
- color: var(--secondary);
- font-size: 12px;
- line-height: 1.4;
- }
-
- .study-maintenance-text {
- display: flex;
- flex-direction: column;
- gap: 1px;
- flex: 1;
- min-width: 0;
- }
-
- .study-maintenance-text strong {
- font-weight: 500;
- font-size: var(--text-sm);
- color: var(--text);
- }
-
- .study-maintenance-text span {
- color: var(--secondary);
- font-size: 11.5px;
- }
-
- .study-maintenance-dismiss {
- background: transparent;
- border: none;
- padding: 4px;
- margin: -4px;
- border-radius: 4px;
- color: var(--secondary);
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- opacity: 0.55;
- transition: opacity 0.15s ease, background 0.15s ease;
- }
-
- .study-maintenance-dismiss:hover {
- opacity: 1;
- background: color-mix(in oklab, var(--text) 6%, transparent);
- }
-
- .omnibox-area {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: var(--space-3);
- width: 100%;
- max-width: 640px;
- }
-
- .mode-toggle-row {
- display: inline-flex;
- background: var(--fill-1);
- border-radius: var(--radius-md);
- padding: 2px;
- gap: 2px;
- margin-bottom: 4px;
- }
- .mode-toggle-btn {
- min-height: 24px;
- padding: 4px 12px;
- font-size: var(--text-sm);
- font-weight: 500;
- color: var(--text-muted);
- background: transparent;
- border: none;
- border-radius: calc(var(--radius-md) - 2px);
- cursor: pointer;
- transition: background var(--duration-fast) var(--ease-out), color var(--duration-fast) var(--ease-out);
- }
- .mode-toggle-btn.active {
- background: var(--surface-hi);
- color: var(--text);
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
- }
- .mode-toggle-btn:not(.active):hover {
- color: var(--text);
- }
- .mode-toggle-btn:focus-visible {
- outline: var(--focus-ring);
- outline-offset: -1px;
- }
-
- .loop-icon {
- pointer-events: none;
- border-radius: 10px;
- user-select: none;
- }
-
- .loop-bounce {
- animation: loopBounce 400ms cubic-bezier(0.34, 1.56, 0.64, 1);
- }
-
- @keyframes loopBounce {
- 0% {
- opacity: 0;
- transform: scale(0.6) translateY(6px);
- }
- 60% {
- opacity: 1;
- transform: scale(1.08) translateY(-2px);
- }
- 100% {
- transform: scale(1) translateY(0);
- }
- }
-
- .loop-pulse {
- animation: loopPulse 1.8s ease-in-out infinite;
- }
-
- @keyframes loopPulse {
- 0%, 100% {
- opacity: 1;
- transform: scale(1);
- }
- 50% {
- opacity: 0.7;
- transform: scale(0.95);
- }
- }
-
- .batch-options {
- display: flex;
- flex-direction: column;
- gap: var(--padding);
- }
-
- .feedback {
- display: flex;
- align-items: center;
- gap: calc(var(--padding) / 2);
- }
-
- .feedback-icon {
- flex-shrink: 0;
- pointer-events: none;
- }
-
- .feedback[data-supported="true"] {
- color: var(--green);
- }
-
- .feedback[data-supported="false"] {
- color: var(--gray);
- }
-
- .feedback-text {
- font-size: var(--text-sm);
- font-weight: 500;
- }
-
- .feedback-sep {
- opacity: 0.5;
- margin: 0 2px;
- }
-
- .feedback-spinner {
- width: 16px;
- height: 16px;
- border: 2px solid var(--input-border);
- border-top-color: var(--secondary);
- border-radius: 50%;
- animation: spin 0.8s linear infinite;
- }
-
- @keyframes spin {
- to {
- transform: rotate(360deg);
- }
- }
-
- .feedback-enter {
- animation: feedbackEnter 300ms cubic-bezier(0.34, 1.56, 0.64, 1);
- }
-
- @keyframes feedbackEnter {
- from {
- opacity: 0;
- transform: scale(0.9);
- }
- to {
- opacity: 1;
- transform: scale(1);
- }
- }
-
- .download-primary-btn {
- background: var(--cta);
- color: var(--on-cta);
- font-size: 15px;
- font-weight: 500;
- padding: 12px 32px;
- border-radius: var(--border-radius);
- border: none;
- cursor: pointer;
- width: 100%;
- max-width: 300px;
- transition: background 150ms;
- }
-
- @media (hover: hover) {
- .download-primary-btn:hover {
- background: var(--cta-hover);
- }
- }
-
- .download-primary-btn:active {
- background: var(--cta-press);
- }
-
- .download-primary-btn:focus-visible {
- outline: var(--focus-ring);
- outline-offset: var(--focus-ring-offset);
- }
-
- .download-primary-btn:disabled {
- opacity: 0.5;
- cursor: not-allowed;
- }
-
- .playlist-picker {
- width: 100%;
- display: flex;
- flex-direction: column;
- gap: 8px;
- padding: 10px 12px;
- background: var(--button);
- border: 1px solid var(--input-border);
- border-radius: var(--border-radius);
- }
-
- .playlist-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 8px;
- }
-
- .playlist-count {
- font-size: var(--text-sm);
- font-weight: 500;
- color: var(--secondary);
- }
-
- .playlist-bulk {
- display: flex;
- gap: 10px;
- }
-
- .playlist-link {
- background: none;
- border: none;
- padding: 0;
- font: inherit;
- font-size: 12px;
- color: var(--accent);
- cursor: pointer;
- }
-
- .playlist-link:hover {
- text-decoration: underline;
- }
-
- .playlist-status {
- display: flex;
- align-items: center;
- gap: 6px;
- font-size: var(--text-sm);
- color: var(--gray);
- }
-
- .playlist-list {
- list-style: none;
- margin: 0;
- padding: 0;
- max-height: 220px;
- overflow-y: auto;
- display: flex;
- flex-direction: column;
- gap: 2px;
- }
-
- .playlist-item {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 5px 4px;
- border-radius: calc(var(--border-radius) - 3px);
- cursor: pointer;
- font-size: 13px;
- color: var(--secondary);
- }
-
- .playlist-item:hover {
- background: var(--button-elevated);
- }
-
- .playlist-idx {
- color: var(--gray);
- font-variant-numeric: tabular-nums;
- flex-shrink: 0;
- }
-
- .playlist-title {
- flex: 1;
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- .torrent-size {
- margin-left: auto;
- flex-shrink: 0;
- padding-left: 8px;
- color: var(--gray);
- font-variant-numeric: tabular-nums;
- }
-
- .options-panel {
- width: 100%;
- }
-
- .options-toggle {
- font-size: var(--text-sm);
- font-weight: 500;
- color: var(--gray);
- cursor: pointer;
- list-style: none;
- text-align: center;
- padding: 4px 0;
- user-select: none;
- }
-
- .options-toggle::-webkit-details-marker {
- display: none;
- }
-
- .options-toggle::marker {
- content: "";
- }
-
- @media (hover: hover) {
- .options-toggle:hover {
- color: var(--secondary);
- }
- }
-
- .options-content {
- display: flex;
- flex-direction: column;
- gap: var(--padding);
- padding-top: var(--padding);
- width: 100%;
- }
-
- .referer-input-wrapper {
- display: flex;
- flex-direction: column;
- gap: 4px;
- }
-
- .referer-label {
- font-size: var(--text-sm);
- font-weight: 500;
- color: var(--gray);
- }
-
- .referer-input {
- padding: 6px var(--padding);
- font-size: 13px;
- background: var(--button);
- border: 1px solid var(--input-border);
- border-radius: calc(var(--border-radius) - 2px);
- color: var(--secondary);
- }
-
- .referer-input::placeholder {
- color: var(--gray);
- }
-
- .referer-input:focus-visible {
- border-color: var(--secondary);
- outline: none;
- }
-
- .timerange-wrapper {
- display: flex;
- flex-direction: column;
- gap: 4px;
- }
-
- .timerange-label {
- font-size: var(--text-sm);
- font-weight: 500;
- color: var(--gray);
- }
-
- .timerange-inputs {
- display: flex;
- align-items: center;
- gap: 8px;
- }
-
- .timerange-input {
- width: 96px;
- padding: 6px var(--padding);
- font-size: 13px;
- background: var(--button);
- border: 1px solid var(--input-border);
- border-radius: calc(var(--border-radius) - 2px);
- color: var(--secondary);
- text-align: center;
- }
-
- .timerange-input::placeholder {
- color: var(--gray);
- }
-
- .timerange-input:focus-visible {
- border-color: var(--secondary);
- outline: none;
- }
-
- .timerange-sep {
- color: var(--gray);
- }
-
- .timerange-hint {
- font-size: 11.5px;
- color: var(--gray);
- }
-
- .schedule-presets {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- margin-bottom: 6px;
- }
-
- .schedule-preset {
- padding: 4px 10px;
- font-size: 12px;
- background: var(--button);
- border: 1px solid var(--input-border);
- border-radius: calc(var(--border-radius) - 2px);
- color: var(--text);
- cursor: pointer;
- }
-
- .schedule-preset:hover {
- background: var(--button-elevated);
- }
-
- .schedule-row {
- flex-wrap: wrap;
- }
-
- .schedule-date {
- width: auto;
- flex: 1 1 auto;
- min-width: 8.6em;
- }
-
- .schedule-time {
- width: auto;
- flex: 0 1 auto;
- min-width: 5.4em;
- }
-
- .cookie-hint {
- display: flex;
- align-items: center;
- gap: 6px;
- margin: 0;
- font-size: 12px;
- color: #f4a72b;
- }
- .cookie-hint.expired {
- color: #e0564f;
- }
- .cookie-hint svg {
- flex-shrink: 0;
- }
- .cookie-hint-link {
- background: none;
- border: 0;
- padding: 0;
- font: inherit;
- font-size: 12px;
- color: var(--accent);
- cursor: pointer;
- text-decoration: underline;
- text-underline-offset: 2px;
- }
- .cookie-hint-link:hover {
- filter: brightness(1.15);
- }
-
- .action-btn {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 6px;
- padding: var(--padding) calc(var(--padding) * 2);
- font-size: var(--text-base);
- font-weight: 500;
- background: var(--button);
- border: none;
- border-radius: var(--border-radius);
- color: var(--button-text);
- cursor: pointer;
- box-shadow: var(--button-box-shadow);
- }
-
- @media (hover: hover) {
- .action-btn:hover {
- background: var(--button-hover);
- }
- }
-
- .action-btn:active {
- background: var(--button-press);
- }
-
- .action-btn:disabled {
- cursor: default;
- }
-
- .feedback-card {
- display: flex;
- flex-direction: column;
- gap: var(--padding);
- padding: var(--padding) calc(var(--padding) * 1.5);
- background: var(--button-elevated);
- border-radius: var(--border-radius);
- border-left: 3px solid var(--blue);
- }
-
- .feedback-card[data-status="error"] {
- border-left-color: var(--red);
- }
-
- .external-url-card {
- width: 100%;
- border-left-color: var(--accent);
- }
-
- .card-row {
- display: flex;
- align-items: center;
- gap: calc(var(--padding) / 2);
- }
-
- .card-text {
- font-size: 13px;
- font-weight: 500;
- color: var(--secondary);
- }
-
- .card-title {
- font-size: 13px;
- font-weight: 500;
- flex: 1;
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- .card-error-text {
- color: var(--secondary);
- }
-
- .card-status-icon {
- flex-shrink: 0;
- pointer-events: none;
- color: var(--blue);
- }
-
- .card-status-icon.error {
- color: var(--red);
- }
-
- .card-actions {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: var(--padding);
- }
-
- .card-subtext {
- font-size: 11.5px;
- font-weight: 500;
- color: var(--gray);
- }
-
- .external-url-text {
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- .card-action-btn {
- padding: 6px 12px;
- font-size: 13px;
- }
-
- .dismiss-btn {
- display: flex;
- align-items: center;
- justify-content: center;
- width: 24px;
- height: 24px;
- background: transparent;
- border: none;
- cursor: pointer;
- color: var(--secondary);
- padding: 0;
- }
-
- .search-hint {
- color: var(--gray);
- }
-
- .quick-actions {
- display: flex;
- gap: var(--space-2);
- margin-bottom: var(--space-3);
- }
-
- .quick-action-btn {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- padding: var(--space-2) var(--space-4);
- font-size: var(--text-sm);
- border: 1px solid var(--border);
- border-radius: var(--radius-sm);
- background: var(--surface);
- color: var(--text);
- cursor: pointer;
- transition: background var(--duration-fast) var(--ease-out), transform var(--duration-fast) var(--ease-out);
- }
-
- @media (hover: hover) {
- .quick-action-btn:hover {
- background: var(--surface-hi);
- transform: translateY(-1px);
- }
- }
-
- .quick-action-btn:active {
- transform: scale(0.98);
- background: var(--surface-hi);
- }
-
- .quick-action-btn svg {
- opacity: 0.7;
- flex-shrink: 0;
- }
-
- @media (prefers-reduced-motion: reduce) {
- .quick-action-btn {
- transition: none;
- }
- .quick-action-btn:hover,
- .quick-action-btn:active {
- transform: none;
- }
- }
-
- .terms-note {
- flex-shrink: 0;
- font-size: 9px;
- color: var(--gray);
- text-align: left;
- opacity: 0.35;
- padding: 0 var(--space-1);
- }
-
- .terms-link {
- color: var(--blue);
- text-decoration: none;
- }
-
- @media (hover: hover) {
- .terms-link:hover {
- text-decoration: underline;
- }
- }
-
- @media (prefers-reduced-motion: reduce) {
- .feedback-enter {
- animation: none;
- }
-
- .feedback-spinner {
- animation-duration: 1.5s;
- }
-
- .loop-bounce {
- animation: none;
- }
-
- .loop-pulse {
- animation: none;
- }
- }
- @media (prefers-reduced-motion: reduce) {
- .feedback-spinner {
- animation: feedback-soft-pulse calc(var(--duration-bounce) * 3) var(--ease-in-out) infinite;
- }
- }
-
- @keyframes feedback-soft-pulse {
- 0%, 100% { opacity: 1; }
- 50% { opacity: 0.45; }
- }
+<script lang="ts">
+ import { invoke } from "@tauri-apps/api/core";
+ import { open } from "@tauri-apps/plugin-dialog";
+ import { goto } from "$app/navigation";
+ import { onMount } from "svelte";
+ import SupportedServices from "$components/services/SupportedServices.svelte";
+ import BilibiliPreviewExtras from "$components/omnibox/BilibiliPreviewExtras.svelte";
+ import DownloadModeSelector from "$components/omnibox/DownloadModeSelector.svelte";
+ import QualityPicker from "$components/omnibox/QualityPicker.svelte";
+ import FormatSelector from "$components/omnibox/FormatSelector.svelte";
+ import CookieAccountPicker from "$components/omnibox/CookieAccountPicker.svelte";
+ import OmniboxAdvanced from "$components/omnibox/OmniboxAdvanced.svelte";
+ import MediaPreview from "$components/omnibox/MediaPreview.svelte";
+ import BatchDownload from "$components/omnibox/BatchDownload.svelte";
+ import SearchResults from "$components/omnibox/SearchResults.svelte";
+ import P2pSendDialog from "$components/p2p/P2pSendDialog.svelte";
+ import P2pReceiveDialog from "$components/p2p/P2pReceiveDialog.svelte";
+ import HomeHero from "$components/home/HomeHero.svelte";
+ import HomeUrlBar from "$components/home/HomeUrlBar.svelte";
+ import HomeInspector from "$components/home/HomeInspector.svelte";
+ import {
+ type OmniState,
+ type PlatformInfo,
+ type SearchResult,
+ type HomeInputMode,
+ showInspectorForState,
+ showOmniboxForState,
+ isUrl,
+ } from "$lib/home/omnibox-controller";
+ import { getDownloads, formatBytes } from "$lib/stores/download-store.svelte";
+ import { getSettings, updateSettings } from "$lib/stores/settings-store.svelte";
+ import { showToast } from "$lib/stores/toast-store.svelte";
+ import { onClipboardUrl } from "$lib/stores/clipboard-monitor";
+ import { getMediaPreview, clearMediaPreview } from "$lib/stores/media-preview-store.svelte";
+ import { clearPendingExternalPrefill, getPendingExternalPrefill, type ExternalUrlEvent } from "$lib/stores/external-url-store.svelte";
+ import { getOmniboxDraftUrl, setOmniboxDraftUrl } from "$lib/stores/omnibox-draft-store.svelte";
+ import { t } from "$lib/i18n";
+ import { translateBackendError } from "$lib/error-translate";
+ import { platformDisplayName } from "$lib/platform-display-names";
+ import { STUDY_MAINTENANCE_NOTICE } from "$lib/study-feature-flags";
+
+ type DownloadStarted = {
+ id: number;
+ title: string;
+ };
+
+ type FormatInfo = {
+ format_id: string;
+ ext: string;
+ resolution: string | null;
+ width: number | null;
+ height: number | null;
+ fps: number | null;
+ vcodec: string | null;
+ acodec: string | null;
+ filesize: number | null;
+ tbr: number | null;
+ has_video: boolean;
+ has_audio: boolean;
+ format_note: string | null;
+ };
+
+ // Platforms whose content is downloaded via the Courses page (courses
+ // plugin + logged-in account), not from a pasted URL.
+ const COURSE_PLATFORMS = new Set(["hotmart", "udemy"]);
+
+ let url = $state(getOmniboxDraftUrl());
+ let homeInputMode = $state<HomeInputMode>("url");
+ let omniState = $state<OmniState>({ kind: "idle" });
+ let debounceTimer = $state<ReturnType<typeof setTimeout> | null>(null);
+ let downloadMode = $state<"auto" | "audio" | "mute">("auto");
+ let selectedQuality = $state("best");
+ let clipStart = $state("");
+ let clipEnd = $state("");
+ let scheduleAt = $state("");
+ let scheduleStop = $state("");
+ let playlistEntries = $state<{ index: number; title: string; url: string }[]>([]);
+ let selectedPlaylistItems = $state<Set<number>>(new Set());
+ let playlistLoading = $state(false);
+ let torrentEntries = $state<{ index: number; path: string; size_bytes: number }[]>([]);
+ let selectedTorrentFiles = $state<Set<number>>(new Set());
+ let torrentLoading = $state(false);
+ let selectedFormatId = $state<string | null>(null);
+ let formats = $state<FormatInfo[]>([]);
+ let loadingFormats = $state(false);
+ let formatError = $state<string | null>(null);
+ let formatFetchGeneration = $state(0);
+ let referer = $state("");
+
+ // Derived quality data from real yt-dlp format info.
+ // These update after the user loads formats via FormatSelector.
+ let availableHeights = $derived(
+ formats.length > 0
+ ? [...new Set(
+ formats
+ .filter(f => f.has_video && typeof f.height === "number" && f.height > 0)
+ .map(f => f.height as number)
+ )].sort((a, b) => b - a)
+ : null
+ );
+ let hasAudioOnly = $derived(
+ formats.some(f => f.has_audio && !f.has_video)
+ );
+
+ type CookieAccount = {
+ slug: string;
+ alias: string;
+ captured_at_ms: number;
+ cookie_count: number;
+ last_used_at_ms: number | null;
+ };
+ let cookieAccounts = $state<CookieAccount[]>([]);
+ let selectedCookieSlug = $state<string | null>(null);
+ let cookieHint = $state<"stale" | "expired" | null>(null);
+ let advancedMode = $state(false);
+ const STUDY_NOTICE_DISMISS_KEY = "omniget.study_maintenance_notice_dismissed_v1";
+ let studyNoticeDismissed = $state(
+ typeof localStorage !== "undefined"
+ && localStorage.getItem(STUDY_NOTICE_DISMISS_KEY) === "1"
+ );
+ function dismissStudyNotice() {
+ studyNoticeDismissed = true;
+ try { localStorage.setItem(STUDY_NOTICE_DISMISS_KEY, "1"); } catch {}
+ }
+ let mediaPreview = $derived(getMediaPreview());
+ let pendingExternalPrefill = $derived(getPendingExternalPrefill());
+ let previewImageLoading = $state(true);
+ let showP2pSendDialog = $state(false);
+ let p2pReceiveCode = $state<string | null>(null);
+ 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(autoDownload ? "toast.auto_download_started" : "toast.clipboard_url_detected"));
+ });
+ if (url.trim()) {
+ queueMicrotask(() => handleInput());
+ }
+ return () => {
+ onClipboardUrl(null);
+ };
+ });
+
+ $effect(() => {
+ setOmniboxDraftUrl(url);
+ });
+
+ const AUTO_DOWNLOAD_DELAY_MS = 2000;
+
+ $effect(() => {
+ if (!pendingAutoDownload) return;
+ if (omniState.kind === "detected") {
+ const info = omniState.info;
+ if (COURSE_PLATFORMS.has(info.platform) || 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);
+ let lastCompletionAt = $state(0);
+ let firstCompletionOfSession = $state(false);
+ let completionSeenIds = new Set<string | number>();
+
+ $effect(() => {
+ for (const [id, item] of downloads.entries()) {
+ if (item.status === "complete" && !completionSeenIds.has(id)) {
+ completionSeenIds.add(id);
+ lastCompletionAt = Date.now();
+ if (!firstCompletionOfSession) {
+ firstCompletionOfSession = true;
+ }
+ break;
+ }
+ }
+ });
+
+ $effect(() => {
+ const interval = setInterval(() => { stallTick++; }, 5000);
+ return () => clearInterval(interval);
+ });
+
+
+ $effect(() => {
+ if (mediaPreview) {
+ previewImageLoading = true;
+ }
+ });
+
+ $effect(() => {
+ const incoming = pendingExternalPrefill;
+ if (!incoming || incoming.id === lastExternalPrefillId) {
+ return;
+ }
+
+ 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();
+ });
+
+ let mascotEmotion = $derived.by((): "idle" | "downloading" | "error" | "stalled" | "queue" | "complete" | "amazed" => {
+ void stallTick;
+
+ if (lastCompletionAt > 0 && Date.now() - lastCompletionAt < 5000) {
+ return firstCompletionOfSession && completionSeenIds.size === 1 ? "amazed" : "complete";
+ }
+
+ if (omniState.kind === "preparing") return "downloading";
+ if (omniState.kind === "error") return "error";
+
+ let hasActiveDownloading = false;
+ let hasActiveStalled = false;
+ let hasItems = false;
+ for (const item of downloads.values()) {
+ hasItems = true;
+ if (item.status === "downloading") {
+ hasActiveDownloading = true;
+ const elapsed = Date.now() - item.lastUpdateAt;
+ if (elapsed > STALL_THRESHOLD) {
+ hasActiveStalled = true;
+ }
+ }
+ }
+
+ if (hasActiveStalled) return "stalled";
+ if (hasActiveDownloading) return "downloading";
+ if (hasItems) return "queue";
+ return "idle";
+ });
+
+ let mascotCompact = $derived(omniState.kind !== "idle");
+
+ function pickRandom(raw: string): string {
+ if (raw.includes("|")) {
+ const opts = raw.split("|");
+ return opts[Math.floor(Math.random() * opts.length)];
+ }
+ return raw;
+ }
+
+ let lastBubbleKey = $state("");
+ let bubbleText = $state("");
+
+ $effect(() => {
+ let key: string;
+ if (mascotEmotion === "amazed") key = "amazed";
+ else if (mascotEmotion === "complete") key = "complete";
+ else if (mascotEmotion === "queue") key = "queue";
+ else if (mascotEmotion === "downloading") key = "downloading";
+ else if (mascotEmotion === "stalled") key = "stalled";
+ else {
+ switch (omniState.kind) {
+ case "idle": key = "idle"; break;
+ case "detecting": key = "detecting"; break;
+ case "detected": key = "detected"; break;
+ case "preparing": key = "preparing"; break;
+ case "searching":
+ case "search-results": key = "search"; break;
+ case "error": key = "error"; break;
+ default: key = ""; break;
+ }
+ }
+ if (key && key !== lastBubbleKey) {
+ lastBubbleKey = key;
+ bubbleText = pickRandom($t(`mascot.${key}`));
+ } else if (!key) {
+ lastBubbleKey = "";
+ bubbleText = "";
+ }
+ });
+
+ let showLoopIcon = $derived(
+ omniState.kind === "detected" ||
+ omniState.kind === "preparing" ||
+ omniState.kind === "batch"
+ );
+
+ let showOmnibox = $derived(showOmniboxForState(omniState));
+ let showInspector = $derived(showInspectorForState(omniState));
+
+ function isValidTimeBound(v: string): boolean {
+ return /^(\d+:)?\d{1,2}:\d{1,2}(\.\d+)?$|^\d+(\.\d+)?$/.test(v.trim());
+ }
+
+ function buildTimeRange(): string | null {
+ const s = clipStart.trim();
+ const e = clipEnd.trim();
+ if (!s && !e) return null;
+ if (s && !isValidTimeBound(s)) return null;
+ if (e && !isValidTimeBound(e)) return null;
+ return `${s || "0"}-${e || "inf"}`;
+ }
+
+ function toEpochMs(v: string): number | null {
+ if (!v) return null;
+ const ms = new Date(v.includes("T") ? v : `${v}T00:00`).getTime();
+ if (Number.isNaN(ms)) return null;
+ return ms;
+ }
+
+ function schedulePart(v: string, part: "date" | "time"): string {
+ if (!v) return "";
+ const [date, time = ""] = v.split("T");
+ return part === "date" ? date : time;
+ }
+
+ function withSchedulePart(current: string, part: "date" | "time", value: string): string {
+ const pad = (n: number) => String(n).padStart(2, "0");
+ let [date, time = ""] = current ? current.split("T") : ["", ""];
+ if (part === "date") date = value;
+ else time = value;
+ if (!date && !time) return "";
+ if (!date) {
+ const now = new Date();
+ date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
+ }
+ if (!time) time = "00:00";
+ return `${date}T${time}`;
+ }
+
+ function setSchedulePreset(kind: "1h" | "tonight" | "1d") {
+ const d = new Date();
+ if (kind === "1h") d.setHours(d.getHours() + 1);
+ else if (kind === "1d") d.setDate(d.getDate() + 1);
+ else {
+ d.setHours(22, 0, 0, 0);
+ if (d.getTime() < Date.now()) d.setDate(d.getDate() + 1);
+ }
+ const pad = (n: number) => String(n).padStart(2, "0");
+ scheduleAt = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
+ }
+
+ function handleInput() {
+ if (debounceTimer) clearTimeout(debounceTimer);
+ clearMediaPreview();
+ clipStart = "";
+ clipEnd = "";
+ scheduleAt = "";
+ scheduleStop = "";
+ cookieHint = null;
+ playlistEntries = [];
+ selectedPlaylistItems = new Set();
+ playlistLoading = false;
+ torrentEntries = [];
+ selectedTorrentFiles = new Set();
+ torrentLoading = false;
+ const currentSettings = getSettings();
+ const saved = currentSettings?.last_download_options;
+ const savedMode = saved?.mode;
+ const settingsQuality = currentSettings?.download.video_quality;
+ selectedQuality = settingsQuality && typeof settingsQuality === "string"
+ ? settingsQuality
+ : "best";
+ downloadMode = savedMode === "audio" || savedMode === "mute" ? savedMode : "auto";
+ selectedFormatId = null;
+ formats = [];
+ loadingFormats = false;
+ formatError = null;
+ formatFetchGeneration++;
+ referer = "";
+
+ const trimmed = url.trim();
+ if (!trimmed) {
+ omniState = { kind: "idle" };
+ return;
+ }
+
+ const urls = trimmed.split(/[\s\n]+/).filter(isUrl);
+
+ if (urls.length > 1) {
+ omniState = { kind: "batch", urls };
+ return;
+ }
+
+ if (isUrl(trimmed)) {
+ omniState = { kind: "detecting" };
+ if (getSettings()?.download.auto_download_on_paste) {
+ pendingAutoDownload = true;
+ }
+ debounceTimer = setTimeout(() => {
+ detectPlatform(trimmed);
+ }, 500);
+ return;
+ }
+
+ if (trimmed.length >= 2) {
+ omniState = { kind: "searching" };
+ debounceTimer = setTimeout(() => {
+ performSearch(trimmed);
+ }, 600);
+ } else {
+ omniState = { kind: "idle" };
+ }
+ }
+
+ async function detectPlatform(value: string) {
+ try {
+ const result = await invoke<PlatformInfo>("detect_platform", { url: value });
+ if (result.supported) {
+ omniState = { kind: "detected", info: result };
+ if (!COURSE_PLATFORMS.has(result.platform)) {
+ invoke("prefetch_media_info", { url: value }).catch(() => {});
+ }
+ loadCookieAccounts(value);
+ if (result.content_type === "playlist") {
+ loadPlaylistEntries(value);
+ }
+ if (isTorrentUrl(value)) {
+ loadTorrentContents(value);
+ }
+ } else {
+ omniState = { kind: "unsupported" };
+ }
+ } catch {
+ omniState = { kind: "unsupported" };
+ }
+ }
+
+ async function loadPlaylistEntries(targetUrl: string) {
+ playlistEntries = [];
+ selectedPlaylistItems = new Set();
+ playlistLoading = true;
+ try {
+ const entries = await invoke<{ index: number; title: string; url: string }[]>(
+ "playlist_entries",
+ { url: targetUrl }
+ );
+ playlistEntries = entries;
+ selectedPlaylistItems = new Set(entries.map((e) => e.index));
+ } catch {
+ playlistEntries = [];
+ } finally {
+ playlistLoading = false;
+ }
+ }
+
+ function togglePlaylistItem(idx: number) {
+ const next = new Set(selectedPlaylistItems);
+ if (next.has(idx)) next.delete(idx);
+ else next.add(idx);
+ selectedPlaylistItems = next;
+ }
+
+ function selectAllPlaylist() {
+ selectedPlaylistItems = new Set(playlistEntries.map((e) => e.index));
+ }
+
+ function selectNonePlaylist() {
+ selectedPlaylistItems = new Set();
+ }
+
+ function isTorrentUrl(value: string): boolean {
+ const v = value.trim().toLowerCase();
+ return v.startsWith("magnet:") || v.endsWith(".torrent");
+ }
+
+ async function loadTorrentContents(targetUrl: string) {
+ torrentEntries = [];
+ selectedTorrentFiles = new Set();
+ torrentLoading = true;
+ try {
+ const entries = await invoke<{ index: number; path: string; size_bytes: number }[]>(
+ "torrent_contents",
+ { url: targetUrl }
+ );
+ torrentEntries = entries;
+ selectedTorrentFiles = new Set(entries.map((e) => e.index));
+ } catch {
+ torrentEntries = [];
+ } finally {
+ torrentLoading = false;
+ }
+ }
+
+ function toggleTorrentFile(idx: number) {
+ const next = new Set(selectedTorrentFiles);
+ if (next.has(idx)) next.delete(idx);
+ else next.add(idx);
+ selectedTorrentFiles = next;
+ }
+
+ function selectAllTorrent() {
+ selectedTorrentFiles = new Set(torrentEntries.map((e) => e.index));
+ }
+
+ function selectNoneTorrent() {
+ selectedTorrentFiles = new Set();
+ }
+
+ async function loadCookieAccounts(targetUrl: string) {
+ try {
+ const result = await invoke<{ domain: string; accounts: CookieAccount[] }>(
+ "cookies_accounts_for_url",
+ { url: targetUrl }
+ );
+ const accounts = result.accounts.slice().sort((a, b) => {
+ const lhs = a.last_used_at_ms ?? a.captured_at_ms;
+ const rhs = b.last_used_at_ms ?? b.captured_at_ms;
+ return rhs - lhs;
+ });
+ cookieAccounts = accounts;
+ selectedCookieSlug = accounts[0]?.slug ?? null;
+ cookieHint = null;
+ if (accounts.length > 0) {
+ try {
+ const h = await invoke<{ items: { domain: string; slug: string; status: string }[] }>(
+ "cookies_health"
+ );
+ const slug = selectedCookieSlug ?? "_default";
+ const item =
+ h.items.find((it) => it.domain === result.domain && it.slug === slug) ??
+ h.items.find((it) => it.domain === result.domain);
+ if (item && item.status !== "fresh") {
+ cookieHint = item.status === "expired" ? "expired" : "stale";
+ }
+ } catch {}
+ }
+ } catch {
+ cookieAccounts = [];
+ selectedCookieSlug = null;
+ cookieHint = null;
+ }
+ }
+
+ async function performSearch(query: string) {
+ try {
+ const results = await invoke<SearchResult[]>("search_videos", {
+ query,
+ platform: "youtube",
+ maxResults: 6,
+ });
+ if (url.trim() !== query) return;
+ if (results.length > 0) {
+ omniState = { kind: "search-results", results };
+ } else {
+ omniState = { kind: "search-empty" };
+ }
+ } catch {
+ if (url.trim() === query) {
+ omniState = { kind: "search-empty" };
+ }
+ }
+ }
+
+ function selectSearchResult(result: SearchResult) {
+ url = result.url;
+ omniState = { kind: "detecting" };
+ detectPlatform(result.url);
+ }
+
+ function getContentTypeLabel(contentType: string | null): string {
+ if (!contentType) return $t("omnibox.content_type.unknown");
+ const key = `omnibox.content_type.${contentType}`;
+ const result = $t(key);
+ if (result === key) return $t("omnibox.content_type.unknown");
+ return result;
+ }
+
+
+ async function loadFormats() {
+ if (loadingFormats) return;
+ if (formats.length > 0) {
+ formats = [];
+ selectedFormatId = null;
+ formatError = null;
+ return;
+ }
+ const targetUrl = url.trim();
+ if (!targetUrl) {
+ formatError = $t("omnibox.formats_error");
+ return;
+ }
+ loadingFormats = true;
+ formatError = null;
+ const gen = ++formatFetchGeneration;
+ try {
+ const result = await invoke<FormatInfo[]>("get_media_formats", { url: targetUrl });
+ if (gen !== formatFetchGeneration) return;
+ formats = result;
+ if (result.length === 0) {
+ formatError = $t("omnibox.no_formats");
+ }
+ } catch (e: any) {
+ if (gen !== formatFetchGeneration) return;
+ formats = [];
+ const msg = typeof e === "string" ? e : e.message ?? "";
+ formatError = msg ? translateBackendError(msg, $t) : $t("omnibox.formats_error");
+ } finally {
+ loadingFormats = false;
+ }
+ }
+
+ function selectFormat(formatId: string) {
+ selectedFormatId = formatId;
+ }
+
+ function clearFormatSelection() {
+ selectedFormatId = null;
+ }
+
+ function presetBest() {
+ selectedFormatId = null;
+ downloadMode = "auto";
+ selectedQuality = "best";
+ }
+
+ function presetMusic() {
+ selectedFormatId = null;
+ downloadMode = "audio";
+ }
+
+ function persistLastDownloadOptions() {
+ const saved = getSettings()?.last_download_options;
+ const nextMode = downloadMode;
+ if (saved?.mode === nextMode) return;
+ updateSettings({
+ last_download_options: {
+ mode: nextMode,
+ quality: saved?.quality ?? "best",
+ },
+ }).catch(() => {});
+ }
+
+ async function handleAction() {
+ if (omniState.kind !== "detected") return;
+ const info = omniState.info;
+
+ if (COURSE_PLATFORMS.has(info.platform)) {
+ goto(`/courses/${encodeURIComponent(info.platform)}`);
+ return;
+ }
+
+ if (info.platform === "p2p") {
+ const trimmed = url.trim();
+ const code = trimmed.replace(/^p2p:/, "");
+ p2pReceiveUrl = trimmed;
+ p2pReceiveCode = code;
+ return;
+ }
+
+ const isPlaylist = info.content_type === "playlist" && playlistEntries.length > 0;
+ if (isPlaylist && selectedPlaylistItems.size === 0) {
+ showToast("error", $t("omnibox.playlist_none_selected") as string);
+ return;
+ }
+
+ const isTorrent = torrentEntries.length > 0;
+ if (isTorrent && selectedTorrentFiles.size === 0) {
+ showToast("error", $t("omnibox.torrent_none_selected") as string);
+ return;
+ }
+
+ const settings = getSettings();
+ let outputDir = settings?.download.default_output_dir ?? "";
+
+ 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"),
+ });
+ if (!selected) return;
+ outputDir = selected;
+ }
+
+ const currentUrl = url.trim();
+ const platform = info.platform;
+ omniState = { kind: "preparing", platform };
+ url = "";
+
+ try {
+ await invoke<DownloadStarted>("download_from_url", {
+ url: currentUrl,
+ outputDir,
+ downloadMode: downloadMode === "auto" ? null : downloadMode,
+ quality: selectedQuality,
+ formatId: selectedFormatId,
+ referer: referer.trim() || null,
+ cookieSlug: selectedCookieSlug,
+ timeRange: buildTimeRange(),
+ playlistItems: isPlaylist ? [...selectedPlaylistItems] : null,
+ torrentFiles: isTorrent ? [...selectedTorrentFiles] : null,
+ scheduledAt: toEpochMs(scheduleAt),
+ stopAt: toEpochMs(scheduleStop),
+ });
+ persistLastDownloadOptions();
+ omniState = { kind: "idle" };
+ } catch (e: any) {
+ const msg = typeof e === "string" ? e : e.message ?? $t("omnibox.error");
+ omniState = {
+ kind: "error",
+ message: msg,
+ originalUrl: currentUrl,
+ platform,
+ };
+ }
+ }
+
+ async function handleBatchDownload() {
+ if (omniState.kind !== "batch") return;
+ const batchUrls = omniState.urls;
+
+ const settings = getSettings();
+ let outputDir = settings?.download.default_output_dir ?? "";
+
+ 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"),
+ });
+ if (!selected) return;
+ outputDir = selected;
+ }
+
+ omniState = { kind: "idle" };
+ url = "";
+
+ const results = await Promise.allSettled(
+ batchUrls.map(u => invoke<DownloadStarted>("download_from_url", {
+ url: u,
+ outputDir,
+ downloadMode: downloadMode === "auto" ? null : downloadMode,
+ quality: selectedQuality,
+ formatId: null,
+ referer: null,
+ cookieSlug: null,
+ }))
+ );
+
+ const queued = results.filter(r => r.status === "fulfilled").length;
+ if (queued > 0) {
+ showToast("info", $t("omnibox.batch_queued", { count: queued }));
+ persistLastDownloadOptions();
+ }
+ }
+
+ function handleRetry() {
+ if (omniState.kind !== "error") return;
+ url = omniState.originalUrl;
+ omniState = { kind: "detecting" };
+ detectPlatform(url.trim());
+ }
+
+ async function handleP2pAccept() {
+ const currentUrl = p2pReceiveUrl;
+ p2pReceiveCode = null;
+ p2pReceiveUrl = "";
+
+ const settings = getSettings();
+ let outputDir = settings?.download.default_output_dir ?? "";
+
+ 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"),
+ });
+ if (!selected) return;
+ outputDir = selected;
+ }
+
+ omniState = { kind: "preparing", platform: "p2p" };
+ url = "";
+
+ try {
+ await invoke("download_from_url", {
+ url: currentUrl,
+ outputDir,
+ downloadMode: null,
+ quality: "best",
+ formatId: null,
+ referer: null,
+ cookieSlug: null,
+ });
+ omniState = { kind: "idle" };
+ } catch (e: any) {
+ const msg = typeof e === "string" ? e : e.message ?? $t("omnibox.error");
+ omniState = { kind: "error", message: msg, originalUrl: currentUrl, platform: "p2p" };
+ }
+ }
+
+ function handleP2pReject() {
+ p2pReceiveCode = null;
+ p2pReceiveUrl = "";
+ }
+
+ async function openTorrentFile() {
+ const selected = await open({
+ title: "Select .torrent file",
+ filters: [{ name: "Torrent", extensions: ["torrent"] }],
+ multiple: false,
+ });
+ if (selected && typeof selected === "string") {
+ url = selected;
+ handleInput();
+ }
+ }
+
+ async function openBatchFile() {
+ const selected = await open({
+ title: $t("omnibox.batch_file_title"),
+ filters: [{ name: "Text", extensions: ["txt"] }],
+ multiple: false,
+ });
+ if (!selected || typeof selected !== "string") return;
+ try {
+ const urls = await invoke<string[]>("parse_batch_file", { path: selected });
+ if (urls.length === 0) {
+ showToast("info", $t("omnibox.batch_file_empty"));
+ return;
+ }
+ if (urls.length === 1) {
+ url = urls[0];
+ handleInput();
+ return;
+ }
+ url = urls.join("\n");
+ omniState = { kind: "batch", urls };
+ } catch (e: any) {
+ const msg = typeof e === "string" ? e : e.message ?? $t("omnibox.error");
+ showToast("error", msg);
+ }
+ }
+
+ function handleHomeModeChange(mode: HomeInputMode) {
+ // batch/torrent/p2p are momentary actions, not persistent input modes:
+ // return to "url" so the tab bar never strands on an empty state when
+ // the picker/dialog is cancelled
+ if (mode === "p2p") {
+ showP2pSendDialog = true;
+ homeInputMode = "url";
+ } else if (mode === "torrent") {
+ void openTorrentFile().finally(() => {
+ homeInputMode = "url";
+ });
+ } else if (mode === "batch") {
+ void openBatchFile().finally(() => {
+ homeInputMode = "url";
+ });
+ }
+ }
+
+ function handleDismiss() {
+ clearMediaPreview();
+ omniState = { kind: "idle" };
+ url = "";
+ }
+</script>
+
+<div class="home-mac">
+ {#if STUDY_MAINTENANCE_NOTICE && !studyNoticeDismissed}
+ <div class="study-maintenance-banner" role="status">
+ <div class="study-maintenance-text">
+ <strong>{$t("study.maintenance.home_banner_title")}</strong>
+ <span>{$t("study.maintenance.home_banner_body")}</span>
+ </div>
+ <button
+ type="button"
+ class="study-maintenance-dismiss"
+ onclick={dismissStudyNotice}
+ aria-label={$t('common.close')}
+ >
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M18 6L6 18M6 6l12 12" />
+ </svg>
+ </button>
+ </div>
+ {/if}
+
+ <div class="home-mac-workspace">
+ <div class="home-mac-hero">
+ <HomeHero
+ emotion={mascotEmotion}
+ compact={mascotCompact}
+ bubbleText={bubbleText || undefined}
+ celebrate={mascotEmotion === "amazed"}
+ />
+ </div>
+ <div class="home-mac-main">
+ <div class="mode-toggle-row">
+ <button
+ type="button"
+ class="mode-toggle-btn"
+ class:active={!advancedMode}
+ onclick={() => { advancedMode = false; }}
+ >
+ {$t('omnibox.mode_normal')}
+ </button>
+ <button
+ type="button"
+ class="mode-toggle-btn"
+ class:active={advancedMode}
+ onclick={() => { advancedMode = true; }}
+ >
+ {$t('omnibox.mode_advanced')}
+ </button>
+ </div>
+
+ {#if advancedMode}
+ <OmniboxAdvanced />
+ {:else}
+ {#if externalNotice}
+ <div class="feedback-card feedback-enter external-url-card">
+ <div class="card-row">
+ <svg class="card-status-icon" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M12 5v14" />
+ <path d="M5 12h14" />
+ </svg>
+ <span class="card-title">{$t('omnibox.external_url_ready')}</span>
+ <button class="dismiss-btn" onclick={() => { externalNotice = null; }} aria-label={$t('common.close')}>
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M18 6L6 18M6 6l12 12" />
+ </svg>
+ </button>
+ </div>
+ <div class="card-row">
+ <span class="card-subtext external-url-text">{externalNotice.url}</span>
+ </div>
+ </div>
+ {/if}
+
+ {#if showLoopIcon}
+ <img
+ src="/loop.png"
+ alt=""
+ width="40"
+ height="40"
+ class="loop-icon"
+ class:loop-bounce={omniState.kind === "detected" || omniState.kind === "batch"}
+ class:loop-pulse={omniState.kind === "preparing"}
+ />
+ {/if}
+
+ {#if omniState.kind === "detecting"}
+ <div class="feedback feedback-enter">
+ <span class="feedback-spinner"></span>
+ </div>
+
+ {:else if omniState.kind === "detected"}
+ <div class="feedback feedback-enter" data-supported="true">
+ <span class="feedback-text">
+ {platformDisplayName(omniState.info.platform)}
+ {#if omniState.info.content_type}
+ <span class="feedback-sep">&middot;</span>
+ {getContentTypeLabel(omniState.info.content_type)}
+ {/if}
+ </span>
+ </div>
+ {/if}
+
+ {#if showOmnibox}
+ <HomeUrlBar bind:url bind:mode={homeInputMode} onInput={handleInput} onModeChange={handleHomeModeChange} />
+ {/if}
+
+ {#if omniState.kind === "batch"}
+ <BatchDownload count={omniState.urls.length} onDownload={handleBatchDownload} />
+
+ {:else if omniState.kind === "searching"}
+ <div class="feedback feedback-enter">
+ <span class="feedback-spinner"></span>
+ <span class="feedback-text search-hint">{$t('omnibox.searching')}</span>
+ </div>
+
+ {:else if omniState.kind === "search-results"}
+ <SearchResults results={omniState.results} onSelect={selectSearchResult} />
+
+ {:else if omniState.kind === "search-empty"}
+ <div class="feedback feedback-enter" data-supported="false">
+ <svg class="feedback-icon" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="11" cy="11" r="8" />
+ <path d="M21 21l-4.35-4.35" />
+ </svg>
+ <span class="feedback-text">{$t('omnibox.search_empty')}</span>
+ </div>
+
+ {:else if omniState.kind === "unsupported"}
+ <div class="feedback feedback-enter" data-supported="false">
+ <svg class="feedback-icon" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="12" r="10" />
+ <path d="M12 8v4m0 4h.01" />
+ </svg>
+ <span class="feedback-text">{$t('omnibox.unsupported')}</span>
+ </div>
+ {/if}
+ {/if}
+
+ {#if omniState.kind === "idle"}
+ <SupportedServices />
+ {/if}
+ </div>
+
+ <HomeInspector open={showInspector} title={$t('home.inspector_title')}>
+ {#if omniState.kind === "detected"}
+ <MediaPreview bind:mediaPreview bind:imageLoading={previewImageLoading} />
+ {#if omniState.info.content_type === "playlist"}
+ <div class="playlist-picker">
+ <div class="playlist-head">
+ <span class="playlist-count">
+ {$t('omnibox.playlist_selected', { selected: selectedPlaylistItems.size, total: playlistEntries.length })}
+ </span>
+ {#if !playlistLoading && playlistEntries.length > 0}
+ <div class="playlist-bulk">
+ <button type="button" class="playlist-link" onclick={selectAllPlaylist}>{$t('omnibox.playlist_all')}</button>
+ <button type="button" class="playlist-link" onclick={selectNonePlaylist}>{$t('omnibox.playlist_none')}</button>
+ </div>
+ {/if}
+ </div>
+ {#if playlistLoading}
+ <div class="playlist-status"><span class="feedback-spinner"></span> {$t('omnibox.playlist_loading')}</div>
+ {:else if playlistEntries.length === 0}
+ <span class="playlist-status">{$t('omnibox.playlist_empty')}</span>
+ {:else}
+ <ul class="playlist-list">
+ {#each playlistEntries as entry (entry.index)}
+ <li>
+ <label class="playlist-item">
+ <input type="checkbox" checked={selectedPlaylistItems.has(entry.index)} onchange={() => togglePlaylistItem(entry.index)} />
+ <span class="playlist-idx">{entry.index}.</span>
+ <span class="playlist-title">{entry.title}</span>
+ </label>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </div>
+ {/if}
+ {#if torrentLoading || torrentEntries.length > 0}
+ <div class="playlist-picker">
+ <div class="playlist-head">
+ <span class="playlist-count">
+ {$t('omnibox.torrent_selected', { selected: selectedTorrentFiles.size, total: torrentEntries.length })}
+ </span>
+ {#if !torrentLoading && torrentEntries.length > 0}
+ <div class="playlist-bulk">
+ <button type="button" class="playlist-link" onclick={selectAllTorrent}>{$t('omnibox.playlist_all')}</button>
+ <button type="button" class="playlist-link" onclick={selectNoneTorrent}>{$t('omnibox.playlist_none')}</button>
+ </div>
+ {/if}
+ </div>
+ {#if torrentLoading}
+ <div class="playlist-status"><span class="feedback-spinner"></span> {$t('omnibox.torrent_loading')}</div>
+ {:else}
+ <ul class="playlist-list">
+ {#each torrentEntries as entry (entry.index)}
+ <li>
+ <label class="playlist-item">
+ <input type="checkbox" checked={selectedTorrentFiles.has(entry.index)} onchange={() => toggleTorrentFile(entry.index)} />
+ <span class="playlist-title">{entry.path}</span>
+ <span class="torrent-size">{formatBytes(entry.size_bytes)}</span>
+ </label>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </div>
+ {/if}
+ {#if cookieHint}
+ <p class="cookie-hint" class:expired={cookieHint === "expired"} role="status">
+ <span>{cookieHint === "expired" ? $t("omnibox.cookie_hint_expired") : $t("omnibox.cookie_hint_stale")}</span>
+ <button type="button" class="cookie-hint-link" onclick={() => goto("/settings?tab=cookies")}>{$t("omnibox.cookie_hint_action")}</button>
+ </p>
+ {/if}
+ {#if COURSE_PLATFORMS.has(omniState.info.platform)}
+ <button class="button action-btn" onclick={handleAction}>{$t(omniState.info.platform === "udemy" ? 'omnibox.go_to_udemy' : 'omnibox.go_to_hotmart')}</button>
+ {:else}
+ {@const playlistBlocked = omniState.info.content_type === "playlist" && playlistEntries.length > 0 && selectedPlaylistItems.size === 0}
+ {@const torrentBlocked = torrentEntries.length > 0 && selectedTorrentFiles.size === 0}
+ {#if omniState.info.platform === "bilibili"}
+ <BilibiliPreviewExtras {url} accountSlug={selectedCookieSlug && selectedCookieSlug !== "_anonymous" ? selectedCookieSlug : null} />
+ {/if}
+ <button class="download-primary-btn" disabled={playlistBlocked || torrentBlocked} onclick={handleAction}>{$t('omnibox.download')}</button>
+ {#if omniState.info.platform !== "direct_file"}
+ <details class="options-panel">
+ <summary class="options-toggle">{$t('omnibox.options')}</summary>
+ <div class="options-content">
+ <DownloadModeSelector bind:downloadMode onChange={() => { selectedFormatId = null; }} />
+ <QualityPicker bind:selectedQuality selectedFormatId {availableHeights} {hasAudioOnly} />
+ {#if cookieAccounts.length > 1}
+ <CookieAccountPicker accounts={cookieAccounts} bind:selectedSlug={selectedCookieSlug} />
+ {/if}
+ <details class="options-panel">
+ <summary class="options-toggle">{$t('omnibox.advanced')}</summary>
+ <div class="options-content">
+ {#if omniState.info.platform === "vimeo" || omniState.info.platform === "generic"}
+ <div class="referer-input-wrapper">
+ <label class="referer-label" for="referer-input">{$t('omnibox.referer_label')}</label>
+ <input id="referer-input" class="referer-input" type="text" placeholder={$t('omnibox.referer_placeholder')} bind:value={referer} spellcheck="false" />
+ </div>
+ {/if}
+ {#if omniState.info.content_type !== "playlist"}
+ <div class="timerange-wrapper">
+ <span class="timerange-label">{$t('omnibox.timerange_label')}</span>
+ <div class="timerange-inputs">
+ <input class="timerange-input" type="text" placeholder={$t('omnibox.timerange_start')} bind:value={clipStart} spellcheck="false" inputmode="numeric" aria-label={$t('omnibox.timerange_start') as string} />
+ <span class="timerange-sep" aria-hidden="true">—</span>
+ <input class="timerange-input" type="text" placeholder={$t('omnibox.timerange_end')} bind:value={clipEnd} spellcheck="false" inputmode="numeric" aria-label={$t('omnibox.timerange_end') as string} />
+ </div>
+ <span class="timerange-hint">{$t('omnibox.timerange_hint')}</span>
+ </div>
+ {/if}
+ <div class="timerange-wrapper">
+ <span class="timerange-label">{$t('omnibox.schedule_label')}</span>
+ <div class="schedule-presets">
+ <button type="button" class="schedule-preset" onclick={() => setSchedulePreset('1h')}>{$t('omnibox.schedule_1h')}</button>
+ <button type="button" class="schedule-preset" onclick={() => setSchedulePreset('tonight')}>{$t('omnibox.schedule_tonight')}</button>
+ <button type="button" class="schedule-preset" onclick={() => setSchedulePreset('1d')}>{$t('omnibox.schedule_1d')}</button>
+ {#if scheduleAt || scheduleStop}
+ <button type="button" class="schedule-preset" onclick={() => { scheduleAt = ""; scheduleStop = ""; }}>{$t('omnibox.schedule_clear')}</button>
+ {/if}
+ </div>
+ <div class="timerange-inputs schedule-row">
+ <input class="timerange-input schedule-date" type="date" value={schedulePart(scheduleAt, "date")} oninput={(e) => { scheduleAt = withSchedulePart(scheduleAt, "date", e.currentTarget.value); }} aria-label={$t('omnibox.schedule_start') as string} />
+ <input class="timerange-input schedule-time" type="time" step="60" value={schedulePart(scheduleAt, "time")} oninput={(e) => { scheduleAt = withSchedulePart(scheduleAt, "time", e.currentTarget.value); }} aria-label={$t('omnibox.schedule_start') as string} />
+ <span class="timerange-sep" aria-hidden="true">—</span>
+ <input class="timerange-input schedule-date" type="date" value={schedulePart(scheduleStop, "date")} oninput={(e) => { scheduleStop = withSchedulePart(scheduleStop, "date", e.currentTarget.value); }} aria-label={$t('omnibox.schedule_stop') as string} />
+ <input class="timerange-input schedule-time" type="time" step="60" value={schedulePart(scheduleStop, "time")} oninput={(e) => { scheduleStop = withSchedulePart(scheduleStop, "time", e.currentTarget.value); }} aria-label={$t('omnibox.schedule_stop') as string} />
+ </div>
+ <span class="timerange-hint">{$t('omnibox.schedule_hint')}</span>
+ </div>
+ <FormatSelector
+ platform={omniState.info.platform}
+ isPlaylist={omniState.info.content_type === "playlist"}
+ bind:formats
+ bind:selectedFormatId
+ {loadingFormats}
+ {formatError}
+ onLoadFormats={loadFormats}
+ onSelectFormat={selectFormat}
+ onClearFormat={clearFormatSelection}
+ onPresetBest={presetBest}
+ onPresetMusic={presetMusic}
+ />
+ </div>
+ </details>
+ </div>
+ </details>
+ {/if}
+ {/if}
+ {:else if omniState.kind === "preparing"}
+ <div class="feedback-card feedback-enter">
+ <div class="card-row">
+ <span class="feedback-spinner"></span>
+ <span class="card-text">{$t('omnibox.preparing')}</span>
+ </div>
+ </div>
+ {:else if omniState.kind === "error"}
+ <div class="feedback-card feedback-enter" data-status="error">
+ <div class="card-row">
+ <span class="card-title card-error-text">{omniState.message}</span>
+ </div>
+ <div class="card-row card-actions">
+ <button class="button card-action-btn" onclick={handleRetry}>{$t('omnibox.retry')}</button>
+ </div>
+ </div>
+ {/if}
+ </HomeInspector>
+ </div>
+
+ {#if showP2pSendDialog}
+ <P2pSendDialog onClose={() => { showP2pSendDialog = false; }} />
+ {/if}
+
+ {#if p2pReceiveCode}
+ <P2pReceiveDialog
+ code={p2pReceiveCode}
+ onAccept={handleP2pAccept}
+ onReject={handleP2pReject}
+ />
+ {/if}
+
+ <div class="terms-note">
+ {$t('terms_note.agreement')}
+ <a href="/about/terms" class="terms-link">{$t('terms_note.link')}</a>
+ </div>
+</div>
+
+<style>
+ .home-mac {
+ width: 100%;
+ }
+
+ .study-maintenance-banner {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ width: 100%;
+ max-width: 640px;
+ padding: 8px 12px;
+ background: color-mix(in oklab, var(--secondary) 8%, transparent);
+ border: 1px solid color-mix(in oklab, var(--secondary) 18%, transparent);
+ border-radius: var(--border-radius);
+ color: var(--secondary);
+ font-size: 12px;
+ line-height: 1.4;
+ }
+
+ .study-maintenance-text {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ flex: 1;
+ min-width: 0;
+ }
+
+ .study-maintenance-text strong {
+ font-weight: 500;
+ font-size: 12.5px;
+ color: var(--text);
+ }
+
+ .study-maintenance-text span {
+ color: var(--secondary);
+ font-size: 11.5px;
+ }
+
+ .study-maintenance-dismiss {
+ background: transparent;
+ border: none;
+ padding: 4px;
+ margin: -4px;
+ border-radius: 4px;
+ color: var(--secondary);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0.55;
+ transition: opacity 0.15s ease, background 0.15s ease;
+ }
+
+ .study-maintenance-dismiss:hover {
+ opacity: 1;
+ background: color-mix(in oklab, var(--text) 6%, transparent);
+ }
+
+ .omnibox-area {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: var(--space-3);
+ width: 100%;
+ max-width: 640px;
+ }
+
+ .mode-toggle-row {
+ display: inline-flex;
+ background: var(--button);
+ border-radius: var(--border-radius);
+ padding: 3px;
+ gap: 2px;
+ margin-bottom: 4px;
+ }
+ .mode-toggle-btn {
+ padding: 5px 14px;
+ font-size: 11.5px;
+ font-weight: 500;
+ color: var(--gray);
+ background: transparent;
+ border: none;
+ border-radius: calc(var(--border-radius) - 3px);
+ cursor: pointer;
+ }
+ .mode-toggle-btn.active {
+ background: var(--cta);
+ color: var(--on-cta);
+ }
+ .mode-toggle-btn:not(.active):hover {
+ color: var(--secondary);
+ background: var(--button-elevated);
+ }
+
+ .loop-icon {
+ pointer-events: none;
+ border-radius: 10px;
+ user-select: none;
+ }
+
+ .loop-bounce {
+ animation: loopBounce 400ms cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+
+ @keyframes loopBounce {
+ 0% {
+ opacity: 0;
+ transform: scale(0.6) translateY(6px);
+ }
+ 60% {
+ opacity: 1;
+ transform: scale(1.08) translateY(-2px);
+ }
+ 100% {
+ transform: scale(1) translateY(0);
+ }
+ }
+
+ .loop-pulse {
+ animation: loopPulse 1.8s ease-in-out infinite;
+ }
+
+ @keyframes loopPulse {
+ 0%, 100% {
+ opacity: 1;
+ transform: scale(1);
+ }
+ 50% {
+ opacity: 0.7;
+ transform: scale(0.95);
+ }
+ }
+
+ .feedback {
+ display: flex;
+ align-items: center;
+ gap: calc(var(--padding) / 2);
+ }
+
+ .feedback-icon {
+ flex-shrink: 0;
+ pointer-events: none;
+ }
+
+ .feedback[data-supported="true"] {
+ color: var(--green);
+ }
+
+ .feedback[data-supported="false"] {
+ color: var(--gray);
+ }
+
+ .feedback-text {
+ font-size: 12.5px;
+ font-weight: 500;
+ }
+
+ .feedback-sep {
+ opacity: 0.5;
+ margin: 0 2px;
+ }
+
+ .feedback-spinner {
+ width: 16px;
+ height: 16px;
+ border: 2px solid var(--input-border);
+ border-top-color: var(--secondary);
+ border-radius: 50%;
+ animation: spin 0.8s linear infinite;
+ }
+
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+
+ .feedback-enter {
+ animation: feedbackEnter 300ms cubic-bezier(0.34, 1.56, 0.64, 1);
+ }
+
+ @keyframes feedbackEnter {
+ from {
+ opacity: 0;
+ transform: scale(0.9);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+ }
+
+ .download-primary-btn {
+ background: var(--cta);
+ color: var(--on-cta);
+ font-size: 15px;
+ font-weight: 500;
+ padding: 12px 32px;
+ border-radius: var(--border-radius);
+ border: none;
+ cursor: pointer;
+ width: 100%;
+ max-width: 300px;
+ transition: background 150ms;
+ }
+
+ @media (hover: hover) {
+ .download-primary-btn:hover {
+ background: var(--cta-hover);
+ }
+ }
+
+ .download-primary-btn:active {
+ background: var(--cta-press);
+ }
+
+ .download-primary-btn:focus-visible {
+ outline: var(--focus-ring);
+ outline-offset: var(--focus-ring-offset);
+ }
+
+ .download-primary-btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+
+ .playlist-picker {
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px 12px;
+ background: var(--button);
+ border: 1px solid var(--input-border);
+ border-radius: var(--border-radius);
+ }
+
+ .playlist-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ }
+
+ .playlist-count {
+ font-size: 12.5px;
+ font-weight: 500;
+ color: var(--secondary);
+ }
+
+ .playlist-bulk {
+ display: flex;
+ gap: 10px;
+ }
+
+ .playlist-link {
+ background: none;
+ border: none;
+ padding: 0;
+ font: inherit;
+ font-size: 12px;
+ color: var(--accent);
+ cursor: pointer;
+ }
+
+ .playlist-link:hover {
+ text-decoration: underline;
+ }
+
+ .playlist-status {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12.5px;
+ color: var(--gray);
+ }
+
+ .playlist-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ max-height: 220px;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+
+ .playlist-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 4px;
+ border-radius: calc(var(--border-radius) - 3px);
+ cursor: pointer;
+ font-size: 13px;
+ color: var(--secondary);
+ }
+
+ .playlist-item:hover {
+ background: var(--button-elevated);
+ }
+
+ .playlist-idx {
+ color: var(--gray);
+ font-variant-numeric: tabular-nums;
+ flex-shrink: 0;
+ }
+
+ .playlist-title {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .torrent-size {
+ margin-left: auto;
+ flex-shrink: 0;
+ padding-left: 8px;
+ color: var(--gray);
+ font-variant-numeric: tabular-nums;
+ }
+
+ .options-panel {
+ width: 100%;
+ }
+
+ .options-toggle {
+ font-size: 12.5px;
+ font-weight: 500;
+ color: var(--gray);
+ cursor: pointer;
+ list-style: none;
+ text-align: center;
+ padding: 4px 0;
+ user-select: none;
+ }
+
+ .options-toggle::-webkit-details-marker {
+ display: none;
+ }
+
+ .options-toggle::marker {
+ content: "";
+ }
+
+ @media (hover: hover) {
+ .options-toggle:hover {
+ color: var(--secondary);
+ }
+ }
+
+ .options-content {
+ display: flex;
+ flex-direction: column;
+ gap: var(--padding);
+ padding-top: var(--padding);
+ width: 100%;
+ }
+
+ .referer-input-wrapper {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+
+ .referer-label {
+ font-size: 12.5px;
+ font-weight: 500;
+ color: var(--gray);
+ }
+
+ .referer-input {
+ padding: 6px var(--padding);
+ font-size: 13px;
+ background: var(--button);
+ border: 1px solid var(--input-border);
+ border-radius: calc(var(--border-radius) - 2px);
+ color: var(--secondary);
+ }
+
+ .referer-input::placeholder {
+ color: var(--gray);
+ }
+
+ .referer-input:focus-visible {
+ border-color: var(--secondary);
+ outline: none;
+ }
+
+ .timerange-wrapper {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+
+ .timerange-label {
+ font-size: 12.5px;
+ font-weight: 500;
+ color: var(--gray);
+ }
+
+ .timerange-inputs {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+
+ .timerange-input {
+ width: 96px;
+ padding: 6px var(--padding);
+ font-size: 13px;
+ background: var(--button);
+ border: 1px solid var(--input-border);
+ border-radius: calc(var(--border-radius) - 2px);
+ color: var(--secondary);
+ text-align: center;
+ }
+
+ .timerange-input::placeholder {
+ color: var(--gray);
+ }
+
+ .timerange-input:focus-visible {
+ border-color: var(--secondary);
+ outline: none;
+ }
+
+ .timerange-sep {
+ color: var(--gray);
+ }
+
+ .timerange-hint {
+ font-size: 11.5px;
+ color: var(--gray);
+ }
+
+ .schedule-presets {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-bottom: 6px;
+ }
+
+ .schedule-preset {
+ padding: 4px 10px;
+ font-size: 12px;
+ background: var(--button);
+ border: 1px solid var(--input-border);
+ border-radius: calc(var(--border-radius) - 2px);
+ color: var(--text);
+ cursor: pointer;
+ }
+
+ .schedule-preset:hover {
+ background: var(--button-elevated);
+ }
+
+ .schedule-row {
+ flex-wrap: wrap;
+ }
+
+ .schedule-date {
+ width: auto;
+ flex: 1 1 auto;
+ min-width: 8.6em;
+ }
+
+ .schedule-time {
+ width: auto;
+ flex: 0 1 auto;
+ min-width: 5.4em;
+ }
+
+ .cookie-hint {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: 0;
+ font-size: 12px;
+ color: #f4a72b;
+ }
+ .cookie-hint.expired {
+ color: #e0564f;
+ }
+ .cookie-hint svg {
+ flex-shrink: 0;
+ }
+ .cookie-hint-link {
+ background: none;
+ border: 0;
+ padding: 0;
+ font: inherit;
+ font-size: 12px;
+ color: var(--accent);
+ cursor: pointer;
+ text-decoration: underline;
+ text-underline-offset: 2px;
+ }
+ .cookie-hint-link:hover {
+ filter: brightness(1.15);
+ }
+
+ .action-btn {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ padding: var(--padding) calc(var(--padding) * 2);
+ font-size: 14.5px;
+ font-weight: 500;
+ background: var(--button);
+ border: none;
+ border-radius: var(--border-radius);
+ color: var(--button-text);
+ cursor: pointer;
+ box-shadow: var(--button-box-shadow);
+ }
+
+ @media (hover: hover) {
+ .action-btn:hover {
+ background: var(--button-hover);
+ }
+ }
+
+ .action-btn:active {
+ background: var(--button-press);
+ }
+
+ .action-btn:disabled {
+ cursor: default;
+ }
+
+ .feedback-card {
+ display: flex;
+ flex-direction: column;
+ gap: var(--padding);
+ padding: var(--padding) calc(var(--padding) * 1.5);
+ background: var(--button-elevated);
+ border-radius: var(--border-radius);
+ border-left: 3px solid var(--blue);
+ }
+
+ .feedback-card[data-status="error"] {
+ border-left-color: var(--red);
+ }
+
+ .external-url-card {
+ width: 100%;
+ border-left-color: var(--accent);
+ }
+
+ .card-row {
+ display: flex;
+ align-items: center;
+ gap: calc(var(--padding) / 2);
+ }
+
+ .card-text {
+ font-size: 13px;
+ font-weight: 500;
+ color: var(--secondary);
+ }
+
+ .card-title {
+ font-size: 13px;
+ font-weight: 500;
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .card-error-text {
+ color: var(--secondary);
+ }
+
+ .card-status-icon {
+ flex-shrink: 0;
+ pointer-events: none;
+ color: var(--blue);
+ }
+
+ .card-status-icon.error {
+ color: var(--red);
+ }
+
+ .card-actions {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--padding);
+ }
+
+ .card-subtext {
+ font-size: 11.5px;
+ font-weight: 500;
+ color: var(--gray);
+ }
+
+ .external-url-text {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .card-action-btn {
+ padding: 6px 12px;
+ font-size: 13px;
+ }
+
+ .dismiss-btn {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ background: transparent;
+ border: none;
+ cursor: pointer;
+ color: var(--secondary);
+ padding: 0;
+ }
+
+ .search-hint {
+ color: var(--gray);
+ }
+
+ .quick-actions {
+ display: flex;
+ gap: var(--space-2);
+ margin-bottom: var(--space-3);
+ }
+
+ .quick-action-btn {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: var(--space-2) var(--space-4);
+ font-size: var(--text-sm);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ background: var(--surface);
+ color: var(--text);
+ cursor: pointer;
+ transition: background var(--duration-fast) var(--ease-out), transform var(--duration-fast) var(--ease-out);
+ }
+
+ @media (hover: hover) {
+ .quick-action-btn:hover {
+ background: var(--surface-hi);
+ transform: translateY(-1px);
+ }
+ }
+
+ .quick-action-btn:active {
+ transform: scale(0.98);
+ background: var(--surface-hi);
+ }
+
+ .quick-action-btn svg {
+ opacity: 0.7;
+ flex-shrink: 0;
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .quick-action-btn {
+ transition: none;
+ }
+ .quick-action-btn:hover,
+ .quick-action-btn:active {
+ transform: none;
+ }
+ }
+
+ .terms-note {
+ flex-shrink: 0;
+ font-size: 9px;
+ color: var(--gray);
+ text-align: left;
+ opacity: 0.35;
+ padding: 0 var(--space-1);
+ }
+
+ .terms-link {
+ color: var(--blue);
+ text-decoration: none;
+ }
+
+ @media (hover: hover) {
+ .terms-link:hover {
+ text-decoration: underline;
+ }
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .feedback-enter {
+ animation: none;
+ }
+
+ .feedback-spinner {
+ animation-duration: 1.5s;
+ }
+
+ .loop-bounce {
+ animation: none;
+ }
+
+ .loop-pulse {
+ animation: none;
+ }
+ }
</style>
diff --git a/src/routes/convert/+page.svelte b/src/routes/convert/+page.svelte
index ee7ff88f..544e9d4f 100644
--- a/src/routes/convert/+page.svelte
+++ b/src/routes/convert/+page.svelte
@@ -356,7 +356,7 @@
</div>
{#if file.status === "converting"}
<div class="progress-bar">
- <div class="progress-fill" style="width: {file.percent}%"></div>
+ <div class="progress-fill" style:width="{file.percent}%"></div>
</div>
{/if}
</div>
diff --git a/src/routes/courses/+page.svelte b/src/routes/courses/+page.svelte
index bc7cda93..a16b97b4 100644
--- a/src/routes/courses/+page.svelte
+++ b/src/routes/courses/+page.svelte
@@ -201,7 +201,7 @@
onclick={() => handleCardClick(platform)}
onkeydown={(e) => handleKeyDown(e, platform)}
>
- <div class="card-icon" style="--platform-color: {platform.color}">
+ <div class="card-icon" style:--platform-color="{platform.color}">
<svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
{@html getIconSvg(platform.icon)}
</svg>
diff --git a/src/routes/downloads/+page.svelte b/src/routes/downloads/+page.svelte
index 38a04802..643d6fb9 100644
--- a/src/routes/downloads/+page.svelte
+++ b/src/routes/downloads/+page.svelte
@@ -27,6 +27,7 @@
import ReencodeDialog from "$components/dialog/ReencodeDialog.svelte";
import ToolsPanel from "$components/downloads/ToolsPanel.svelte";
import VideoOpsOverlay from "$components/downloads/VideoOpsOverlay.svelte";
+ import { getSettings, updateSettings } from "$lib/stores/settings-store.svelte";
import { locale as i18nLocale } from "$lib/i18n";
import { get } from "svelte/store";
import timeAgo from "$lib/time-ago";
@@ -300,6 +301,16 @@
let historyEntries = $state<HistoryEntry[]>([]);
let historyLoading = $state(false);
+ async function openFileFolder(filePath: string) {
+ try {
+ await invoke("reveal_file", { path: filePath });
+ } catch {
+ try {
+ await invoke("open_path_default", { path: filePath });
+ } catch {}
+ }
+ }
+
async function loadHistory() {
historyLoading = true;
try {
@@ -492,6 +503,21 @@
{$t('downloads.history_clear')}
</button>
{/if}
+ <select
+ class="speed-limit-selector"
+ value={getSettings()?.download.speed_limit || "unlimited"}
+ onchange={(e) => {
+ const val = e.currentTarget.value;
+ updateSettings({ download: { speed_limit: val === "unlimited" ? "" : val } });
+ }}
+ title={$t('settings.download.speed_limit') as string}
+ >
+ <option value="unlimited">⚡ Unlimited</option>
+ <option value="1M">1 MB/s</option>
+ <option value="2M">2 MB/s</option>
+ <option value="5M">5 MB/s</option>
+ <option value="10M">10 MB/s</option>
+ </select>
<button
class="history-toggle"
class:on={viewMode === "history"}
@@ -898,6 +924,18 @@
{/if}
</button>
{:else if item.status === "complete"}
+ {#if item.filePath}
+ <button
+ class="action-icon-btn"
+ onclick={() => openFileFolder(item.filePath!)}
+ aria-label={$t('downloads.open_folder')}
+ title={$t('downloads.open_folder')}
+ >
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" />
+ </svg>
+ </button>
+ {/if}
{#if item.filePath && item.queueKind === "video"}
<button
class="action-icon-btn"
@@ -972,7 +1010,7 @@
{:else if item.phase === "waiting_rate_limit"}
<span class="item-detail">{$t('downloads.phase_waiting_rate_limit')}</span>
{:else if item.phase === "merging"}
- <span class="item-detail">{$t('downloads.phase_merging')}</span>
+ <span class="item-detail phase-merging-badge">{$t('downloads.phase_merging')}</span>
{:else if item.phase === "extracting_audio"}
<span class="item-detail">{$t('downloads.phase_extracting_audio')}</span>
{:else if item.phase === "embedding_subtitles"}
@@ -990,7 +1028,7 @@
<span>{formatSpeed(item.speed)}</span>
{#if formatEta(item.etaSeconds)}
<span class="stats-sep">&middot;</span>
- <span>ETA {formatEta(item.etaSeconds)}</span>
+ <span class="eta-pill">ETA {formatEta(item.etaSeconds)}</span>
{/if}
<DownloadSpeedGraph points={getSpeedHistory(item.id)} />
{/if}
@@ -1034,7 +1072,7 @@
<div
class="progress-fill"
data-status={item.status}
- style="width: {Math.max(0, item.percent).toFixed(1)}%"
+ style:width="{Math.max(0, item.percent).toFixed(1)}%"
></div>
</div>
<span class="item-percent">{Math.max(0, item.percent).toFixed(0)}%</span>
@@ -1107,7 +1145,7 @@
<div
class="progress-fill"
data-status={item.status}
- style="width: {Math.max(0, item.percent).toFixed(1)}%"
+ style:width="{Math.max(0, item.percent).toFixed(1)}%"
></div>
</div>
@@ -1125,7 +1163,8 @@
flex-direction: column;
align-items: center;
justify-content: center;
- min-height: calc(100vh - var(--padding) * 4);
+ flex: 1;
+ min-height: 0;
gap: calc(var(--padding) * 1.5);
color: var(--gray);
}
@@ -1142,6 +1181,10 @@
max-width: 800px;
margin: 0 auto;
width: 100%;
+ /* Scroll within the fixed-height pane (parent has overflow:hidden) */
+ overflow-y: auto;
+ flex: 1;
+ min-height: 0;
}
.downloads-header {
@@ -1442,6 +1485,31 @@
opacity: 0.5;
}
+ .phase-merging-badge {
+ color: var(--accent);
+ font-weight: 500;
+ }
+
+ .eta-pill {
+ background: color-mix(in srgb, var(--accent) 15%, transparent);
+ color: var(--accent);
+ padding: 1px 6px;
+ border-radius: 4px;
+ font-size: 11px;
+ font-weight: 500;
+ }
+
+ .speed-limit-selector {
+ padding: 4px 8px;
+ font-size: 11.5px;
+ font-weight: 500;
+ color: var(--text);
+ background: var(--button);
+ border: 1px solid var(--content-border);
+ border-radius: calc(var(--border-radius) - 4px);
+ cursor: pointer;
+ }
+
.item-error {
font-size: var(--text-sm);
font-weight: 500;
diff --git a/src/routes/misc/library/+page.svelte b/src/routes/misc/library/+page.svelte
index 0a0b640c..94aa0398 100644
--- a/src/routes/misc/library/+page.svelte
+++ b/src/routes/misc/library/+page.svelte
@@ -333,7 +333,7 @@
<div class="card-path mono" title={item.file_path}>{item.file_path}</div>
{#if item.progress_pct > 0}
<div class="progress" aria-label="Progress">
- <div class="progress-fill" style="width: {(item.progress_pct * 100).toFixed(0)}%"></div>
+ <div class="progress-fill" style:width="{(item.progress_pct * 100).toFixed(0)}%"></div>
</div>
{/if}
<div class="card-foot">
@@ -370,7 +370,7 @@
<div class="progress-bar-mini">
<div
class="progress-fill-mini"
- style="width: {transcribeProgress[item.id] ?? 0}%"
+ style:width="{transcribeProgress[item.id] ?? 0}%"
></div>
</div>
<span class="progress-pct">{transcribeProgress[item.id] ?? 0}%</span>
diff --git a/src/routes/misc/models/+page.svelte b/src/routes/misc/models/+page.svelte
index cc801a48..cba1d366 100644
--- a/src/routes/misc/models/+page.svelte
+++ b/src/routes/misc/models/+page.svelte
@@ -198,7 +198,7 @@
<div class="progress-bar">
<div
class="progress-fill"
- style="width: {Math.min(100, prog.percent).toFixed(1)}%"
+ style:width="{Math.min(100, prog.percent).toFixed(1)}%"
></div>
</div>
<div class="progress-label mono">
diff --git a/src/routes/misc/studio/+page.svelte b/src/routes/misc/studio/+page.svelte
index 3b2f39ba..47e033ec 100644
--- a/src/routes/misc/studio/+page.svelte
+++ b/src/routes/misc/studio/+page.svelte
@@ -506,7 +506,7 @@
<div class="progress-bar-mini">
<div
class="progress-fill-mini"
- style="width: {transcribeProgress[clip.queue_id] ?? 0}%"
+ style:width="{transcribeProgress[clip.queue_id] ?? 0}%"
></div>
</div>
<span class="progress-pct">{transcribeProgress[clip.queue_id] ?? 0}%</span>
diff --git a/src/routes/misc/tracking/+page.svelte b/src/routes/misc/tracking/+page.svelte
index b5deeec4..1be4ad92 100644
--- a/src/routes/misc/tracking/+page.svelte
+++ b/src/routes/misc/tracking/+page.svelte
@@ -612,7 +612,7 @@
{/if}
<a class="card-link" href="/misc/tracking/{pkg.id}" aria-label={title}>
<div class="card-head">
- <div class="carrier-icon" style="--carrier-color: {icon.color}" title={carrierLabel} aria-hidden="true">
+ <div class="carrier-icon" style:--carrier-color="{icon.color}" title={carrierLabel} aria-hidden="true">
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<path d={icon.svgPath} />
</svg>
@@ -628,7 +628,7 @@
{#if pkg.canonical_status}
<span
class="status-icon"
- style="--status-color: {status.color}"
+ style:--status-color="{status.color}"
title={statusLabel}
aria-label={statusLabel}
>
@@ -641,7 +641,7 @@
<div class="card-body">
{#if pkg.canonical_status}
- <span class="status-badge" style="--status-color: {status.color}">
+ <span class="status-badge" style:--status-color="{status.color}">
{statusLabel}
</span>
{:else if pkg.last_status}
diff --git a/src/routes/misc/tracking/[id]/+page.svelte b/src/routes/misc/tracking/[id]/+page.svelte
index b1eae876..fcbb06a1 100644
--- a/src/routes/misc/tracking/[id]/+page.svelte
+++ b/src/routes/misc/tracking/[id]/+page.svelte
@@ -311,7 +311,7 @@
<header class="hero">
<div
class="carrier-icon-lg"
- style="--carrier-color: {icon.color}"
+ style:--carrier-color="{icon.color}"
title={carrierLabel}
aria-hidden="true"
>
@@ -331,7 +331,7 @@
{#if pkg.canonical_status}
<div
class="status-icon-lg"
- style="--status-color: {status.color}"
+ style:--status-color="{status.color}"
title={statusLabel}
aria-label={statusLabel}
>
@@ -353,7 +353,7 @@
<div class="hero-text">
<h1>{hasAlias ? title : maskCode(pkg.code)}</h1>
<p class="hero-meta">
- <span class="carrier-name" style="color: {icon.color}">{carrierLabel}</span>
+ <span class="carrier-name" style:color="{icon.color}">{carrierLabel}</span>
{#if hasAlias}
<span class="dot-sep">·</span>
<span class="mono small">{maskCode(pkg.code)}</span>
@@ -389,7 +389,7 @@
<span
class="status-badge-big"
class:delivered={pkg.is_delivered}
- style="--status-color: {status.color}"
+ style:--status-color="{status.color}"
>
<span class="status-badge-label">{statusLabel}</span>
{#if pkg.last_status && pkg.last_status.toLowerCase() !== statusLabel.toLowerCase()}
@@ -512,7 +512,7 @@
<li class="event" class:first={i === 0} class:repeat={samePrev}>
<div
class="event-icon"
- style="--status-color: {evIcon.color}"
+ style:--status-color="{evIcon.color}"
title={evLabel}
aria-label={evLabel}
>
@@ -536,7 +536,7 @@
{/if}
<p class="event-meta">
{#if ev.status}
- <span class="event-status-chip" style="--status-color: {evIcon.color}">{ev.status}</span>
+ <span class="event-status-chip" style:--status-color="{evIcon.color}">{ev.status}</span>
{/if}
{#if ev.date}<span>{fmtDate(ev.date)}</span>{/if}
{#if ev.time}<span class="dot-sep">·</span><span>{ev.time}</span>{/if}
diff --git a/src/routes/settings/+page.svelte b/src/routes/settings/+page.svelte
index 15188e52..ac13904a 100644
--- a/src/routes/settings/+page.svelte
+++ b/src/routes/settings/+page.svelte
@@ -25,6 +25,9 @@
name: string;
installed: boolean;
version: string | null;
+ /** "managed" | "system" | "flatpak" | "missing" */
+ source: string;
+ path: string | null;
outdated: boolean;
};
diff --git a/src/routes/study/+layout.svelte b/src/routes/study/+layout.svelte
index 37e8e714..1e768fc9 100644
--- a/src/routes/study/+layout.svelte
+++ b/src/routes/study/+layout.svelte
@@ -1080,7 +1080,7 @@
>
<div
class="palette-bar-fill"
- style="width: {xpState.level_progress_pct}%"
+ style:width="{xpState.level_progress_pct}%"
></div>
</div>
<span class="palette-hint"
diff --git a/src/routes/study/+page.svelte b/src/routes/study/+page.svelte
index e7c6e556..88b42c79 100644
--- a/src/routes/study/+page.svelte
+++ b/src/routes/study/+page.svelte
@@ -288,7 +288,7 @@
type="button"
onclick={() => goto("/study/progress")}
title={goalMet ? $t("study.hub.goal_met") : ""}
- style="--streak-color: {streakColor};"
+ style:--streak-color="{streakColor}"
>
<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true">
<path d="M13.5 0.67s.74 2.65.74 4.8c0 2.06-1.35 3.73-3.41 3.73S7 7.53 7 5.47c0-1.02.25-1.98.58-2.82-.84 1.5-1.58 3.3-1.58 5.19 0 4.42 3.58 8 8 8s8-3.58 8-8c0-5.9-4.5-9.17-8.5-12.17z"></path>
@@ -306,7 +306,7 @@
<h2 class="hero-title">{hero.course.title}</h2>
<div class="hero-progress">
<div class="progress-track">
- <div class="progress-fill" style="width: {Math.round(hero.course.progress_pct ?? 0)}%"></div>
+ <div class="progress-fill" style:width="{Math.round(hero.course.progress_pct ?? 0)}%"></div>
</div>
<span class="mono hero-pct">{Math.round(hero.course.progress_pct ?? 0)}%</span>
</div>
diff --git a/src/routes/study/anki/_ReviewSession.svelte b/src/routes/study/anki/_ReviewSession.svelte
index 2485ae2f..bbbe6ab3 100644
--- a/src/routes/study/anki/_ReviewSession.svelte
+++ b/src/routes/study/anki/_ReviewSession.svelte
@@ -291,7 +291,7 @@
{:else}
<header class="progress-row">
<div class="progress-track" aria-hidden="true">
- <div class="progress-fill" style="width: {progressPct}%"></div>
+ <div class="progress-fill" style:width="{progressPct}%"></div>
</div>
<span class="progress-text">{answered} / {initialTotal}</span>
</header>
diff --git a/src/routes/study/anki/browse/+page.svelte b/src/routes/study/anki/browse/+page.svelte
index de2108a0..bd9bdb9e 100644
--- a/src/routes/study/anki/browse/+page.svelte
+++ b/src/routes/study/anki/browse/+page.svelte
@@ -598,7 +598,7 @@
onclick={() => bulkSetFlag(n as number)}
disabled={busy}
>
- <span class="flag-swatch" style="background: {color}"></span>
+ <span class="flag-swatch" style:background="{color}"></span>
<span>{label}</span>
</button>
{/each}
@@ -706,7 +706,7 @@
/>
</td>
<td class="flag-col">
- <span class="flag-dot" style="background: {flagDot(c.flag)}"></span>
+ <span class="flag-dot" style:background="{flagDot(c.flag)}"></span>
</td>
<td class="front">{strip(sfld) || `card ${c.id}`}</td>
<td class="deck">{decksById[c.did] ?? c.did}</td>
diff --git a/src/routes/study/anki/decks/+page.svelte b/src/routes/study/anki/decks/+page.svelte
index a0cc16ab..2ee7071f 100644
--- a/src/routes/study/anki/decks/+page.svelte
+++ b/src/routes/study/anki/decks/+page.svelte
@@ -325,7 +325,7 @@
{#each nodes as node (node.deck_id)}
{@const count = countsByDeck[node.deck_id] ?? 0}
<li class="node" data-level={node.level}>
- <div class="row" style="padding-left: {node.level * 16}px">
+ <div class="row" style:padding-left="{node.level * 16}px">
<div class="row-main">
{#if editingId === node.deck_id}
<input
diff --git a/src/routes/study/anki/stats/+page.svelte b/src/routes/study/anki/stats/+page.svelte
index 58461d9e..522109ed 100644
--- a/src/routes/study/anki/stats/+page.svelte
+++ b/src/routes/study/anki/stats/+page.svelte
@@ -266,7 +266,7 @@
<li>
<span class="bar-label">{r.bucket}</span>
<span class="bar-track" aria-hidden="true">
- <span class="bar-fill" style="width: {pct}%"></span>
+ <span class="bar-fill" style:width="{pct}%"></span>
</span>
<span class="bar-count">{fmtNumber(r.count)}</span>
</li>
@@ -291,7 +291,7 @@
{@const h = max === 0 ? 0 : (f.count / max) * 100}
<span
class="vbar-col"
- style="--h: {h}%"
+ style:--h="{h}%"
title="Dia +{f.day}: {f.count} cards"
>
<span class="vbar-fill"></span>
diff --git a/src/routes/study/course/[id]/+page.svelte b/src/routes/study/course/[id]/+page.svelte
index 1b3ed9af..e74027e0 100644
--- a/src/routes/study/course/[id]/+page.svelte
+++ b/src/routes/study/course/[id]/+page.svelte
@@ -566,7 +566,7 @@
<div
class="module-bar-fill"
class:full={mPct >= 100}
- style="width: {mPct}%"
+ style:width="{mPct}%"
></div>
</div>
<ul>
@@ -624,7 +624,7 @@
<div
class="module-bar-fill"
class:full={loosePct >= 100}
- style="width: {loosePct}%"
+ style:width="{loosePct}%"
></div>
</div>
<ul>
diff --git a/src/routes/study/focus/+page.svelte b/src/routes/study/focus/+page.svelte
index 69a4e5ae..052c02a0 100644
--- a/src/routes/study/focus/+page.svelte
+++ b/src/routes/study/focus/+page.svelte
@@ -759,7 +759,7 @@
<span>{xpState ? `${xpState.xp} XP` : "XP"}</span>
</div>
<div class="level-meter" aria-hidden="true">
- <div style="width: {xpState?.level_progress_pct ?? 0}%"></div>
+ <div style:width="{xpState?.level_progress_pct ?? 0}%"></div>
</div>
</div>
</header>
@@ -874,8 +874,8 @@
{:else}
<div class="line-display" aria-label={timerText}>
<div class="line-track">
- <div class="line-fill" style="width: {progressPct}%"></div>
- <div class="line-knob" style="left: {progressPct}%"></div>
+ <div class="line-fill" style:width="{progressPct}%"></div>
+ <div class="line-knob" style:left="{progressPct}%"></div>
</div>
<span>{timerText}</span>
</div>
diff --git a/src/routes/study/library/+page.svelte b/src/routes/study/library/+page.svelte
index 1731b35c..d835f13b 100644
--- a/src/routes/study/library/+page.svelte
+++ b/src/routes/study/library/+page.svelte
@@ -1925,7 +1925,7 @@
</svg>
{/if}
<span class="kind-badge">{$t("study.library.kind_course")}</span>
- <div class="progress" style="--pct: {c.progress_pct}%"></div>
+ <div class="progress" style:--pct="{c.progress_pct}%"></div>
</div>
<div class="meta">
<div class="title-row">
diff --git a/src/routes/study/music/genres/+page.svelte b/src/routes/study/music/genres/+page.svelte
index 374b59ad..2007bf9d 100644
--- a/src/routes/study/music/genres/+page.svelte
+++ b/src/routes/study/music/genres/+page.svelte
@@ -67,7 +67,7 @@
<button
type="button"
class="card"
- style="--seed: {genreColor(g.name)};"
+ style:--seed="{genreColor(g.name)}"
onclick={() => open(g)}
>
<span class="title">{g.name}</span>
diff --git a/src/routes/study/progress/+page.svelte b/src/routes/study/progress/+page.svelte
index 33003954..2c635d55 100644
--- a/src/routes/study/progress/+page.svelte
+++ b/src/routes/study/progress/+page.svelte
@@ -403,7 +403,7 @@
{#each weeks as week, wi (wi)}
<div class="col">
{#each week as c (c.date)}
- <span class="cell" style="background: {cellColor(c)}" title={cellTitle(c)}></span>
+ <span class="cell" style:background="{cellColor(c)}" title={cellTitle(c)}></span>
{/each}
</div>
{/each}
@@ -592,7 +592,7 @@
</div>
<div class="ab-progress">
<div class="ab-track">
- <div class="ab-fill" style="width: {Math.round(readStats.active_book.reading_pct * 100)}%"></div>
+ <div class="ab-fill" style:width="{Math.round(readStats.active_book.reading_pct * 100)}%"></div>
</div>
<span class="ab-pct">{Math.round(readStats.active_book.reading_pct * 100)}%</span>
</div>
diff --git a/src/routes/study/read/+page.svelte b/src/routes/study/read/+page.svelte
index 627e78af..4ab8b009 100644
--- a/src/routes/study/read/+page.svelte
+++ b/src/routes/study/read/+page.svelte
@@ -981,7 +981,7 @@
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
</svg>
</span>
- <div class="progress" style="--pct: {Math.round(b.reading_pct)}%"></div>
+ <div class="progress" style:--pct="{Math.round(b.reading_pct)}%"></div>
</div>
<div class="meta">
<div class="title">{deriveTitle(b)}</div>
diff --git a/src/routes/study/read/[id]/+page.svelte b/src/routes/study/read/[id]/+page.svelte
index b2b3c194..46129053 100644
--- a/src/routes/study/read/[id]/+page.svelte
+++ b/src/routes/study/read/[id]/+page.svelte
@@ -1717,14 +1717,14 @@
role="toolbar"
tabindex="-1"
aria-label="highlight"
- style="left: {epubPopupPos.x}px; top: {epubPopupPos.y}px;"
+ style:left="{epubPopupPos.x}px" style:top="{epubPopupPos.y}px"
onmousedown={(e) => e.stopPropagation()}
>
{#each COLOR_PALETTE as c (c.key)}
<button
type="button"
class="hl-color"
- style="background: {c.css};"
+ style:background="{c.css}"
title={c.key}
onclick={() => saveEpubHighlight(c.key)}
></button>
@@ -1818,7 +1818,7 @@
type="button"
class="ink-swatch"
class:selected={inkColor === c.css && !inkEraser}
- style="background: {c.css};"
+ style:background="{c.css}"
onclick={() => {
inkEraser = false;
persistInkColor(c.css);
@@ -2045,7 +2045,7 @@
class:active={a && a.page === currentPage}
onclick={() => a && jumpTo(a.page)}
>
- <span class="hl-dot" style="background: {colorCss(h.color)};"></span>
+ <span class="hl-dot" style:background="{colorCss(h.color)}"></span>
<span class="outline-title hl-text-clamp">{h.text ?? "—"}</span>
<span class="outline-page mono">{a?.page ?? "?"}</span>
</button>
@@ -2073,7 +2073,7 @@
{#if h.kind === "note"}
<span class="hl-dot" style="background: var(--accent);"></span>
{:else}
- <span class="hl-dot" style="background: {colorCss(h.color)};"></span>
+ <span class="hl-dot" style:background="{colorCss(h.color)}"></span>
{/if}
<span class="note-body">
{#if h.text}
@@ -2166,7 +2166,7 @@
<div
class="canvas-frame scroll-page"
data-page={p}
- style="aspect-ratio: {pageSize.w > 0 ? `${pageSize.w} / ${pageSize.h}` : '612 / 792'};"
+ style:aspect-ratio="{pageSize.w > 0 ? `${pageSize.w} / ${pageSize.h}` : '612 / 792'}"
>
{#if scrollImgs[p]}
<img class="page-img" src={scrollImgs[p]} alt="page {p}" loading="lazy" />
@@ -2190,7 +2190,7 @@
role="region"
aria-label="page"
bind:this={pageFrameEl}
- style="aspect-ratio: {pageSize.w} / {pageSize.h};"
+ style:aspect-ratio="{pageSize.w} / {pageSize.h}"
onmouseup={onTextSelectionEnd}
onpointerdown={onInkDown}
onpointermove={onInkMove}
@@ -2211,7 +2211,7 @@
type="button"
class="hl-rect"
data-drawer={h.drawer ?? "lighten"}
- style="left: {s.left}px; top: {s.top}px; width: {s.width}px; height: {s.height}px; --hl-color: {colorCss(h.color)};"
+ style:left="{s.left}px" style:top="{s.top}px" style:width="{s.width}px" style:height="{s.height}px" style:--hl-color="{colorCss(h.color)}"
onclick={(e) => openHighlightEditor(h, e)}
title={h.note ? `nota: ${h.note}` : "editar"}
>
@@ -2265,7 +2265,7 @@
<span
class="char-span"
data-tw={s.width}
- style="left: {s.left}px; top: {s.top}px; height: {s.height}px; font-size: {Math.max(6, s.height * 0.95)}px;"
+ style:left="{s.left}px" style:top="{s.top}px" style:height="{s.height}px" style:font-size="{Math.max(6, s.height * 0.95)}px"
>{c.c}</span>
{/each}
</div>
@@ -2278,14 +2278,14 @@
role="toolbar"
tabindex="-1"
aria-label="highlight"
- style="left: {popupPos.x}px; top: {popupPos.y}px;"
+ style:left="{popupPos.x}px" style:top="{popupPos.y}px"
onmousedown={(e) => e.stopPropagation()}
>
{#each COLOR_PALETTE as c (c.key)}
<button
type="button"
class="hl-color"
- style="background: {c.css};"
+ style:background="{c.css}"
title={c.key}
onclick={() => saveHighlight(c.key)}
></button>
@@ -2300,7 +2300,7 @@
role="dialog"
tabindex="-1"
aria-label="Editar highlight"
- style="left: {editPopupPos.x}px; top: {editPopupPos.y}px;"
+ style:left="{editPopupPos.x}px" style:top="{editPopupPos.y}px"
onmousedown={(e) => e.stopPropagation()}
onkeydown={onEditorKey}
>
@@ -2326,7 +2326,7 @@
type="button"
class="ep-color"
class:active={editingHighlight.color === c.key}
- style="background: {c.css};"
+ style:background="{c.css}"
title={c.key}
onclick={() => updateHighlightField("color", c.key)}
></button>
@@ -2492,7 +2492,7 @@
{/if}
{#snippet outlineNode(node: OutlineNode, depth: number)}
- <li class="outline-item" style="--depth: {depth};">
+ <li class="outline-item" style:--depth="{depth}">
{#if node.page != null}
<button type="button" class="outline-link" onclick={() => jumpTo(node.page!)}>
<span class="outline-title">{node.title}</span>
diff --git a/src/routes/study/read/manga/+page.svelte b/src/routes/study/read/manga/+page.svelte
index 059e1022..7998f005 100644
--- a/src/routes/study/read/manga/+page.svelte
+++ b/src/routes/study/read/manga/+page.svelte
@@ -280,7 +280,7 @@
>
{s.favorite ? "★" : "☆"}
</span>
- <div class="progress" style="--pct: {Math.round(s.progress_pct * 100)}%"></div>
+ <div class="progress" style:--pct="{Math.round(s.progress_pct * 100)}%"></div>
</div>
<div class="meta">
<div class="title">{s.title}</div>
diff --git a/src/routes/telegram/+page.svelte b/src/routes/telegram/+page.svelte
index a0a19f76..f7bc2bf5 100644
--- a/src/routes/telegram/+page.svelte
+++ b/src/routes/telegram/+page.svelte
@@ -1421,7 +1421,7 @@
<div class="batch-progress-bar-outer">
<div
class="batch-progress-bar-inner"
- style="width: {batchPercent}%"
+ style:width="{batchPercent}%"
></div>
</div>
<span class="subtext">