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(bilibili): add authentication commands and progress tracking

Tonho1734488d0afb
diff --git a/src-tauri/omniget-core/src/core/dependencies.rs b/src-tauri/omniget-core/src/core/dependencies.rs
index a98c5b8f..6e311696 100644
--- a/src-tauri/omniget-core/src/core/dependencies.rs
+++ b/src-tauri/omniget-core/src/core/dependencies.rs
@@ -606,6 +606,70 @@ async fn download_deno() -> anyhow::Result<PathBuf> {
Ok(deno_target)
}
+pub async fn ensure_gallerydl() -> Option<PathBuf> {
+ if let Some(path) = find_tool("gallery-dl").await {
+ return Some(path);
+ }
+
+ #[cfg(any(target_os = "windows", target_os = "linux"))]
+ {
+ match download_gallerydl().await {
+ Ok(path) => return Some(path),
+ Err(e) => tracing::warn!("Failed to download gallery-dl: {}", e),
+ }
+ }
+
+ None
+}
+
+#[cfg(any(target_os = "windows", target_os = "linux"))]
+async fn download_gallerydl() -> anyhow::Result<PathBuf> {
+ let bin_dir = managed_bin_dir().ok_or_else(|| anyhow!("Could not determine data directory"))?;
+ std::fs::create_dir_all(&bin_dir)?;
+
+ let target = bin_dir.join(bin_name("gallery-dl"));
+
+ #[cfg(target_os = "windows")]
+ let url = "https://github.com/mikf/gallery-dl/releases/latest/download/gallery-dl.exe";
+ #[cfg(target_os = "linux")]
+ let url = "https://github.com/mikf/gallery-dl/releases/latest/download/gallery-dl.bin";
+
+ let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .timeout(std::time::Duration::from_secs(180))
+ .build()?;
+
+ let response = client.get(url).send().await?;
+ if !response.status().is_success() {
+ return Err(anyhow!(
+ "Failed to download gallery-dl: HTTP {}",
+ response.status()
+ ));
+ }
+
+ let bytes = response.bytes().await?;
+ let data = bytes.to_vec();
+ let target_clone = target.clone();
+ tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
+ std::fs::write(&target_clone, &data)?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mut perm = std::fs::metadata(&target_clone)?.permissions();
+ perm.set_mode(0o755);
+ std::fs::set_permissions(&target_clone, perm)?;
+ }
+ Ok(())
+ })
+ .await
+ .map_err(|e| anyhow!("Spawn blocking failed: {}", e))??;
+
+ if !target.exists() {
+ return Err(anyhow!("gallery-dl binary not found after download"));
+ }
+
+ Ok(target)
+}
+
pub async fn ensure_aria2c() -> Option<PathBuf> {
if let Some(path) = find_tool("aria2c").await {
return Some(path);
diff --git a/src-tauri/omniget-core/src/core/direct_downloader.rs b/src-tauri/omniget-core/src/core/direct_downloader.rs
index c02d0b76..8553da32 100644
--- a/src-tauri/omniget-core/src/core/direct_downloader.rs
+++ b/src-tauri/omniget-core/src/core/direct_downloader.rs
@@ -12,6 +12,7 @@ use tokio_util::sync::CancellationToken;
use crate::core::http_fetcher::{
get_global_max_concurrent_segments, HttpFetcher, HttpFetcherConfig,
};
+use crate::models::progress::ProgressUpdate;
const CHUNK_TIMEOUT: Duration = Duration::from_secs(45);
const MAX_RETRIES: u32 = 3;
@@ -45,7 +46,7 @@ pub async fn download_direct(
client: &reqwest::Client,
url: &str,
output: &Path,
- progress_tx: mpsc::Sender<f64>,
+ progress_tx: mpsc::Sender<ProgressUpdate>,
cancel: Option<&CancellationToken>,
) -> anyhow::Result<u64> {
download_direct_with_headers(client, url, output, progress_tx, None, cancel).await
@@ -55,7 +56,7 @@ pub async fn download_direct_with_headers(
client: &reqwest::Client,
url: &str,
output: &Path,
- progress_tx: mpsc::Sender<f64>,
+ progress_tx: mpsc::Sender<ProgressUpdate>,
headers: Option<reqwest::header::HeaderMap>,
cancel: Option<&CancellationToken>,
) -> anyhow::Result<u64> {
@@ -154,7 +155,7 @@ async fn download_attempt(
client: &reqwest::Client,
url: &str,
output: &Path,
- progress_tx: &mpsc::Sender<f64>,
+ progress_tx: &mpsc::Sender<ProgressUpdate>,
headers: Option<reqwest::header::HeaderMap>,
cancel: Option<&CancellationToken>,
) -> anyhow::Result<u64> {
@@ -224,7 +225,7 @@ async fn download_attempt(
}
std::fs::rename(&part_path, output)?;
- let _ = progress_tx.send(100.0).await;
+ let _ = progress_tx.send(ProgressUpdate::percent(100.0)).await;
let size = std::fs::metadata(output)?.len();
Ok(size)
@@ -234,7 +235,7 @@ async fn run_http_fetcher(
client: &reqwest::Client,
url: &str,
output: &Path,
- progress_tx: &mpsc::Sender<f64>,
+ progress_tx: &mpsc::Sender<ProgressUpdate>,
headers: Option<reqwest::header::HeaderMap>,
cancel: Option<&CancellationToken>,
) -> anyhow::Result<u64> {
@@ -267,7 +268,7 @@ async fn download_single_stream(
part_path: &Path,
existing_bytes: u64,
total_size: Option<u64>,
- progress_tx: &mpsc::Sender<f64>,
+ progress_tx: &mpsc::Sender<ProgressUpdate>,
headers: Option<reqwest::header::HeaderMap>,
cancel: Option<&CancellationToken>,
) -> anyhow::Result<()> {
@@ -322,6 +323,11 @@ async fn download_single_stream(
let mut downloaded = offset;
let mut stream = response.bytes_stream();
+ let mut last_emit = std::time::Instant::now();
+ let mut speed_anchor_bytes = downloaded;
+ let mut speed_anchor_time = std::time::Instant::now();
+ let mut speed_ema: f64 = 0.0;
+
loop {
if let Some(token) = cancel {
if token.is_cancelled() {
@@ -337,14 +343,44 @@ async fn download_single_stream(
.map_err(|e| anyhow!("Write error (disk full?): {}", e))?;
downloaded += chunk.len() as u64;
- if let Some(total) = total_size {
- if total > 0 {
- let percent = (downloaded as f64 / total as f64) * 100.0;
- let _ = progress_tx.send(percent).await;
+ if last_emit.elapsed() >= std::time::Duration::from_millis(250) {
+ let dt = speed_anchor_time.elapsed().as_secs_f64();
+ if dt >= 0.2 {
+ let instant = (downloaded.saturating_sub(speed_anchor_bytes)) as f64 / dt;
+ speed_ema = if speed_ema > 0.0 {
+ speed_ema * 0.6 + instant * 0.4
+ } else {
+ instant
+ };
+ speed_anchor_bytes = downloaded;
+ speed_anchor_time = std::time::Instant::now();
}
- } else {
- let percent = (downloaded as f64 / (downloaded as f64 + 500_000.0)) * 100.0;
- let _ = progress_tx.send(percent.min(95.0)).await;
+ let speed = (speed_ema > 0.0).then_some(speed_ema);
+ let (percent, eta) = match total_size {
+ Some(total) if total > 0 => {
+ let pct = (downloaded as f64 / total as f64) * 100.0;
+ let eta = speed.and_then(|s| {
+ (s > 0.0 && total > downloaded)
+ .then(|| ((total - downloaded) as f64 / s) as u64)
+ });
+ (pct, eta)
+ }
+ _ => (
+ ((downloaded as f64 / (downloaded as f64 + 500_000.0)) * 100.0)
+ .min(95.0),
+ None,
+ ),
+ };
+ let _ = progress_tx
+ .send(ProgressUpdate::rich(
+ percent,
+ Some(downloaded),
+ total_size.filter(|t| *t > 0),
+ speed,
+ eta,
+ ))
+ .await;
+ last_emit = std::time::Instant::now();
}
}
Ok(Some(Err(e))) => {
diff --git a/src-tauri/omniget-core/src/core/ffmpeg.rs b/src-tauri/omniget-core/src/core/ffmpeg.rs
index 6ad0967d..2b7fa982 100644
--- a/src-tauri/omniget-core/src/core/ffmpeg.rs
+++ b/src-tauri/omniget-core/src/core/ffmpeg.rs
@@ -6,6 +6,8 @@ use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
+use crate::models::progress::ProgressUpdate;
+
static FFMPEG_AVAILABLE_CACHE: std::sync::RwLock<Option<bool>> = std::sync::RwLock::new(None);
pub async fn is_ffmpeg_available() -> bool {
@@ -266,7 +268,7 @@ pub async fn get_duration_us(path: &Path) -> anyhow::Result<u64> {
pub async fn convert(
opts: &ConversionOptions,
cancel_token: CancellationToken,
- progress_tx: mpsc::Sender<f64>,
+ progress_tx: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<ConversionResult> {
let input_path = Path::new(&opts.input_path);
let output_path = Path::new(&opts.output_path);
@@ -360,7 +362,7 @@ pub async fn convert(
if let Some(us) = parse_out_time_us(&line) {
if total_duration_us > 0 {
let pct = (us as f64 / total_duration_us as f64 * 100.0).min(100.0);
- let _ = progress.send(pct).await;
+ let _ = progress.send(ProgressUpdate::percent(pct)).await;
}
}
}
@@ -386,7 +388,7 @@ pub async fn convert(
match result {
Ok(status) if status.success() => {
- let _ = progress_tx.send(100.0).await;
+ let _ = progress_tx.send(ProgressUpdate::percent(100.0)).await;
let meta = std::fs::metadata(output_path);
let file_size = meta.map(|m| m.len()).unwrap_or(0);
diff --git a/src-tauri/omniget-core/src/core/http_fetcher.rs b/src-tauri/omniget-core/src/core/http_fetcher.rs
index 975ca21e..05f82712 100644
--- a/src-tauri/omniget-core/src/core/http_fetcher.rs
+++ b/src-tauri/omniget-core/src/core/http_fetcher.rs
@@ -10,6 +10,8 @@ use tokio::io::{AsyncSeekExt, AsyncWriteExt};
use tokio::sync::{mpsc, Mutex};
use tokio_util::sync::CancellationToken;
+use crate::models::progress::ProgressUpdate;
+
const SEG_PENDING: u8 = 0;
const SEG_RUNNING: u8 = 1;
const SEG_DONE: u8 = 2;
@@ -197,7 +199,7 @@ impl HttpFetcher {
pub async fn download(
&self,
- progress_tx: mpsc::Sender<f64>,
+ progress_tx: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<HttpFetcherResult> {
let probe = self.probe().await?;
@@ -260,7 +262,7 @@ impl HttpFetcher {
if self.config.use_sidecar_resume {
let _ = tokio::fs::remove_file(&resume_path).await;
}
- let _ = progress_tx.send(100.0).await;
+ let _ = progress_tx.send(ProgressUpdate::percent(100.0)).await;
let bytes = tokio::fs::metadata(&self.output_path)
.await
.map(|m| m.len())
@@ -303,7 +305,7 @@ impl HttpFetcher {
async fn download_streaming(
&self,
part_path: &Path,
- progress_tx: &mpsc::Sender<f64>,
+ progress_tx: &mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<HttpFetcherResult> {
let _ = tokio::fs::remove_file(part_path).await;
@@ -321,6 +323,11 @@ impl HttpFetcher {
let mut downloaded: u64 = 0;
let mut stream = resp.bytes_stream();
+ let mut last_emit = std::time::Instant::now();
+ let mut anchor_bytes = 0u64;
+ let mut anchor_time = std::time::Instant::now();
+ let mut speed_ema: f64 = 0.0;
+
loop {
if let Some(token) = &self.cancel {
if token.is_cancelled() {
@@ -331,9 +338,45 @@ impl HttpFetcher {
Ok(Some(Ok(chunk))) => {
file.write_all(&chunk).await?;
downloaded += chunk.len() as u64;
- if let Some(t) = total.filter(|t| *t > 0) {
- let pct = (downloaded as f64 / t as f64) * 100.0;
- let _ = progress_tx.send(pct.min(99.9)).await;
+ if last_emit.elapsed() >= Duration::from_millis(250) {
+ let elapsed = anchor_time.elapsed().as_secs_f64();
+ if elapsed >= 0.3 {
+ let instant =
+ (downloaded.saturating_sub(anchor_bytes)) as f64 / elapsed;
+ speed_ema = if speed_ema > 0.0 {
+ speed_ema * 0.6 + instant * 0.4
+ } else {
+ instant
+ };
+ anchor_bytes = downloaded;
+ anchor_time = std::time::Instant::now();
+ }
+ let speed = (speed_ema > 0.0).then_some(speed_ema);
+ let (pct, eta) = match total.filter(|t| *t > 0) {
+ Some(t) => {
+ let p = ((downloaded as f64 / t as f64) * 100.0).min(99.9);
+ let e = speed.and_then(|s| {
+ (s > 0.0 && t > downloaded)
+ .then(|| ((t - downloaded) as f64 / s) as u64)
+ });
+ (p, e)
+ }
+ None => (
+ ((downloaded as f64 / (downloaded as f64 + 500_000.0)) * 100.0)
+ .min(95.0),
+ None,
+ ),
+ };
+ let _ = progress_tx
+ .send(ProgressUpdate::rich(
+ pct,
+ Some(downloaded),
+ total.filter(|t| *t > 0),
+ speed,
+ eta,
+ ))
+ .await;
+ last_emit = std::time::Instant::now();
}
}
Ok(Some(Err(e))) => return Err(anyhow!("stream error: {}", e)),
@@ -350,7 +393,7 @@ impl HttpFetcher {
file.flush().await?;
drop(file);
tokio::fs::rename(part_path, &self.output_path).await?;
- let _ = progress_tx.send(100.0).await;
+ let _ = progress_tx.send(ProgressUpdate::percent(100.0)).await;
Ok(HttpFetcherResult {
bytes_written: downloaded,
})
@@ -363,7 +406,7 @@ impl HttpFetcher {
seg_specs: Vec<ResumeSegment>,
resume_path: &Path,
url_hash: &str,
- progress_tx: &mpsc::Sender<f64>,
+ progress_tx: &mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<()> {
let segments: Arc<Mutex<Vec<Arc<Segment>>>> = Arc::new(Mutex::new(
seg_specs
@@ -385,6 +428,10 @@ impl HttpFetcher {
let cancel = cancel.clone();
tokio::spawn(async move {
let mut last_emit = std::time::Instant::now() - Duration::from_secs(1);
+ let mut anchor_bytes = 0u64;
+ let mut anchor_time = std::time::Instant::now();
+ let mut speed_ema: f64 = 0.0;
+ let mut anchor_init = false;
loop {
if cancel.is_cancelled() {
break;
@@ -396,9 +443,37 @@ impl HttpFetcher {
.map(|s| s.downloaded.load(Ordering::Relaxed))
.sum()
};
+ if !anchor_init {
+ anchor_bytes = dl;
+ anchor_time = std::time::Instant::now();
+ anchor_init = true;
+ }
if last_emit.elapsed() >= Duration::from_millis(200) {
- let pct = (dl as f64 / total as f64) * 100.0;
- let _ = progress_tx.send(pct.min(99.9)).await;
+ let elapsed = anchor_time.elapsed().as_secs_f64();
+ if elapsed >= 0.4 {
+ let instant = (dl.saturating_sub(anchor_bytes)) as f64 / elapsed;
+ speed_ema = if speed_ema > 0.0 {
+ speed_ema * 0.6 + instant * 0.4
+ } else {
+ instant
+ };
+ anchor_bytes = dl;
+ anchor_time = std::time::Instant::now();
+ }
+ let speed = (speed_ema > 0.0).then_some(speed_ema);
+ let pct = ((dl as f64 / total as f64) * 100.0).min(99.9);
+ let eta = speed.and_then(|s| {
+ (s > 0.0 && total > dl).then(|| ((total - dl) as f64 / s) as u64)
+ });
+ let _ = progress_tx
+ .send(ProgressUpdate::rich(
+ pct,
+ Some(dl),
+ Some(total),
+ speed,
+ eta,
+ ))
+ .await;
last_emit = std::time::Instant::now();
}
}
@@ -1034,11 +1109,11 @@ mod tests {
let url = format!("http://{}/file.bin", addr);
let fetcher = HttpFetcher::new(client, url, output.clone());
- let (tx, mut rx) = tokio::sync::mpsc::channel::<f64>(32);
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<ProgressUpdate>(32);
let progress_collector = tokio::spawn(async move {
let mut last = 0.0;
while let Some(p) = rx.recv().await {
- last = p;
+ last = p.percent;
}
last
});
@@ -1158,11 +1233,11 @@ mod tests {
};
let fetcher = HttpFetcher::new(client, url, output.clone()).with_config(cfg);
- let (tx, mut rx) = tokio::sync::mpsc::channel::<f64>(64);
+ let (tx, mut rx) = tokio::sync::mpsc::channel::<ProgressUpdate>(64);
let progress_collector = tokio::spawn(async move {
let mut last = 0.0;
while let Some(p) = rx.recv().await {
- last = p;
+ last = p.percent;
}
last
});
diff --git a/src-tauri/omniget-core/src/core/subtitle_merge.rs b/src-tauri/omniget-core/src/core/subtitle_merge.rs
index 2c7d844e..2040542d 100644
--- a/src-tauri/omniget-core/src/core/subtitle_merge.rs
+++ b/src-tauri/omniget-core/src/core/subtitle_merge.rs
@@ -127,7 +127,125 @@ fn fmt_ts(ms: u64) -> String {
format!("{:02}:{:02}:{:02},{:03}", h, m, s, milli)
}
+fn parse_ass_ts(s: &str) -> Option<u64> {
+ // ASS uses H:MM:SS.cc (centiseconds, 2 digits).
+ let s = s.trim();
+ let (hms, cc) = s.rsplit_once('.')?;
+ let centis: u64 = cc.chars().take(2).collect::<String>().parse().ok()?;
+ let parts: Vec<&str> = hms.split(':').collect();
+ let (h, m, sec): (u64, u64, u64) = match parts.as_slice() {
+ [h, m, s] => (
+ h.trim().parse().ok()?,
+ m.trim().parse().ok()?,
+ s.trim().parse().ok()?,
+ ),
+ [m, s] => (0, m.trim().parse().ok()?, s.trim().parse().ok()?),
+ _ => return None,
+ };
+ Some(((h * 3600 + m * 60 + sec) * 1000) + centis * 10)
+}
+
+fn fmt_ass_ts(ms: u64) -> String {
+ let h = ms / 3_600_000;
+ let m = (ms % 3_600_000) / 60_000;
+ let s = (ms % 60_000) / 1000;
+ let cs = (ms % 1000) / 10;
+ format!("{}:{:02}:{:02}.{:02}", h, m, s, cs)
+}
+
+fn strip_ass_overrides(raw: &str) -> String {
+ let mut out = String::with_capacity(raw.len());
+ let mut depth = 0u32;
+ for ch in raw.chars() {
+ match ch {
+ '{' => depth += 1,
+ '}' => depth = depth.saturating_sub(1),
+ _ if depth == 0 => out.push(ch),
+ _ => {}
+ }
+ }
+ out.replace("\\N", "\n")
+ .replace("\\n", "\n")
+ .trim()
+ .to_string()
+}
+
+pub fn parse_cues_ass(content: &str) -> Vec<Cue> {
+ let normalized = content.replace('\r', "");
+ let mut cues = Vec::new();
+ let mut in_events = false;
+ let mut start_col = 1usize;
+ let mut end_col = 2usize;
+ let mut text_col = 9usize;
+
+ for line in normalized.lines() {
+ let trimmed = line.trim();
+ if trimmed.starts_with('[') && trimmed.ends_with(']') {
+ in_events = trimmed.eq_ignore_ascii_case("[Events]");
+ continue;
+ }
+ if !in_events {
+ continue;
+ }
+ if let Some(fmt) = trimmed.strip_prefix("Format:") {
+ for (i, name) in fmt.split(',').map(|s| s.trim().to_lowercase()).enumerate() {
+ match name.as_str() {
+ "start" => start_col = i,
+ "end" => end_col = i,
+ "text" => text_col = i,
+ _ => {}
+ }
+ }
+ continue;
+ }
+ if let Some(rest) = trimmed.strip_prefix("Dialogue:") {
+ let max_split = text_col.max(start_col).max(end_col);
+ let fields: Vec<&str> = rest.splitn(max_split + 1, ',').collect();
+ let (Some(s), Some(e), Some(t)) = (
+ fields.get(start_col).and_then(|v| parse_ass_ts(v)),
+ fields.get(end_col).and_then(|v| parse_ass_ts(v)),
+ fields.get(text_col),
+ ) else {
+ continue;
+ };
+ let text = strip_ass_overrides(t);
+ if !text.is_empty() {
+ cues.push(Cue {
+ start_ms: s,
+ end_ms: e,
+ text,
+ });
+ }
+ }
+ }
+ cues
+}
+
+pub fn cues_to_ass(cues: &[Cue]) -> String {
+ let mut out = String::from(
+ "[Script Info]\nScriptType: v4.00+\nWrapStyle: 0\nScaledBorderAndShadow: yes\n\n\
+[V4+ Styles]\n\
+Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n\
+Style: Default,Arial,48,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1\n\n\
+[Events]\n\
+Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n",
+ );
+ for c in cues {
+ let text = c.text.replace('\n', "\\N");
+ out.push_str(&format!(
+ "Dialogue: 0,{},{},Default,,0,0,0,,{}\n",
+ fmt_ass_ts(c.start_ms),
+ fmt_ass_ts(c.end_ms),
+ text
+ ));
+ }
+ out
+}
+
pub fn parse_cues(content: &str) -> Vec<Cue> {
+ if content.contains("[Events]") || content.contains("Dialogue:") {
+ return parse_cues_ass(content);
+ }
let normalized = content.replace('\r', "");
let mut cues = Vec::new();
for part in normalized.split("\n\n") {
@@ -304,4 +422,42 @@ mod tests {
assert_eq!(cues[0].text, "Hi there");
assert!(cues_to_vtt(&cues).starts_with("WEBVTT"));
}
+
+ #[test]
+ fn ass_roundtrip_and_autodetect() {
+ let cues = vec![
+ Cue {
+ start_ms: 1500,
+ end_ms: 2250,
+ text: "Hello".to_string(),
+ },
+ Cue {
+ start_ms: 60000,
+ end_ms: 62000,
+ text: "two\nlines".to_string(),
+ },
+ ];
+ let ass = cues_to_ass(&cues);
+ assert!(ass.contains("[Events]"));
+ assert!(ass.contains("Dialogue: 0,0:00:01.50,0:00:02.25,Default,,0,0,0,,Hello"));
+ // parse_cues must auto-detect ASS and restore \N as newline.
+ let back = parse_cues(&ass);
+ assert_eq!(back.len(), 2);
+ assert_eq!(back[0].start_ms, 1500);
+ assert_eq!(back[0].end_ms, 2250);
+ assert_eq!(back[1].start_ms, 60000);
+ assert_eq!(back[1].text, "two\nlines");
+ }
+
+ #[test]
+ fn ass_strips_override_tags_and_respects_format_columns() {
+ let ass = "[Events]\n\
+Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\
+Dialogue: 0,0:00:03.00,0:00:04.50,Default,,0,0,0,,{\\b1}Bold{\\b0} text";
+ let cues = parse_cues_ass(ass);
+ assert_eq!(cues.len(), 1);
+ assert_eq!(cues[0].start_ms, 3000);
+ assert_eq!(cues[0].end_ms, 4500);
+ assert_eq!(cues[0].text, "Bold text");
+ }
}
diff --git a/src-tauri/omniget-core/src/core/ytdlp.rs b/src-tauri/omniget-core/src/core/ytdlp.rs
index aa66edcd..69e36dde 100644
--- a/src-tauri/omniget-core/src/core/ytdlp.rs
+++ b/src-tauri/omniget-core/src/core/ytdlp.rs
@@ -11,6 +11,7 @@ use tokio_util::sync::CancellationToken;
use crate::core::log_hook;
use crate::models::media::{DownloadResult, FormatInfo};
+use crate::models::progress::ProgressUpdate;
type ExtCookiePathFn = Box<dyn Fn() -> PathBuf + Send + Sync>;
type GlobalCookieFileFn = Box<dyn Fn() -> Option<String> + Send + Sync>;
@@ -665,6 +666,65 @@ pub async fn ensure_ytdlp() -> anyhow::Result<PathBuf> {
Ok(path)
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum YtdlpChannel {
+ Stable,
+ Nightly,
+}
+
+fn ytdlp_channel() -> YtdlpChannel {
+ match std::env::var("OMNIGET_YTDLP_CHANNEL") {
+ Ok(v) if v.trim().eq_ignore_ascii_case("nightly") => YtdlpChannel::Nightly,
+ _ => YtdlpChannel::Stable,
+ }
+}
+
+fn ytdlp_asset_name() -> &'static str {
+ if cfg!(target_os = "windows") {
+ "yt-dlp.exe"
+ } else if cfg!(target_os = "macos") {
+ "yt-dlp_macos"
+ } else if cfg!(target_arch = "aarch64") {
+ "yt-dlp_linux_aarch64"
+ } else {
+ "yt-dlp"
+ }
+}
+
+fn ytdlp_release_base(channel: YtdlpChannel) -> &'static str {
+ match channel {
+ YtdlpChannel::Stable => "https://github.com/yt-dlp/yt-dlp/releases/latest/download",
+ YtdlpChannel::Nightly => {
+ "https://github.com/yt-dlp/yt-dlp-nightly-builds/releases/latest/download"
+ }
+ }
+}
+
+/// Finds the expected sha256 (lowercased hex) for `asset` in a yt-dlp
+/// `SHA2-256SUMS` file. Lines are `"<64-hex> <filename>"`.
+fn parse_sha256sums(text: &str, asset: &str) -> Option<String> {
+ for line in text.lines() {
+ let mut parts = line.split_whitespace();
+ let hash = parts.next()?;
+ let name = parts.next()?;
+ if name == asset && hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()) {
+ return Some(hash.to_lowercase());
+ }
+ }
+ None
+}
+
+fn sha256_hex(bytes: &[u8]) -> String {
+ use sha2::{Digest, Sha256};
+ let mut hasher = Sha256::new();
+ hasher.update(bytes);
+ hasher
+ .finalize()
+ .iter()
+ .map(|b| format!("{:02x}", b))
+ .collect()
+}
+
async fn download_ytdlp_binary() -> anyhow::Result<PathBuf> {
let target =
managed_ytdlp_path().ok_or_else(|| anyhow!("Could not determine data directory"))?;
@@ -673,21 +733,17 @@ async fn download_ytdlp_binary() -> anyhow::Result<PathBuf> {
std::fs::create_dir_all(parent)?;
}
- let download_url = if cfg!(target_os = "windows") {
- "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe"
- } else if cfg!(target_os = "macos") {
- "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos"
- } else if cfg!(target_arch = "aarch64") {
- "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_aarch64"
- } else {
- "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp"
- };
+ let channel = ytdlp_channel();
+ let asset = ytdlp_asset_name();
+ let base = ytdlp_release_base(channel);
+ let download_url = format!("{}/{}", base, asset);
+ let sums_url = format!("{}/SHA2-256SUMS", base);
let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
.timeout(std::time::Duration::from_secs(120))
.build()?;
- let response = client.get(download_url).send().await?;
+ let response = client.get(&download_url).send().await?;
if !response.status().is_success() {
return Err(anyhow!(
@@ -697,6 +753,34 @@ async fn download_ytdlp_binary() -> anyhow::Result<PathBuf> {
}
let bytes = response.bytes().await?;
+
+ // Verify against the release's published checksums. Fail closed on a
+ // mismatch; fail open only when the sums file itself can't be fetched, so
+ // a transient GitHub hiccup doesn't block downloads entirely.
+ match client.get(&sums_url).send().await {
+ Ok(r) if r.status().is_success() => {
+ let sums = r.text().await.unwrap_or_default();
+ match parse_sha256sums(&sums, asset) {
+ Some(expected) => {
+ let actual = sha256_hex(&bytes);
+ if actual != expected {
+ return Err(anyhow!(
+ "yt-dlp checksum mismatch (expected {}, got {}) — refusing to install",
+ expected,
+ actual
+ ));
+ }
+ tracing::info!("[ytdlp] sha256 verified ({:?} channel)", channel);
+ }
+ None => tracing::warn!(
+ "[ytdlp] {} not listed in SHA2-256SUMS — skipping verification",
+ asset
+ ),
+ }
+ }
+ _ => tracing::warn!("[ytdlp] could not fetch SHA2-256SUMS — skipping verification"),
+ }
+
let target_clone = target.clone();
tokio::task::spawn_blocking(move || std::fs::write(&target_clone, &bytes))
.await
@@ -1224,6 +1308,10 @@ pub async fn get_playlist_info(
}
let stdout = String::from_utf8_lossy(&output.stdout);
+ Ok(parse_playlist_dump(&stdout))
+}
+
+fn parse_playlist_dump(stdout: &str) -> (String, Vec<PlaylistEntry>) {
let mut entries = Vec::new();
let mut playlist_title = String::new();
@@ -1269,7 +1357,7 @@ pub async fn get_playlist_info(
}
}
- Ok((playlist_title, entries))
+ (playlist_title, entries)
}
pub struct PlaylistEntry {
@@ -1279,6 +1367,128 @@ pub struct PlaylistEntry {
pub duration: Option<f64>,
}
+/// yt-dlp `--download-archive` line prefix for a channel URL, or `None` when
+/// the platform's archive id format is not known well enough to rely on
+/// `--break-on-existing`. Callers that get `None` should fall back to a full
+/// (non-incremental) listing and dedupe in their own seen-set.
+pub fn archive_extractor_prefix(url: &str) -> Option<&'static str> {
+ let host = url::Url::parse(url)
+ .ok()
+ .and_then(|u| u.host_str().map(|h| h.to_lowercase()))?;
+ if host.contains("youtube.com") || host.contains("youtu.be") {
+ Some("youtube")
+ } else {
+ // Other platforms' archive id formats are not stable enough across
+ // yt-dlp versions to rely on --break-on-existing; callers fall back to
+ // a full listing + seen-set dedupe, which stays correct either way.
+ None
+ }
+}
+
+/// Incremental playlist listing for channel polling. Writes a temporary
+/// yt-dlp archive built from `seen_ids` and passes `--break-on-existing` so
+/// yt-dlp stops enumerating as soon as it reaches a video that was already
+/// seen. Tolerates the non-zero exit yt-dlp returns when it breaks early and
+/// still parses whatever entries were emitted before the stop.
+pub async fn get_playlist_info_incremental(
+ ytdlp: &Path,
+ url: &str,
+ seen_ids: &[String],
+ extractor_prefix: &str,
+ playlist_end: u32,
+) -> anyhow::Result<(String, Vec<PlaylistEntry>)> {
+ if is_youtube_url(url) {
+ yt_rate_limiter().acquire().await;
+ }
+
+ let archive_path = std::env::temp_dir().join(format!(
+ "omniget-chan-archive-{}.txt",
+ std::process::id()
+ ));
+ {
+ let mut content = String::with_capacity(seen_ids.len() * 24);
+ for id in seen_ids {
+ if !id.is_empty() {
+ content.push_str(extractor_prefix);
+ content.push(' ');
+ content.push_str(id);
+ content.push('\n');
+ }
+ }
+ std::fs::write(&archive_path, content)?;
+ }
+
+ let mut args = vec![
+ "--flat-playlist".to_string(),
+ "--dump-json".to_string(),
+ "--no-warnings".to_string(),
+ "--encoding".to_string(),
+ "utf-8".to_string(),
+ "--socket-timeout".to_string(),
+ "30".to_string(),
+ "--retries".to_string(),
+ "3".to_string(),
+ "--extractor-retries".to_string(),
+ "3".to_string(),
+ "--user-agent".to_string(),
+ CHROME_UA.to_string(),
+ "--lazy-playlist".to_string(),
+ "--break-on-existing".to_string(),
+ "--download-archive".to_string(),
+ archive_path.to_string_lossy().to_string(),
+ "--playlist-end".to_string(),
+ playlist_end.to_string(),
+ ];
+ args.extend(js_runtime_args());
+ if is_youtube_url(url) {
+ args.push("--extractor-args".to_string());
+ args.push("youtube:player_client=default".to_string());
+ }
+ args.extend(proxy_args());
+ args.push(url.to_string());
+
+ let output = tokio::time::timeout(
+ std::time::Duration::from_secs(120),
+ crate::core::process::command(ytdlp)
+ .args(&args)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output(),
+ )
+ .await;
+
+ let _ = std::fs::remove_file(&archive_path);
+
+ let output = output
+ .map_err(|_| anyhow!("Timeout fetching playlist (120s)"))?
+ .map_err(|e| anyhow!("Failed to run yt-dlp: {}", e))?;
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let (title, entries) = parse_playlist_dump(&stdout);
+
+ if !output.status.success() && entries.is_empty() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let stderr_lower = stderr.to_lowercase();
+ // An empty result with a clean "stopped due to --break-on-existing"
+ // is the normal "no new videos" case, not a failure.
+ if stderr_lower.contains("--break-on-existing")
+ || stderr_lower.contains("already been recorded")
+ || stderr_lower.contains("stopping further")
+ {
+ return Ok((title, entries));
+ }
+ if stderr_lower.contains("http error 429") {
+ rate_limit_429_increment();
+ }
+ return Err(anyhow!(
+ "yt-dlp playlist failed: {}",
+ extract_error_message(&stderr)
+ ));
+ }
+
+ Ok((title, entries))
+}
+
fn parse_destination_line(line: &str) -> Option<String> {
let line = line.trim();
@@ -1321,7 +1531,7 @@ pub async fn download_video(
url: &str,
output_dir: &Path,
quality_height: Option<u32>,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
download_mode: Option<&str>,
format_id: Option<&str>,
filename_template: Option<&str>,
@@ -1339,7 +1549,7 @@ pub async fn download_video(
yt_rate_limiter().acquire().await;
}
- let _ = progress.send(-1.0).await;
+ let _ = progress.send(ProgressUpdate::percent(-1.0)).await;
let mode = download_mode.unwrap_or("auto");
let is_audio_only = mode == "audio";
@@ -1630,7 +1840,7 @@ pub async fn download_video(
"--no-playlist".to_string(),
"--newline".to_string(),
"--progress-template".to_string(),
- "download:%(progress._percent_str)s|eta:%(progress.eta)s".to_string(),
+ "download:%(progress._percent_str)s|eta:%(progress.eta)s|spd:%(progress.speed)s|dl:%(progress.downloaded_bytes)s|tot:%(progress.total_bytes)s|est:%(progress.total_bytes_estimate)s".to_string(),
"-o".to_string(),
output_template,
"--skip-unavailable-fragments".to_string(),
@@ -1793,7 +2003,7 @@ pub async fn download_video(
attempt + 1
);
- let _ = progress.send(-2.0).await;
+ let _ = progress.send(ProgressUpdate::percent(-2.0)).await;
let stdout = child.stdout.take().ok_or_else(|| anyhow!("No stdout"))?;
let stderr_pipe = child.stderr.take().ok_or_else(|| anyhow!("No stderr"))?;
@@ -1852,7 +2062,7 @@ pub async fn download_video(
if line.contains("[Merger]") {
if 99.0 > max_reported {
max_reported = 99.0;
- let _ = progress_tx.send(99.0).await;
+ let _ = progress_tx.send(ProgressUpdate::percent(99.0)).await;
last_send = std::time::Instant::now();
}
continue;
@@ -1865,14 +2075,18 @@ pub async fn download_video(
_timer_start.elapsed()
);
}
- if let Some(id) = log_id {
- if let Some(eta) = parse_eta_line(&line) {
- record_eta(id, eta);
- }
+ let eta = parse_eta_line(&line);
+ let speed = parse_speed_line(&line);
+ if let (Some(id), Some(e)) = (log_id, eta) {
+ record_eta(id, e);
}
if is_audio_only {
if pct >= 99.0 || last_send.elapsed() >= throttle {
- let _ = progress_tx.send(pct).await;
+ let dl = parse_downloaded_bytes_line(&line);
+ let tot = parse_total_bytes_line(&line);
+ let _ = progress_tx
+ .send(ProgressUpdate::rich(pct, dl, tot, speed, eta))
+ .await;
last_send = std::time::Instant::now();
}
} else {
@@ -1885,10 +2099,27 @@ pub async fn download_video(
&& (adjusted >= 99.0 || last_send.elapsed() >= throttle)
{
max_reported = adjusted;
- let _ = progress_tx.send(adjusted).await;
+ let _ = progress_tx
+ .send(ProgressUpdate::rich(adjusted, None, None, speed, eta))
+ .await;
last_send = std::time::Instant::now();
}
}
+ } else if line.trim_start().starts_with("download:")
+ || line.contains("[download]")
+ {
+ let dl = parse_downloaded_bytes_line(&line)
+ .or_else(|| parse_default_download_line(&line).map(|(d, _)| d as u64));
+ let speed = parse_speed_line(&line)
+ .or_else(|| parse_default_download_line(&line).map(|(_, s)| s));
+ if (dl.is_some() || speed.is_some())
+ && last_send.elapsed() >= throttle
+ {
+ let _ = progress_tx
+ .send(ProgressUpdate::rich(0.0, dl, None, speed, None))
+ .await;
+ last_send = std::time::Instant::now();
+ }
}
}
});
@@ -1924,7 +2155,7 @@ pub async fn download_video(
let stderr_content = stderr_reader.await.unwrap_or_default();
if status.success() {
- let _ = progress.send(100.0).await;
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
let file_path = {
let guard = captured_path.lock().unwrap();
@@ -2340,21 +2571,85 @@ fn parse_aria2c_progress(line: &str) -> Option<f64> {
after[..close].trim().parse::<f64>().ok()
}
-fn parse_eta_line(line: &str) -> Option<u64> {
+fn template_field<'a>(line: &'a str, key: &str) -> Option<&'a str> {
let body = line.trim().strip_prefix("download:")?;
for part in body.split('|') {
let part = part.trim();
- if let Some(rest) = part.strip_prefix("eta:") {
+ if let Some(rest) = part.strip_prefix(key) {
let rest = rest.trim();
if rest.is_empty() || rest.eq_ignore_ascii_case("na") {
return None;
}
- return rest.parse::<u64>().ok();
+ return Some(rest);
}
}
None
}
+fn parse_eta_line(line: &str) -> Option<u64> {
+ let raw = template_field(line, "eta:")?;
+ raw.parse::<u64>()
+ .ok()
+ .or_else(|| raw.parse::<f64>().ok().map(|f| f.max(0.0) as u64))
+}
+
+fn parse_speed_line(line: &str) -> Option<f64> {
+ let raw = template_field(line, "spd:")?;
+ raw.parse::<f64>().ok().filter(|s| *s > 0.0)
+}
+
+fn parse_total_bytes_line(line: &str) -> Option<u64> {
+ template_field(line, "tot:")
+ .and_then(|v| v.parse::<f64>().ok())
+ .or_else(|| template_field(line, "est:").and_then(|v| v.parse::<f64>().ok()))
+ .filter(|v| *v > 0.0)
+ .map(|v| v as u64)
+}
+
+fn parse_downloaded_bytes_line(line: &str) -> Option<u64> {
+ template_field(line, "dl:")
+ .and_then(|v| v.parse::<f64>().ok())
+ .filter(|v| *v >= 0.0)
+ .map(|v| v as u64)
+}
+
+fn parse_size_token(token: &str) -> Option<f64> {
+ let t = token.trim().trim_end_matches("/s").trim();
+ let split = t
+ .find(|c: char| c.is_ascii_alphabetic())
+ .unwrap_or(t.len());
+ let (num, unit) = t.split_at(split);
+ let value: f64 = num.trim().parse().ok()?;
+ let mult = match unit.trim() {
+ "" | "B" => 1.0,
+ "KiB" => 1024.0,
+ "MiB" => 1024.0 * 1024.0,
+ "GiB" => 1024.0 * 1024.0 * 1024.0,
+ "TiB" => 1024.0 * 1024.0 * 1024.0 * 1024.0,
+ "KB" | "kB" | "K" => 1000.0,
+ "MB" | "M" => 1_000_000.0,
+ "GB" | "G" => 1_000_000_000.0,
+ "TB" | "T" => 1_000_000_000_000.0,
+ _ => return None,
+ };
+ Some(value * mult)
+}
+
+/// Parse the default (non-template) yt-dlp download line used for live /
+/// size-unknown streams, e.g. `[download] 2.87MiB at 506.63KiB/s (00:00:07)`.
+/// Returns (downloaded_bytes, speed_bytes_per_sec).
+fn parse_default_download_line(line: &str) -> Option<(f64, f64)> {
+ let body = line.split("[download]").nth(1)?.trim();
+ if body.contains('%') {
+ return None;
+ }
+ let (size_part, rest) = body.split_once(" at ")?;
+ let size = parse_size_token(size_part.trim())?;
+ let speed_token = rest.trim().split_whitespace().next()?;
+ let speed = parse_size_token(speed_token)?;
+ Some((size, speed))
+}
+
async fn find_downloaded_file(output_dir: &Path, url: &str) -> anyhow::Result<PathBuf> {
let video_id = extract_id_from_url(url).unwrap_or_default();
let media_extensions: &[&str] = &[
@@ -2581,6 +2876,108 @@ mod tests {
assert_eq!(parse_progress_line("download:100%"), Some(100.0));
}
+ #[test]
+ fn sha256sums_parsing() {
+ let sums = "abc not-ours\n\
+e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 yt-dlp.exe\n\
+1111111111111111111111111111111111111111111111111111111111111111 yt-dlp_macos\n";
+ assert_eq!(
+ parse_sha256sums(sums, "yt-dlp.exe").as_deref(),
+ Some("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
+ );
+ assert_eq!(
+ parse_sha256sums(sums, "yt-dlp_macos").as_deref(),
+ Some("1111111111111111111111111111111111111111111111111111111111111111")
+ );
+ assert_eq!(parse_sha256sums(sums, "yt-dlp_missing"), None);
+ assert_eq!(parse_sha256sums("garbage line", "yt-dlp"), None);
+ }
+
+ #[test]
+ fn sha256_hex_known_vector() {
+ // SHA-256 of the empty input.
+ assert_eq!(
+ sha256_hex(b""),
+ "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ );
+ }
+
+ #[test]
+ fn ytdlp_release_base_per_channel() {
+ assert!(ytdlp_release_base(YtdlpChannel::Stable).contains("yt-dlp/yt-dlp/releases"));
+ assert!(ytdlp_release_base(YtdlpChannel::Nightly).contains("yt-dlp-nightly-builds"));
+ }
+
+ #[test]
+ fn archive_prefix_youtube_only() {
+ assert_eq!(
+ archive_extractor_prefix("https://www.youtube.com/@chan/videos"),
+ Some("youtube")
+ );
+ assert_eq!(
+ archive_extractor_prefix("https://youtu.be/abc"),
+ Some("youtube")
+ );
+ assert_eq!(
+ archive_extractor_prefix("https://space.bilibili.com/123"),
+ None
+ );
+ assert_eq!(archive_extractor_prefix("not a url"), None);
+ }
+
+ #[test]
+ fn parse_speed_from_template() {
+ let line = "download: 45.2%|eta:30|spd:1572864.0|dl:5242880|tot:11534336|est:NA";
+ assert_eq!(parse_speed_line(line), Some(1572864.0));
+ assert_eq!(parse_downloaded_bytes_line(line), Some(5242880));
+ assert_eq!(parse_total_bytes_line(line), Some(11534336));
+ assert_eq!(parse_eta_line(line), Some(30));
+ }
+
+ #[test]
+ fn parse_total_falls_back_to_estimate() {
+ let line = "download: 10.0%|eta:NA|spd:NA|dl:1000|tot:NA|est:9999.0";
+ assert_eq!(parse_total_bytes_line(line), Some(9999));
+ assert_eq!(parse_speed_line(line), None);
+ }
+
+ #[test]
+ fn live_template_line_has_no_numeric_percent() {
+ let line = "download: N/A%|eta:NA|spd:518542.0|dl:3010560|tot:NA|est:NA";
+ assert_eq!(parse_progress_line(line), None);
+ assert_eq!(parse_downloaded_bytes_line(line), Some(3010560));
+ assert_eq!(parse_speed_line(line), Some(518542.0));
+ }
+
+ #[test]
+ fn parse_size_token_units() {
+ assert_eq!(parse_size_token("1B"), Some(1.0));
+ assert_eq!(parse_size_token("2KiB"), Some(2048.0));
+ assert_eq!(parse_size_token("2.87MiB"), Some(2.87 * 1024.0 * 1024.0));
+ assert_eq!(parse_size_token("506.63KiB/s"), Some(506.63 * 1024.0));
+ assert_eq!(parse_size_token("garbage"), None);
+ }
+
+ #[test]
+ fn parse_default_live_download_line() {
+ let line = "[download] 2.87MiB at 506.63KiB/s (00:00:07) (frag 91/2097)";
+ let (dl, spd) = parse_default_download_line(line).unwrap();
+ assert!((dl - 2.87 * 1024.0 * 1024.0).abs() < 1.0);
+ assert!((spd - 506.63 * 1024.0).abs() < 1.0);
+ }
+
+ #[test]
+ fn parse_default_download_line_ignores_percent_and_destination() {
+ assert_eq!(
+ parse_default_download_line("[download] 45.2% of 10.00MiB at 1.00MiB/s"),
+ None
+ );
+ assert_eq!(
+ parse_default_download_line("[download] Destination: video.mp4"),
+ None
+ );
+ }
+
#[test]
fn parse_progress_with_eta_field() {
assert_eq!(parse_progress_line("download: 45.2%|eta:30"), Some(45.2));
diff --git a/src-tauri/omniget-core/src/models/mod.rs b/src-tauri/omniget-core/src/models/mod.rs
index fb97db1d..65cb06a6 100644
--- a/src-tauri/omniget-core/src/models/mod.rs
+++ b/src-tauri/omniget-core/src/models/mod.rs
@@ -1,3 +1,4 @@
pub mod download;
pub mod media;
+pub mod progress;
pub mod settings;
diff --git a/src-tauri/omniget-core/src/models/progress.rs b/src-tauri/omniget-core/src/models/progress.rs
new file mode 100644
index 00000000..25420c07
--- /dev/null
+++ b/src-tauri/omniget-core/src/models/progress.rs
@@ -0,0 +1,43 @@
+#[derive(Debug, Clone, Default)]
+pub struct ProgressUpdate {
+ pub percent: f64,
+ pub downloaded_bytes: Option<u64>,
+ pub total_bytes: Option<u64>,
+ pub speed_bps: Option<f64>,
+ pub eta_seconds: Option<u64>,
+}
+
+impl ProgressUpdate {
+ pub fn percent(percent: f64) -> Self {
+ Self {
+ percent,
+ ..Default::default()
+ }
+ }
+
+ pub fn rich(
+ percent: f64,
+ downloaded_bytes: Option<u64>,
+ total_bytes: Option<u64>,
+ speed_bps: Option<f64>,
+ eta_seconds: Option<u64>,
+ ) -> Self {
+ Self {
+ percent,
+ downloaded_bytes,
+ total_bytes,
+ speed_bps,
+ eta_seconds,
+ }
+ }
+
+ pub fn has_real_metrics(&self) -> bool {
+ self.downloaded_bytes.is_some() || self.speed_bps.is_some() || self.eta_seconds.is_some()
+ }
+}
+
+impl From<f64> for ProgressUpdate {
+ fn from(percent: f64) -> Self {
+ Self::percent(percent)
+ }
+}
diff --git a/src-tauri/omniget-core/src/models/settings.rs b/src-tauri/omniget-core/src/models/settings.rs
index f1c8236e..035edac8 100644
--- a/src-tauri/omniget-core/src/models/settings.rs
+++ b/src-tauri/omniget-core/src/models/settings.rs
@@ -143,6 +143,82 @@ pub struct DownloadSettings {
pub always_use_managed_cookies: bool,
#[serde(default)]
pub continuous_lecture_numbers: bool,
+ #[serde(default)]
+ pub bilibili_danmaku_enabled: bool,
+ #[serde(default = "default_bilibili_danmaku_format")]
+ pub bilibili_danmaku_format: String,
+ #[serde(default = "default_bilibili_container")]
+ pub bilibili_container: String,
+ #[serde(default)]
+ pub bilibili_nfo_enabled: bool,
+ #[serde(default)]
+ pub bilibili_cover_sidecar: bool,
+ #[serde(default = "default_bilibili_cover_format")]
+ pub bilibili_cover_format: String,
+ #[serde(default = "default_bilibili_naming_video")]
+ pub bilibili_naming_video: String,
+ #[serde(default = "default_bilibili_naming_multi_part")]
+ pub bilibili_naming_multi_part: String,
+ #[serde(default = "default_bilibili_naming_bangumi")]
+ pub bilibili_naming_bangumi: String,
+ #[serde(default = "default_bilibili_naming_cheese")]
+ pub bilibili_naming_cheese: String,
+ #[serde(default = "default_bilibili_naming_collection")]
+ pub bilibili_naming_collection: String,
+ #[serde(default)]
+ pub bilibili_cdn_hosts: String,
+ #[serde(default)]
+ pub bilibili_cdn_prefer_alternatives: bool,
+ #[serde(default = "default_bilibili_preferred_qn")]
+ pub bilibili_preferred_qn: u32,
+ #[serde(default = "default_bilibili_preferred_codec")]
+ pub bilibili_preferred_codec: u32,
+ #[serde(default = "default_bilibili_preferred_audio_qn")]
+ pub bilibili_preferred_audio_qn: u32,
+}
+
+fn default_bilibili_preferred_qn() -> u32 {
+ 200
+}
+
+fn default_bilibili_preferred_codec() -> u32 {
+ 20
+}
+
+fn default_bilibili_preferred_audio_qn() -> u32 {
+ 30300
+}
+
+fn default_bilibili_cover_format() -> String {
+ "jpg".to_string()
+}
+
+fn default_bilibili_naming_video() -> String {
+ "{title}".to_string()
+}
+
+fn default_bilibili_naming_multi_part() -> String {
+ "{parent_title}/P{page} - {leaf_title}".to_string()
+}
+
+fn default_bilibili_naming_bangumi() -> String {
+ "{series_title}/Season {season_number}/{episode_number_pad2} - {episode_title}".to_string()
+}
+
+fn default_bilibili_naming_cheese() -> String {
+ "{series_title}/{section_title}/{episode_number_pad2} - {episode_title}".to_string()
+}
+
+fn default_bilibili_naming_collection() -> String {
+ "{collection_title}/{title}".to_string()
+}
+
+fn default_bilibili_danmaku_format() -> String {
+ "xml".to_string()
+}
+
+fn default_bilibili_container() -> String {
+ "mp4".to_string()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -410,6 +486,22 @@ impl Default for AppSettings {
cookie_file: String::new(),
always_use_managed_cookies: true,
continuous_lecture_numbers: false,
+ bilibili_danmaku_enabled: false,
+ bilibili_danmaku_format: "xml".into(),
+ bilibili_container: "mp4".into(),
+ bilibili_nfo_enabled: false,
+ bilibili_cover_sidecar: false,
+ bilibili_cover_format: "jpg".into(),
+ bilibili_naming_video: default_bilibili_naming_video(),
+ bilibili_naming_multi_part: default_bilibili_naming_multi_part(),
+ bilibili_naming_bangumi: default_bilibili_naming_bangumi(),
+ bilibili_naming_cheese: default_bilibili_naming_cheese(),
+ bilibili_naming_collection: default_bilibili_naming_collection(),
+ bilibili_cdn_hosts: String::new(),
+ bilibili_cdn_prefer_alternatives: false,
+ bilibili_preferred_qn: default_bilibili_preferred_qn(),
+ bilibili_preferred_codec: default_bilibili_preferred_codec(),
+ bilibili_preferred_audio_qn: default_bilibili_preferred_audio_qn(),
},
advanced: AdvancedSettings {
max_concurrent_segments: 20,
diff --git a/src-tauri/omniget-core/src/platforms/traits.rs b/src-tauri/omniget-core/src/platforms/traits.rs
index 62b0d3ef..8dc81cb3 100644
--- a/src-tauri/omniget-core/src/platforms/traits.rs
+++ b/src-tauri/omniget-core/src/platforms/traits.rs
@@ -1,6 +1,7 @@
use async_trait::async_trait;
use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo};
+pub use crate::models::progress::ProgressUpdate;
#[async_trait]
pub trait PlatformDownloader: Send + Sync {
@@ -11,6 +12,6 @@ pub trait PlatformDownloader: Send + Sync {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: tokio::sync::mpsc::Sender<f64>,
+ progress: tokio::sync::mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult>;
}
diff --git a/src-tauri/src/commands/bilibili_auth.rs b/src-tauri/src/commands/bilibili_auth.rs
new file mode 100644
index 00000000..65505cd8
--- /dev/null
+++ b/src-tauri/src/commands/bilibili_auth.rs
@@ -0,0 +1,355 @@
+use serde::{Deserialize, Serialize};
+
+use crate::platforms::bilibili::api::ApiClient;
+use crate::platforms::bilibili::auth::{self, qr, sms};
+use crate::platforms::bilibili::parser;
+use crate::platforms::bilibili::preview;
+use crate::platforms::bilibili::url_kind::{self, UrlKind};
+
+fn build_anonymous_client(user_agent: Option<String>) -> Result<ApiClient, String> {
+ let mut client = ApiClient::new().map_err(|e| e.i18n_key().to_string())?;
+ if let Some(ua) = user_agent.filter(|s| !s.is_empty()) {
+ client = client.with_user_agent(ua);
+ }
+ let _ = crate::platforms::bilibili::cookie::ensure_fresh();
+ client = client.with_anonymous_cookies();
+ Ok(client)
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BilibiliWebviewLoginResult {
+ pub slug: String,
+ pub uname: String,
+ pub mid: u64,
+ pub is_vip: bool,
+}
+
+#[tauri::command]
+pub async fn bilibili_webview_login(
+ app: tauri::AppHandle,
+) -> Result<BilibiliWebviewLoginResult, String> {
+ use crate::commands::auth_webview::{open_auth_webview, AuthWebviewRequest};
+
+ let request = AuthWebviewRequest {
+ url: "https://passport.bilibili.com/login".to_string(),
+ title: "Sign in to Bilibili".to_string(),
+ cookie_domains: vec![
+ ".bilibili.com".to_string(),
+ "passport.bilibili.com".to_string(),
+ "www.bilibili.com".to_string(),
+ ],
+ success_url_contains: None,
+ wait_for_cookie: Some("SESSDATA".to_string()),
+ initialization_script: None,
+ width: Some(480.0),
+ height: Some(720.0),
+ };
+
+ let result = open_auth_webview(app, request)
+ .await
+ .map_err(|e| format!("errors.bilibili.network_failed: {}", e))?;
+
+ let mut cookies: Vec<(String, String)> = Vec::new();
+ for c in result.cookies {
+ if matches!(
+ c.name.as_str(),
+ "SESSDATA" | "bili_jct" | "DedeUserID" | "DedeUserID__ckMd5" | "sid"
+ ) {
+ cookies.push((c.name, c.value));
+ }
+ }
+ if cookies.is_empty() {
+ return Err("errors.bilibili.not_logged_in".to_string());
+ }
+
+ let cookie_header = cookies
+ .iter()
+ .map(|(k, v)| format!("{}={}", k, v))
+ .collect::<Vec<_>>()
+ .join("; ");
+ let probe = ApiClient::new()
+ .map_err(|e| e.i18n_key().to_string())?
+ .with_raw_cookies(cookie_header);
+ let info = auth::fetch_account_info(&probe)
+ .await
+ .map_err(|e| e.i18n_key().to_string())?;
+ let slug = auth::persist_account(&cookies, &info.uname, "Webview login")
+ .map_err(|_| "errors.bilibili.content_unavailable".to_string())?;
+ Ok(BilibiliWebviewLoginResult {
+ slug,
+ uname: info.uname,
+ mid: info.mid,
+ is_vip: info.is_vip,
+ })
+}
+
+#[tauri::command]
+pub async fn bilibili_qr_generate(
+ user_agent: Option<String>,
+) -> Result<qr::QrSession, String> {
+ let _ = crate::platforms::bilibili::cookie::ensure_fresh().await;
+ let client = build_anonymous_client(user_agent)?;
+ qr::generate(&client)
+ .await
+ .map_err(|e| e.i18n_key().to_string())
+}
+
+#[tauri::command]
+pub async fn bilibili_qr_poll(
+ qrcode_key: String,
+ user_agent: Option<String>,
+) -> Result<qr::QrPollStatus, String> {
+ let client = build_anonymous_client(user_agent)?;
+ qr::poll(&client, &qrcode_key)
+ .await
+ .map_err(|e| e.i18n_key().to_string())
+}
+
+#[tauri::command]
+pub async fn bilibili_captcha_challenge(
+ user_agent: Option<String>,
+) -> Result<auth::captcha::CaptchaChallenge, String> {
+ let client = build_anonymous_client(user_agent)?;
+ auth::captcha::request_challenge(&client)
+ .await
+ .map_err(|e| e.i18n_key().to_string())
+}
+
+#[tauri::command]
+pub async fn bilibili_sms_send(
+ input: sms::SmsSendInput,
+ user_agent: Option<String>,
+) -> Result<sms::SmsSendResult, String> {
+ let client = build_anonymous_client(user_agent)?;
+ sms::send(&client, input)
+ .await
+ .map_err(|e| e.i18n_key().to_string())
+}
+
+#[tauri::command]
+pub async fn bilibili_sms_verify(
+ input: sms::SmsVerifyInput,
+ user_agent: Option<String>,
+) -> Result<sms::SmsVerifyResult, String> {
+ let client = build_anonymous_client(user_agent)?;
+ sms::verify(&client, input)
+ .await
+ .map_err(|e| e.i18n_key().to_string())
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BilibiliAccountStatus {
+ pub logged_in: bool,
+ pub slug: Option<String>,
+ pub uname: Option<String>,
+ pub mid: Option<u64>,
+ pub is_vip: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BilibiliCodecOption {
+ pub codec_id: u32,
+ pub label_key: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BilibiliQualityOption {
+ pub qn: u32,
+ pub label_key: String,
+ pub codecs: Vec<BilibiliCodecOption>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BilibiliAudioOption {
+ pub qn: u32,
+ pub label_key: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BilibiliPreviewSummary {
+ pub kind_label_key: String,
+ pub item_title: String,
+ pub item_count: u32,
+ pub qualities: Vec<BilibiliQualityOption>,
+ pub audios: Vec<BilibiliAudioOption>,
+ pub premium_required: bool,
+}
+
+#[tauri::command]
+pub async fn bilibili_preview_info(
+ url: String,
+ slug: Option<String>,
+) -> Result<BilibiliPreviewSummary, String> {
+ let _ = crate::platforms::bilibili::cookie::ensure_fresh().await;
+ let mut client = ApiClient::new().map_err(|e| e.i18n_key().to_string())?;
+ client = match slug.as_deref() {
+ Some(s) if !s.is_empty() => client.with_account(s),
+ _ => client.with_anonymous_cookies(),
+ };
+
+ let mut effective_url = url.clone();
+ if url_kind::is_b23_short(&effective_url) {
+ if let Ok(resolved) = url_kind::resolve_b23(&client, &effective_url).await {
+ effective_url = resolved;
+ }
+ }
+ let kind = url_kind::detect(&effective_url).map_err(|e| e.i18n_key().to_string())?;
+ let parsed = parser::parse(&client, &kind)
+ .await
+ .map_err(|e| e.i18n_key().to_string())?;
+ let item = parsed
+ .items
+ .first()
+ .ok_or_else(|| "errors.bilibili.content_unavailable".to_string())?;
+
+ let preview_info = preview::fetch(&client, item, &kind).await.ok();
+
+ let mut qualities: Vec<BilibiliQualityOption> = Vec::new();
+ let mut audios: Vec<BilibiliAudioOption> = Vec::new();
+ let mut premium = false;
+ if let Some(info) = preview_info.as_ref() {
+ premium = info.premium_required;
+ for qn in info.available_qns() {
+ let codecs: Vec<BilibiliCodecOption> = info
+ .available_codecs_for(qn)
+ .into_iter()
+ .map(|c| BilibiliCodecOption {
+ codec_id: c,
+ label_key: preview::codec_label(c).to_string(),
+ })
+ .collect();
+ qualities.push(BilibiliQualityOption {
+ qn,
+ label_key: preview::qn_label(qn).to_string(),
+ codecs,
+ });
+ }
+ for qn in info.available_audio_qns() {
+ audios.push(BilibiliAudioOption {
+ qn,
+ label_key: preview::audio_qn_label(qn).to_string(),
+ });
+ }
+ }
+
+ Ok(BilibiliPreviewSummary {
+ kind_label_key: kind.label_key().to_string(),
+ item_title: item.title.clone(),
+ item_count: parsed.items.len() as u32,
+ qualities,
+ audios,
+ premium_required: premium,
+ })
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BilibiliImportedItem {
+ pub url: String,
+ pub title: String,
+ pub cover_url: Option<String>,
+ pub duration_seconds: Option<f64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BilibiliImportResult {
+ pub total: u32,
+ pub items: Vec<BilibiliImportedItem>,
+}
+
+async fn run_import(slug: String, kind: UrlKind) -> Result<BilibiliImportResult, String> {
+ let _ = crate::platforms::bilibili::cookie::ensure_fresh().await;
+ let client = ApiClient::new()
+ .map_err(|e| e.i18n_key().to_string())?
+ .with_account(&slug);
+ let mut all_items: Vec<BilibiliImportedItem> = Vec::new();
+ let mut total: u32 = 0;
+ let mut current_page: u32 = 1;
+ loop {
+ let kind_ref = match &kind {
+ UrlKind::WatchLater => UrlKind::WatchLater,
+ UrlKind::History => UrlKind::History,
+ other => other.clone(),
+ };
+ let parsed = match kind_ref {
+ UrlKind::WatchLater => {
+ crate::platforms::bilibili::parser::watch_later::parse(&client, current_page).await
+ }
+ UrlKind::History => {
+ crate::platforms::bilibili::parser::history::parse(&client, current_page).await
+ }
+ _ => return Err("errors.bilibili.content_unavailable".to_string()),
+ }
+ .map_err(|e| e.i18n_key().to_string())?;
+ if let Some(pg) = parsed.pagination.as_ref() {
+ total = pg.total_items;
+ }
+ for it in &parsed.items {
+ if let Some(url) = it.url.clone() {
+ all_items.push(BilibiliImportedItem {
+ url,
+ title: it.title.clone(),
+ cover_url: it.cover_url.clone(),
+ duration_seconds: it.duration_seconds,
+ });
+ }
+ }
+ match parsed.pagination {
+ Some(pg) if current_page < pg.total_pages && current_page < 50 => {
+ current_page += 1;
+ }
+ _ => break,
+ }
+ }
+ if total == 0 {
+ total = all_items.len() as u32;
+ }
+ Ok(BilibiliImportResult {
+ total,
+ items: all_items,
+ })
+}
+
+#[tauri::command]
+pub async fn bilibili_import_watch_later(slug: String) -> Result<BilibiliImportResult, String> {
+ let _ = parser::watch_later::parse;
+ run_import(slug, UrlKind::WatchLater).await
+}
+
+#[tauri::command]
+pub async fn bilibili_import_history(slug: String) -> Result<BilibiliImportResult, String> {
+ run_import(slug, UrlKind::History).await
+}
+
+#[tauri::command]
+pub async fn bilibili_account_status(slug: Option<String>) -> Result<BilibiliAccountStatus, String> {
+ let client = match slug.as_deref() {
+ Some(s) if !s.is_empty() => ApiClient::new()
+ .map_err(|e| e.i18n_key().to_string())?
+ .with_account(s),
+ _ => {
+ return Ok(BilibiliAccountStatus {
+ logged_in: false,
+ slug: None,
+ uname: None,
+ mid: None,
+ is_vip: false,
+ });
+ }
+ };
+ match auth::fetch_account_info(&client).await {
+ Ok(info) => Ok(BilibiliAccountStatus {
+ logged_in: true,
+ slug,
+ uname: Some(info.uname),
+ mid: Some(info.mid),
+ is_vip: info.is_vip,
+ }),
+ Err(_) => Ok(BilibiliAccountStatus {
+ logged_in: false,
+ slug: None,
+ uname: None,
+ mid: None,
+ is_vip: false,
+ }),
+ }
+}
diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs
index 06b8c8fd..87c24836 100644
--- a/src-tauri/src/commands/mod.rs
+++ b/src-tauri/src/commands/mod.rs
@@ -1,6 +1,7 @@
pub mod ai;
pub mod app_lifecycle;
pub mod auth_webview;
+pub mod bilibili_auth;
pub mod autostart;
pub mod browser_extension;
pub mod channels;
diff --git a/src-tauri/src/commands/subtitle_ws.rs b/src-tauri/src/commands/subtitle_ws.rs
index 4a8c52ed..005e8131 100644
--- a/src-tauri/src/commands/subtitle_ws.rs
+++ b/src-tauri/src/commands/subtitle_ws.rs
@@ -16,10 +16,10 @@ pub async fn subtitle_load(path: String) -> Result<Vec<Cue>, String> {
#[cfg(not(target_os = "android"))]
#[tauri::command]
pub async fn subtitle_save(path: String, cues: Vec<Cue>, format: String) -> Result<(), String> {
- let body = if format == "vtt" {
- subtitle_merge::cues_to_vtt(&cues)
- } else {
- subtitle_merge::cues_to_srt(&cues)
+ let body = match format.as_str() {
+ "vtt" => subtitle_merge::cues_to_vtt(&cues),
+ "ass" => subtitle_merge::cues_to_ass(&cues),
+ _ => subtitle_merge::cues_to_srt(&cues),
};
tokio::fs::write(&path, body)
.await
@@ -74,3 +74,56 @@ translated numbered lines, nothing else.",
}
Ok(result)
}
+
+#[cfg(not(target_os = "android"))]
+#[tauri::command]
+pub async fn subtitle_grammar_fix(cues: Vec<Cue>, style: String) -> Result<Vec<Cue>, String> {
+ if !omniget_core::core::ai::get().is_configured() {
+ return Err("ai_not_configured".to_string());
+ }
+ if cues.is_empty() {
+ return Ok(cues);
+ }
+ let tone = match style.as_str() {
+ "formal" => "Use a formal register.",
+ "casual" => "Use a casual, conversational register.",
+ _ => "Keep the original register and wording as close as possible.",
+ };
+ let joined: String = cues
+ .iter()
+ .enumerate()
+ .map(|(i, c)| format!("{}\u{241F}{}", i + 1, c.text.replace('\n', "\u{2424}")))
+ .collect::<Vec<_>>()
+ .join("\n");
+ let system = format!(
+ "Fix grammar, spelling and punctuation in each numbered line without \
+changing its meaning. {} Keep the exact same numbering and line count. \
+Preserve the \u{2424} markers as line breaks. Output ONLY the corrected \
+numbered lines, nothing else.",
+ tone
+ );
+ let out = omniget_core::core::ai::chat(&system, &joined).await?;
+
+ let mut map: std::collections::HashMap<usize, String> = std::collections::HashMap::new();
+ for line in out.lines() {
+ let line = line.trim();
+ if line.is_empty() {
+ continue;
+ }
+ if let Some((num, rest)) = line.split_once('\u{241F}') {
+ if let Ok(idx) = num.trim().parse::<usize>() {
+ map.insert(idx, rest.replace('\u{2424}', "\n"));
+ }
+ }
+ }
+ if map.len() != cues.len() {
+ return Err("grammar_mismatch".to_string());
+ }
+ let mut result = cues;
+ for (i, c) in result.iter_mut().enumerate() {
+ if let Some(t) = map.get(&(i + 1)) {
+ c.text = t.trim().to_string();
+ }
+ }
+ Ok(result)
+}
diff --git a/src-tauri/src/core/channel_poller.rs b/src-tauri/src/core/channel_poller.rs
index b085a6bf..72b1280c 100644
--- a/src-tauri/src/core/channel_poller.rs
+++ b/src-tauri/src/core/channel_poller.rs
@@ -42,8 +42,26 @@ fn is_due(ch: &ChannelFollow, now: u64) -> bool {
async fn poll_channel(ch: &ChannelFollow) -> Option<Vec<NewVideo>> {
let ytdlp = crate::core::ytdlp::find_ytdlp_cached().await?;
- let extra = vec!["--playlist-end".to_string(), PLAYLIST_END.to_string()];
- match crate::core::ytdlp::get_playlist_info(&ytdlp, &ch.url, &extra).await {
+
+ let playlist_end: u32 = PLAYLIST_END.parse().unwrap_or(30);
+ let listing = match crate::core::ytdlp::archive_extractor_prefix(&ch.url) {
+ Some(prefix) if !ch.seen_ids.is_empty() => {
+ crate::core::ytdlp::get_playlist_info_incremental(
+ &ytdlp,
+ &ch.url,
+ &ch.seen_ids,
+ prefix,
+ playlist_end,
+ )
+ .await
+ }
+ _ => {
+ let extra = vec!["--playlist-end".to_string(), PLAYLIST_END.to_string()];
+ crate::core::ytdlp::get_playlist_info(&ytdlp, &ch.url, &extra).await
+ }
+ };
+
+ match listing {
Ok((_title, entries)) => {
let fetched_ids: Vec<String> = entries.iter().map(|e| e.id.clone()).collect();
let new_ids = channels::record_poll(&ch.id, &fetched_ids);
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 30b43e99..641c1651 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -59,6 +59,7 @@ pub fn run() {
torrent_session.clone(),
)));
registry.register(Arc::new(platforms::p2p::P2pDownloader::new()));
+ registry.register(Arc::new(platforms::gallerydl::GalleryDlDownloader::new()));
registry.register(Arc::new(
platforms::generic_ytdlp::GenericYtdlpDownloader::new(),
));
@@ -126,6 +127,15 @@ pub fn run() {
))
.setup(|app| {
commands::host_queue::register_event_listeners(app.handle());
+ {
+ let handle = app.handle().clone();
+ platforms::bilibili::notify::set_emitter(Box::new(
+ move |event: &str, payload: serde_json::Value| {
+ use tauri::Emitter;
+ let _ = handle.emit(event, payload);
+ },
+ ));
+ }
let settings = storage::config::load_settings(app.handle());
core::http_client::init_proxy(settings.proxy.clone());
core::http_fetcher::set_global_max_concurrent_segments(
@@ -457,6 +467,16 @@ pub fn run() {
})
.invoke_handler(tauri::generate_handler![
commands::auth_webview::open_auth_webview,
+ commands::bilibili_auth::bilibili_qr_generate,
+ commands::bilibili_auth::bilibili_qr_poll,
+ commands::bilibili_auth::bilibili_captcha_challenge,
+ commands::bilibili_auth::bilibili_sms_send,
+ commands::bilibili_auth::bilibili_sms_verify,
+ commands::bilibili_auth::bilibili_account_status,
+ commands::bilibili_auth::bilibili_import_watch_later,
+ commands::bilibili_auth::bilibili_import_history,
+ commands::bilibili_auth::bilibili_preview_info,
+ commands::bilibili_auth::bilibili_webview_login,
commands::browser_extension::browser_extension_status,
commands::browser_extension::browser_extension_export,
commands::browser_extension::browser_extension_open_folder,
@@ -504,6 +524,7 @@ pub fn run() {
commands::subtitle_ws::subtitle_load,
commands::subtitle_ws::subtitle_save,
commands::subtitle_ws::subtitle_translate,
+ commands::subtitle_ws::subtitle_grammar_fix,
commands::downloads::metadata_fetch,
commands::downloads::thumbnails_list,
commands::downloads::thumbnail_save,
diff --git a/src-tauri/src/platforms/bilibili/engine/mod.rs b/src-tauri/src/platforms/bilibili/engine/mod.rs
new file mode 100644
index 00000000..82e8510d
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/engine/mod.rs
@@ -0,0 +1,458 @@
+use std::path::PathBuf;
+
+use omniget_core::models::progress::ProgressUpdate;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use super::api::{ApiClient, BilibiliError, Result};
+use super::parser::{ContentMetadata, EpisodeItem, ParsedContent};
+use super::preview::{self, AudioStream, MediaContainer, PreviewInfo, VideoStream};
+use super::url_kind::UrlKind;
+
+pub mod fetch;
+pub mod mux;
+pub mod query;
+
+pub struct EngineOptions {
+ pub output_dir: PathBuf,
+ pub container: mux::Container,
+ pub video_qn_pref: u32,
+ pub video_codec_pref: u32,
+ pub audio_qn_pref: u32,
+ pub embed_cover: bool,
+ pub keep_streams: bool,
+ pub filename: String,
+ pub cancel: CancellationToken,
+ pub danmaku_enabled: bool,
+ pub danmaku_format: Option<super::danmaku::DanmakuFormat>,
+ pub nfo_enabled: bool,
+ pub cover_sidecar_enabled: bool,
+ pub cover_format: super::cover::CoverFormat,
+ pub cdn_alt_hosts: Vec<String>,
+ pub cdn_prefer_alternatives: bool,
+}
+
+pub struct EngineResult {
+ pub final_path: PathBuf,
+ pub bytes: u64,
+}
+
+pub async fn run_single(
+ client: &ApiClient,
+ item: &EpisodeItem,
+ kind: &UrlKind,
+ opts: &EngineOptions,
+ metadata: Option<&ContentMetadata>,
+ progress: mpsc::Sender<ProgressUpdate>,
+) -> Result<EngineResult> {
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
+ let preview_info: PreviewInfo = preview::fetch(client, item, kind).await?;
+
+ if preview_info.container != MediaContainer::Dash {
+ return run_progressive(client, item, &preview_info, opts, progress).await;
+ }
+
+ let video = preview_info
+ .pick_video(opts.video_qn_pref, opts.video_codec_pref)
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let audio = preview_info.pick_audio(opts.audio_qn_pref);
+
+ let _ = progress.send(ProgressUpdate::percent(2.0)).await;
+ let cdn_prefs = query::CdnPreferences {
+ alt_hosts: opts.cdn_alt_hosts.clone(),
+ prefer_alternatives: opts.cdn_prefer_alternatives,
+ };
+ let video_url = query::resolve_best_url_with_cdn(
+ client,
+ &video.base_url,
+ &video.backup_urls,
+ &cdn_prefs,
+ )
+ .await?;
+ let audio_resolved = if let Some(a) = audio {
+ Some(
+ query::resolve_best_url_with_cdn(client, &a.base_url, &a.backup_urls, &cdn_prefs)
+ .await?,
+ )
+ } else {
+ None
+ };
+
+ std::fs::create_dir_all(&opts.output_dir).ok();
+ let temp_stem = sanitize_for_temp(&opts.filename);
+
+ let temp_video = opts
+ .output_dir
+ .join(format!(".{}.video.tmp", temp_stem));
+ let temp_audio = opts
+ .output_dir
+ .join(format!(".{}.audio.tmp", temp_stem));
+ let temp_cover = opts
+ .output_dir
+ .join(format!(".{}.cover.tmp", temp_stem));
+
+ let (ua, cookie_header) = (
+ client.user_agent().to_string(),
+ client.cookie_header().map(|s| s.to_string()),
+ );
+ let referer = item
+ .url
+ .clone()
+ .unwrap_or_else(|| "https://www.bilibili.com".to_string());
+
+ let total_streams = 1 + audio_resolved.as_ref().map(|_| 1).unwrap_or(0);
+
+ let (video_tx, mut video_rx) = mpsc::channel::<ProgressUpdate>(32);
+ let progress_video = progress.clone();
+ let agg_total_video = video_url.size;
+ let agg_total_audio = audio_resolved.as_ref().map(|a| a.size).unwrap_or(0);
+ let total_size_hint = agg_total_video + agg_total_audio;
+ tokio::spawn(async move {
+ while let Some(p) = video_rx.recv().await {
+ let scaled = scale_progress(p.percent, 0, total_streams);
+ let _ = progress_video
+ .send(ProgressUpdate::rich(
+ scaled,
+ p.downloaded_bytes,
+ Some(total_size_hint.max(1)),
+ p.speed_bps,
+ p.eta_seconds,
+ ))
+ .await;
+ }
+ });
+
+ let video_handle = {
+ let cancel = opts.cancel.clone();
+ let url = video_url.url.clone();
+ let path = temp_video.clone();
+ let referer = referer.clone();
+ let ua = ua.clone();
+ let cookie = cookie_header.clone();
+ tokio::spawn(async move {
+ fetch::fetch_stream(
+ fetch::FetchOptions {
+ url: &url,
+ output_path: &path,
+ referer: &referer,
+ user_agent: &ua,
+ cookie_header: cookie.as_deref(),
+ cancel: Some(cancel),
+ },
+ video_tx,
+ )
+ .await
+ })
+ };
+
+ let audio_handle = if let Some(audio_res) = audio_resolved.clone() {
+ let (audio_tx, mut audio_rx) = mpsc::channel::<ProgressUpdate>(32);
+ let progress_audio = progress.clone();
+ tokio::spawn(async move {
+ while let Some(p) = audio_rx.recv().await {
+ let scaled = scale_progress(p.percent, 1, total_streams);
+ let _ = progress_audio
+ .send(ProgressUpdate::rich(
+ scaled,
+ p.downloaded_bytes,
+ Some(total_size_hint.max(1)),
+ p.speed_bps,
+ p.eta_seconds,
+ ))
+ .await;
+ }
+ });
+ let cancel = opts.cancel.clone();
+ let url = audio_res.url.clone();
+ let path = temp_audio.clone();
+ let referer = referer.clone();
+ let ua = ua.clone();
+ let cookie = cookie_header.clone();
+ Some(tokio::spawn(async move {
+ fetch::fetch_stream(
+ fetch::FetchOptions {
+ url: &url,
+ output_path: &path,
+ referer: &referer,
+ user_agent: &ua,
+ cookie_header: cookie.as_deref(),
+ cancel: Some(cancel),
+ },
+ audio_tx,
+ )
+ .await
+ }))
+ } else {
+ None
+ };
+
+ let video_result = video_handle
+ .await
+ .map_err(|_| BilibiliError::ContentUnavailable)??;
+ let audio_result = match audio_handle {
+ Some(h) => Some(
+ h.await
+ .map_err(|_| BilibiliError::ContentUnavailable)??,
+ ),
+ None => None,
+ };
+
+ if opts.cancel.is_cancelled() {
+ cleanup(&[&temp_video, &temp_audio, &temp_cover]);
+ return Err(BilibiliError::Cancelled);
+ }
+
+ let cover_path_opt = if opts.embed_cover {
+ if let Some(cover_url) = item.cover_url.as_deref() {
+ download_cover(client, cover_url, &temp_cover).await.ok()
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ let _ = progress.send(ProgressUpdate::percent(95.0)).await;
+
+ let final_path = opts
+ .output_dir
+ .join(format!("{}.{}", opts.filename, opts.container.extension()));
+ if let Some(parent) = final_path.parent() {
+ std::fs::create_dir_all(parent).ok();
+ }
+
+ if audio_result.is_some() {
+ mux::mux(mux::MuxInputs {
+ video: &temp_video,
+ audio: &temp_audio,
+ cover: cover_path_opt.as_deref(),
+ output: &final_path,
+ container: opts.container,
+ })
+ .await?;
+ } else {
+ std::fs::rename(&temp_video, &final_path)
+ .map_err(|_| BilibiliError::ContentUnavailable)?;
+ }
+
+ if !opts.keep_streams {
+ cleanup(&[&temp_video, &temp_audio, &temp_cover]);
+ }
+
+ let folder_for_sidecars = final_path
+ .parent()
+ .map(|p| p.to_path_buf())
+ .unwrap_or_else(|| opts.output_dir.clone());
+ let file_stem_for_sidecars = final_path
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| opts.filename.clone());
+
+ if opts.danmaku_enabled {
+ let cid = item.cid;
+ let duration = item.duration_seconds.unwrap_or(0.0).max(0.0) as u64;
+ if let (Some(cid_v), format) = (cid, opts.danmaku_format.unwrap_or(super::danmaku::DanmakuFormat::Xml)) {
+ if duration > 0 {
+ match super::danmaku::fetch_elems(client, cid_v, duration).await {
+ Ok(elems) => {
+ let rendered = super::danmaku::render(&elems, format);
+ let dm_path = folder_for_sidecars.join(format!(
+ "{}.danmaku.{}",
+ file_stem_for_sidecars,
+ format.extension()
+ ));
+ if let Err(e) = std::fs::write(&dm_path, rendered) {
+ tracing::warn!("[bilibili] failed to write danmaku: {}", e);
+ }
+ }
+ Err(e) => {
+ tracing::warn!("[bilibili] danmaku fetch failed: {:?}", e);
+ }
+ }
+ }
+ }
+ }
+
+ if opts.cover_sidecar_enabled {
+ if let Some(cover_url) = item.cover_url.as_deref() {
+ let cover_path = folder_for_sidecars.join(format!(
+ "{}.{}",
+ file_stem_for_sidecars,
+ opts.cover_format.extension()
+ ));
+ if let Err(e) =
+ super::cover::download_to(client, cover_url, &cover_path, opts.cover_format).await
+ {
+ tracing::warn!("[bilibili] cover sidecar failed: {:?}", e);
+ }
+ }
+ }
+
+ if opts.nfo_enabled {
+ if let Some(meta_ref) = metadata {
+ let folder_for_extras = final_path
+ .parent()
+ .map(|p| p.to_path_buf())
+ .unwrap_or_else(|| opts.output_dir.clone());
+ let file_stem = final_path
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| opts.filename.clone());
+ write_nfo_files(item, meta_ref, kind, client, &folder_for_extras, &file_stem).await;
+ }
+ }
+
+ let bytes = std::fs::metadata(&final_path).map(|m| m.len()).unwrap_or(0);
+
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
+
+ let _ = video_result;
+ Ok(EngineResult { final_path, bytes })
+}
+
+pub async fn run_parsed_content(
+ client: &ApiClient,
+ parsed: &ParsedContent,
+ kind: &UrlKind,
+ opts: &EngineOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+) -> Result<EngineResult> {
+ let first = parsed
+ .items
+ .first()
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ run_single(client, first, kind, opts, Some(&parsed.metadata), progress).await
+}
+
+async fn write_nfo_files(
+ item: &EpisodeItem,
+ metadata: &ContentMetadata,
+ kind: &UrlKind,
+ client: &ApiClient,
+ output_dir: &std::path::Path,
+ filename: &str,
+) {
+ use super::nfo;
+ let nfo_kind = match nfo::classify(kind) {
+ Some(k) => k,
+ None => return,
+ };
+
+ let mut tags: Vec<String> = Vec::new();
+ if nfo_kind == nfo::NfoKind::Movie {
+ if let Some(b) = item.bvid.as_deref() {
+ tags = nfo::fetch_tags(client, b).await;
+ }
+ }
+
+ let xml = nfo::render(nfo_kind, item, metadata, &tags);
+ let path = match nfo_kind {
+ nfo::NfoKind::Movie => output_dir.join(format!("{}.nfo", filename)),
+ nfo::NfoKind::Episode => output_dir.join(format!("{}.nfo", filename)),
+ nfo::NfoKind::TvShow => output_dir.join("tvshow.nfo"),
+ };
+ if let Err(e) = std::fs::write(&path, xml) {
+ tracing::warn!("[bilibili] nfo write failed: {}", e);
+ }
+
+ if nfo::season_uses_tvshow(kind) {
+ let tvshow_path = output_dir.join("tvshow.nfo");
+ if !tvshow_path.exists() {
+ let tvshow_xml = nfo::render(nfo::NfoKind::TvShow, item, metadata, &[]);
+ if let Err(e) = std::fs::write(&tvshow_path, tvshow_xml) {
+ tracing::warn!("[bilibili] tvshow nfo write failed: {}", e);
+ }
+ }
+ }
+}
+
+async fn run_progressive(
+ client: &ApiClient,
+ item: &EpisodeItem,
+ info: &PreviewInfo,
+ opts: &EngineOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+) -> Result<EngineResult> {
+ let stream: &VideoStream = info
+ .video_streams
+ .first()
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let cdn_prefs = query::CdnPreferences {
+ alt_hosts: opts.cdn_alt_hosts.clone(),
+ prefer_alternatives: opts.cdn_prefer_alternatives,
+ };
+ let resolved = query::resolve_best_url_with_cdn(
+ client,
+ &stream.base_url,
+ &stream.backup_urls,
+ &cdn_prefs,
+ )
+ .await?;
+ let final_path = opts
+ .output_dir
+ .join(format!("{}.{}", opts.filename, opts.container.extension()));
+ let referer = item
+ .url
+ .clone()
+ .unwrap_or_else(|| "https://www.bilibili.com".to_string());
+ let (ua, cookie_header) = (
+ client.user_agent().to_string(),
+ client.cookie_header().map(|s| s.to_string()),
+ );
+ let result = fetch::fetch_stream(
+ fetch::FetchOptions {
+ url: &resolved.url,
+ output_path: &final_path,
+ referer: &referer,
+ user_agent: &ua,
+ cookie_header: cookie_header.as_deref(),
+ cancel: Some(opts.cancel.clone()),
+ },
+ progress.clone(),
+ )
+ .await?;
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
+ Ok(EngineResult {
+ final_path,
+ bytes: result.bytes_written,
+ })
+}
+
+async fn download_cover(
+ client: &ApiClient,
+ cover_url: &str,
+ out_path: &std::path::Path,
+) -> Result<std::path::PathBuf> {
+ let bytes = client.get_bytes(cover_url).await?;
+ if let Some(parent) = out_path.parent() {
+ std::fs::create_dir_all(parent).ok();
+ }
+ std::fs::write(out_path, bytes).map_err(|_| BilibiliError::ContentUnavailable)?;
+ Ok(out_path.to_path_buf())
+}
+
+fn cleanup(paths: &[&std::path::Path]) {
+ for p in paths {
+ let _ = std::fs::remove_file(p);
+ }
+}
+
+fn sanitize_for_temp(s: &str) -> String {
+ s.chars()
+ .map(|c| match c {
+ '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*' => '_',
+ _ => c,
+ })
+ .take(80)
+ .collect()
+}
+
+fn scale_progress(local_pct: f64, stream_index: u32, total_streams: u32) -> f64 {
+ let denom = total_streams.max(1) as f64;
+ let base = stream_index as f64 / denom;
+ let scaled = base + (local_pct / 100.0) / denom;
+ (scaled * 100.0).clamp(0.0, 95.0)
+}
+
+#[allow(dead_code)]
+fn unused_audio_stream(_: &AudioStream) {}
diff --git a/src-tauri/tdl-study.md b/src-tauri/tdl-study.md
deleted file mode 100644
index 9d8644ab..00000000
--- a/src-tauri/tdl-study.md
+++ /dev/null
@@ -1,552 +0,0 @@
-# Estudo: tdl-master — Implementação de Download do Telegram
-
-Estudo completo da implementação de download do [tdl](https://github.com/iyear/tdl) (Go), com foco em traduzir os padrões para Rust/grammers no OmniGet.
-
----
-
-## 1. Arquitetura Geral
-
-O tdl usa uma arquitetura em 3 camadas:
-
-```
-cmd/dl.go → CLI (Cobra)
-app/dl/dl.go → Orquestração (iterator, progress, resume)
-core/downloader/ → Engine de download (chunks, errgroup, WriteAt)
-core/dcpool/ → Pool de conexões por DC
-core/middlewares/ → Retry, Recovery, FloodWait, Takeout
-```
-
----
-
-## 2. A Chave: DC Proativo (Não Reativo)
-
-### O problema que temos no OmniGet
-
-O OmniGet usa `client.invoke(&request)` para baixar arquivos. Quando o arquivo está em outro DC (ex: DC 4), Telegram retorna `FILE_MIGRATE_4`. O grammers tenta lidar internamente no `iter_download`, mas nosso código custom (`download_parallel`) não consegue porque `copy_auth_to_dc()` é `pub(crate)`.
-
-### Como o tdl resolve
-
-**O tdl NUNCA recebe FILE_MIGRATE.** Ele lê o campo `dc_id` da metadata do documento/foto e conecta ao DC correto ANTES de baixar.
-
-```go
-// core/tmedia/document.go
-func GetDocumentInfo(doc *tg.MessageMediaDocument) (*Media, bool) {
- d := doc.Document.(*tg.Document)
- return &Media{
- InputFileLoc: &tg.InputDocumentFileLocation{
- ID: d.ID, AccessHash: d.AccessHash, FileReference: d.FileReference,
- },
- DC: d.DCID, // ← DC onde o arquivo está armazenado
- Size: d.Size,
- }, true
-}
-
-// core/tmedia/photo.go
-func GetPhotoInfo(photo *tg.MessageMediaPhoto) (*Media, bool) {
- p := photo.Photo.(*tg.Photo)
- return &Media{
- InputFileLoc: &tg.InputPhotoFileLocation{...},
- DC: p.DCID, // ← DC onde a foto está
- Size: int64(size),
- }, true
-}
-```
-
-Depois, na hora de baixar:
-
-```go
-// core/downloader/downloader.go
-func (d *Downloader) download(ctx context.Context, elem Elem) error {
- client := d.opts.Pool.Client(ctx, elem.File().DC()) // ← conecta ao DC certo
- // ...
- downloader.NewDownloader().Download(client, elem.File().Location()).Parallel(ctx, writer)
-}
-```
-
-### Equivalente no Rust/grammers
-
-O `dc_id` está disponível como campo público nos tipos TL gerados do grammers:
-
-```rust
-// grammers-tl-types (gerado de api.tl)
-pub struct Document {
- pub id: i64,
- pub access_hash: i64,
- pub file_reference: Vec<u8>,
- pub dc_id: i32, // ← campo público!
- pub size: i64,
- // ...
-}
-
-pub struct Photo {
- pub id: i64,
- pub access_hash: i64,
- pub file_reference: Vec<u8>,
- pub dc_id: i32, // ← campo público!
- pub sizes: Vec<PhotoSize>,
- // ...
-}
-```
-
-**Acesso:**
-
-```rust
-// Extraindo dc_id de MessageMedia
-match &raw_media {
- tl::enums::MessageMedia::Document(doc_media) => {
- if let tl::enums::Document::Document(d) = doc_media.document.as_ref()? {
- let dc_id = d.dc_id; // i32
- let size = d.size; // i64
- }
- }
- tl::enums::MessageMedia::Photo(photo_media) => {
- if let tl::enums::Photo::Photo(p) = photo_media.photo.as_ref()? {
- let dc_id = p.dc_id; // i32
- }
- }
-}
-```
-
----
-
-## 3. DC Pool — Conexão por DC com Auth Transfer
-
-### Padrão do tdl
-
-```go
-// core/dcpool/dcpool.go
-type Pool interface {
- Client(ctx context.Context, dc int) *tg.Client
- Default(ctx context.Context) *tg.Client
- Close() error
-}
-
-func (p *pool) invoker(ctx context.Context, dc int) tg.Invoker {
- if i, ok := p.invokers[dc]; ok {
- return i // já conectado, reusar
- }
-
- if dc == p.current() {
- invoker, _ = p.api.Pool(p.size) // home DC: pool de conexões
- } else {
- invoker, _ = p.api.DC(ctx, dc, p.size) // outro DC: auth transfer automático
- }
-
- p.invokers[dc] = chainMiddlewares(invoker, p.middlewares...)
- return p.invokers[dc]
-}
-```
-
-**Pontos-chave:**
-- `api.DC(ctx, dc, size)` faz `auth.exportAuthorization` → `auth.importAuthorization` internamente (gotd library)
-- Lazy init: só conecta ao DC quando necessário
-- Cache: reutiliza conexões existentes
-- Mutex-protected: thread-safe
-- Fallback: se falhar, usa o client principal (vai dar FILE_MIGRATE, mas não crasha)
-
-### Equivalente no grammers
-
-O grammers tem `client.invoke_in_dc(dc, &request)` que é público, e internamente chama `copy_auth_to_dc()` (que é `pub(crate)`). O `iter_download` do grammers já usa isso. Mas para nosso uso direto, podemos:
-
-**Opção A — Usar `iter_download` do grammers** (mais simples, o que tentamos):
-```rust
-let mut iter = client.iter_download(&media);
-while let Some(chunk) = iter.next().await? { ... }
-```
-Isso funciona, mas é sequencial e sem controle de chunk size > 512KB.
-
-**Opção B — Usar `invoke_in_dc` diretamente** (o que o tdl faz, mas precisa do dc_id):
-```rust
-let request = tl::functions::upload::GetFile { location, offset, limit: 1048576 };
-let result = client.invoke_in_dc(dc_id, &request).await;
-```
-O `invoke_in_dc` é público no grammers e chama `copy_auth_to_dc` internamente na primeira vez.
-
-**IMPORTANTE**: O `invoke_in_dc` do grammers chama `copy_auth_to_dc()` internamente quando necessário. O problema anterior era que chamávamos `invoke_in_dc` sem saber o DC correto (reagindo ao erro), e possivelmente o grammers não fazia o auth copy corretamente. Com o `dc_id` lido da metadata, podemos usar `invoke_in_dc` de forma proativa.
-
----
-
-## 4. Download Paralelo — errgroup + WriteAt
-
-### Padrão do tdl
-
-```go
-// core/downloader/downloader.go — MaxPartSize = 1MB
-func (d *Downloader) Download(ctx context.Context, limit int) error {
- wg, wgctx := errgroup.WithContext(ctx)
- wg.SetLimit(limit) // max N downloads em paralelo
-
- for d.opts.Iter.Next(wgctx) {
- elem := d.opts.Iter.Value()
- wg.Go(func() error {
- d.opts.Progress.OnAdd(elem)
- defer func() { d.opts.Progress.OnDone(elem, rerr) }()
- if err := d.download(wgctx, elem); err != nil {
- if errors.Is(err, context.Canceled) {
- return err // propaga cancelamento
- }
- // log e continua para o próximo arquivo
- }
- return nil
- })
- }
- return wg.Wait()
-}
-```
-
-O download de cada arquivo usa gotd's `downloader.Parallel`:
-- Divide o arquivo em chunks de 1MB
-- `BestThreads(fileSize, maxThreads)` determina paralelismo por arquivo
-- `io.WriterAt` para escrita em offsets arbitrários (paralelo)
-- Cada chunk vai para o DC correto via pool
-
-### BestThreads
-
-```go
-// core/util/tutil/tutil.go
-func BestThreads(size int64, max int) int {
- // < 1 MB → 1 thread
- // < 5 MB → 2 threads
- // < 20 MB → 4 threads
- // < 50 MB → 8 threads
- // >= 50 MB → max threads
-}
-```
-
-### Equivalente no Rust
-
-```rust
-// Usando JoinSet + Semaphore (como tínhamos antes, mas agora com dc_id)
-let semaphore = Arc::new(Semaphore::new(threads));
-let mut join_set = JoinSet::new();
-
-for part_idx in 0..num_parts {
- let permit = semaphore.clone().acquire_owned().await?;
- join_set.spawn(async move {
- let _permit = permit;
- let request = tl::functions::upload::GetFile {
- precise: true, cdn_supported: false,
- location: location.clone(),
- offset: (part_idx * PART_SIZE) as i64,
- limit: PART_SIZE,
- };
- // USA invoke_in_dc com o dc_id correto!
- let result = client.invoke_in_dc(dc_id, &request).await;
- // ... write chunk at offset ...
- });
-}
-```
-
----
-
-## 5. Middleware Chain
-
-### Padrão do tdl (3 camadas)
-
-```
-recovery → retry → floodwait → RPC
-```
-
-1. **FloodWait** (innermost): `FLOOD_WAIT_X` → sleep X seconds, retry automaticamente
-2. **Retry** (middle): Erros internos do Telegram (Timedout, RPC_CALL_FAIL, WORKER_BUSY) → até 5 retries
-3. **Recovery** (outermost): Erros de rede (connection reset, timeout TCP) → backoff exponencial
-
-**O que NÃO é retriado:**
-- `FILE_MIGRATE` — nunca acontece porque usa DC correto
-- Erros de negócio (CHAT_ADMIN_REQUIRED, etc.) — propagados imediatamente
-
-### Equivalente no Rust
-
-```rust
-// Retry wrapper para nosso download
-async fn invoke_with_retry<R>(
- client: &Client,
- dc_id: i32,
- request: &R,
- max_retries: u32,
-) -> Result<R::Return, anyhow::Error> {
- let mut last_err = None;
- for attempt in 0..=max_retries {
- if attempt > 0 {
- let delay = 1000 * (1u64 << (attempt - 1).min(4));
- tokio::time::sleep(Duration::from_millis(delay)).await;
- }
- match client.invoke_in_dc(dc_id, request).await {
- Ok(response) => return Ok(response),
- Err(InvocationError::Rpc(ref err)) if err.code == 420 => {
- // FLOOD_WAIT: sleep pelo tempo indicado
- let wait = err.value.unwrap_or(5) as u64;
- tracing::warn!("[tg] FLOOD_WAIT_{}, sleeping {}s", wait, wait);
- tokio::time::sleep(Duration::from_secs(wait)).await;
- continue; // não conta como retry
- }
- Err(e) => {
- last_err = Some(e);
- continue;
- }
- }
- }
- Err(anyhow::anyhow!("Failed after {} retries: {:?}", max_retries, last_err))
-}
-```
-
----
-
-## 6. Resolução de Peers (Canais Privados)
-
-### Padrão do tdl
-
-```go
-// pkg/tmessage/urls.go — Parse de URLs
-// t.me/c/1234567890/123 → channel_id = 1234567890, msg_id = 123
-// t.me/username/123 → username = "username", msg_id = 123
-
-// core/util/tutil/tutil.go
-func GetInputPeer(ctx, manager, from string) (peers.Peer, error) {
- id, err := strconv.ParseInt(from, 10, 64)
- if err != nil {
- return manager.Resolve(ctx, from) // por username
- }
- // Tenta channel, depois user, depois chat
- if p, err = manager.ResolveChannelID(ctx, id); err == nil { return p, nil }
- if p, err = manager.ResolveUserID(ctx, id); err == nil { return p, nil }
- if p, err = manager.ResolveChatID(ctx, id); err == nil { return p, nil }
-}
-```
-
-**Pontos-chave:**
-- Usa `peers.Manager` com storage persistente (BoltDB) para cache de access_hash
-- Para canais privados, o access_hash precisa ter sido visto antes (via dialogs)
-- Resolve cascata: channel → user → chat
-
----
-
-## 7. Progress Tracking com WriteAt
-
-### Padrão do tdl
-
-```go
-// core/downloader/progress.go
-type writeAt struct {
- elem Elem
- progress Progress
- partSize int
- downloaded *atomic.Int64
-}
-
-func (w *writeAt) WriteAt(p []byte, off int64) (int, error) {
- at, err := w.elem.To().WriteAt(p, off)
- w.progress.OnDownload(w.elem, ProgressState{
- Downloaded: w.downloaded.Add(int64(at)),
- Total: w.elem.File().Size(),
- })
- return at, nil
-}
-```
-
-- `atomic.Int64` para thread-safety
-- Cada chunk atualiza o progresso imediatamente
-- `OnAdd` no início, `OnDone` no final (com erro ou sucesso)
-
-### Equivalente no Rust
-
-```rust
-let downloaded = Arc::new(AtomicU64::new(0));
-
-// Em cada task de chunk:
-let prev = downloaded.fetch_add(chunk_len, Ordering::Relaxed);
-let percent = ((prev + chunk_len) as f64 / total_size as f64) * 100.0;
-let _ = progress_tx.send(percent.min(100.0)).await;
-```
-
----
-
-## 8. Tratamento de Erros
-
-### Padrão do tdl
-
-| Erro | Ação |
-|------|------|
-| `FLOOD_WAIT_X` | Sleep X seconds, retry |
-| `FILE_REFERENCE_EXPIRED` | Re-fetch message, retry |
-| `Timedout`, `RPC_CALL_FAIL` | Retry até 5x |
-| Connection reset, TCP timeout | Backoff exponencial |
-| `context.Canceled` (Ctrl+C) | Propaga, para tudo |
-| Outros erros | Log + skip arquivo, continua batch |
-
-### Equivalente no Rust
-
-```rust
-match result {
- Err(InvocationError::Rpc(err)) if err.code == 420 => { /* FLOOD_WAIT */ }
- Err(InvocationError::Rpc(err)) if err.code == 400
- && err.name.contains("FILE_REFERENCE") => { /* re-fetch */ }
- Err(InvocationError::Rpc(err)) if err.code == 500 => { /* retry interno */ }
- Err(e) if is_network_error(&e) => { /* backoff exponencial */ }
- Err(e) => { /* log e skip */ }
-}
-```
-
----
-
-## 9. Takeout Sessions (Opcional)
-
-O tdl suporta "Takeout" — modo de export bulk do Telegram com rate limits elevados:
-
-```go
-// Inicia takeout session
-sid, _ := c.API().AccountInitTakeoutSession(ctx, &tg.AccountInitTakeoutSessionRequest{
- Files: true,
- FileMaxSize: 4000 * 1024 * 1024, // 4 GB
-})
-
-// Middleware wraps todas as requests
-tg.InvokeWithTakeoutRequest{TakeoutID: sid, Query: request}
-
-// Finaliza
-c.API().AccountFinishTakeoutSession(ctx, &tg.AccountFinishTakeoutSessionRequest{Success: true})
-```
-
-Útil para downloads massivos. Pode ser implementado como feature futura no OmniGet.
-
----
-
-## 10. Plano de Implementação para o OmniGet
-
-### Passo 1: Extrair dc_id da media
-
-No `parallel_download.rs`, modificar `media_to_input_location` para retornar `dc_id`:
-
-```rust
-pub struct MediaLocation {
- pub location: tl::enums::InputFileLocation,
- pub size: u64,
- pub dc_id: i32,
-}
-
-pub fn media_to_location(media: &tl::enums::MessageMedia) -> Option<MediaLocation> {
- match media {
- tl::enums::MessageMedia::Document(doc_media) => {
- let doc = match doc_media.document.as_ref()? {
- tl::enums::Document::Document(d) => d,
- _ => return None,
- };
- Some(MediaLocation {
- location: tl::enums::InputFileLocation::InputDocumentFileLocation(...),
- size: doc.size as u64,
- dc_id: doc.dc_id,
- })
- }
- tl::enums::MessageMedia::Photo(photo_media) => {
- let photo = match photo_media.photo.as_ref()? {
- tl::enums::Photo::Photo(p) => p,
- _ => return None,
- };
- Some(MediaLocation {
- location: tl::enums::InputFileLocation::InputPhotoFileLocation(...),
- size: largest.size as u64,
- dc_id: photo.dc_id,
- })
- }
- _ => None,
- }
-}
-```
-
-### Passo 2: Download paralelo com invoke_in_dc usando dc_id
-
-```rust
-pub async fn download_parallel(
- client: &Client,
- media: &MediaLocation,
- output_path: &Path,
- progress_tx: mpsc::Sender<f64>,
- cancel_token: &CancellationToken,
- max_threads: usize,
-) -> anyhow::Result<u64> {
- let threads = best_threads(media.size, max_threads);
- let num_parts = media.size.div_ceil(PART_SIZE as u64);
- let dc_id = media.dc_id;
-
- // Pre-criar arquivo com tamanho total
- let file = Arc::new(std::fs::File::create(output_path)?);
- file.set_len(media.size)?;
-
- let downloaded = Arc::new(AtomicU64::new(0));
- let semaphore = Arc::new(Semaphore::new(threads));
- let mut join_set = JoinSet::new();
-
- for part_idx in 0..num_parts {
- let offset = part_idx * PART_SIZE as u64;
- // ... clone vars ...
- join_set.spawn(async move {
- let _permit = semaphore.acquire().await?;
-
- let request = tl::functions::upload::GetFile {
- precise: true, cdn_supported: false,
- location: location.clone(),
- offset: offset as i64,
- limit: PART_SIZE,
- };
-
- // ★ CHAVE: usa invoke_in_dc com o dc_id da metadata
- let result = client.invoke_in_dc(dc_id, &request).await;
-
- match result {
- Ok(tl::enums::upload::File::File(f)) => {
- write_at_offset(&file, &f.bytes, offset)?;
- // update progress...
- }
- Err(e) => { /* retry logic */ }
- }
- });
- }
- // ... join_set.join_next() ...
-}
-```
-
-### Passo 3: Retry com FLOOD_WAIT
-
-Implementar retry wrapper que trata FLOOD_WAIT automaticamente, como o tdl faz com middleware.
-
-### Passo 4: Fallback para sequencial
-
-Se `invoke_in_dc` falhar por qualquer motivo, fall back para `client.iter_download()` do grammers que tem seu próprio FILE_MIGRATE handling.
-
-### Passo 5: (Futuro) Takeout sessions
-
-Para downloads massivos de canais inteiros.
-
----
-
-## 11. Diferenças Chave: tdl (gotd) vs OmniGet (grammers)
-
-| Aspecto | tdl (gotd/Go) | OmniGet (grammers/Rust) |
-|---------|---------------|------------------------|
-| DC Pool | `api.DC(ctx, dc, size)` — pool de N conexões por DC | `client.invoke_in_dc(dc, &req)` — uma conexão |
-| Auth Transfer | `api.DC()` faz internamente | `invoke_in_dc` chama `copy_auth_to_dc()` internamente |
-| FILE_MIGRATE | Nunca acontece (DC proativo) | Pode acontecer se dc_id incorreto |
-| Parallel chunks | gotd `downloader.Parallel` com `io.WriterAt` | Custom `JoinSet` + `Semaphore` |
-| Chunk size | 1 MB (max API) | 1 MB (nosso) ou 512 KB (grammers default) |
-| FloodWait | Middleware automático | Manual (implementar) |
-| Takeout | Suportado | Não implementado |
-| Resume | Fingerprint + KV storage | Não implementado |
-| Connection pooling | N conexões por DC | 1 conexão por DC |
-
----
-
-## 12. Resumo das Lições
-
-1. **Ler `dc_id` da metadata** — O campo `dc_id` está nos tipos `Document` e `Photo` do grammers-tl-types. Usar ele para conectar ao DC correto ANTES de baixar.
-
-2. **`invoke_in_dc(dc_id, &request)`** — O grammers faz `copy_auth_to_dc()` internamente. Usar diretamente com o `dc_id` da metadata.
-
-3. **Parallel com WriteAt** — Dividir em chunks de 1MB, usar `Semaphore` para limitar threads, `seek_write`/`write_all_at` para escrita paralela.
-
-4. **FLOOD_WAIT handler** — Detectar código 420, sleep pelo tempo indicado, retry.
-
-5. **Batch error handling** — Erro em 1 arquivo não para o batch. Só `context.Canceled` propaga.
-
-6. **Temp file pattern** — Download para `.tmp`, rename no final.
-
-7. **BestThreads** — Escalar paralelismo por tamanho do arquivo.