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: enhance Instagram downloader with error handling and last download options persistence

Tonho4cb27c0426c5
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 8c38d66c..d0b56591 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use std::sync::Arc;
use tauri::Manager;
+use tauri_plugin_deep_link::DeepLinkExt;
use tokio_util::sync::CancellationToken;
@@ -167,6 +168,22 @@ pub fn run() {
});
}
}
+ {
+ let app_handle = app.handle().clone();
+ app.deep_link().on_open_url(move |event| {
+ for url in event.urls() {
+ let raw = url.to_string();
+ let handle = app_handle.clone();
+ tauri::async_runtime::spawn(async move {
+ if let Err(error) =
+ external_url::handle_external_url(&handle, raw, "deep-link").await
+ {
+ tracing::warn!("Failed to handle deep-link URL: {}", error);
+ }
+ });
+ }
+ });
+ }
tray::setup(app.handle())?;
hotkey::register_from_settings(app.handle());
if let Err(error) = native_host::ensure_registered() {
diff --git a/src-tauri/src/platforms/instagram/mod.rs b/src-tauri/src/platforms/instagram/mod.rs
index a5068562..713c3b47 100644
--- a/src-tauri/src/platforms/instagram/mod.rs
+++ b/src-tauri/src/platforms/instagram/mod.rs
@@ -539,6 +539,44 @@ impl InstagramDownloader {
headers
}
+ fn post_url_from_title(title: &str) -> Option<String> {
+ let post_id = title.strip_prefix("instagram_")?;
+ if post_id.is_empty() {
+ return None;
+ }
+ Some(format!("https://www.instagram.com/p/{}/", post_id))
+ }
+
+ fn is_html_block_error(err: &anyhow::Error) -> bool {
+ let msg = err.to_string();
+ msg.contains("HTML instead of media")
+ }
+
+ async fn ytdlp_download_post(
+ post_url: &str,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;
+ crate::core::ytdlp::download_video(
+ &ytdlp_path,
+ post_url,
+ &opts.output_dir,
+ None,
+ progress,
+ opts.download_mode.as_deref(),
+ opts.format_id.as_deref(),
+ opts.filename_template.as_deref(),
+ Some("https://www.instagram.com/"),
+ opts.cancel_token.clone(),
+ None,
+ opts.concurrent_fragments,
+ false,
+ &[],
+ )
+ .await
+ }
+
fn extract_media_from_embed(data: &serde_json::Value) -> anyhow::Result<InstagramMedia> {
if let Some(video_url) = data.get("gql_data").and_then(|g| {
g.get("shortcode_media")
@@ -695,24 +733,7 @@ impl PlatformDownloader for InstagramDownloader {
let quality = info.available_qualities.first().unwrap();
if quality.format == "ytdlp" {
- let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;
- return crate::core::ytdlp::download_video(
- &ytdlp_path,
- &quality.url,
- &opts.output_dir,
- None,
- progress,
- opts.download_mode.as_deref(),
- opts.format_id.as_deref(),
- opts.filename_template.as_deref(),
- Some("https://www.instagram.com/"),
- opts.cancel_token.clone(),
- None,
- opts.concurrent_fragments,
- false,
- &[],
- )
- .await;
+ return Self::ytdlp_download_post(&quality.url, opts, progress).await;
}
let filename = format!(
@@ -724,22 +745,37 @@ impl PlatformDownloader for InstagramDownloader {
let headers = Some(Self::instagram_headers());
- let bytes = download_direct_with_headers(
+ match download_direct_with_headers(
&self.client,
&quality.url,
&output,
- progress,
+ progress.clone(),
headers,
None,
)
- .await?;
-
- return Ok(DownloadResult {
- file_path: output,
- file_size_bytes: bytes,
- duration_seconds: 0.0,
- torrent_id: None,
- });
+ .await
+ {
+ Ok(bytes) => {
+ return Ok(DownloadResult {
+ file_path: output,
+ file_size_bytes: bytes,
+ duration_seconds: 0.0,
+ torrent_id: None,
+ });
+ }
+ Err(e) => {
+ if Self::is_html_block_error(&e) {
+ if let Some(post_url) = Self::post_url_from_title(&info.title) {
+ tracing::warn!(
+ "[instagram] direct CDN fetch returned HTML for {}; falling back to yt-dlp",
+ post_url
+ );
+ return Self::ytdlp_download_post(&post_url, opts, progress).await;
+ }
+ }
+ return Err(e);
+ }
+ }
}
let mut total_bytes = 0u64;
@@ -757,7 +793,7 @@ impl PlatformDownloader for InstagramDownloader {
let headers = Some(Self::instagram_headers());
- let bytes = download_direct_with_headers(
+ match download_direct_with_headers(
&self.client,
&quality.url,
&output,
@@ -765,13 +801,30 @@ impl PlatformDownloader for InstagramDownloader {
headers,
None,
)
- .await?;
-
- total_bytes += bytes;
- last_path = output;
-
- let percent = ((i + 1) as f64 / count as f64) * 100.0;
- let _ = progress.send(percent).await;
+ .await
+ {
+ Ok(bytes) => {
+ total_bytes += bytes;
+ last_path = output;
+
+ let percent = ((i + 1) as f64 / count as f64) * 100.0;
+ let _ = progress.send(percent).await;
+ }
+ Err(e) => {
+ if Self::is_html_block_error(&e) {
+ if let Some(post_url) = Self::post_url_from_title(&info.title) {
+ tracing::warn!(
+ "[instagram] carousel item {}/{} returned HTML for {}; falling back to yt-dlp for full post",
+ i + 1,
+ count,
+ post_url
+ );
+ return Self::ytdlp_download_post(&post_url, opts, progress).await;
+ }
+ }
+ return Err(e);
+ }
+ }
}
Ok(DownloadResult {
diff --git a/src/lib/stores/settings-store.svelte.ts b/src/lib/stores/settings-store.svelte.ts
index 35cc716b..50934bcf 100644
--- a/src/lib/stores/settings-store.svelte.ts
+++ b/src/lib/stores/settings-store.svelte.ts
@@ -49,6 +49,10 @@ export type AppSettings = {
onboarding_completed: boolean;
start_with_windows: boolean;
legal_acknowledged?: boolean;
+ last_download_options?: {
+ mode?: "auto" | "audio" | "mute" | null;
+ quality?: string | null;
+ };
};
let settings = $state<AppSettings | null>(null);
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index 6a199b5f..92740e72 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -19,6 +19,7 @@
import ConfirmCloseDialog from "$components/dialog/ConfirmCloseDialog.svelte";
import ShortcutsDialog from "$components/dialog/ShortcutsDialog.svelte";
import LegalDialog from "$components/dialog/LegalDialog.svelte";
+ import RecoveryDialog from "$components/dialog/RecoveryDialog.svelte";
import OnboardingWizard from "$components/onboarding/OnboardingWizard.svelte";
import { needsOnboarding } from "$lib/stores/onboarding-store.svelte";
import { isYtdlpAvailable, isDepsChecked, refreshYtdlpStatus } from "$lib/stores/dependency-store.svelte";
@@ -245,6 +246,7 @@
<ConfirmCloseDialog />
<ShortcutsDialog />
<LegalDialog />
+<RecoveryDialog />
{#if showOnboarding}
<OnboardingWizard />
{/if}
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index 8ea50339..36621871 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -15,7 +15,7 @@
import P2pSendDialog from "$components/p2p/P2pSendDialog.svelte";
import P2pReceiveDialog from "$components/p2p/P2pReceiveDialog.svelte";
import { getDownloads } from "$lib/stores/download-store.svelte";
- import { getSettings } from "$lib/stores/settings-store.svelte";
+ import { getSettings, updateSettings } from "$lib/stores/settings-store.svelte";
import { showToast } from "$lib/stores/toast-store.svelte";
import { onClipboardUrl } from "$lib/stores/clipboard-monitor";
import { getMediaPreview, clearMediaPreview } from "$lib/stores/media-preview-store.svelte";
@@ -238,7 +238,11 @@
function handleInput() {
if (debounceTimer) clearTimeout(debounceTimer);
clearMediaPreview();
- selectedQuality = "best";
+ const saved = getSettings()?.last_download_options;
+ const savedQuality = saved?.quality;
+ const savedMode = saved?.mode;
+ selectedQuality = savedQuality && typeof savedQuality === "string" ? savedQuality : "best";
+ downloadMode = savedMode === "audio" || savedMode === "mute" ? savedMode : "auto";
selectedFormatId = null;
formats = [];
loadingFormats = false;
@@ -395,6 +399,19 @@
selectedFormatId = null;
}
+ function persistLastDownloadOptions() {
+ const saved = getSettings()?.last_download_options;
+ const nextMode = downloadMode;
+ const nextQuality = selectedQuality;
+ if (saved?.mode === nextMode && saved?.quality === nextQuality) return;
+ updateSettings({
+ last_download_options: {
+ mode: nextMode,
+ quality: nextQuality,
+ },
+ }).catch(() => {});
+ }
+
async function handleAction() {
if (omniState.kind !== "detected") return;
const info = omniState.info;
@@ -438,6 +455,7 @@
formatId: selectedFormatId,
referer: referer.trim() || null,
});
+ persistLastDownloadOptions();
omniState = { kind: "idle" };
} catch (e: any) {
const msg = typeof e === "string" ? e : e.message ?? $t("omnibox.error");
@@ -483,6 +501,7 @@
const queued = results.filter(r => r.status === "fulfilled").length;
if (queued > 0) {
showToast("info", $t("omnibox.batch_queued", { count: queued }));
+ persistLastDownloadOptions();
}
}
@@ -546,6 +565,32 @@
}
}
+ async function openBatchFile() {
+ const selected = await open({
+ title: $t("omnibox.batch_file_title"),
+ filters: [{ name: "Text", extensions: ["txt"] }],
+ multiple: false,
+ });
+ if (!selected || typeof selected !== "string") return;
+ try {
+ const urls = await invoke<string[]>("parse_batch_file", { path: selected });
+ if (urls.length === 0) {
+ showToast("info", $t("omnibox.batch_file_empty"));
+ return;
+ }
+ if (urls.length === 1) {
+ url = urls[0];
+ handleInput();
+ return;
+ }
+ url = urls.join("\n");
+ omniState = { kind: "batch", urls };
+ } catch (e: any) {
+ const msg = typeof e === "string" ? e : e.message ?? $t("omnibox.error");
+ showToast("error", msg);
+ }
+ }
+
function handleDismiss() {
clearMediaPreview();
omniState = { kind: "idle" };
@@ -757,6 +802,15 @@
</svg>
{$t("torrent.open_file")}
</button>
+ <button class="quick-action-btn" onclick={openBatchFile}>
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
+ <polyline points="14 2 14 8 20 8" />
+ <line x1="8" y1="13" x2="16" y2="13" />
+ <line x1="8" y1="17" x2="16" y2="17" />
+ </svg>
+ {$t("omnibox.batch_file_open")}
+ </button>
</div>
<div class="terms-note">