Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

feat: add DanmakuElem struct and decoding functions for Bilibili platform

Tonho8052ac82e815
diff --git a/src-tauri/src/platforms/bilibili/danmaku/proto.rs b/src-tauri/src/platforms/bilibili/danmaku/proto.rs
new file mode 100644
index 00000000..5101ad29
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/danmaku/proto.rs
@@ -0,0 +1,245 @@
+use super::super::api::{BilibiliError, Result};
+
+#[derive(Debug, Clone, Default)]
+pub struct DanmakuElem {
+ pub id: i64,
+ pub progress_ms: i32,
+ pub mode: i32,
+ pub fontsize: i32,
+ pub color: u32,
+ pub mid_hash: String,
+ pub content: String,
+ pub ctime: i64,
+ pub weight: i32,
+ pub pool: i32,
+ pub attr: i32,
+}
+
+pub fn decode_segment(bytes: &[u8]) -> Result<Vec<DanmakuElem>> {
+ let mut elems: Vec<DanmakuElem> = Vec::new();
+ let mut idx = 0usize;
+ while idx < bytes.len() {
+ let (key, k_len) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += k_len;
+ let field = (key >> 3) as u32;
+ let wire = (key & 0x07) as u8;
+ if field == 1 && wire == 2 {
+ let (len, l_len) =
+ read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += l_len;
+ let end = idx
+ .checked_add(len as usize)
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ if end > bytes.len() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+ let elem = decode_elem(&bytes[idx..end])?;
+ elems.push(elem);
+ idx = end;
+ } else {
+ idx = skip_field(bytes, idx, wire).ok_or(BilibiliError::ContentUnavailable)?;
+ }
+ }
+ Ok(elems)
+}
+
+fn decode_elem(bytes: &[u8]) -> Result<DanmakuElem> {
+ let mut elem = DanmakuElem::default();
+ let mut idx = 0usize;
+ while idx < bytes.len() {
+ let (key, k_len) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += k_len;
+ let field = (key >> 3) as u32;
+ let wire = (key & 0x07) as u8;
+ match (field, wire) {
+ (1, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.id = v as i64;
+ }
+ (2, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.progress_ms = v as i32;
+ }
+ (3, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.mode = v as i32;
+ }
+ (4, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.fontsize = v as i32;
+ }
+ (5, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.color = v as u32;
+ }
+ (6, 2) => {
+ let (v, vl) = read_length_delimited(bytes, idx)
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.mid_hash = String::from_utf8(v.to_vec()).unwrap_or_default();
+ }
+ (7, 2) => {
+ let (v, vl) = read_length_delimited(bytes, idx)
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.content = String::from_utf8(v.to_vec()).unwrap_or_default();
+ }
+ (8, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.ctime = v as i64;
+ }
+ (9, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.weight = v as i32;
+ }
+ (11, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.pool = v as i32;
+ }
+ (13, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.attr = v as i32;
+ }
+ _ => {
+ idx = skip_field(bytes, idx, wire).ok_or(BilibiliError::ContentUnavailable)?;
+ }
+ }
+ }
+ Ok(elem)
+}
+
+fn read_varint(bytes: &[u8], start: usize) -> Option<(u64, usize)> {
+ let mut result: u64 = 0;
+ let mut shift = 0u32;
+ let mut idx = start;
+ while idx < bytes.len() {
+ let b = bytes[idx];
+ idx += 1;
+ result |= ((b & 0x7F) as u64) << shift;
+ if b & 0x80 == 0 {
+ return Some((result, idx - start));
+ }
+ shift += 7;
+ if shift >= 64 {
+ return None;
+ }
+ }
+ None
+}
+
+fn read_length_delimited(bytes: &[u8], start: usize) -> Option<(&[u8], usize)> {
+ let (len, l_len) = read_varint(bytes, start)?;
+ let body_start = start + l_len;
+ let body_end = body_start.checked_add(len as usize)?;
+ if body_end > bytes.len() {
+ return None;
+ }
+ Some((&bytes[body_start..body_end], body_end - start))
+}
+
+fn skip_field(bytes: &[u8], start: usize, wire: u8) -> Option<usize> {
+ match wire {
+ 0 => {
+ let (_, len) = read_varint(bytes, start)?;
+ Some(start + len)
+ }
+ 1 => {
+ if start + 8 > bytes.len() {
+ None
+ } else {
+ Some(start + 8)
+ }
+ }
+ 2 => {
+ let (_, len) = read_length_delimited(bytes, start)?;
+ Some(start + len)
+ }
+ 5 => {
+ if start + 4 > bytes.len() {
+ None
+ } else {
+ Some(start + 4)
+ }
+ }
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn build_elem_bytes() -> Vec<u8> {
+ let mut buf: Vec<u8> = Vec::new();
+ write_tag_varint(&mut buf, 2, 1234);
+ write_tag_varint(&mut buf, 3, 1);
+ write_tag_varint(&mut buf, 4, 25);
+ write_tag_varint(&mut buf, 5, 0xFFFFFF);
+ write_tag_str(&mut buf, 7, "hello danmaku");
+ write_tag_varint(&mut buf, 8, 1700000000);
+ buf
+ }
+
+ fn write_varint(buf: &mut Vec<u8>, mut v: u64) {
+ while v >= 0x80 {
+ buf.push(((v & 0x7F) as u8) | 0x80);
+ v >>= 7;
+ }
+ buf.push(v as u8);
+ }
+
+ fn write_tag_varint(buf: &mut Vec<u8>, field: u32, value: u64) {
+ let key = (field << 3) | 0;
+ write_varint(buf, key as u64);
+ write_varint(buf, value);
+ }
+
+ fn write_tag_str(buf: &mut Vec<u8>, field: u32, s: &str) {
+ let key = (field << 3) | 2;
+ write_varint(buf, key as u64);
+ write_varint(buf, s.len() as u64);
+ buf.extend_from_slice(s.as_bytes());
+ }
+
+ fn build_segment_bytes(elems: usize) -> Vec<u8> {
+ let elem_bytes = build_elem_bytes();
+ let mut buf: Vec<u8> = Vec::new();
+ for _ in 0..elems {
+ let key = (1 << 3) | 2;
+ write_varint(&mut buf, key as u64);
+ write_varint(&mut buf, elem_bytes.len() as u64);
+ buf.extend_from_slice(&elem_bytes);
+ }
+ buf
+ }
+
+ #[test]
+ fn decode_single_elem() {
+ let bytes = build_segment_bytes(1);
+ let elems = decode_segment(&bytes).unwrap();
+ assert_eq!(elems.len(), 1);
+ let e = &elems[0];
+ assert_eq!(e.progress_ms, 1234);
+ assert_eq!(e.mode, 1);
+ assert_eq!(e.fontsize, 25);
+ assert_eq!(e.color, 0xFFFFFF);
+ assert_eq!(e.content, "hello danmaku");
+ assert_eq!(e.ctime, 1700000000);
+ }
+
+ #[test]
+ fn decode_multiple_elems() {
+ let bytes = build_segment_bytes(5);
+ let elems = decode_segment(&bytes).unwrap();
+ assert_eq!(elems.len(), 5);
+ }
+}
diff --git a/src-tauri/src/platforms/bluesky/mod.rs b/src-tauri/src/platforms/bluesky/mod.rs
index dde93ce5..dc0f4263 100644
--- a/src-tauri/src/platforms/bluesky/mod.rs
+++ b/src-tauri/src/platforms/bluesky/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use anyhow::anyhow;
use async_trait::async_trait;
use tokio::sync::mpsc;
@@ -245,7 +246,7 @@ impl PlatformDownloader for BlueskyDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
if let Some(quality) = info.available_qualities.first() {
if quality.format == "ytdlp" {
@@ -285,7 +286,7 @@ impl PlatformDownloader for BlueskyDownloader {
let downloader =
HlsDownloader::new().with_user_agent_override(opts.user_agent.clone());
- let _ = progress.send(0.0).await;
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
let result = downloader
.download(
@@ -299,7 +300,7 @@ impl PlatformDownloader for BlueskyDownloader {
)
.await?;
- let _ = progress.send(100.0).await;
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
Ok(DownloadResult {
file_path: result.path,
@@ -339,7 +340,7 @@ impl PlatformDownloader for BlueskyDownloader {
last_path = output;
let percent = ((i + 1) as f64 / count as f64) * 100.0;
- let _ = progress.send(percent).await;
+ let _ = progress.send(ProgressUpdate::percent(percent)).await;
}
Ok(DownloadResult {
diff --git a/src-tauri/src/platforms/douyin/mod.rs b/src-tauri/src/platforms/douyin/mod.rs
index e616727f..ce6350ea 100644
--- a/src-tauri/src/platforms/douyin/mod.rs
+++ b/src-tauri/src/platforms/douyin/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use std::collections::HashSet;
use std::time::Duration;
@@ -205,9 +206,9 @@ impl PlatformDownloader for DouyinDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
- let _ = progress.send(0.0).await;
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
let ytdlp_path = match &opts.ytdlp_path {
Some(p) => p.clone(),
diff --git a/src-tauri/src/platforms/gallerydl/mod.rs b/src-tauri/src/platforms/gallerydl/mod.rs
new file mode 100644
index 00000000..ffa31761
--- /dev/null
+++ b/src-tauri/src/platforms/gallerydl/mod.rs
@@ -0,0 +1,313 @@
+use std::path::{Path, PathBuf};
+use std::process::Stdio;
+use std::time::SystemTime;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::io::{AsyncBufReadExt, BufReader};
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use omniget_core::models::progress::ProgressUpdate;
+use omniget_core::platforms::traits::PlatformDownloader;
+
+const GALLERY_HOSTS: &[&str] = &[
+ "deviantart.com",
+ "pixiv.net",
+ "artstation.com",
+ "flickr.com",
+ "tumblr.com",
+ "danbooru.donmai.us",
+ "gelbooru.com",
+ "e621.net",
+ "rule34.xxx",
+ "konachan.com",
+ "yande.re",
+ "newgrounds.com",
+ "kemono.su",
+ "kemono.party",
+ "coomer.su",
+ "fanbox.cc",
+ "weibo.com",
+ "boards.4chan.org",
+ "boards.4channel.org",
+ "imgur.com",
+ "imgchest.com",
+ "nhentai.net",
+ "hentai-foundry.com",
+ "baraag.net",
+ "wallhaven.cc",
+ "subscribestar.adult",
+];
+
+pub fn is_gallery_url(url: &str) -> bool {
+ let host = match url::Url::parse(url) {
+ Ok(u) => u.host_str().map(|h| h.trim_start_matches("www.").to_lowercase()),
+ Err(_) => None,
+ };
+ let Some(host) = host else {
+ return false;
+ };
+ GALLERY_HOSTS
+ .iter()
+ .any(|h| host == *h || host.ends_with(&format!(".{}", h)))
+}
+
+pub struct GalleryDlDownloader;
+
+impl GalleryDlDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+impl Default for GalleryDlDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+fn title_from_url(url: &str) -> String {
+ if let Ok(parsed) = url::Url::parse(url) {
+ let host = parsed
+ .host_str()
+ .unwrap_or("gallery")
+ .trim_start_matches("www.")
+ .to_string();
+ let last = parsed
+ .path_segments()
+ .and_then(|s| s.filter(|p| !p.is_empty()).last())
+ .unwrap_or("")
+ .to_string();
+ if last.is_empty() {
+ host
+ } else {
+ format!("{} - {}", host, last)
+ }
+ } else {
+ "gallery".to_string()
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for GalleryDlDownloader {
+ fn name(&self) -> &str {
+ "gallery"
+ }
+
+ fn can_handle(&self, url: &str) -> bool {
+ is_gallery_url(url)
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ let title = title_from_url(url);
+ Ok(MediaInfo {
+ title,
+ author: String::new(),
+ platform: "gallery".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "Gallery".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "gallery".to_string(),
+ }],
+ media_type: MediaType::Carousel,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+ ) -> anyhow::Result<DownloadResult> {
+ let url = info
+ .available_qualities
+ .first()
+ .map(|q| q.url.clone())
+ .ok_or_else(|| anyhow!("No gallery URL available"))?;
+
+ let bin = omniget_core::core::dependencies::ensure_gallerydl()
+ .await
+ .ok_or_else(|| {
+ anyhow!("gallery-dl is not available. Install gallery-dl to download from this site.")
+ })?;
+
+ std::fs::create_dir_all(&opts.output_dir)?;
+ let _ = progress.send(ProgressUpdate::percent(-2.0)).await;
+
+ let mut cmd = omniget_core::core::process::command(&bin);
+ cmd.arg("--no-colors")
+ .arg("-D")
+ .arg(&opts.output_dir)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ if let Some(data_dir) = omniget_core::core::paths::app_data_dir() {
+ let archive_dir = data_dir.join("archive");
+ if std::fs::create_dir_all(&archive_dir).is_ok() {
+ cmd.arg("--download-archive")
+ .arg(archive_dir.join("gallery-dl.txt"));
+ }
+ let cookie_file = data_dir.join("chrome-extension-cookies.txt");
+ if std::fs::metadata(&cookie_file).map(|m| m.len() > 0).unwrap_or(false) {
+ cmd.arg("--cookies").arg(&cookie_file);
+ }
+ }
+
+ cmd.arg("--").arg(&url);
+
+ let mut child = cmd
+ .spawn()
+ .map_err(|e| anyhow!("Failed to start gallery-dl: {}", e))?;
+
+ let stdout = child
+ .stdout
+ .take()
+ .ok_or_else(|| anyhow!("No stdout from gallery-dl"))?;
+ let stderr_pipe = child
+ .stderr
+ .take()
+ .ok_or_else(|| anyhow!("No stderr from gallery-dl"))?;
+
+ let started_at = SystemTime::now();
+
+ let progress_tx = progress.clone();
+ let reader_task = tokio::spawn(async move {
+ let mut lines = BufReader::new(stdout).lines();
+ let mut count: u64 = 0;
+ let mut last_emit = std::time::Instant::now();
+ while let Ok(Some(line)) = lines.next_line().await {
+ let trimmed = line.trim();
+ if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('[') {
+ continue;
+ }
+ count += 1;
+ if last_emit.elapsed() >= std::time::Duration::from_millis(250) {
+ let pct = ((count as f64 / (count as f64 + 4.0)) * 100.0).min(95.0);
+ let _ = progress_tx.send(ProgressUpdate::percent(pct)).await;
+ last_emit = std::time::Instant::now();
+ }
+ }
+ count
+ });
+
+ let stderr_task = tokio::spawn(async move {
+ let mut buf = String::new();
+ let mut lines = BufReader::new(stderr_pipe).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ buf.push_str(&line);
+ buf.push('\n');
+ }
+ buf
+ });
+
+ let status = tokio::select! {
+ s = child.wait() => s.map_err(|e| anyhow!("gallery-dl process failed: {}", e))?,
+ _ = opts.cancel_token.cancelled() => {
+ let _ = child.kill().await;
+ let _ = reader_task.await;
+ let _ = stderr_task.await;
+ anyhow::bail!("Download cancelled");
+ }
+ };
+
+ let _ = reader_task.await;
+ let stderr_content = stderr_task.await.unwrap_or_default();
+
+ if !status.success() {
+ let detail = stderr_content
+ .lines()
+ .rev()
+ .find(|l| {
+ let l = l.to_lowercase();
+ l.contains("error")
+ || l.contains("forbidden")
+ || l.contains("not found")
+ || l.contains("unsupported")
+ })
+ .unwrap_or("gallery-dl failed")
+ .trim()
+ .to_string();
+ return Err(anyhow!(detail));
+ }
+
+ let (file_path, total_bytes) = collect_new_files(&opts.output_dir, started_at);
+ if total_bytes == 0 {
+ return Err(anyhow!(
+ "gallery-dl completed but downloaded no new files (already archived or empty gallery)"
+ ));
+ }
+
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
+
+ Ok(DownloadResult {
+ file_path,
+ file_size_bytes: total_bytes,
+ duration_seconds: 0.0,
+ torrent_id: None,
+ })
+ }
+}
+
+fn collect_new_files(dir: &Path, since: SystemTime) -> (PathBuf, u64) {
+ let mut total: u64 = 0;
+ let mut newest: Option<(SystemTime, PathBuf)> = None;
+ let mut new_count = 0usize;
+ let mut single: Option<PathBuf> = None;
+
+ if let Ok(entries) = std::fs::read_dir(dir) {
+ for entry in entries.flatten() {
+ let path = entry.path();
+ let Ok(meta) = entry.metadata() else {
+ continue;
+ };
+ if !meta.is_file() {
+ continue;
+ }
+ let modified = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
+ if modified < since {
+ continue;
+ }
+ total += meta.len();
+ new_count += 1;
+ single = Some(path.clone());
+ if newest.as_ref().map(|(t, _)| modified > *t).unwrap_or(true) {
+ newest = Some((modified, path));
+ }
+ }
+ }
+
+ let file_path = if new_count == 1 {
+ single.unwrap_or_else(|| dir.to_path_buf())
+ } else {
+ dir.to_path_buf()
+ };
+ (file_path, total)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::is_gallery_url;
+
+ #[test]
+ fn matches_curated_gallery_hosts() {
+ assert!(is_gallery_url("https://www.deviantart.com/someartist/gallery"));
+ assert!(is_gallery_url("https://www.pixiv.net/en/users/12345"));
+ assert!(is_gallery_url("https://danbooru.donmai.us/posts?tags=foo"));
+ assert!(is_gallery_url("https://imgur.com/a/abcd"));
+ assert!(is_gallery_url("https://blog.tumblr.com/"));
+ }
+
+ #[test]
+ fn ignores_non_gallery_hosts() {
+ assert!(!is_gallery_url("https://www.youtube.com/watch?v=x"));
+ assert!(!is_gallery_url("https://www.instagram.com/p/abc/"));
+ assert!(!is_gallery_url("https://example.com/image.jpg"));
+ assert!(!is_gallery_url("not a url"));
+ }
+}
diff --git a/src-tauri/src/platforms/generic_ytdlp/mod.rs b/src-tauri/src/platforms/generic_ytdlp/mod.rs
index 2672ddd8..417de6cd 100644
--- a/src-tauri/src/platforms/generic_ytdlp/mod.rs
+++ b/src-tauri/src/platforms/generic_ytdlp/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use std::collections::HashSet;
use anyhow::anyhow;
@@ -257,9 +258,9 @@ impl PlatformDownloader for GenericYtdlpDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
- let _ = progress.send(0.0).await;
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
let first = info
.available_qualities
@@ -343,7 +344,7 @@ impl PlatformDownloader for GenericYtdlpDownloader {
let client = builder.build().unwrap_or_default();
let downloader = HlsDownloader::with_client(client)
.with_user_agent_override(opts.user_agent.clone());
- let _ = progress.send(0.0).await;
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
let result = downloader
.download(
@@ -357,7 +358,7 @@ impl PlatformDownloader for GenericYtdlpDownloader {
)
.await?;
- let _ = progress.send(100.0).await;
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
return Ok(DownloadResult {
file_path: result.path,
diff --git a/src-tauri/src/platforms/instagram/mod.rs b/src-tauri/src/platforms/instagram/mod.rs
index 97747c68..dff3d17c 100644
--- a/src-tauri/src/platforms/instagram/mod.rs
+++ b/src-tauri/src/platforms/instagram/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use anyhow::anyhow;
use async_trait::async_trait;
use rand::RngExt;
@@ -582,7 +583,7 @@ impl InstagramDownloader {
async fn ytdlp_download_post(
post_url: &str,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;
crate::core::ytdlp::download_video(
@@ -755,7 +756,7 @@ impl PlatformDownloader for InstagramDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
let count = info.available_qualities.len();
@@ -842,7 +843,7 @@ impl PlatformDownloader for InstagramDownloader {
last_path = output;
let percent = ((i + 1) as f64 / count as f64) * 100.0;
- let _ = progress.send(percent).await;
+ let _ = progress.send(ProgressUpdate::percent(percent)).await;
}
Err(e) => {
if Self::is_html_block_error(&e) {
diff --git a/src-tauri/src/platforms/magnet/mod.rs b/src-tauri/src/platforms/magnet/mod.rs
index ee0d60a6..2c9ece64 100644
--- a/src-tauri/src/platforms/magnet/mod.rs
+++ b/src-tauri/src/platforms/magnet/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use std::path::PathBuf;
use std::sync::Arc;
@@ -87,9 +88,9 @@ impl PlatformDownloader for MagnetDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
- let _ = progress.send(0.0).await;
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
let url = match info.available_qualities.first() {
Some(q) => &q.url,
@@ -242,7 +243,7 @@ impl PlatformDownloader for MagnetDownloader {
if total > 0 {
let pct = (downloaded as f64 / total as f64) * 100.0;
- let _ = progress.send(pct).await;
+ let _ = progress.send(ProgressUpdate::percent(pct)).await;
tracing::debug!(
"[magnet] progress: {:.1}% ({:.1} MB / {:.1} MB)",
pct,
@@ -268,7 +269,7 @@ impl PlatformDownloader for MagnetDownloader {
if let Err(e) = res {
anyhow::bail!("Torrent download failed: {}", e);
}
- let _ = progress.send(100.0).await;
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
tracing::info!("[magnet] download complete (id={})", torrent_id);
break;
}
diff --git a/src-tauri/src/platforms/p2p/mod.rs b/src-tauri/src/platforms/p2p/mod.rs
index bd52d191..af1e318e 100644
--- a/src-tauri/src/platforms/p2p/mod.rs
+++ b/src-tauri/src/platforms/p2p/mod.rs
@@ -1,5 +1,6 @@
pub mod words;
+use omniget_core::models::progress::ProgressUpdate;
use std::path::PathBuf;
use std::sync::Arc;
@@ -104,7 +105,7 @@ impl PlatformDownloader for P2pDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
let url = match info.available_qualities.first() {
Some(q) => &q.url,
@@ -115,7 +116,7 @@ impl PlatformDownloader for P2pDownloader {
.strip_prefix("p2p:")
.ok_or_else(|| anyhow!("Invalid P2P URL"))?;
- let _ = progress.send(-2.0).await;
+ let _ = progress.send(ProgressUpdate::percent(-2.0)).await;
tracing::info!("[p2p] connecting to relay for code: {}", code);
@@ -147,7 +148,7 @@ impl PlatformDownloader for P2pDownloader {
write_half.write_all(b"OK\n").await?;
write_half.flush().await?;
- let _ = progress.send(0.0).await;
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
let sanitized = sanitize_filename::sanitize(&file_name);
let output_path = opts.output_dir.join(&sanitized);
@@ -176,14 +177,14 @@ impl PlatformDownloader for P2pDownloader {
if file_size > 0 {
let pct = (received as f64 / file_size as f64) * 100.0;
- let _ = progress.send(pct).await;
+ let _ = progress.send(ProgressUpdate::percent(pct)).await;
}
}
file.flush().await?;
drop(file);
- let _ = progress.send(100.0).await;
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
tracing::info!("[p2p] download complete: {}", output_path.display());
diff --git a/src-tauri/src/platforms/pinterest/mod.rs b/src-tauri/src/platforms/pinterest/mod.rs
index 70a274d9..23b5fb4e 100644
--- a/src-tauri/src/platforms/pinterest/mod.rs
+++ b/src-tauri/src/platforms/pinterest/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use std::sync::LazyLock;
use anyhow::anyhow;
@@ -200,7 +201,7 @@ impl PlatformDownloader for PinterestDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
if let Some(quality) = info.available_qualities.first() {
if quality.format == "ytdlp" {
diff --git a/src-tauri/src/platforms/reddit/mod.rs b/src-tauri/src/platforms/reddit/mod.rs
index be416a24..c8c54f56 100644
--- a/src-tauri/src/platforms/reddit/mod.rs
+++ b/src-tauri/src/platforms/reddit/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use anyhow::anyhow;
use async_trait::async_trait;
use tokio::sync::mpsc;
@@ -205,7 +206,7 @@ impl RedditDownloader {
&self,
video_url: &str,
output: &std::path::Path,
- progress_tx: mpsc::Sender<f64>,
+ progress_tx: mpsc::Sender<ProgressUpdate>,
cancel: Option<&tokio_util::sync::CancellationToken>,
) -> anyhow::Result<u64> {
let variants = Self::get_resolution_variants(video_url);
@@ -370,7 +371,7 @@ impl PlatformDownloader for RedditDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
if let Some(quality) = info.available_qualities.first() {
if quality.format == "ytdlp" {
@@ -532,7 +533,7 @@ impl RedditDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
match info.media_type {
MediaType::Video => {
@@ -564,14 +565,16 @@ impl RedditDownloader {
.output_dir
.join(format!("{}.mp4", sanitize_filename::sanitize(&info.title)));
- let _ = progress.send(0.0).await;
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
- let (vtx, mut vrx) = mpsc::channel::<f64>(8);
+ let (vtx, mut vrx) = mpsc::channel::<ProgressUpdate>(8);
let progress_video = progress.clone();
tokio::spawn(async move {
while let Some(p) = vrx.recv().await {
- let scaled = p * 0.6;
- let _ = progress_video.send(scaled).await;
+ let scaled = p.percent * 0.6;
+ let _ = progress_video
+ .send(ProgressUpdate::rich(scaled, None, None, p.speed_bps, None))
+ .await;
}
});
@@ -584,15 +587,17 @@ impl RedditDownloader {
)
.await?;
- let _ = progress.send(60.0).await;
+ let _ = progress.send(ProgressUpdate::percent(60.0)).await;
let audio_url = &audio_quality.unwrap().url;
- let (atx, mut arx) = mpsc::channel::<f64>(8);
+ let (atx, mut arx) = mpsc::channel::<ProgressUpdate>(8);
let progress_audio = progress.clone();
tokio::spawn(async move {
while let Some(p) = arx.recv().await {
- let scaled = 60.0 + p * 0.25;
- let _ = progress_audio.send(scaled).await;
+ let scaled = 60.0 + p.percent * 0.25;
+ let _ = progress_audio
+ .send(ProgressUpdate::rich(scaled, None, None, p.speed_bps, None))
+ .await;
}
});
@@ -606,13 +611,13 @@ impl RedditDownloader {
.await
.is_ok();
- let _ = progress.send(85.0).await;
+ let _ = progress.send(ProgressUpdate::percent(85.0)).await;
if audio_ok && ffmpeg_available {
ffmpeg::mux_video_audio(&video_tmp, &audio_tmp, &output).await?;
let _ = tokio::fs::remove_file(&video_tmp).await;
let _ = tokio::fs::remove_file(&audio_tmp).await;
- let _ = progress.send(100.0).await;
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
let file_size = tokio::fs::metadata(&output).await?.len();
Ok(DownloadResult {
@@ -639,7 +644,7 @@ impl RedditDownloader {
let _ = tokio::fs::remove_file(&audio_tmp).await;
}
- let _ = progress.send(100.0).await;
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
Ok(DownloadResult {
file_path: video_final,
@@ -749,7 +754,7 @@ impl RedditDownloader {
last_path = output;
let percent = ((i + 1) as f64 / count as f64) * 100.0;
- let _ = progress.send(percent).await;
+ let _ = progress.send(ProgressUpdate::percent(percent)).await;
}
Ok(DownloadResult {
diff --git a/src-tauri/src/platforms/tiktok/mod.rs b/src-tauri/src/platforms/tiktok/mod.rs
index 43250f35..f8a8da4e 100644
--- a/src-tauri/src/platforms/tiktok/mod.rs
+++ b/src-tauri/src/platforms/tiktok/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use std::sync::Arc;
use anyhow::anyhow;
@@ -501,7 +502,7 @@ impl PlatformDownloader for TikTokDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
if let Some(quality) = info.available_qualities.first() {
if quality.format == "ytdlp" {
@@ -629,7 +630,7 @@ impl PlatformDownloader for TikTokDownloader {
last_path = output;
let percent = ((i + 1) as f64 / count as f64) * 100.0;
- let _ = progress.send(percent).await;
+ let _ = progress.send(ProgressUpdate::percent(percent)).await;
}
Ok(DownloadResult {
diff --git a/src-tauri/src/platforms/twitch/mod.rs b/src-tauri/src/platforms/twitch/mod.rs
index 7eb3c028..3e889d71 100644
--- a/src-tauri/src/platforms/twitch/mod.rs
+++ b/src-tauri/src/platforms/twitch/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use anyhow::anyhow;
use async_trait::async_trait;
use tokio::sync::mpsc;
@@ -294,7 +295,7 @@ impl PlatformDownloader for TwitchClipsDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
if let Some(quality) = info.available_qualities.first() {
if quality.format == "ytdlp" {
diff --git a/src-tauri/src/platforms/twitter/mod.rs b/src-tauri/src/platforms/twitter/mod.rs
index d968a171..8cf508e7 100644
--- a/src-tauri/src/platforms/twitter/mod.rs
+++ b/src-tauri/src/platforms/twitter/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use std::sync::Arc;
use anyhow::anyhow;
@@ -730,7 +731,7 @@ impl PlatformDownloader for TwitterDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
if let Some(quality) = info.available_qualities.first() {
if quality.format == "ytdlp" {
@@ -821,7 +822,7 @@ impl PlatformDownloader for TwitterDownloader {
last_path = output;
let percent = ((i + 1) as f64 / count as f64) * 100.0;
- let _ = progress.send(percent).await;
+ let _ = progress.send(ProgressUpdate::percent(percent)).await;
}
Ok(DownloadResult {
diff --git a/src-tauri/src/platforms/youtube/mod.rs b/src-tauri/src/platforms/youtube/mod.rs
index 7eb0fad9..3ebb7b36 100644
--- a/src-tauri/src/platforms/youtube/mod.rs
+++ b/src-tauri/src/platforms/youtube/mod.rs
@@ -1,3 +1,4 @@
+use omniget_core::models::progress::ProgressUpdate;
use std::collections::HashSet;
use anyhow::anyhow;
@@ -280,9 +281,9 @@ impl PlatformDownloader for YouTubeDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
- let _ = progress.send(0.0).await;
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
let ytdlp_path = if let Some(ref p) = opts.ytdlp_path {
p.clone()
@@ -343,7 +344,7 @@ impl YouTubeDownloader {
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
ytdlp_path: &std::path::Path,
quality_height: Option<u32>,
) -> anyhow::Result<DownloadResult> {
@@ -361,17 +362,19 @@ impl YouTubeDownloader {
anyhow::bail!("Download cancelado");
}
- let (video_tx, mut video_rx) = mpsc::channel::<f64>(16);
+ let (video_tx, mut video_rx) = mpsc::channel::<ProgressUpdate>(16);
let progress_tx = progress.clone();
let video_idx = i;
let video_total = total;
let forwarder = tokio::spawn(async move {
let mut max_pct = 0.0_f64;
- while let Some(pct) = video_rx.recv().await {
- max_pct = max_pct.max(pct);
+ while let Some(pu) = video_rx.recv().await {
+ max_pct = max_pct.max(pu.percent);
let overall = (video_idx as f64 / video_total as f64) * 100.0
+ (max_pct / video_total as f64);
- let _ = progress_tx.send(overall).await;
+ let _ = progress_tx
+ .send(ProgressUpdate::rich(overall, None, None, pu.speed_bps, None))
+ .await;
}
});
@@ -406,7 +409,7 @@ impl YouTubeDownloader {
let _ = forwarder.await;
}
- let _ = progress.send(100.0).await;
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
Ok(DownloadResult {
file_path: last_path,