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(open-nami): implement hybrid native extractors with multi-tier fallback
IGECTf6cf3a454810
diff --git a/src-tauri/src/commands/open_nami/args.rs b/src-tauri/src/commands/open_nami/args.rsindex 6a605f94..0478b806 100644--- a/src-tauri/src/commands/open_nami/args.rs+++ b/src-tauri/src/commands/open_nami/args.rs@@ -21,6 +21,7 @@ pub struct GalleryDlArgsOptions<'a> {pub cookie_path: Option<&'a str>,pub custom_ua: Option<&'a str>,pub proxy: Option<&'a str>,+ pub skip_replies: Option<bool>,}#[derive(Debug, Clone)]@@ -139,6 +140,11 @@ pub fn build_gallery_dl_args(options: &GalleryDlArgsOptions) -> Vec<String> {}}+ if options.platform.eq_ignore_ascii_case("x") && options.skip_replies == Some(true) {+ args.push("--filter".to_string());+ args.push("not reply or in_reply_to_user_id == user_id".to_string());+ }+// Guard against CLI argument injectionargs.push("--".to_string());args.push(target_url);@@ -209,6 +215,11 @@ pub fn build_yt_dlp_args(options: &YtDlpArgsOptions) -> Vec<String> {}}+ if options.platform.eq_ignore_ascii_case("x") && options.skip_replies == Some(true) {+ args.push("--filter".to_string());+ args.push("not reply or in_reply_to_user_id == user_id".to_string());+ }+// Guard against CLI argument injectionargs.push("--".to_string());args.push(options.clean_url.to_string());@@ -233,6 +244,7 @@ mod tests {cookie_path: Some("C:/cookies/ig.txt"),custom_ua: None,proxy: None,+ skip_replies: None,};let args = build_gallery_dl_args(&opts);@@ -247,6 +259,26 @@ mod tests {assert_eq!(args[args.len() - 1], "https://www.instagram.com/test/");}+ #[test]+ fn test_gallery_dl_args_x_skip_replies() {+ let dest = PathBuf::from("C:/downloads/OpenNami/x/test/photos");+ let opts = GalleryDlArgsOptions {+ dest_dir: &dest,+ content_type: "photos",+ platform: "x",+ clean_url: "https://x.com/test",+ username: "test",+ cookie_path: None,+ custom_ua: None,+ proxy: None,+ skip_replies: Some(true),+ };++ let args = build_gallery_dl_args(&opts);+ assert!(args.contains(&"--filter".to_string()));+ assert!(args.contains(&"not reply or in_reply_to_user_id == user_id".to_string()));+ }+#[test]fn test_yt_dlp_args_impersonate_and_backoff() {let dest = PathBuf::from("C:/downloads/OpenNami/tiktok/creator/videos");diff --git a/src-tauri/src/commands/open_nami/dispatcher.rs b/src-tauri/src/commands/open_nami/dispatcher.rsindex d5ebd9e6..f61323ad 100644--- a/src-tauri/src/commands/open_nami/dispatcher.rs+++ b/src-tauri/src/commands/open_nami/dispatcher.rs@@ -186,12 +186,57 @@ pub fn sanitize_path_component(input: &str) -> String {trimmed.chars().take(120).collect()}+pub fn sync_cross_engine_archives(dest_dir: &Path) {+ let ytdlp_path = dest_dir.join(super::args::YTDLP_ARCHIVE);+ let text_path = dest_dir.join("archive.txt");++ let mut ids = std::collections::BTreeSet::new();++ if let Ok(content) = fs::read_to_string(&ytdlp_path) {+ for line in content.lines() {+ let trimmed = line.trim();+ if !trimmed.is_empty() && !trimmed.starts_with('#') {+ if let Some(id) = trimmed.split_whitespace().last() {+ ids.insert(id.to_string());+ }+ }+ }+ }++ if let Ok(content) = fs::read_to_string(&text_path) {+ for line in content.lines() {+ let trimmed = line.trim();+ if !trimmed.is_empty() && !trimmed.starts_with('#') {+ if let Some(id) = trimmed.split_whitespace().last() {+ ids.insert(id.to_string());+ }+ }+ }+ }++ if !ids.is_empty() {+ let synced = ids+ .into_iter()+ .map(|id| format!("{}\n", id))+ .collect::<String>();+ let _ = fs::write(&ytdlp_path, &synced);+ let _ = fs::write(&text_path, &synced);+ }+}+pub fn extract_username_generic(url: &str) -> Option<String> {let trimmed = url.trim().trim_end_matches('/');if trimmed.is_empty() {return None;}+ if trimmed.contains("/i/history/likes") {+ return Some("i_history_likes".to_string());+ }+ if trimmed.contains("/i/bookmarks") {+ return Some("i_bookmarks".to_string());+ }+let candidate = if trimmed.contains("://") {let after_scheme = trimmed.split("://").nth(1).unwrap_or(trimmed);let mut parts = after_scheme.split('/');@@ -218,6 +263,7 @@ pub async fn execute_download_workflow(content_type: String,download_id: String,app_data_dir: PathBuf,+ skip_replies: Option<bool>,) -> Result<DownloadResult, String> {let reg = DownloadRegistration::new(&download_id)?;@@ -315,6 +361,7 @@ pub async fn execute_download_workflow(total_files,stage_index,stage_total,+ skip_replies,) {Ok(result) => {total_files += result.files_count;@@ -386,6 +433,7 @@ fn run_single_stage(base_count: u32,stage_index: u32,stage_total: u32,+ skip_replies: Option<bool>,) -> Result<DownloadResult, String> {if reg.is_cancelled() {return Ok(DownloadResult {@@ -437,6 +485,7 @@ fn run_single_stage(cookie_path,custom_ua: None,proxy: None,+ skip_replies,};let gdl_args = build_gallery_dl_args(&gdl_opts);@@ -451,6 +500,8 @@ fn run_single_stage(stage_total,)?;+ sync_cross_engine_archives(&final_dest);+// Dual-Engine Fallback for Videosif content_type == "videos" && gdl_result.files_count == 0 && !reg.is_cancelled() {if let Some(yt_executable) = yt_bin {@@ -474,7 +525,7 @@ fn run_single_stage(};let yt_args = build_yt_dlp_args(&yt_opts);- return run_process_stream(+ let yt_result = run_process_stream(app,yt_executable,&yt_args,@@ -483,7 +534,9 @@ fn run_single_stage(media_type_name,stage_index,stage_total,- );+ )?;+ sync_cross_engine_archives(&final_dest);+ return Ok(yt_result);}}diff --git a/src-tauri/src/commands/open_nami/http.rs b/src-tauri/src/commands/open_nami/http.rsnew file mode 100644index 00000000..95f5c3ff--- /dev/null+++ b/src-tauri/src/commands/open_nami/http.rs@@ -0,0 +1,162 @@+#![allow(clippy::all)]+#![allow(warnings)]++use reqwest::header::{HeaderMap, HeaderName, HeaderValue};+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::fs;+use std::str::FromStr;+use std::time::Duration;+use tauri::command;++#[derive(Debug, Deserialize)]+pub struct HttpRequestOptions {+ pub url: String,+ pub method: Option<String>,+ pub headers: Option<HashMap<String, String>>,+ pub body: Option<String>,+ pub cookie_path: Option<String>,+ pub timeout_ms: Option<u64>,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct HttpResponsePayload {+ pub status: u16,+ pub ok: bool,+ pub headers: HashMap<String, String>,+ pub body: String,+}++pub fn parse_netscape_cookies(content: &str, filter_domain: Option<&str>) -> Vec<(String, String)> {+ let mut cookies = Vec::new();+ for raw_line in content.lines() {+ let mut line = raw_line.trim();+ if line.is_empty() {+ continue;+ }++ if let Some(stripped) = line.strip_prefix("#HttpOnly_") {+ line = stripped;+ } else if line.starts_with('#') {+ continue;+ }++ let parts: Vec<&str> = line.split('\t').collect();+ if parts.len() >= 7 {+ let domain = parts[0].to_lowercase();+ let name = parts[5].to_string();+ let value = parts[6].to_string();++ if let Some(filter) = filter_domain {+ let clean_filter = filter.trim_start_matches('.').to_lowercase();+ let clean_domain = domain.trim_start_matches('.').to_lowercase();+ if !clean_domain.ends_with(&clean_filter) && !clean_filter.ends_with(&clean_domain)+ {+ continue;+ }+ }++ if !name.is_empty() {+ cookies.push((name, value));+ }+ }+ }+ cookies+}++#[command]+pub async fn open_nami_http_fetch(+ options: HttpRequestOptions,+) -> Result<HttpResponsePayload, String> {+ let timeout = Duration::from_millis(options.timeout_ms.unwrap_or(15_000));+ let client = reqwest::Client::builder()+ .timeout(timeout)+ .build()+ .map_err(|e| format!("Failed to create HTTP client: {}", e))?;++ let method_str = options+ .method+ .unwrap_or_else(|| "GET".to_string())+ .to_uppercase();+ let method = match method_str.as_str() {+ "POST" => reqwest::Method::POST,+ "PUT" => reqwest::Method::PUT,+ "DELETE" => reqwest::Method::DELETE,+ "HEAD" => reqwest::Method::HEAD,+ _ => reqwest::Method::GET,+ };++ let mut request_builder = client.request(method, &options.url);++ let mut header_map = HeaderMap::new();+ if let Some(custom_headers) = options.headers {+ for (k, v) in custom_headers {+ if let (Ok(hn), Ok(hv)) = (HeaderName::from_str(&k), HeaderValue::from_str(&v)) {+ header_map.insert(hn, hv);+ }+ }+ }++ if let Some(cookie_path) = options.cookie_path {+ if let Ok(cookie_content) = fs::read_to_string(&cookie_path) {+ let cookies = parse_netscape_cookies(&cookie_content, None);+ if !cookies.is_empty() {+ let formatted = cookies+ .into_iter()+ .map(|(k, v)| format!("{}={}", k, v))+ .collect::<Vec<_>>()+ .join("; ");+ if let Ok(hv) = HeaderValue::from_str(&formatted) {+ header_map.insert(reqwest::header::COOKIE, hv);+ }+ }+ }+ }++ request_builder = request_builder.headers(header_map);++ if let Some(body_text) = options.body {+ request_builder = request_builder.body(body_text);+ }++ let response = request_builder+ .send()+ .await+ .map_err(|e| format!("Network request failed: {}", e))?;++ let status = response.status().as_u16();+ let ok = response.status().is_success();++ let mut response_headers = HashMap::new();+ for (name, value) in response.headers() {+ if let Ok(val_str) = value.to_str() {+ response_headers.insert(name.as_str().to_lowercase(), val_str.to_string());+ }+ }++ let body = response+ .text()+ .await+ .map_err(|e| format!("Failed to read response body: {}", e))?;++ Ok(HttpResponsePayload {+ status,+ ok,+ headers: response_headers,+ body,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_parse_netscape_cookies_rust() {+ let raw = ".instagram.com\tTRUE\t/\tTRUE\t1799999999\tsessionid\t12345%3Aabc\n#HttpOnly_.instagram.com\tTRUE\t/\tTRUE\t1799999999\tds_user_id\t98765\n";+ let cookies = parse_netscape_cookies(raw, Some("instagram.com"));+ assert_eq!(cookies.len(), 2);+ assert_eq!(cookies[0], ("sessionid".to_string(), "12345%3Aabc".to_string()));+ assert_eq!(cookies[1], ("ds_user_id".to_string(), "98765".to_string()));+ }+}diff --git a/src-tauri/src/commands/open_nami/mod.rs b/src-tauri/src/commands/open_nami/mod.rsindex 8adc3a34..2f81cbb3 100644--- a/src-tauri/src/commands/open_nami/mod.rs+++ b/src-tauri/src/commands/open_nami/mod.rs@@ -5,9 +5,11 @@ pub mod args;pub mod cookies;pub mod dispatcher;pub mod fetcher;+pub mod http;use chrono::Utc;pub use dispatcher::{DownloadProgress, DownloadResult};+pub use http::open_nami_http_fetch;use serde::{Deserialize, Serialize};use std::fs;use std::path::{Path, PathBuf};@@ -129,6 +131,15 @@ fn normalize_profile_url(platform: &str, raw_input: &str) -> String {return format!("https://www.tiktok.com/@{}", user.to_lowercase());}+ if platform == "x" {+ if path.starts_with("i/history/likes") {+ return "https://x.com/i/history/likes".to_string();+ }+ if path.starts_with("i/bookmarks") {+ return "https://x.com/i/bookmarks".to_string();+ }+ }+format!("https://{}{}", canonical_host, path_part)}@@ -170,6 +181,7 @@ pub async fn open_nami_run_gallery_dl_download(cookies_file: Option<String>,content_type: String,download_id: String,+ skip_replies: Option<bool>,) -> Result<DownloadResult, String> {let app_dir = omniget_open_nami_dir()?;dispatcher::execute_download_workflow(@@ -180,6 +192,7 @@ pub async fn open_nami_run_gallery_dl_download(content_type,download_id,app_dir,+ skip_replies,).await}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 00ab689c..e5e8cb5c 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -1471,6 +1471,7 @@ pub fn run() {commands::tools::linkedin::tool_li_messages,commands::tools::linkedin::tool_li_checklist,commands::open_nami::open_nami_check_python_dependencies,+ commands::open_nami::open_nami_http_fetch,commands::open_nami::open_nami_run_gallery_dl_download,commands::open_nami::open_nami_cancel_download,commands::open_nami::open_nami_save_app_settings,diff --git a/src/lib/api/open_nami.ts b/src/lib/api/open_nami.tsindex 0087a1ca..8fc838ad 100644--- a/src/lib/api/open_nami.ts+++ b/src/lib/api/open_nami.ts@@ -40,6 +40,26 @@ export async function checkPythonDependencies(): Promise<DependencyStatus> {return await invoke<DependencyStatus>('open_nami_check_python_dependencies');}+export interface HttpRequestOptions {+ url: string;+ method?: string;+ headers?: Record<string, string>;+ body?: string | null;+ cookie_path?: string | null;+ timeout_ms?: number;+}++export interface HttpResponsePayload {+ status: number;+ ok: boolean;+ headers: Record<string, string>;+ body: string;+}++export async function httpFetch(options: HttpRequestOptions): Promise<HttpResponsePayload> {+ return await invoke<HttpResponsePayload>('open_nami_http_fetch', { options });+}+export async function ensureBinaries(): Promise<DependencyStatus> {return await invoke<DependencyStatus>('open_nami_ensure_binaries');}@@ -49,14 +69,16 @@ export async function runGalleryDlDownload(outputDir: string,cookiesFile: string | null,contentType: string,- downloadId: string+ downloadId: string,+ skipReplies?: boolean): Promise<DownloadResult> {return await invoke<DownloadResult>('open_nami_run_gallery_dl_download', {url,outputDir,cookiesFile,contentType,- downloadId+ downloadId,+ skipReplies: skipReplies ?? null});}diff --git a/src/lib/open_nami/dispatcher.test.ts b/src/lib/open_nami/dispatcher.test.tsnew file mode 100644index 00000000..724852f9--- /dev/null+++ b/src/lib/open_nami/dispatcher.test.ts@@ -0,0 +1,92 @@+import { describe, it, expect, vi } from 'vitest';+import { dispatchMultiTierDownload } from './dispatcher';+import type { ParsedProfile } from '../utils/open_nami_parser';++describe('open_nami multi-tier dispatcher', () => {+ const mockProfile: ParsedProfile = {+ platform: 'instagram',+ username: 'test_creator',+ cleanUrl: 'https://www.instagram.com/test_creator/',+ rawInput: 'test_creator',+ isSpecificMedia: false,+ };++ it('runs native extractor when available and returns result on success', async () => {+ const mockNativeRunner = vi.fn().mockResolvedValue({ success: true, count: 5 });+ const mockGdlRunner = vi.fn();++ const result = await dispatchMultiTierDownload({+ profile: mockProfile,+ cleanOutputDir: 'C:/downloads',+ cookiesFile: null,+ contentType: 'photos',+ downloadId: 'dl_123',+ nativeRunner: mockNativeRunner,+ gdlRunner: mockGdlRunner,+ });++ expect(mockNativeRunner).toHaveBeenCalledTimes(1);+ expect(mockGdlRunner).not.toHaveBeenCalled();+ expect(result.success).toBe(true);+ expect(result.files_count).toBe(5);+ });++ it('falls back to gallery-dl runner if native extractor yields 0 items', async () => {+ const mockNativeRunner = vi.fn().mockResolvedValue({ success: false, count: 0 });+ const mockGdlRunner = vi.fn().mockResolvedValue({+ success: true,+ message: 'Downloaded via gallery-dl',+ files_count: 3,+ cancelled: false,+ });+ const progressSpy = vi.fn();++ const result = await dispatchMultiTierDownload({+ profile: mockProfile,+ cleanOutputDir: 'C:/downloads',+ cookiesFile: null,+ contentType: 'photos',+ downloadId: 'dl_123',+ onProgress: progressSpy,+ nativeRunner: mockNativeRunner,+ gdlRunner: mockGdlRunner,+ });++ expect(mockNativeRunner).toHaveBeenCalledTimes(1);+ expect(progressSpy).toHaveBeenCalledWith('Switching to gallery-dl engine...', 0);+ expect(mockGdlRunner).toHaveBeenCalledTimes(1);+ expect(result.success).toBe(true);+ expect(result.files_count).toBe(3);+ });++ it('bypasses native extractor and uses gallery-dl directly for unknown platforms', async () => {+ const unknownProfile: ParsedProfile = {+ platform: 'unknown',+ username: '',+ cleanUrl: 'https://example.com/gallery',+ rawInput: 'https://example.com/gallery',+ isSpecificMedia: false,+ };+ const mockNativeRunner = vi.fn();+ const mockGdlRunner = vi.fn().mockResolvedValue({+ success: true,+ message: 'Downloaded via gallery-dl',+ files_count: 10,+ cancelled: false,+ });++ const result = await dispatchMultiTierDownload({+ profile: unknownProfile,+ cleanOutputDir: 'C:/downloads',+ cookiesFile: null,+ contentType: 'all',+ downloadId: 'dl_456',+ nativeRunner: mockNativeRunner,+ gdlRunner: mockGdlRunner,+ });++ expect(mockNativeRunner).not.toHaveBeenCalled();+ expect(mockGdlRunner).toHaveBeenCalledTimes(1);+ expect(result.files_count).toBe(10);+ });+});diff --git a/src/lib/open_nami/dispatcher.ts b/src/lib/open_nami/dispatcher.tsnew file mode 100644index 00000000..267880c2--- /dev/null+++ b/src/lib/open_nami/dispatcher.ts@@ -0,0 +1,51 @@+import { runGalleryDlDownload, type DownloadResult } from '$lib/api/open_nami';+import type { ParsedProfile } from '$lib/utils/open_nami_parser';++export interface MultiTierOptions {+ profile: ParsedProfile;+ cleanOutputDir: string;+ cookiesFile: string | null;+ contentType: string;+ downloadId: string;+ skipReplies?: boolean;+ onProgress?: (statusText: string, count: number) => void;+ nativeRunner?: (profile: ParsedProfile) => Promise<{ count: number; success: boolean }>;+ gdlRunner?: () => Promise<DownloadResult>;+}++export async function dispatchMultiTierDownload(options: MultiTierOptions): Promise<DownloadResult> {+ const { profile, cleanOutputDir, cookiesFile, contentType, downloadId, skipReplies, onProgress } = options;++ if (profile.platform && profile.platform !== 'unknown') {+ try {+ if (options.nativeRunner) {+ const nativeRes = await options.nativeRunner(profile);+ if (nativeRes.success && nativeRes.count > 0) {+ return {+ success: true,+ message: `Successfully downloaded ${nativeRes.count} file(s) via native extractor`,+ files_count: nativeRes.count,+ cancelled: false,+ };+ }+ }+ } catch {+ // Graceful fallback to gallery-dl on any native extractor exception+ }+ }++ // Fallback to gallery-dl orchestrator+ onProgress?.('Switching to gallery-dl engine...', 0);+ if (options.gdlRunner) {+ return await options.gdlRunner();+ }++ return await runGalleryDlDownload(+ profile.cleanUrl,+ cleanOutputDir,+ cookiesFile,+ contentType,+ downloadId,+ skipReplies+ );+}diff --git a/src/lib/open_nami/extractors/extractors.test.ts b/src/lib/open_nami/extractors/extractors.test.tsnew file mode 100644index 00000000..56cd9ce0--- /dev/null+++ b/src/lib/open_nami/extractors/extractors.test.ts@@ -0,0 +1,72 @@+import { describe, it, expect } from 'vitest';+import { getExtractor } from './index';+import { parseIgNodeToMediaItems } from './instagram';+import { parseTikTokRehydrationJson } from './tiktok';+import { extractFacebookMediaFromHtml } from './facebook';+import { shouldSkipTweetReply } from './x';++describe('open_nami extractors suite', () => {+ it('instantiates all 4 platform extractors cleanly', () => {+ expect(getExtractor('instagram').platform).toBe('instagram');+ expect(getExtractor('tiktok').platform).toBe('tiktok');+ expect(getExtractor('facebook').platform).toBe('facebook');+ expect(getExtractor('x').platform).toBe('x');+ });++ it('parses instagram media nodes and carousels', () => {+ const mockNode = {+ id: '123456789',+ shortcode: 'C_xyz123',+ is_video: false,+ display_url: 'https://instagram.com/pic.jpg',+ taken_at_timestamp: 1700000000,+ };+ const items = parseIgNodeToMediaItems(mockNode, 'creator');+ expect(items.length).toBe(1);+ expect(items[0].id).toBe('C_xyz123');+ expect(items[0].type).toBe('photo');+ expect(items[0].url).toBe('https://instagram.com/pic.jpg');+ expect(items[0].filename).toContain('creator_1700000000');+ });++ it('parses tiktok rehydration json structures', () => {+ const mockHtml = `<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__">{"__DEFAULT_SCOPE__":{"webapp.user-detail":{"userInfo":{"user":{"uniqueId":"nami_zone"}}}}}</script>`;+ const data = parseTikTokRehydrationJson(mockHtml);+ expect(data['webapp.user-detail'].userInfo.user.uniqueId).toBe('nami_zone');+ });++ it('extracts facebook video items from HTML fragments', () => {+ const mockHtml = `<div><video src="https://video.xx.fbcdn.net/v/t42/test.mp4"></video></div>`;+ const items = extractFacebookMediaFromHtml(mockHtml, 'fb_creator');+ expect(items.length).toBe(1);+ expect(items[0].type).toBe('video');+ expect(items[0].url).toBe('https://video.xx.fbcdn.net/v/t42/test.mp4');+ });++ it('preserves author self-reply threads while skipping conversational replies on x', () => {+ const selfReplyTweet = {+ legacy: {+ id_str: '100',+ user_id_str: '999',+ in_reply_to_user_id_str: '999',+ },+ };+ const conversationalReplyTweet = {+ legacy: {+ id_str: '101',+ user_id_str: '999',+ in_reply_to_user_id_str: '888',+ },+ };+ const originalPostTweet = {+ legacy: {+ id_str: '102',+ user_id_str: '999',+ },+ };++ expect(shouldSkipTweetReply(originalPostTweet, '999')).toBe(false);+ expect(shouldSkipTweetReply(selfReplyTweet, '999')).toBe(false);+ expect(shouldSkipTweetReply(conversationalReplyTweet, '999')).toBe(true);+ });+});diff --git a/src/lib/open_nami/extractors/facebook.ts b/src/lib/open_nami/extractors/facebook.tsnew file mode 100644index 00000000..73ce6b9d--- /dev/null+++ b/src/lib/open_nami/extractors/facebook.ts@@ -0,0 +1,347 @@+import {HttpClient, sleep} from '../http'+import type {Extractor, ExtractOptions, MediaItem} from '../types'+import type {ParsedProfile} from '../../utils/open_nami_parser'++export function decodeEscapedUrl(raw: string): string {+ const sanitized = raw.replace(/[\r\n\t]/g, '').trim()+ try {+ return JSON.parse(`"${sanitized.replace(/"/g, '\\"')}"`)+ } catch {+ return sanitized+ .replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))+ .replace(/\\(["\\\/bfnrt])/g, (_, ch) => {+ const escapes: Record<string, string> = {+ '"': '"',+ '\\': '\\',+ '/': '/',+ b: '\b',+ f: '\f',+ n: '\n',+ r: '\r',+ t: '\t',+ }+ return escapes[ch] || ch+ })+ }+}++export function extractFacebookMediaFromHtml(html: string, username: string): MediaItem[] {+ const items: MediaItem[] = []+ const seenUrls = new Set<string>()++ // 1. HD / SD and playable video URLs+ const videoPatterns = [+ /"browser_native_hd_url":"([^"]+)"/g,+ /"browser_native_sd_url":"([^"]+)"/g,+ /"playable_url_quality_hd":"([^"]+)"/g,+ /"playable_url":"([^"]+)"/g,+ /<video[^>]+src=["'](https?:[^"']+)["']/gi,+ ]++ let videoIndex = 1+ for (const regex of videoPatterns) {+ let vMatch: RegExpExecArray | null+ while ((vMatch = regex.exec(html)) !== null) {+ const rawUrl = vMatch[1]+ const videoUrl = decodeEscapedUrl(rawUrl).replace(/&/g, '&')+ if (videoUrl.startsWith('http') && !seenUrls.has(videoUrl)) {+ seenUrls.add(videoUrl)+ items.push({+ id: `fb_video_${videoIndex}`,+ url: videoUrl,+ filename: `${username}_video_${videoIndex}`,+ extension: 'mp4',+ type: 'video',+ })+ videoIndex+++ }+ }+ }++ // 2. High-res photo URI nodes in JSON+ const photoRegex = /,"(?:image|viewer_image|full_size_image|display_image)":\{"uri":"([^"]+)"/g+ let match: RegExpExecArray | null+ let photoIndex = 1++ while ((match = photoRegex.exec(html)) !== null) {+ const rawUrl = match[1]+ const photoUrl = decodeEscapedUrl(rawUrl).replace(/&/g, '&')+ if (!seenUrls.has(photoUrl)) {+ seenUrls.add(photoUrl)+ items.push({+ id: `fb_photo_${photoIndex}`,+ url: photoUrl,+ filename: `${username}_photo_${photoIndex}`,+ extension: 'jpg',+ type: 'photo',+ })+ photoIndex+++ }+ }++ // 3. Mobile / mbasic server-rendered photo image tags+ const mbasicImgRegex = /<img[^>]+src=["'](https:\/\/[^"'\s]*scontent[^"'\s]*\.(?:jpg|png|webp)[^"'\s]*)["']/gi+ let mMatch: RegExpExecArray | null+ while ((mMatch = mbasicImgRegex.exec(html)) !== null) {+ const rawUrl = mMatch[1]+ const photoUrl = decodeEscapedUrl(rawUrl).replace(/&/g, '&')+ if (!seenUrls.has(photoUrl)) {+ seenUrls.add(photoUrl)+ items.push({+ id: `fb_photo_${photoIndex}`,+ url: photoUrl,+ filename: `${username}_photo_${photoIndex}`,+ extension: 'jpg',+ type: 'photo',+ })+ photoIndex+++ }+ }++ // 4. Fallback: scontent photo links in raw HTML+ if (items.length === 0) {+ const scontentRegex = /https:\/\/[^"'\s<>]*scontent[^"'\s<>]*\.(?:jpg|png|webp)[^"'\s<>]*/gi+ let sMatch: RegExpExecArray | null+ while ((sMatch = scontentRegex.exec(html)) !== null) {+ const cleanUrl = sMatch[0].replace(/\\/g, '').replace(/&/g, '&')+ if (!seenUrls.has(cleanUrl)) {+ seenUrls.add(cleanUrl)+ items.push({+ id: `fb_photo_${photoIndex}`,+ url: cleanUrl,+ filename: `${username}_photo_${photoIndex}`,+ extension: 'jpg',+ type: 'photo',+ })+ photoIndex+++ }+ }+ }++ return items+}++export function extractFacebookPaginationCursor(html: string): string | null {+ // 1. JSON page_info end_cursor or cursor+ const jsonCursorMatch = html.match(/"end_cursor":"([^"]+)"/) || html.match(/"cursor":"([^"]+)"/)+ if (jsonCursorMatch && jsonCursorMatch[1]) {+ return jsonCursorMatch[1]+ }++ // 2. Mobile / mbasic pagination links with cursor or after parameter+ const linkCursorMatch = html.match(/[?&](?:cursor|after)=([^"'\s&<>]+)/i)+ if (linkCursorMatch && linkCursorMatch[1]) {+ try {+ return decodeURIComponent(linkCursorMatch[1])+ } catch {+ return linkCursorMatch[1]+ }+ }++ return null+}++export function resolveFacebookUrl(href: string, currentUrl: string): string {+ const cleanHref = href.replace(/\\/g, '').replace(/&/g, '&')+ try {+ return new URL(cleanHref, currentUrl).toString()+ } catch {+ return cleanHref+ }+}++export function extractFacebookNextPageUrl(html: string, currentUrl: string): string | null {+ // 1. Check for dedicated more item containers in mbasic / mobile HTML+ const moreItemMatch = html.match(/<div[^>]*id=["'](?:m_more_item|m_more_posts)["'][^>]*>\s*<a[^>]+href=["']([^"']+)["']/i)+ if (moreItemMatch && moreItemMatch[1]) {+ return resolveFacebookUrl(moreItemMatch[1], currentUrl)+ }++ // 2. Check for anchor tag with cursor/after and pagination label+ const cursorLabelMatch = html.match(/<a[^>]+href=["']([^"']*(?:cursor=|after=)[^"']+)["'][^>]*>[\s\S]*?(?:See [Mm]ore|More [Pp]hotos|More|Next|Older [Pp]osts)[\s\S]*?<\/a>/i)+ if (cursorLabelMatch && cursorLabelMatch[1]) {+ return resolveFacebookUrl(cursorLabelMatch[1], currentUrl)+ }++ // 3. Check for any link containing cursor= or after=+ const genericCursorMatch = html.match(/<a[^>]+href=["']([^"']*(?:[?&]|&)(?:cursor|after)=[^"']+)["']/i)+ if (genericCursorMatch && genericCursorMatch[1]) {+ return resolveFacebookUrl(genericCursorMatch[1], currentUrl)+ }++ // 4. Fallback: if cursor is present in JSON or HTML, append it to currentUrl+ const cursor = extractFacebookPaginationCursor(html)+ if (cursor) {+ try {+ const u = new URL(currentUrl)+ if (u.searchParams.get('cursor') !== cursor) {+ u.searchParams.set('cursor', cursor)+ return u.toString()+ }+ } catch {+ if (!currentUrl.includes(cursor)) {+ const sep = currentUrl.includes('?') ? '&' : '?'+ return `${currentUrl}${sep}cursor=${encodeURIComponent(cursor)}`+ }+ }+ }++ return null+}++export class FacebookExtractor implements Extractor {+ platform = 'facebook' as const+ private httpClient: HttpClient++ constructor(httpClient?: HttpClient) {+ this.httpClient = httpClient ?? new HttpClient({+ 'Referer': 'https://www.facebook.com/',+ })+ }++ async *extract(profile: ParsedProfile, options: ExtractOptions): AsyncGenerator<MediaItem, void, unknown> {+ const username = profile.username+ const subDir = options.subDir++ options.onProgress?.({+ stage: 'Profile',+ found: 0,+ message: `Fetching Facebook profile @${username}...`,+ })++ const targetPath = subDir === 'Photos' ? 'photos' : 'videos'+ const desktopUrl = `https://www.facebook.com/${encodeURIComponent(username)}/${targetPath}`+ const mbasicUrl = `https://mbasic.facebook.com/${encodeURIComponent(username)}/${targetPath}`+ const mobileUrl = `https://m.facebook.com/${encodeURIComponent(username)}/${targetPath}`++ let currentUrl = desktopUrl+ let html = ''++ try {+ html = await this.httpClient.fetchText(desktopUrl, {+ cookiePath: options.cookiePath,+ cookieDomain: 'facebook.com',+ signal: options.signal,+ retries: 0,+ timeoutMs: 4000,+ })+ } catch {+ html = ''+ }++ let initialItems = extractFacebookMediaFromHtml(html, username)++ // Fallback to mobile endpoints if desktop returns blank shell+ if (initialItems.length === 0) {+ options.onProgress?.({+ stage: 'Profile',+ found: 0,+ message: `Desktop yielded 0 items. Falling back to mbasic.facebook.com for @${username}...`,+ })+ try {+ const mbasicHtml = await this.httpClient.fetchText(mbasicUrl, {+ cookiePath: options.cookiePath,+ cookieDomain: 'facebook.com',+ signal: options.signal,+ retries: 1,+ timeoutMs: 5000,+ headers: {+ 'Referer': 'https://mbasic.facebook.com/',+ },+ })+ const mbasicItems = extractFacebookMediaFromHtml(mbasicHtml, username)+ if (mbasicItems.length > 0 || mbasicHtml.length > 200) {+ html = mbasicHtml+ currentUrl = mbasicUrl+ initialItems = mbasicItems+ }+ } catch {+ // Fall through to m.facebook.com+ }++ if (initialItems.length === 0) {+ try {+ const mobileHtml = await this.httpClient.fetchText(mobileUrl, {+ cookiePath: options.cookiePath,+ cookieDomain: 'facebook.com',+ signal: options.signal,+ retries: 0,+ timeoutMs: 5000,+ headers: {+ 'User-Agent':+ 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36',+ 'Referer': 'https://m.facebook.com/',+ },+ })+ const mobileItems = extractFacebookMediaFromHtml(mobileHtml, username)+ if (mobileItems.length > 0) {+ html = mobileHtml+ currentUrl = mobileUrl+ initialItems = mobileItems+ }+ } catch {+ // Fallbacks exhausted+ }+ }+ }++ const seenUrls = new Set<string>()+ let found = 0+ let page = 1+ const maxPages = 5++ while (true) {+ const items = extractFacebookMediaFromHtml(html, username)+ let pageNewCount = 0++ for (const item of items) {+ if (subDir === 'Photos' && item.type !== 'photo') continue+ if (subDir === 'Videos' && item.type !== 'video') continue+ if (seenUrls.has(item.url)) continue++ seenUrls.add(item.url)+ found+++ pageNewCount+++ options.onProgress?.({+ stage: subDir,+ found,+ message: `Found item: ${item.filename}`,+ })+ yield item+ }++ if (page >= maxPages || options.signal?.aborted) {+ break+ }++ const nextUrl = extractFacebookNextPageUrl(html, currentUrl)+ if (!nextUrl || nextUrl === currentUrl) {+ break+ }++ if (pageNewCount === 0 && page > 1) {+ break+ }++ await sleep(1000, 2000, options.signal)++ try {+ currentUrl = nextUrl+ html = await this.httpClient.fetchText(currentUrl, {+ cookiePath: options.cookiePath,+ cookieDomain: 'facebook.com',+ signal: options.signal,+ retries: 1,+ timeoutMs: 5000,+ headers: {+ 'Referer': currentUrl.includes('mbasic') ? 'https://mbasic.facebook.com/' : 'https://www.facebook.com/',+ },+ })+ page+++ } catch {+ break+ }+ }+ }+}+diff --git a/src/lib/open_nami/extractors/index.ts b/src/lib/open_nami/extractors/index.tsnew file mode 100644index 00000000..1fa3e436--- /dev/null+++ b/src/lib/open_nami/extractors/index.ts@@ -0,0 +1,28 @@+import { InstagramExtractor } from './instagram';+import { XExtractor } from './x';+import { TikTokExtractor } from './tiktok';+import { FacebookExtractor } from './facebook';+import type { Extractor } from '../types';+import type { SupportedPlatform } from '../../utils/open_nami_parser';++export * from '../types';+export * from '../http';+export * from './instagram';+export * from './x';+export * from './tiktok';+export * from './facebook';++export function getExtractor(platform: SupportedPlatform): Extractor {+ switch (platform) {+ case 'instagram':+ return new InstagramExtractor();+ case 'x':+ return new XExtractor();+ case 'tiktok':+ return new TikTokExtractor();+ case 'facebook':+ return new FacebookExtractor();+ default:+ throw new Error(`Unsupported extractor platform: ${platform}`);+ }+}diff --git a/src/lib/open_nami/extractors/instagram.ts b/src/lib/open_nami/extractors/instagram.tsnew file mode 100644index 00000000..865ef4f7--- /dev/null+++ b/src/lib/open_nami/extractors/instagram.ts@@ -0,0 +1,823 @@++import {HttpClient, sleep, loadCookiesFromPath} from '../http'+import type {Extractor, ExtractOptions, MediaItem} from '../types'+import type {ParsedProfile} from '../../utils/open_nami_parser'++export const IG_APP_ID = '936619743392459'+export const IG_TIMELINE_QUERY_HASH = '69cba40317214236af40e7efa697781d'++export const IG_QUERIES = {+ PolarisProfilePostsTabContentQuery_connection: '39229011733413759',+ PolarisProfileReelsTabContentQuery_connection: '28989741540630190',+ PolarisProfileTaggedTabContentQuery_connection: '28794602806842110',+ PolarisProfileStoryHighlightsTrayContentQuery: '26970053832668570',+ PolarisStoriesV3ReelPageGalleryQuery: '28262315486766731',+ PolarisStoriesV3TrayContainerQuery: '27703822975903310',+ PolarisProfilePageContentQuery: '28649589871350527',+} as const++export const IG_POLARIS_DOC_ID = IG_QUERIES.PolarisProfilePostsTabContentQuery_connection++function logExtractorDebug(endpoint: string, err: unknown): void {+ if (process.env.DEBUG || process.env.OPEN_NAMI_DEBUG) {+ const message = err instanceof Error ? err.message : String(err)+ console.debug(`[open-nami:instagram] ${endpoint} query fallback: ${message}`)+ }+}++export interface IgUser {+ id: string+ username: string+ full_name?: string+ is_private?: boolean+ followed_by_viewer?: boolean+ friendship_status?: {+ following?: boolean+ followed_by?: boolean+ blocking?: boolean+ is_private?: boolean+ } | null+ edge_owner_to_timeline_media?: {+ count?: number+ edges: Array<{node: IgMediaNode}>+ page_info?: {has_next_page: boolean; end_cursor?: string}+ }+ edge_felix_video_timeline?: {+ count?: number+ edges: Array<{node: IgMediaNode}>+ }+}++export interface IgMediaNode {+ id: string+ shortcode?: string+ is_video?: boolean+ display_url?: string+ video_url?: string+ taken_at_timestamp?: number+ edge_sidecar_to_children?: {+ edges: Array<{node: IgMediaNode}>+ }+ video_versions?: Array<{+ url?: string+ width?: number+ height?: number+ }>+ image_versions2?: {+ candidates?: Array<{+ url?: string+ width?: number+ height?: number+ }>+ }+ dimensions?: {+ width?: number+ height?: number+ }+}++export function parseIgNodeToMediaItems(node: IgMediaNode, username: string): MediaItem[] {+ const items: MediaItem[] = []+ const anyNode = node as any+ const baseId = node.shortcode || node.id || anyNode.pk+ const date = node.taken_at_timestamp || anyNode.taken_at++ // Handle carousel / sidecar posts (GraphQL edge_sidecar_to_children or REST carousel_media)+ const childrenEdges = node.edge_sidecar_to_children?.edges+ const carouselMedia = anyNode.carousel_media+ const childrenList: IgMediaNode[] = childrenEdges+ ? childrenEdges.map(e => e.node)+ : Array.isArray(carouselMedia)+ ? carouselMedia+ : []++ if (childrenList.length > 0) {+ childrenList.forEach((childNode, index) => {+ const subItems = parseIgNodeToMediaItems(childNode, username)+ for (const item of subItems) {+ item.id = `${baseId}_${index + 1}`+ item.filename = `${username}_${date || baseId}_${index + 1}`+ items.push(item)+ }+ })+ return items+ }++ const isVideo = Boolean(node.is_video || node.video_url || (node.video_versions && node.video_versions.length > 0))++ if (isVideo) {+ const video = node.video_versions?.[0]+ const videoUrl = node.video_url || video?.url+ if (videoUrl) {+ items.push({+ id: baseId,+ url: videoUrl,+ filename: `${username}_${date || baseId}`,+ extension: 'mp4',+ type: 'video',+ date,+ width: video?.width ?? node.dimensions?.width,+ height: video?.height ?? node.dimensions?.height,+ thumbnailUrl: node.display_url,+ })+ } else {+ // Static video recovery (upstream v1.32.17): retain static video / post with missing direct video URL as photo+ const candidate = node.image_versions2?.candidates?.[0]+ const photoUrl = candidate?.url || node.display_url+ if (photoUrl) {+ items.push({+ id: baseId,+ url: photoUrl,+ filename: `${username}_${date || baseId}`,+ extension: 'jpg',+ type: 'photo',+ date,+ width: candidate?.width ?? node.dimensions?.width,+ height: candidate?.height ?? node.dimensions?.height,+ })+ }+ }+ } else {+ const candidate = node.image_versions2?.candidates?.[0]+ const photoUrl = candidate?.url || node.display_url+ if (photoUrl) {+ items.push({+ id: baseId,+ url: photoUrl,+ filename: `${username}_${date || baseId}`,+ extension: 'jpg',+ type: 'photo',+ date,+ width: candidate?.width ?? node.dimensions?.width,+ height: candidate?.height ?? node.dimensions?.height,+ })+ }+ }++ return items+}++export function parseReelItemToMediaItem(item: any, username: string): MediaItem | null {+ const id = item.id || item.pk || String(Date.now())+ const date = item.taken_at || item.created_at+ const isVideo = item.media_type === 2 || Boolean(item.video_versions && item.video_versions.length > 0)++ if (isVideo) {+ const video = item.video_versions?.[0]+ const videoUrl = video?.url+ if (!videoUrl) return null++ return {+ id,+ url: videoUrl,+ filename: `${username}_${date || id}`,+ extension: 'mp4',+ type: 'video',+ date,+ width: video?.width ?? item.original_width,+ height: video?.height ?? item.original_height,+ thumbnailUrl: item.image_versions2?.candidates?.[0]?.url,+ }+ } else {+ const candidate = item.image_versions2?.candidates?.[0]+ const photoUrl = candidate?.url+ if (!photoUrl) return null++ return {+ id,+ url: photoUrl,+ filename: `${username}_${date || id}`,+ extension: 'jpg',+ type: 'photo',+ date,+ width: candidate?.width ?? item.original_width,+ height: candidate?.height ?? item.original_height,+ }+ }+}++export class InstagramExtractor implements Extractor {+ platform = 'instagram' as const+ private httpClient: HttpClient++ constructor(httpClient?: HttpClient) {+ this.httpClient = httpClient ?? new HttpClient({+ 'X-IG-App-ID': IG_APP_ID,+ 'Referer': 'https://www.instagram.com/',+ })+ }++ async fetchUserProfile(username: string, options: ExtractOptions): Promise<IgUser> {+ const url = `https://www.instagram.com/api/v1/users/web_profile_info/?username=${encodeURIComponent(username)}`+ const res = await this.httpClient.fetchJson<{data?: {user?: IgUser}}>(url, {+ cookiePath: options.cookiePath,+ cookieDomain: 'instagram.com',+ signal: options.signal,+ retries: 0,+ timeoutMs: 4000,+ headers: {+ 'X-IG-App-ID': IG_APP_ID,+ 'Referer': `https://www.instagram.com/${username}/`,+ },+ })++ if (!res.data?.user) {+ throw new Error(`Instagram user not found or private profile: ${username}`)+ }++ const user = res.data.user+ if (user.is_private) {+ const fs = user.friendship_status+ const isFollowing = fs ? Boolean(fs.following) : Boolean(user.followed_by_viewer)+ if (!isFollowing) {+ throw new Error(`Instagram profile @${username} is private. You must provide a session cookie jar of an account following this profile.`)+ }+ }++ return user+ }++ async fetchHighlightsTray(userId: string, options: ExtractOptions): Promise<any[]> {+ // 1. Try GraphQL PolarisProfileStoryHighlightsTrayContentQuery (gallery-dl upstream v1.32.16+)+ try {+ const variables = JSON.stringify({user_id: userId})+ const body = new URLSearchParams({+ doc_id: IG_QUERIES.PolarisProfileStoryHighlightsTrayContentQuery,+ variables,+ }).toString()++ const res = await this.httpClient.fetchJson<any>('https://www.instagram.com/graphql/query', {+ method: 'POST',+ body,+ cookiePath: options.cookiePath,+ cookieDomain: 'instagram.com',+ signal: options.signal,+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ 'X-IG-App-ID': IG_APP_ID,+ 'X-FB-Friendly-Name': 'PolarisProfileStoryHighlightsTrayContentQuery',+ 'Referer': 'https://www.instagram.com/',+ },+ })++ if (res?.errors && Array.isArray(res.errors) && res.errors.length > 0) {+ const errMsg = res.errors.map((e: any) => e.message || JSON.stringify(e)).join('; ')+ throw new Error(`Instagram GraphQL query error: ${errMsg}`)+ }++ const edges = res?.data?.highlights?.edges+ if (Array.isArray(edges) && edges.length > 0) {+ return edges.map((e: any) => e.node)+ }+ } catch (err) {+ logExtractorDebug('PolarisProfileStoryHighlightsTrayContentQuery', err)+ }++ // Fallback to legacy REST endpoint+ const url = `https://www.instagram.com/api/v1/highlights/${userId}/highlights_tray/`+ try {+ const res = await this.httpClient.fetchJson<{tray?: any[]}>(url, {+ cookiePath: options.cookiePath,+ cookieDomain: 'instagram.com',+ signal: options.signal,+ headers: {+ 'X-IG-App-ID': IG_APP_ID,+ },+ })+ return res.tray ?? []+ } catch (err) {+ logExtractorDebug('Highlights legacy REST', err)+ return []+ }+ }++ async fetchReelsMedia(reelIds: string[], options: ExtractOptions): Promise<any[]> {+ if (reelIds.length === 0) return []+ const idsParam = reelIds.join(',')+ const url = `https://www.instagram.com/api/v1/feed/reels_media/?reel_ids=${encodeURIComponent(idsParam)}`++ try {+ const res = await this.httpClient.fetchJson<{reels_media?: any[]; reels?: Record<string, any>}>(url, {+ cookiePath: options.cookiePath,+ cookieDomain: 'instagram.com',+ signal: options.signal,+ headers: {+ 'X-IG-App-ID': IG_APP_ID,+ },+ })++ if (res.reels_media) return res.reels_media+ if (res.reels) return Object.values(res.reels)+ return []+ } catch {+ return []+ }+ }++ async fetchWebTokens(+ username: string,+ options: ExtractOptions,+ ): Promise<{lsd?: string; fbDtsg?: string; csrfToken?: string; userId?: string}> {+ let csrfToken: string | undefined+ if (options.cookiePath) {+ try {+ const cookies = await loadCookiesFromPath(options.cookiePath, 'instagram.com')+ csrfToken = cookies['csrftoken']+ } catch {}+ }+ if (!csrfToken) {+ csrfToken = Array.from(typeof crypto !== 'undefined' && crypto.getRandomValues ? crypto.getRandomValues(new Uint8Array(16)) : Array.from({length: 16}, () => Math.floor(Math.random() * 256))).map(b => b.toString(16).padStart(2, '0')).join('')+ }++ try {+ const html = await this.httpClient.fetchText(`https://www.instagram.com/${encodeURIComponent(username)}/`, {+ cookiePath: options.cookiePath,+ cookieDomain: 'instagram.com',+ signal: options.signal,+ headers: {+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',+ },+ })++ let lsd: string | undefined+ let fbDtsg: string | undefined+ let userId: string | undefined++ const eqmcMatch = html.match(/id="__eqmc"[^>]*>([^<]+)<\/script>/)+ if (eqmcMatch) {+ try {+ const eqmc = JSON.parse(eqmcMatch[1])+ if (eqmc.l) lsd = eqmc.l+ if (eqmc.f) fbDtsg = eqmc.f+ } catch {}+ }++ if (!lsd) {+ const m = html.match(/"lsd":"([^"]+)"/) || html.match(/"LSD",\[\],\{"token":"([^"]+)"/)+ if (m) lsd = m[1]+ }+ if (!fbDtsg) {+ const m = html.match(/"dtsg":\{"token":"([^"]+)"/)+ if (m) fbDtsg = m[1]+ }++ const uMatch = html.match(/"profile_id":"([^"]+)"/) || html.match(/"user_id":"([^"]+)"/)+ if (uMatch) userId = uMatch[1]++ return {lsd, fbDtsg, csrfToken, userId}+ } catch (err) {+ logExtractorDebug('fetchWebTokens', err)+ return {csrfToken}+ }+ }++ async fetchPostsTabGraphQL(+ username: string,+ cursor: string | undefined,+ tokens: {lsd?: string; fbDtsg?: string; csrfToken?: string},+ options: ExtractOptions,+ ): Promise<{edges: Array<{node: IgMediaNode}>; hasNextPage: boolean; nextCursor?: string; userId?: string}> {+ const postVariables = JSON.stringify({+ after: cursor || null,+ before: null,+ data: {+ count: 12,+ include_reel_media_seen_timestamp: true,+ include_relationship_info: true,+ latest_besties_reel_media: true,+ latest_reel_media: true,+ },+ first: 12,+ include_multi_captions: true,+ last: null,+ username,+ __relay_internal__pv__PolarisMultiCaptionCarouselEnabledrelayprovider: true,+ __relay_internal__pv__PolarisShortDramaEnabledrelayprovider: true,+ __relay_internal__pv__PolarisThreadsStyleCommentsEnabledrelayprovider: false,+ __relay_internal__pv__PolarisReelsRecoDebugOverlayEnabledrelayprovider: false,+ })++ const bodyParams = new URLSearchParams({+ av: '17841415137994167',+ __d: 'www',+ __user: '0',+ __a: '1',+ __req: '0',+ __hs: '20731.HYP:instagram_web_pkg.2.1...0',+ dpr: '1',+ __ccg: 'EXCELLENT',+ __rev: '1049285836',+ __hsi: '7693193318680449885',+ __comet_req: '7',+ jazoest: '26461',+ fb_api_caller_class: 'RelayModern',+ fb_api_req_friendly_name: 'PolarisProfilePostsTabContentQuery_connection',+ server_timestamps: 'true',+ variables: postVariables,+ doc_id: IG_POLARIS_DOC_ID,+ })++ if (tokens.fbDtsg) bodyParams.set('fb_dtsg', tokens.fbDtsg)+ if (tokens.lsd) bodyParams.set('lsd', tokens.lsd)++ const headers: Record<string, string> = {+ 'Accept': '*/*',+ 'Content-Type': 'application/x-www-form-urlencoded',+ 'X-IG-App-ID': IG_APP_ID,+ 'X-IG-Max-Touch-Points': '0',+ 'X-FB-Friendly-Name': 'PolarisProfilePostsTabContentQuery_connection',+ 'Referer': `https://www.instagram.com/${username}/`,+ 'Origin': 'https://www.instagram.com',+ 'X-ASBD-ID': '359341',+ 'Sec-Fetch-Dest': 'empty',+ 'Sec-Fetch-Mode': 'cors',+ 'Sec-Fetch-Site': 'same-origin',+ }+ if (tokens.csrfToken) headers['X-CSRFToken'] = tokens.csrfToken+ if (tokens.lsd) headers['X-FB-LSD'] = tokens.lsd++ const res = await this.httpClient.fetchJson<any>('https://www.instagram.com/graphql/query', {+ method: 'POST',+ body: bodyParams.toString(),+ cookiePath: options.cookiePath,+ cookieDomain: 'instagram.com',+ signal: options.signal,+ headers,+ })++ if (res?.errors && Array.isArray(res.errors) && res.errors.length > 0) {+ const errMsg = res.errors.map((e: any) => e.message || JSON.stringify(e)).join('; ')+ throw new Error(`Instagram GraphQL query error: ${errMsg}`)+ }++ const connection =+ res?.data?.xdt_api__v1__feed__user_timeline_graphql_connection ||+ res?.data?.user?.edge_owner_to_timeline_media++ if (connection?.edges && Array.isArray(connection.edges)) {+ let resolvedUserId: string | undefined+ for (const edge of connection.edges) {+ const node = edge?.node+ if (node?.owner_id) {+ resolvedUserId = String(node.owner_id)+ break+ }+ if (node?.user?.pk || node?.user?.id) {+ resolvedUserId = String(node.user.pk || node.user.id)+ break+ }+ if (typeof node?.id === 'string' && node.id.includes('_')) {+ resolvedUserId = node.id.split('_')[1]+ break+ }+ }+ return {+ edges: connection.edges,+ hasNextPage: Boolean(connection.page_info?.has_next_page),+ nextCursor: connection.page_info?.end_cursor,+ userId: resolvedUserId,+ }+ }++ return {edges: [], hasNextPage: false}+ }++ async fetchNextPostsPage(+ userId: string,+ username: string,+ cursor: string,+ options: ExtractOptions,+ tokens?: {lsd?: string; fbDtsg?: string; csrfToken?: string},+ ): Promise<{edges: Array<{node: IgMediaNode}>; hasNextPage: boolean; nextCursor?: string}> {+ // 1. Try GraphQL query endpoint with query_hash if userId is present+ if (userId) {+ const variables = JSON.stringify({id: userId, first: 12, after: cursor})+ const url = `https://www.instagram.com/graphql/query/?query_hash=${IG_TIMELINE_QUERY_HASH}&variables=${encodeURIComponent(variables)}`++ try {+ const res = await this.httpClient.fetchJson<any>(url, {+ cookiePath: options.cookiePath,+ cookieDomain: 'instagram.com',+ signal: options.signal,+ headers: {+ 'X-IG-App-ID': IG_APP_ID,+ 'Referer': `https://www.instagram.com/${username}/`,+ },+ })++ const data = res?.data?.user?.edge_owner_to_timeline_media+ if (data?.edges && data.edges.length > 0) {+ return {+ edges: data.edges,+ hasNextPage: Boolean(data.page_info?.has_next_page),+ nextCursor: data.page_info?.end_cursor,+ }+ }+ } catch (err) {+ logExtractorDebug('edge_owner_to_timeline_media', err)+ }+ }++ // 2. PolarisProfilePostsTabContentQuery GraphQL connection+ try {+ const page = await this.fetchPostsTabGraphQL(username, cursor, tokens || {}, options)+ if (page.edges && page.edges.length > 0) {+ return page+ }+ } catch (err) {+ logExtractorDebug('PolarisProfilePostsTabContentQuery_connection', err)+ }++ // 3. v1 user feed REST endpoint+ if (userId) {+ try {+ const restUrl = `https://www.instagram.com/api/v1/feed/user/${userId}/?count=12&max_id=${encodeURIComponent(cursor)}`+ const res = await this.httpClient.fetchJson<any>(restUrl, {+ cookiePath: options.cookiePath,+ cookieDomain: 'instagram.com',+ signal: options.signal,+ headers: {+ 'X-IG-App-ID': IG_APP_ID,+ 'Referer': `https://www.instagram.com/${username}/`,+ },+ })++ if (Array.isArray(res?.items) && res.items.length > 0) {+ const edges = res.items.map((item: any) => ({node: item}))+ return {+ edges,+ hasNextPage: Boolean(res.more_available),+ nextCursor: res.next_max_id ? String(res.next_max_id) : undefined,+ }+ }+ } catch (err) {+ logExtractorDebug('v1 user feed REST', err)+ }+ }++ return {edges: [], hasNextPage: false}+ }++ async fetchNextReelsPage(+ userId: string,+ cursor: string,+ options: ExtractOptions,+ ): Promise<{edges: Array<{node: IgMediaNode}>; hasNextPage: boolean; nextCursor?: string}> {+ try {+ const variables = JSON.stringify({+ after: cursor,+ first: 12,+ id: userId,+ data: {+ include_feed_video: true,+ page_size: 12,+ target_user_id: userId,+ },+ })+ const postUrl = 'https://www.instagram.com/graphql/query'+ const body = new URLSearchParams({+ doc_id: IG_QUERIES.PolarisProfileReelsTabContentQuery_connection,+ variables,+ }).toString()++ const res = await this.httpClient.fetchJson<any>(postUrl, {+ method: 'POST',+ body,+ cookiePath: options.cookiePath,+ cookieDomain: 'instagram.com',+ signal: options.signal,+ headers: {+ 'Content-Type': 'application/x-www-form-urlencoded',+ 'X-IG-App-ID': IG_APP_ID,+ 'X-FB-Friendly-Name': 'PolarisProfileReelsTabContentQuery_connection',+ 'Referer': 'https://www.instagram.com/',+ },+ })++ if (res?.errors && Array.isArray(res.errors) && res.errors.length > 0) {+ const errMsg = res.errors.map((e: any) => e.message || JSON.stringify(e)).join('; ')+ throw new Error(`Instagram GraphQL query error: ${errMsg}`)+ }++ const reelsData = res?.data?.fetch__XDTUserDict+ let connection = reelsData?.reels+ if (!connection && reelsData) {+ for (const val of Object.values(reelsData)) {+ if (val && typeof val === 'object' && 'edges' in val) {+ connection = val as any+ break+ }+ }+ }++ if (connection?.edges && Array.isArray(connection.edges)) {+ return {+ edges: connection.edges,+ hasNextPage: Boolean(connection.page_info?.has_next_page),+ nextCursor: connection.page_info?.end_cursor,+ }+ }+ } catch (err) {+ logExtractorDebug('PolarisProfileReelsTabContentQuery_connection', err)+ }++ return {edges: [], hasNextPage: false}+ }++ async *extract(profile: ParsedProfile, options: ExtractOptions): AsyncGenerator<MediaItem, void, unknown> {+ const username = profile.username+ const subDir = options.subDir++ options.onProgress?.({+ stage: 'Profile',+ found: 0,+ message: `Fetching Instagram profile @${username}...`,+ })++ let user: IgUser | null = null+ try {+ user = await this.fetchUserProfile(username, options)+ } catch (err) {+ logExtractorDebug('fetchUserProfile', err)+ }++ let webTokens: {lsd?: string; fbDtsg?: string; userId?: string} = {}+ if (!user) {+ webTokens = await this.fetchWebTokens(username, options)+ }++ let userId = user?.id || webTokens.userId++ if (!userId && (subDir === 'Stories' || subDir === 'Highlights')) {+ try {+ const probe = await this.fetchPostsTabGraphQL(username, undefined, webTokens, options)+ if (probe.userId) {+ userId = probe.userId+ }+ } catch (err) {+ logExtractorDebug('userId probe', err)+ }+ }++ if (subDir === 'Stories') {+ if (!userId) return+ options.onProgress?.({+ stage: 'Stories',+ found: 0,+ message: `Fetching stories for @${username}...`,+ })+ const reels = await this.fetchReelsMedia([userId], options)+ for (const reel of reels) {+ for (const rawItem of reel.items || []) {+ const item = parseReelItemToMediaItem(rawItem, username)+ if (item) yield item+ }+ }+ return+ }++ if (subDir === 'Highlights') {+ if (!userId) return+ options.onProgress?.({+ stage: 'Highlights',+ found: 0,+ message: `Fetching highlights tray for @${username}...`,+ })+ const tray = await this.fetchHighlightsTray(userId, options)+ const highlightIds = tray.map(t => t.id).filter(Boolean)++ if (highlightIds.length > 0) {+ const chunkSize = 5+ for (let i = 0; i < highlightIds.length; i += chunkSize) {+ if (options.signal?.aborted) break+ const chunk = highlightIds.slice(i, i + chunkSize)+ const reels = await this.fetchReelsMedia(chunk, options)+ for (const reel of reels) {+ for (const rawItem of reel.items || []) {+ const item = parseReelItemToMediaItem(rawItem, username)+ if (item) yield item+ }+ }+ await sleep(1000, 1500, options.signal)+ }+ }+ return+ }++ let found = 0+ const emittedItemIds = new Set<string>()++ let currentEdges = user?.edge_owner_to_timeline_media?.edges ?? []+ let hasNextPage = Boolean(user?.edge_owner_to_timeline_media?.page_info?.has_next_page)+ let endCursor = user?.edge_owner_to_timeline_media?.page_info?.end_cursor++ if (!user) {+ try {+ const firstPage = await this.fetchPostsTabGraphQL(username, undefined, webTokens, options)+ currentEdges = firstPage.edges+ hasNextPage = firstPage.hasNextPage+ endCursor = firstPage.nextCursor+ if (!userId && firstPage.userId) {+ userId = firstPage.userId+ }+ } catch (err) {+ logExtractorDebug('fetchPostsTabGraphQL initial', err)+ }+ }++ while (true) {+ for (const edge of currentEdges) {+ const items = parseIgNodeToMediaItems(edge.node, username)+ for (const item of items) {+ if (subDir === 'Photos' && item.type !== 'photo') continue+ if (subDir === 'Videos' && item.type !== 'video') continue++ if (emittedItemIds.has(item.id)) continue+ emittedItemIds.add(item.id)++ found+++ options.onProgress?.({+ stage: subDir,+ found,+ message: `Found item: ${item.filename}`,+ })+ yield item+ }+ }++ if (!hasNextPage || !endCursor || options.signal?.aborted) {+ break+ }++ await sleep(1500, 2500, options.signal)++ try {+ const nextPage = await this.fetchNextPostsPage(userId || '', username, endCursor, options, webTokens)+ currentEdges = nextPage.edges+ hasNextPage = nextPage.hasNextPage+ endCursor = nextPage.nextCursor+ if (currentEdges.length === 0) {+ break+ }+ } catch {+ break+ }+ }++ if (subDir === 'Videos' && userId) {+ const videoEdges = user?.edge_felix_video_timeline?.edges ?? []+ for (const edge of videoEdges) {+ const items = parseIgNodeToMediaItems(edge.node, username)+ for (const item of items) {+ if (item.type !== 'video') continue+ if (emittedItemIds.has(item.id)) continue+ emittedItemIds.add(item.id)++ found+++ options.onProgress?.({+ stage: 'Videos',+ found,+ message: `Found reel: ${item.filename}`,+ })+ yield item+ }+ }++ let reelsCursor = ''+ let hasMoreReels = true++ while (hasMoreReels && !options.signal?.aborted) {+ try {+ const reelsPage = await this.fetchNextReelsPage(userId, reelsCursor, options)+ if (!reelsPage.edges || reelsPage.edges.length === 0) break++ for (const edge of reelsPage.edges) {+ const items = parseIgNodeToMediaItems(edge.node, username)+ for (const item of items) {+ if (item.type !== 'video') continue+ if (emittedItemIds.has(item.id)) continue+ emittedItemIds.add(item.id)++ found+++ options.onProgress?.({+ stage: 'Videos',+ found,+ message: `Found reel: ${item.filename}`,+ })+ yield item+ }+ }++ if (reelsPage.hasNextPage && reelsPage.nextCursor && reelsPage.nextCursor !== reelsCursor) {+ reelsCursor = reelsPage.nextCursor+ await sleep(1500, 2500, options.signal)+ } else {+ hasMoreReels = false+ }+ } catch {+ break+ }+ }+ }+ }+}diff --git a/src/lib/open_nami/extractors/tiktok.ts b/src/lib/open_nami/extractors/tiktok.tsnew file mode 100644index 00000000..cc908e9b--- /dev/null+++ b/src/lib/open_nami/extractors/tiktok.ts@@ -0,0 +1,261 @@+import {HttpClient, sleep} from '../http'+import type {Extractor, ExtractOptions, MediaItem} from '../types'+import type {ParsedProfile} from '../../utils/open_nami_parser'++export function parseTikTokRehydrationJson(html: string): any {+ // Pattern 1: Modern __UNIVERSAL_DATA_FOR_REHYDRATION__+ const universalMatch = html.match(+ /<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__"[^>]*>([\s\S]*?)<\/script>/,+ )+ if (universalMatch) {+ try {+ const raw = JSON.parse(universalMatch[1])+ const scope = raw?.['__DEFAULT_SCOPE__'] || raw+ if (scope) return scope+ } catch {}+ }++ // Pattern 2: SIGI_STATE script tag+ const sigiTagMatch = html.match(+ /<script id="SIGI_STATE"[^>]*>([\s\S]*?)<\/script>/,+ )+ if (sigiTagMatch) {+ try {+ const raw = JSON.parse(sigiTagMatch[1])+ const user = Object.values(raw?.UserModule?.users || {})[0] as any+ const items = Object.values(raw?.ItemModule || {}) as any[]+ return {+ 'webapp.user-detail': {+ userInfo: { user },+ itemList: items,+ },+ SIGI_STATE: raw,+ }+ } catch {}+ }++ // Pattern 3: window['SIGI_STATE'] assignment+ const sigiWindowMatch = html.match(+ /(?:window\[['"]SIGI_STATE['"]\]|SIGI_STATE)\s*=\s*(\{[\s\S]*?\})\s*;/i,+ )+ if (sigiWindowMatch) {+ try {+ const raw = JSON.parse(sigiWindowMatch[1])+ const user = Object.values(raw?.UserModule?.users || {})[0] as any+ const items = Object.values(raw?.ItemModule || {}) as any[]+ return {+ 'webapp.user-detail': {+ userInfo: { user },+ itemList: items,+ },+ SIGI_STATE: raw,+ }+ } catch {}+ }++ // Pattern 4: __NEXT_DATA__ script tag+ const nextDataMatch = html.match(+ /<script id="__NEXT_DATA__"[^>]*>([\s\S]*?)<\/script>/,+ )+ if (nextDataMatch) {+ try {+ const raw = JSON.parse(nextDataMatch[1])+ const pageProps = raw?.props?.pageProps+ if (pageProps) {+ return {+ 'webapp.user-detail': {+ userInfo: pageProps.userInfo,+ itemList: pageProps.items || pageProps.itemList || [],+ },+ __NEXT_DATA__: raw,+ }+ }+ } catch {}+ }++ // Pattern 5: Direct SecUid fallback regex+ const secUidMatch = html.match(/(?:secUid|sec_uid)["':=\s]+(MS4wLjABAAAA[\w-]{32,64})/i)+ if (secUidMatch) {+ return {+ 'webapp.user-detail': {+ userInfo: {+ user: {+ secUid: secUidMatch[1],+ },+ },+ itemList: [],+ },+ }+ }++ return null+}+++export function parseTikTokItem(item: any, username: string): MediaItem[] {+ const items: MediaItem[] = []+ const id = item.id || item.itemId || String(Date.now())+ const date = Number(item.createTime) || undefined+ const caption = item.desc++ const imageList = item.imagePost?.images+ if (Array.isArray(imageList) && imageList.length > 0) {+ imageList.forEach((img: any, idx: number) => {+ const imgUrl = img.imageURL?.urlList?.[0] || img.displayImage?.urlList?.[0]+ if (imgUrl) {+ items.push({+ id: `${id}_${idx + 1}`,+ url: imgUrl,+ filename: `${username}_${id}_${idx + 1}`,+ extension: 'jpg',+ type: 'photo',+ caption,+ date,+ })+ }+ })+ return items+ }++ const video = item.video+ const videoUrl = video?.playAddr || video?.downloadAddr+ if (videoUrl) {+ items.push({+ id,+ url: videoUrl,+ filename: `${username}_${id}`,+ extension: 'mp4',+ type: 'video',+ caption,+ date,+ width: video?.width,+ height: video?.height,+ thumbnailUrl: video?.cover || video?.originCover,+ })+ }++ return items+}++export class TikTokExtractor implements Extractor {+ platform = 'tiktok' as const+ private httpClient: HttpClient++ constructor(httpClient?: HttpClient) {+ this.httpClient = httpClient ?? new HttpClient({+ 'Referer': 'https://www.tiktok.com/',+ })+ }++ async *extract(profile: ParsedProfile, options: ExtractOptions): AsyncGenerator<MediaItem, void, unknown> {+ const cleanUsername = profile.username.replace(/^@/, '')+ const subDir = options.subDir++ options.onProgress?.({+ stage: 'Profile',+ found: 0,+ message: `Fetching TikTok profile @${cleanUsername}...`,+ })++ const profileUrl = `https://www.tiktok.com/@${cleanUsername}`+ const html = await this.httpClient.fetchText(profileUrl, {+ cookiePath: options.cookiePath,+ cookieDomain: 'tiktok.com',+ signal: options.signal,+ retries: 0,+ timeoutMs: 4000,+ })++ const scope = parseTikTokRehydrationJson(html)+ const userDetail = scope?.['webapp.user-detail']+ const userInfo = userDetail?.userInfo?.user+ const secUid = userInfo?.secUid++ let found = 0++ // Initial SSR hydration items+ const initialItems = userDetail?.itemList || []+ for (const rawItem of initialItems) {+ const mediaList = parseTikTokItem(rawItem, cleanUsername)+ for (const item of mediaList) {+ if (subDir === 'Photos' && item.type !== 'photo') continue+ if (subDir === 'Videos' && item.type !== 'video') continue++ found+++ options.onProgress?.({+ stage: subDir,+ found,+ message: `Found item: ${item.filename}`,+ })+ yield item+ }+ }++ if (!secUid) {+ return+ }++ // Paginated posts via item_list API+ let cursor = '0'+ let hasMore = true+ const visitedCursors = new Set<string>()++ while (hasMore) {+ if (options.signal?.aborted) break+ if (visitedCursors.has(cursor)) break+ visitedCursors.add(cursor)++ const deviceId = `${Math.floor(7250000000000000000 + Math.random() * 75000000000000000)}`+ const queryParams = new URLSearchParams({+ aid: '1988',+ app_name: 'tiktok_web',+ device_platform: 'web_pc',+ channel: 'tiktok_web',+ device_id: deviceId,+ secUid,+ count: '30',+ cursor,+ post_item_list_request_type: '0',+ })+ const apiUrl = `https://www.tiktok.com/api/post/item_list/?${queryParams.toString()}`++ let res: any+ try {+ res = await this.httpClient.fetchJson<any>(apiUrl, {+ cookiePath: options.cookiePath,+ cookieDomain: 'tiktok.com',+ signal: options.signal,+ headers: {+ 'Referer': profileUrl,+ },+ })+ } catch {+ break+ }++ const items = res?.itemList || []+ if (items.length === 0) break++ for (const rawItem of items) {+ const mediaList = parseTikTokItem(rawItem, cleanUsername)+ for (const item of mediaList) {+ if (subDir === 'Photos' && item.type !== 'photo') continue+ if (subDir === 'Videos' && item.type !== 'video') continue++ found+++ options.onProgress?.({+ stage: subDir,+ found,+ message: `Found item: ${item.filename}`,+ })+ yield item+ }+ }++ hasMore = Boolean(res?.hasMore)+ cursor = String(res?.cursor ?? '0')++ await sleep(1000, 2000, options.signal)+ }+ }+}diff --git a/src/lib/open_nami/extractors/x.ts b/src/lib/open_nami/extractors/x.tsnew file mode 100644index 00000000..bda6e04e--- /dev/null+++ b/src/lib/open_nami/extractors/x.ts@@ -0,0 +1,387 @@+import {HttpClient, sleep, loadCookiesFromPath} from '../http'+import type {Extractor, ExtractOptions, MediaItem} from '../types'+import type {ParsedProfile} from '../../utils/open_nami_parser'++export const TWITTER_BEARER_TOKEN =+ 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA'++export const TWITTER_FEATURES = {+ responsive_web_graphql_exclude_directive_enabled: true,+ verified_phone_label_enabled: false,+ responsive_web_graphql_timeline_navigation_enabled: true,+ responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,+ tweetypie_unmention_optimization_enabled: true,+ vibe_api_enabled: true,+ responsive_web_edit_tweet_api_enabled: true,+ graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,+ view_counts_everywhere_api_enabled: true,+ longform_notetweets_consumption_enabled: true,+ tweet_awards_web_tipping_enabled: false,+ freedom_of_speech_not_reach_fetch_enabled: true,+ standardized_nudges_misinfo: true,+ tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,+ interactive_text_enabled: true,+ responsive_web_text_conversations_enabled: false,+ longform_notetweets_rich_text_read_enabled: true,+ longform_notetweets_inline_media_enabled: true,+ responsive_web_enhance_cards_enabled: false,+ creator_subscriptions_tweet_preview_api_enabled: true,+ communities_web_enable_tweet_community_results_fetch: true,+ c9s_tweet_anatomy_moderator_badge_enabled: true,+ articles_preview_enabled: true,+ responsive_web_twitter_article_tweet_consumption_enabled: true,+ responsive_web_grok_analyze_post_followups_enabled: true,+ responsive_web_jetfuel_frame: true,+ responsive_web_grok_share_attachment_enabled: true,+ responsive_web_grok_analysis_button_from_backend: true,+ responsive_web_grok_image_annotation_enabled: true,+ responsive_web_grok_imagine_annotation_enabled: true,+ profile_label_improvements_pcf_label_in_post_enabled: true,+ rweb_tipjar_consumption_enabled: true,+}++export function shouldSkipTweetReply(+ tweet: any,+ targetUserId?: string,+ mode: 'timeline' | 'likes' = 'timeline',+): boolean {+ const tweetResult = tweet.tweet || tweet+ const legacy = tweetResult.legacy || tweetResult+ const replyToUserId = legacy.in_reply_to_user_id_str++ // Top-level tweet (not a reply) -> never skip+ if (!replyToUserId) {+ return false+ }++ const authorId = legacy.user_id_str || tweetResult.core?.user_results?.result?.rest_id++ if (mode === 'timeline') {+ // If targetUserId is provided, self-reply means target author replied to themselves+ if (targetUserId) {+ if (replyToUserId !== targetUserId || (authorId && authorId !== targetUserId)) {+ return true+ }+ return false+ }+ // If targetUserId is unknown, check whether author replied to themselves+ return Boolean(authorId && replyToUserId !== authorId)+ }++ // In likes mode (upstream cb#501):+ // Liked items come from varied authors. Keep self-threads by the creator,+ // skip conversational replies directed to other accounts.+ if (authorId && replyToUserId === authorId) {+ return false+ }++ return true+}+++export interface TwitterMediaVariant {+ bitrate?: number+ content_type?: string+ url: string+}++export interface TwitterMediaEntity {+ id_str: string+ type: 'photo' | 'video' | 'animated_gif'+ media_url_https: string+ original_info?: {width?: number; height?: number}+ video_info?: {+ aspect_ratio?: number[]+ duration_millis?: number+ variants: TwitterMediaVariant[]+ }+}++export function parseTweetMediaEntities(+ tweet: any,+ username: string,+): MediaItem[] {+ const items: MediaItem[] = []+ const tweetResult = tweet.tweet || tweet+ const legacy = tweetResult.legacy || tweetResult+ const entities = legacy.extended_entities?.media || legacy.entities?.media || []+ const tweetId = tweetResult.rest_id || legacy.id_str || String(Date.now())+ const rawDate = legacy.created_at ? new Date(legacy.created_at).getTime() / 1000 : undefined++ for (let idx = 0; idx < entities.length; idx++) {+ const media: TwitterMediaEntity = entities[idx]+ const subIndex = idx + 1+ const baseFilename = `${username}_${tweetId}_${subIndex}`++ if (media.type === 'video' || media.type === 'animated_gif') {+ const variants = (media.video_info?.variants || [])+ .filter(v => v.content_type === 'video/mp4')+ .sort((a, b) => (b.bitrate ?? 0) - (a.bitrate ?? 0))++ const bestVariant = variants[0]+ if (bestVariant?.url) {+ items.push({+ id: `${tweetId}_${media.id_str}`,+ url: bestVariant.url,+ filename: baseFilename,+ extension: 'mp4',+ type: 'video',+ date: rawDate,+ thumbnailUrl: media.media_url_https,+ })+ }+ } else {+ let photoUrl = media.media_url_https+ if (photoUrl) {+ // Strip query params and request original quality+ const cleanUrl = photoUrl.replace(/:[a-zA-Z]+$/, '')+ const urlWithOrig = cleanUrl.includes('?') ? `${cleanUrl}&name=orig` : `${cleanUrl}?name=orig`+ const extMatch = photoUrl.match(/\.([a-zA-Z0-9]+)(?:$|\?)/)+ const ext = extMatch ? extMatch[1] : 'jpg'++ items.push({+ id: `${tweetId}_${media.id_str}`,+ url: urlWithOrig,+ filename: baseFilename,+ extension: ext,+ type: 'photo',+ date: rawDate,+ width: media.original_info?.width,+ height: media.original_info?.height,+ })+ }+ }+ }++ return items+}++export class XExtractor implements Extractor {+ platform = 'x' as const+ private httpClient: HttpClient+ private guestToken?: string++ constructor(httpClient?: HttpClient) {+ this.httpClient = httpClient ?? new HttpClient({+ 'Authorization': `Bearer ${TWITTER_BEARER_TOKEN}`,+ 'Referer': 'https://x.com/',+ 'x-twitter-active-user': 'yes',+ 'x-twitter-client-language': 'en',+ })+ }++ async ensureGuestToken(options: ExtractOptions): Promise<string> {+ if (this.guestToken) return this.guestToken++ try {+ const res = await this.httpClient.fetchJson<{guest_token?: string}>(+ 'https://api.twitter.com/1.1/guest/activate.json',+ {+ method: 'POST',+ cookiePath: options.cookiePath,+ cookieDomain: 'x.com',+ signal: options.signal,+ retries: 0,+ timeoutMs: 3000,+ headers: {+ 'Authorization': `Bearer ${TWITTER_BEARER_TOKEN}`,+ },+ },+ )+ if (res.guest_token) {+ this.guestToken = res.guest_token+ this.httpClient.setHeader('x-guest-token', res.guest_token)+ return res.guest_token+ }+ } catch (err: unknown) {+ if (options.signal?.aborted) throw err+ const msg = err instanceof Error ? err.message : String(err)+ throw new Error(`Failed to activate X/Twitter guest session: ${msg}`)+ }++ throw new Error('Failed to activate X/Twitter guest session: no guest token returned')+ }++ async fetchUserRestId(username: string, options: ExtractOptions): Promise<string> {+ if (username.startsWith('id:')) {+ return username.slice(3)+ }++ if (username === 'i_history_likes') {+ if (options.cookiePath) {+ let cookies = await loadCookiesFromPath(options.cookiePath, 'x.com')+ if (!cookies['twid']) {+ cookies = await loadCookiesFromPath(options.cookiePath, 'twitter.com')+ }+ if (!cookies['twid']) {+ cookies = await loadCookiesFromPath(options.cookiePath)+ }+ const twid = cookies['twid']+ if (twid) {+ const decoded = decodeURIComponent(twid).replace(/^"|"$/g, '').trim()+ const rawId = decoded.startsWith('u=')+ ? decoded.slice(2)+ : decoded.includes('=')+ ? decoded.split('=').pop()?.trim()+ : decoded+ if (rawId && /^[a-zA-Z0-9_-]+$/.test(rawId)) {+ return rawId+ }+ }+ }+ throw new Error("Authentication required for X/Twitter likes history: missing 'twid' cookie")+ }++ await this.ensureGuestToken(options)++ const variables = JSON.stringify({+ screen_name: username,+ withSafetyModeUserFields: true,+ })+ const features = JSON.stringify(TWITTER_FEATURES)+ const url = `https://x.com/i/api/graphql/ck5KkZ8t5cOmoLssopN99Q/UserByScreenName?variables=${encodeURIComponent(variables)}&features=${encodeURIComponent(features)}`++ try {+ const res = await this.httpClient.fetchJson<any>(url, {+ cookiePath: options.cookiePath,+ cookieDomain: 'x.com',+ signal: options.signal,+ retries: 0,+ timeoutMs: 4000,+ })++ const restId = res.data?.user?.result?.rest_id+ if (restId) return restId+ } catch {}++ // Fallback: syndication widget+ const syndiUrl = `https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names=${encodeURIComponent(username)}`+ try {+ const res = await this.httpClient.fetchJson<any[]>(syndiUrl, {+ signal: options.signal,+ retries: 0,+ timeoutMs: 3000,+ })+ if (res[0]?.id) return String(res[0].id)+ } catch {}++ throw new Error(`Failed to resolve X/Twitter user ID for @${username}`)+ }++ async *extract(profile: ParsedProfile, options: ExtractOptions): AsyncGenerator<MediaItem, void, unknown> {+ const username = profile.username+ const subDir = options.subDir+ const isLikes = username === 'i_history_likes' || profile.cleanUrl?.endsWith('/likes')++ // Read session cookies to attach CSRF token and auth-type headers+ const authHeaders: Record<string, string> = {}+ if (options.cookiePath) {+ let cookies = await loadCookiesFromPath(options.cookiePath, 'x.com')+ if (!cookies['ct0'] && !cookies['auth_token']) {+ const twCookies = await loadCookiesFromPath(options.cookiePath, 'twitter.com')+ cookies = {...twCookies, ...cookies}+ }+ if (cookies['ct0']) {+ authHeaders['x-csrf-token'] = cookies['ct0']+ }+ if (cookies['auth_token']) {+ authHeaders['x-twitter-auth-type'] = 'OAuth2Session'+ }+ }++ options.onProgress?.({+ stage: isLikes ? 'Likes' : 'Profile',+ found: 0,+ message: isLikes ? 'Fetching liked posts from X...' : `Fetching X profile @${username}...`,+ })++ const userId = await this.fetchUserRestId(username, options)++ // UserMedia endpoint or Likes endpoint (gallery-dl upstream v1.32.16+)+ const endpoint = isLikes+ ? 'https://x.com/i/api/graphql/TGEKkJG_meudeaFcqaxM-Q/Likes'+ : 'https://x.com/i/api/graphql/jCRhbOzdgOHp6u9H4g2tEg/UserMedia'+ let cursor: string | undefined+ let hasMore = true+ let found = 0++ while (hasMore) {+ if (options.signal?.aborted) break++ const variables: Record<string, any> = {+ userId,+ count: 50,+ includePromotedContent: false,+ withClientEventToken: false,+ withBirdwatchNotes: false,+ withVoice: true,+ }+ if (cursor) {+ variables.cursor = cursor+ }++ const features = JSON.stringify(TWITTER_FEATURES)+ const url = `${endpoint}?variables=${encodeURIComponent(JSON.stringify(variables))}&features=${encodeURIComponent(features)}`++ let res: any+ try {+ res = await this.httpClient.fetchJson<any>(url, {+ cookiePath: options.cookiePath,+ cookieDomain: 'x.com',+ signal: options.signal,+ headers: authHeaders,+ })+ } catch (err) {+ break+ }++ if (res?.errors?.length && !res?.data?.user?.result) {+ throw new Error(`X/Twitter API error: ${res.errors[0]?.message || 'GraphQL query failed'}`)+ }++ const instructions = res?.data?.user?.result?.timeline_v2?.timeline?.instructions || []+ let newCursor: string | undefined+ let pageItemCount = 0++ for (const inst of instructions) {+ const entries = inst.entries || (inst.entry ? [inst.entry] : [])+ for (const entry of entries) {+ if (entry.entryId?.startsWith('cursor-bottom-')) {+ newCursor = entry.content?.value+ continue+ }++ const tweetContent = entry.content?.itemContent?.tweet_results?.result+ if (tweetContent) {+ // Filter third-party conversational replies while retaining self-threads+ if (shouldSkipTweetReply(tweetContent, userId, isLikes ? 'likes' : 'timeline')) {+ continue+ }++ const mediaItems = parseTweetMediaEntities(tweetContent, username)+ for (const item of mediaItems) {+ if (subDir === 'Photos' && item.type !== 'photo') continue+ if (subDir === 'Videos' && item.type !== 'video') continue++ found+++ pageItemCount+++ options.onProgress?.({+ stage: subDir,+ found,+ message: `Found item: ${item.filename}`,+ })+ yield item+ }+ }+ }+ }++ if (!newCursor || newCursor === cursor || pageItemCount === 0) {+ hasMore = false+ } else {+ cursor = newCursor+ await sleep(1500, 2500, options.signal)+ }+ }+ }+}diff --git a/src/lib/open_nami/http.test.ts b/src/lib/open_nami/http.test.tsnew file mode 100644index 00000000..fb04c612--- /dev/null+++ b/src/lib/open_nami/http.test.ts@@ -0,0 +1,48 @@+import { describe, it, expect, vi } from 'vitest';+import { HttpClient, parseNetscapeCookies, formatCookieHeader } from './http';++describe('open_nami http client', () => {+ it('parses netscape cookie format correctly', () => {+ const raw = `# Netscape HTTP Cookie File+.instagram.com\tTRUE\t/\tTRUE\t1799999999\tsessionid\t12345%3Aabc+#HttpOnly_.instagram.com\tTRUE\t/\tTRUE\t1799999999\tds_user_id\t98765+.facebook.com\tTRUE\t/\tTRUE\t1799999999\tc_user\t111222+`;+ const igCookies = parseNetscapeCookies(raw, 'instagram.com');+ expect(igCookies['sessionid']).toBe('12345%3Aabc');+ expect(igCookies['ds_user_id']).toBe('98765');+ expect(igCookies['c_user']).toBeUndefined();+ });++ it('formats cookie headers properly', () => {+ const cookies = { sessionid: 'abc', ds_user_id: '123' };+ const header = formatCookieHeader(cookies);+ expect(header).toBe('sessionid=abc; ds_user_id=123');+ });++ it('dispatches requests through custom invoker', async () => {+ const mockInvoker = vi.fn().mockResolvedValue({+ status: 200,+ ok: true,+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ data: { user: { id: '42' } } }),+ });++ const client = new HttpClient({ invoker: mockInvoker });+ const res = await client.request('https://www.instagram.com/graphql/query');++ expect(mockInvoker).toHaveBeenCalledWith(+ 'open_nami_http_fetch',+ {+ options: expect.objectContaining({+ url: 'https://www.instagram.com/graphql/query',+ }),+ }+ );+ expect(res.status).toBe(200);+ expect(res.ok).toBe(true);++ const json = await res.json();+ expect(json.data.user.id).toBe('42');+ });+});diff --git a/src/lib/open_nami/http.ts b/src/lib/open_nami/http.tsnew file mode 100644index 00000000..c5b0726d--- /dev/null+++ b/src/lib/open_nami/http.ts@@ -0,0 +1,288 @@+import { invoke } from '@tauri-apps/api/core';++export const DEFAULT_USER_AGENT =+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';++export const DEFAULT_CHROME_HEADERS: Record<string, string> = {+ 'User-Agent': DEFAULT_USER_AGENT,+ 'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',+ 'sec-ch-ua-mobile': '?0',+ 'sec-ch-ua-platform': '"Windows"',+ Accept: '*/*',+ 'Accept-Language': 'en-US,en;q=0.9',+};++export function parseNetscapeCookies(content: string, filterDomain?: string): Record<string, string> {+ const cookies: Record<string, string> = {};+ const lines = content.split(/\r?\n/);++ for (const rawLine of lines) {+ let line = rawLine.trim();+ if (!line) continue;++ if (line.startsWith('#HttpOnly_')) {+ line = line.slice('#HttpOnly_'.length);+ } else if (line.startsWith('#')) {+ continue;+ }++ const parts = line.split('\t');+ if (parts.length >= 7) {+ const domain = parts[0].toLowerCase();+ const name = parts[5];+ const value = parts[6];++ if (filterDomain) {+ const cleanDomain = filterDomain.toLowerCase().replace(/^\./, '');+ const lineDomain = domain.replace(/^\./, '');+ if (!lineDomain.endsWith(cleanDomain) && !cleanDomain.endsWith(lineDomain)) {+ continue;+ }+ }++ if (name) {+ cookies[name] = value;+ }+ }+ }++ return cookies;+}++export async function loadCookiesFromPath(+ filePath: string,+ filterDomain?: string+): Promise<Record<string, string>> {+ try {+ const fs = await import('node:fs/promises');+ const content = await fs.readFile(filePath, 'utf-8');+ return parseNetscapeCookies(content, filterDomain);+ } catch {+ return {};+ }+}++export function formatCookieHeader(cookies: Record<string, string>): string {+ return Object.entries(cookies)+ .map(([k, v]) => `${k}=${v}`)+ .join('; ');+}++export async function sleep(minMs: number, maxMs?: number, signal?: AbortSignal): Promise<void> {+ const ms = maxMs !== undefined ? Math.floor(minMs + Math.random() * (maxMs - minMs)) : minMs;+ if (ms <= 0) return;+ if (signal?.aborted) {+ throw signal.reason ?? new Error('Aborted');+ }+ return new Promise((resolve, reject) => {+ const timer = setTimeout(resolve, ms);+ if (signal) {+ signal.addEventListener(+ 'abort',+ () => {+ clearTimeout(timer);+ reject(signal.reason ?? new Error('Aborted'));+ },+ { once: true }+ );+ }+ });+}++export interface RequestOptions {+ method?: string;+ headers?: Record<string, string>;+ body?: string;+ cookies?: Record<string, string> | string;+ cookiePath?: string | null;+ cookieDomain?: string;+ retries?: number;+ retryDelayMs?: number;+ timeoutMs?: number;+ signal?: AbortSignal;+}++export interface HttpResponsePayload {+ status: number;+ ok: boolean;+ headers: Record<string, string>;+ body: string;+}++export type InvokerFn = (cmd: string, args: Record<string, unknown>) => Promise<HttpResponsePayload>;++export class HttpResponse {+ readonly status: number;+ readonly statusText: string;+ readonly ok: boolean;+ readonly headers: Headers;+ readonly body: { cancel: () => Promise<void> } | null;+ private readonly rawBody: string;++ constructor(payload: HttpResponsePayload) {+ this.status = payload.status;+ this.statusText = payload.ok ? 'OK' : 'Error';+ this.ok = payload.ok;+ this.headers = new Headers(payload.headers);+ this.rawBody = payload.body;+ this.body = { cancel: async () => {} };+ }++ async text(): Promise<string> {+ return this.rawBody;+ }++ async json<T = any>(): Promise<T> {+ return JSON.parse(this.rawBody);+ }+}++export class HttpClient {+ private defaultCookies: Record<string, string> = {};+ private defaultHeaders: Record<string, string>;+ private cookieCache: Map<string, Record<string, string>> = new Map();+ private invoker: InvokerFn;++ constructor(+ headersOrOptions?: Record<string, string> | { headers?: Record<string, string>; cookies?: Record<string, string>; invoker?: InvokerFn },+ cookies?: Record<string, string>,+ invoker?: InvokerFn+ ) {+ if (headersOrOptions && ('headers' in headersOrOptions || 'cookies' in headersOrOptions || 'invoker' in headersOrOptions)) {+ const opts = headersOrOptions as { headers?: Record<string, string>; cookies?: Record<string, string>; invoker?: InvokerFn };+ this.defaultHeaders = { ...DEFAULT_CHROME_HEADERS, ...(opts.headers || {}) };+ if (opts.cookies) {+ this.defaultCookies = { ...opts.cookies };+ }+ this.invoker =+ opts.invoker ||+ (typeof window !== 'undefined'+ ? ((cmd, args) => invoke<HttpResponsePayload>(cmd, args))+ : async () => ({ status: 200, ok: true, headers: {}, body: '{}' }));+ } else {+ this.defaultHeaders = { ...DEFAULT_CHROME_HEADERS, ...(headersOrOptions as Record<string, string> || {}) };+ if (cookies) {+ this.defaultCookies = { ...cookies };+ }+ this.invoker =+ invoker ||+ (typeof window !== 'undefined'+ ? ((cmd, args) => invoke<HttpResponsePayload>(cmd, args))+ : async () => ({ status: 200, ok: true, headers: {}, body: '{}' }));+ }+ }++ setCookie(name: string, value: string): void {+ this.defaultCookies[name] = value;+ }++ setHeader(name: string, value: string): void {+ this.defaultHeaders[name] = value;+ }++ clearCookieCache(): void {+ this.cookieCache.clear();+ }++ private async getCachedCookies(filePath: string, domain?: string): Promise<Record<string, string>> {+ const cacheKey = `${filePath}::${domain || ''}`;+ const cached = this.cookieCache.get(cacheKey);+ if (cached) {+ return cached;+ }+ const loaded = await loadCookiesFromPath(filePath, domain);+ this.cookieCache.set(cacheKey, loaded);+ return loaded;+ }++ async loadCookies(filePath: string, domain?: string): Promise<void> {+ const loaded = await this.getCachedCookies(filePath, domain);+ Object.assign(this.defaultCookies, loaded);+ }++ async request(url: string, options: RequestOptions = {}): Promise<HttpResponse> {+ let cookieHeader = '';+ if (options.cookiePath) {+ const fromPath = await this.getCachedCookies(options.cookiePath, options.cookieDomain);+ const merged = { ...this.defaultCookies, ...fromPath };+ cookieHeader = formatCookieHeader(merged);+ } else if (typeof options.cookies === 'string') {+ cookieHeader = options.cookies;+ } else if (options.cookies) {+ const merged = { ...this.defaultCookies, ...options.cookies };+ cookieHeader = formatCookieHeader(merged);+ } else if (Object.keys(this.defaultCookies).length > 0) {+ cookieHeader = formatCookieHeader(this.defaultCookies);+ }++ const headers: Record<string, string> = {+ ...this.defaultHeaders,+ ...(options.headers || {}),+ };++ if (cookieHeader) {+ headers['Cookie'] = cookieHeader;+ }++ const payload = await this.invoker('open_nami_http_fetch', {+ options: {+ url,+ method: options.method || 'GET',+ headers,+ body: options.body || null,+ cookie_path: options.cookiePath || null,+ timeout_ms: options.timeoutMs || 15000,+ },+ });++ return new HttpResponse(payload);+ }++ async get(url: string, options: RequestOptions = {}): Promise<HttpResponse> {+ return this.request(url, { ...options, method: 'GET' });+ }++ async post(url: string, options: RequestOptions = {}): Promise<HttpResponse> {+ return this.request(url, { ...options, method: 'POST' });+ }++ async getText(url: string, options: RequestOptions = {}): Promise<string> {+ const res = await this.get(url, options);+ return res.text();+ }++ async getJson<T = any>(url: string, options: RequestOptions = {}): Promise<T> {+ const res = await this.get(url, options);+ return res.json<T>();+ }++ async fetchJson<T = unknown>(url: string, options: RequestOptions = {}): Promise<T> {+ const res = await this.request(url, {+ ...options,+ headers: {+ Accept: 'application/json, text/plain, */*',+ ...(options.headers as Record<string, string>),+ },+ });+ if (!res.ok) {+ try {+ await res.body?.cancel();+ } catch {}+ throw new Error(`HTTP ${res.status} (${res.statusText}) for ${url}`);+ }+ const text = await res.text();+ const cleanText = text.replace(/^\s*(?:for\s*\(\s*;\s*;\s*\);|\)\]\}',)/, '').trim();+ return JSON.parse(cleanText) as T;+ }++ async fetchText(url: string, options: RequestOptions = {}): Promise<string> {+ const res = await this.request(url, options);+ if (!res.ok) {+ try {+ await res.body?.cancel();+ } catch {}+ throw new Error(`HTTP ${res.status} (${res.statusText}) for ${url}`);+ }+ return await res.text();+ }+}diff --git a/src/lib/open_nami/types.ts b/src/lib/open_nami/types.tsnew file mode 100644index 00000000..ef106a0d--- /dev/null+++ b/src/lib/open_nami/types.ts@@ -0,0 +1,36 @@+import type { ParsedProfile, SupportedPlatform } from '../utils/open_nami_parser';++export type MediaType = 'photo' | 'video';++export interface MediaItem {+ id: string;+ url: string;+ filename: string;+ extension: string;+ type: MediaType;+ caption?: string;+ date?: number;+ width?: number;+ height?: number;+ thumbnailUrl?: string;+}++export type SubDirChoice = 'Photos' | 'Videos' | 'Stories' | 'Highlights';++export interface ExtractProgress {+ stage: string;+ found: number;+ message?: string;+}++export interface ExtractOptions {+ subDir: SubDirChoice;+ cookiePath?: string | null;+ signal?: AbortSignal;+ onProgress?: (progress: ExtractProgress) => void;+}++export interface Extractor {+ platform: SupportedPlatform;+ extract(profile: ParsedProfile, options: ExtractOptions): AsyncGenerator<MediaItem, void, unknown>;+}diff --git a/src/lib/stores/open_nami_download_store.svelte.ts b/src/lib/stores/open_nami_download_store.svelte.tsindex 5d0b9fe1..11ca5585 100644--- a/src/lib/stores/open_nami_download_store.svelte.ts+++ b/src/lib/stores/open_nami_download_store.svelte.ts@@ -7,6 +7,7 @@ import {type DownloadResult,} from "$lib/api/open_nami";import { parseProfileUrl } from "$lib/utils/open_nami_parser";+import { dispatchMultiTierDownload } from "$lib/open_nami/dispatcher";export type StatusType = "success" | "error" | "info";@@ -155,18 +156,22 @@ export async function startDownload(try {unlisten = await listenToDownloadProgress(id, applyProgress);- const result = await runGalleryDlDownload(- cleanUrl,+ const result = await dispatchMultiTierDownload({+ profile: parsed,cleanOutputDir,- cleanCookiesFile || null,+ cookiesFile: cleanCookiesFile || null,contentType,- id,- );+ downloadId: id,+ onProgress: (msg) => {+ status = msg;+ lastMessage = msg;+ },+ });filesDownloaded = result.files_count;if (result.cancelled) {- status = `Download cancelled — ${result.files_count} file(s) saved before stopping.`;+ status = `Download cancelled: ${result.files_count} file(s) saved before stopping.`;statusType = "info";statusDetail = "";} else if (result.success) {diff --git a/src/lib/utils/open_nami_parser.test.ts b/src/lib/utils/open_nami_parser.test.tsindex 81b9545f..8b82336b 100644--- a/src/lib/utils/open_nami_parser.test.ts+++ b/src/lib/utils/open_nami_parser.test.ts@@ -36,6 +36,24 @@ describe('open_nami_parser', () => {expect(parsed.cleanUrl).toBe('https://x.com/OpenSelena');});+ it('parses x/twitter personal likes history URL', () => {+ const raw = 'https://x.com/i/history/likes';+ const parsed = parseProfileUrl(raw);+ expect(parsed.platform).toBe('x');+ expect(parsed.username).toBe('i_history_likes');+ expect(parsed.cleanUrl).toBe('https://x.com/i/history/likes');+ expect(parsed.isSpecificMedia).toBe(false);+ });++ it('parses x/twitter personal bookmarks URL', () => {+ const raw = 'https://twitter.com/i/bookmarks';+ const parsed = parseProfileUrl(raw);+ expect(parsed.platform).toBe('x');+ expect(parsed.username).toBe('i_bookmarks');+ expect(parsed.cleanUrl).toBe('https://twitter.com/i/bookmarks');+ expect(parsed.isSpecificMedia).toBe(false);+ });+it('parses facebook profile URL', () => {const raw = 'https://www.facebook.com/nami.official';const parsed = parseProfileUrl(raw);diff --git a/src/lib/utils/open_nami_parser.ts b/src/lib/utils/open_nami_parser.tsindex cda99312..c8e350e8 100644--- a/src/lib/utils/open_nami_parser.ts+++ b/src/lib/utils/open_nami_parser.ts@@ -174,6 +174,27 @@ export function parseProfileUrl(raw: string): ParsedProfile {// 4. X / Twitterif (host.includes('x.com') || host.includes('twitter.com')) {const firstPart = pathParts[0]?.toLowerCase() || '';++ // Personal likes / bookmarks history+ if (firstPart === 'i' && pathParts[1]?.toLowerCase() === 'history' && pathParts[2]?.toLowerCase() === 'likes') {+ return {+ platform: 'x',+ username: 'i_history_likes',+ cleanUrl: `${url.origin}/i/history/likes`,+ rawInput: raw,+ isSpecificMedia: false,+ };+ }+ if (firstPart === 'i' && pathParts[1]?.toLowerCase() === 'bookmarks') {+ return {+ platform: 'x',+ username: 'i_bookmarks',+ cleanUrl: `${url.origin}/i/bookmarks`,+ rawInput: raw,+ isSpecificMedia: false,+ };+ }+const reserved = ['home', 'explore', 'notifications', 'messages', 'i', 'settings'];if (firstPart && !reserved.includes(firstPart)) {const username = pathParts[0].replace(/^@/, '');