Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
feat: enhance download functionality with speed tracking and metadata handling
Tonho0cf334ba97f7
diff --git a/src-tauri/src/external_url.rs b/src-tauri/src/external_url.rsindex ba8a64c2..c13b48b7 100644--- a/src-tauri/src/external_url.rs+++ b/src-tauri/src/external_url.rs@@ -131,21 +131,25 @@ pub async fn queue_url_with_defaults(} else {return None;};- let title = url::Url::parse(&url)- .ok()- .and_then(|u| {- let path = u.path();- let last = path.rsplit('/').next()?;- if last.is_empty() {- return None;- }- Some(- urlencoding::decode(last)- .unwrap_or_else(|_| last.into())- .to_string(),- )+ let title = m+ .title+ .as_deref()+ .filter(|s| !s.is_empty())+ .map(|s| sanitize_filename::sanitize(s))+ .or_else(|| {+ url::Url::parse(&url).ok().and_then(|u| {+ let path = u.path();+ let last = path.rsplit('/').next()?;+ if last.is_empty() {+ return None;+ }+ Some(sanitize_filename::sanitize(+ &urlencoding::decode(last)+ .unwrap_or_else(|_| last.into())+ .to_string(),+ ))+ })})- .map(|n| sanitize_filename::sanitize(&n)).unwrap_or_else(|| "download".to_string());Some(crate::models::media::MediaInfo {@@ -153,7 +157,7 @@ pub async fn queue_url_with_defaults(author: String::new(),platform: "generic".to_string(),duration_seconds: None,- thumbnail_url: None,+ thumbnail_url: m.thumbnail.clone(),available_qualities: vec![crate::models::media::VideoQuality {label: "original".to_string(),width: 0,@@ -170,20 +174,45 @@ pub async fn queue_url_with_defaults(})});+ let ext_title = ext_meta+ .as_ref()+ .and_then(|m| m.title.as_deref())+ .filter(|s| !s.is_empty())+ .map(String::from);+ let ext_thumbnail = ext_meta.as_ref().and_then(|m| m.thumbnail.clone());++ let preview_media_info = ext_media_info.or_else(|| {+ if ext_title.is_none() && ext_thumbnail.is_none() {+ return None;+ }+ Some(crate::models::media::MediaInfo {+ title: ext_title.clone().unwrap_or_else(|| url.clone()),+ author: String::new(),+ platform: "generic".to_string(),+ duration_seconds: None,+ thumbnail_url: ext_thumbnail.clone(),+ available_qualities: Vec::new(),+ media_type: crate::models::media::MediaType::Video,+ file_size_bytes: None,+ })+ });++ let queue_title = ext_title.clone().unwrap_or_else(|| url.clone());+{let mut q = download_queue.lock().await;q.enqueue(download_id,url.clone(),platform_name,- url.clone(),+ queue_title,output_dir,None,None,None,ext_referer,ext_headers,- ext_media_info,+ preview_media_info,None,None,downloader,@@ -246,8 +275,14 @@ pub async fn handle_external_url(let can_queue_directly = !settings.download.always_ask_path&& has_valid_output_dir(&settings.download.default_output_dir);+ let open_app_flag = crate::native_host::peek_extension_open_app(&url);+let action = if can_queue_directly {- match queue_url_with_defaults(app, url.clone(), false).await? {+ let outcome = queue_url_with_defaults(app, url.clone(), false).await?;+ if open_app_flag == Some(true) {+ crate::tray::show_window(app);+ }+ match outcome {QueueUrlOutcome::Queued => ExternalUrlAction::Queued,QueueUrlOutcome::AlreadyQueued => ExternalUrlAction::AlreadyQueued,}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 86474239..94f07401 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -242,6 +242,30 @@ pub fn run() {commands::p2p::p2p_get_active_sends,commands::p2p::p2p_validate_code,])- .run(tauri::generate_context!())- .expect("error while running tauri application");+ .build(tauri::generate_context!())+ .expect("error while building tauri application")+ .run(|app_handle, event| {+ if let tauri::RunEvent::ExitRequested { .. } = &event {+ let state = app_handle.state::<AppState>();+ let session_mutex = state.torrent_session.clone();+ tauri::async_runtime::block_on(async move {+ let session_guard = session_mutex.lock().await;+ let session = session_guard.as_ref().cloned();+ drop(session_guard);+ if let Some(session) = session {+ match tokio::time::timeout(+ std::time::Duration::from_secs(5),+ session.stop(),+ )+ .await+ {+ Ok(()) => tracing::info!("torrent session stopped cleanly"),+ Err(_) => tracing::warn!(+ "torrent session stop timed out after 5s; exiting anyway"+ ),+ }+ }+ });+ }+ });}diff --git a/src-tauri/src/native_host.rs b/src-tauri/src/native_host.rsindex 66f67995..397f71bd 100644--- a/src-tauri/src/native_host.rs+++ b/src-tauri/src/native_host.rs@@ -33,6 +33,12 @@ struct NativeHostRequest {media_type: Option<String>,#[serde(default, rename = "contentType")]content_type: Option<String>,+ #[serde(default)]+ title: Option<String>,+ #[serde(default)]+ thumbnail: Option<String>,+ #[serde(default, rename = "openApp")]+ open_app: Option<bool>,}#[derive(Debug, Deserialize)]@@ -462,6 +468,9 @@ fn write_extension_metadata(request: &NativeHostRequest) -> anyhow::Result<()> {"headers": request.headers,"mediaType": request.media_type,"contentType": request.content_type,+ "title": request.title,+ "thumbnail": request.thumbnail,+ "openApp": request.open_app,"timestamp": now,});@@ -474,6 +483,9 @@ pub struct ExtensionMetadata {pub headers: Option<std::collections::HashMap<String, String>>,pub media_type: Option<String>,pub content_type: Option<String>,+ pub title: Option<String>,+ pub thumbnail: Option<String>,+ pub open_app: Option<bool>,}pub fn read_extension_metadata(url: &str) -> Option<ExtensionMetadata> {@@ -515,6 +527,17 @@ pub fn read_extension_metadata(url: &str) -> Option<ExtensionMetadata> {.get("contentType").and_then(|v| v.as_str()).map(String::from),+ title: meta+ .get("title")+ .and_then(|v| v.as_str())+ .filter(|s| !s.is_empty())+ .map(String::from),+ thumbnail: meta+ .get("thumbnail")+ .and_then(|v| v.as_str())+ .filter(|s| !s.is_empty())+ .map(String::from),+ open_app: meta.get("openApp").and_then(|v| v.as_bool()),};let _ = fs::remove_file(&path);@@ -522,6 +545,28 @@ pub fn read_extension_metadata(url: &str) -> Option<ExtensionMetadata> {Some(result)}+pub fn peek_extension_open_app(url: &str) -> Option<bool> {+ let path = extension_metadata_path();+ let content = fs::read_to_string(&path).ok()?;+ let meta: serde_json::Value = serde_json::from_str(&content).ok()?;++ let meta_url = meta.get("url")?.as_str()?;+ if meta_url != url {+ return None;+ }++ let timestamp = meta.get("timestamp")?.as_u64()?;+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs();+ if now.saturating_sub(timestamp) > 60 {+ return None;+ }++ meta.get("openApp").and_then(|v| v.as_bool())+}+fn handle_request(request: NativeHostRequest) -> NativeHostResponse {if request.kind != "enqueue" {return NativeHostResponse {@@ -547,7 +592,13 @@ fn handle_request(request: NativeHostRequest) -> NativeHostResponse {}}- if request.referer.is_some() || request.headers.is_some() || request.media_type.is_some() {+ if request.referer.is_some()+ || request.headers.is_some()+ || request.media_type.is_some()+ || request.title.is_some()+ || request.thumbnail.is_some()+ || request.open_app.is_some()+ {if let Err(e) = write_extension_metadata(&request) {eprintln!("[OmniGet] Warning: failed to write extension metadata: {e}");}diff --git a/src-tauri/src/platforms/pinterest/mod.rs b/src-tauri/src/platforms/pinterest/mod.rsindex f8569169..e5f8df5d 100644--- a/src-tauri/src/platforms/pinterest/mod.rs+++ b/src-tauri/src/platforms/pinterest/mod.rs@@ -1,3 +1,5 @@+use std::sync::LazyLock;+use anyhow::anyhow;use async_trait::async_trait;use regex::Regex;@@ -10,6 +12,18 @@ use crate::platforms::traits::PlatformDownloader;const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";+static PIN_NOT_FOUND_RE: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(r#""__typename"\s*:\s*"PinNotFound""#).expect("valid PIN_NOT_FOUND_RE")+});++static VIDEO_URL_RE: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(r#""url":"(https://v1\.pinimg\.com/videos/.*?)""#).expect("valid VIDEO_URL_RE")+});++static IMAGE_URL_RE: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(r#"src="(https://i\.pinimg\.com/.*?\.(jpg|gif))""#).expect("valid IMAGE_URL_RE")+});+pub struct PinterestDownloader {client: reqwest::Client,}@@ -102,24 +116,20 @@ impl PinterestDownloader {}fn check_pin_not_found(html: &str) -> bool {- let re = Regex::new(r#""__typename"\s*:\s*"PinNotFound""#).unwrap();- re.is_match(html)+ PIN_NOT_FOUND_RE.is_match(html)}fn extract_video_url(html: &str) -> Option<String> {- let re = Regex::new(r#""url":"(https://v1\.pinimg\.com/videos/.*?)""#).unwrap();- let result = re+ VIDEO_URL_RE.captures_iter(html).filter_map(|cap| cap.get(1).map(|m| m.as_str().to_string()))- .find(|url| url.ends_with(".mp4"));- result+ .find(|url| url.ends_with(".mp4"))}fn extract_image_url(html: &str) -> Option<(String, bool)> {- let re = Regex::new(r#"src="(https://i\.pinimg\.com/.*?\.(jpg|gif))""#).unwrap();let mut best: Option<(String, bool)> = None;- for cap in re.captures_iter(html) {+ for cap in IMAGE_URL_RE.captures_iter(html) {if let Some(url_match) = cap.get(1) {let url = url_match.as_str().to_string();let is_gif = url.ends_with(".gif");diff --git a/src/routes/about/+page.svelte b/src/routes/about/+page.svelteindex 45217075..17ff50fb 100644--- a/src/routes/about/+page.svelte+++ b/src/routes/about/+page.svelte@@ -1,12 +1,19 @@<script lang="ts">import { t } from "$lib/i18n";import { getVersion } from "@tauri-apps/api/app";+ import { BUILD_INFO } from "$lib/build-info";let version = $state("");$effect(() => {getVersion().then(v => { version = v; }).catch(() => {});});++ const buildDetails = $derived(+ [BUILD_INFO.commitShort, BUILD_INFO.branch, BUILD_INFO.date]+ .filter((part) => part && part !== "unknown")+ .join(" · ")+ );</script><div class="about-page">@@ -18,6 +25,9 @@{#if version}<span class="about-version">{$t("about.version")} {version}</span>{/if}+ {#if buildDetails}+ <span class="about-build">{buildDetails}</span>+ {/if}</div><div class="about-links">@@ -98,6 +108,15 @@border-radius: var(--border-radius);}+ .about-build {+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);+ font-size: 10.5px;+ color: var(--tertiary);+ opacity: 0.75;+ letter-spacing: 0.3px;+ user-select: all;+ }+.about-links {display: flex;flex-wrap: wrap;diff --git a/src/routes/courses/[platform]/+page.svelte b/src/routes/courses/[platform]/+page.svelteindex 667889e6..98200686 100644--- a/src/routes/courses/[platform]/+page.svelte+++ b/src/routes/courses/[platform]/+page.svelte@@ -323,7 +323,7 @@}function getDownloadStatus(item: any): "idle" | "downloading" | "complete" | "error" {- const id = getItemId(item);+ const id = Number(getItemId(item));const dl = downloads.get(id);if (!dl) return "idle";const s = dl.status;@@ -332,7 +332,7 @@}function getDownloadPercent(item: any): number {- return downloads.get(getItemId(item))?.percent ?? 0;+ return downloads.get(Number(getItemId(item)))?.percent ?? 0;}async function downloadItem(item: any) {diff --git a/src/routes/downloads/+page.svelte b/src/routes/downloads/+page.svelteindex b3b0cb81..ab2f9e2e 100644--- a/src/routes/downloads/+page.svelte+++ b/src/routes/downloads/+page.svelte@@ -8,6 +8,7 @@formatBytes,formatSpeed,getFinishedCount,+ getSpeedHistory,type CourseDownloadItem,type GenericDownloadItem,} from "$lib/stores/download-store.svelte";@@ -15,6 +16,7 @@import PlatformIcon from "$components/icons/PlatformIcon.svelte";import Mascot from "$components/mascot/Mascot.svelte";import ContextHint from "$components/hints/ContextHint.svelte";+ import DownloadSpeedGraph from "$components/download/DownloadSpeedGraph.svelte";let downloads = $derived(getDownloads());let courseList = $derived(@@ -388,6 +390,7 @@{/if}{#if item.speed > 0}<span>{formatSpeed(item.speed)}</span>+ <DownloadSpeedGraph points={getSpeedHistory(item.id)} />{/if}</div>{/if}@@ -400,6 +403,7 @@{/if}{#if item.speed > 0}<span>{formatSpeed(item.speed)}</span>+ <DownloadSpeedGraph points={getSpeedHistory(item.id)} />{/if}</div>{:else if item.status === "paused"}@@ -479,6 +483,9 @@<div class="item-stats"><span>{formatSpeed(item.speed)}</span>+ {#if item.speed > 0}+ <DownloadSpeedGraph points={getSpeedHistory(item.id)} />+ {/if}</div>{/if}