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
Phase 2: port Pinterest, Reddit, Instagram, TikTok to core
Hanako0fcbd3826e5c
diff --git a/src-tauri/omniget-core/src/platforms/instagram.rs b/src-tauri/omniget-core/src/platforms/instagram.rsnew file mode 100644index 00000000..7c9b8509--- /dev/null+++ b/src-tauri/omniget-core/src/platforms/instagram.rs@@ -0,0 +1,1001 @@+use anyhow::anyhow;+use async_trait::async_trait;+use crate::models::progress::ProgressUpdate;+use rand::RngExt;+use regex::Regex;+use tokio::sync::mpsc;++use crate::core::direct_downloader::download_direct_with_headers;+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};+use crate::platforms::traits::PlatformDownloader;++const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";+const IG_APP_ID: &str = "936619743392459";+const GQL_DOC_ID: &str = "8845758582119845";++pub struct InstagramDownloader {+ client: reqwest::Client,+ redirect_client: reqwest::Client,+}++enum InstagramMedia {+ Single { url: String, is_video: bool },+ Carousel { items: Vec<CarouselItem> },+}++struct CarouselItem {+ url: String,+ is_video: bool,+}++struct GqlParams {+ csrf_token: String,+ device_id: String,+ machine_id: String,+ lsd_token: String,+ app_id: String,+ haste_session: String,+ hsi: String,+ rollout_hash: String,+ spin_r: String,+ spin_b: String,+ spin_t: String,+ comet_req: String,+ jazoest: String,+ bloks_version_id: String,+}++impl Default for InstagramDownloader {+ fn default() -> Self {+ Self::new()+ }+}++impl InstagramDownloader {+ pub fn new() -> Self {+ let mut builder = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())+ .user_agent(USER_AGENT)+ .timeout(std::time::Duration::from_secs(120))+ .connect_timeout(std::time::Duration::from_secs(15));++ if let Some(jar) =+ crate::core::cookie_parser::load_extension_cookies_for_domain("instagram.com")+ {+ builder = builder.cookie_provider(jar);+ }++ let client = builder.build().unwrap_or_default();++ let redirect_client =+ crate::core::http_client::apply_global_proxy(reqwest::Client::builder())+ .user_agent("curl/7.88.1")+ .timeout(std::time::Duration::from_secs(120))+ .connect_timeout(std::time::Duration::from_secs(15))+ .build()+ .unwrap_or_default();++ Self {+ client,+ redirect_client,+ }+ }++ fn extract_post_id(url: &str) -> Option<String> {+ let parsed = url::Url::parse(url).ok()?;+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();++ match segments.first() {+ Some(&"p") | Some(&"reel") | Some(&"reels") | Some(&"tv") => {+ segments.get(1).map(|s| s.to_string())+ }+ _ => None,+ }+ }++ fn extract_share_id(url: &str) -> Option<String> {+ let parsed = url::Url::parse(url).ok()?;+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();++ if segments.first() == Some(&"share") {+ return segments.get(1).map(|s| s.to_string());+ }++ None+ }++ fn is_story_url(url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ let path = parsed.path().to_lowercase();+ return path.starts_with("/stories/");+ }+ false+ }++ async fn resolve_share_link(&self, share_id: &str) -> anyhow::Result<String> {+ let url = format!("https://www.instagram.com/share/{}/", share_id);++ let response = self.redirect_client.get(&url).send().await?;+ let final_url = response.url().to_string();++ if final_url.contains("/share/") || final_url == url {+ return Err(anyhow!("Could not resolve share link"));+ }++ Ok(final_url)+ }++ fn regex_extract(pattern: &str, text: &str) -> Option<String> {+ let re = Regex::new(pattern).ok()?;+ re.captures(text)?.get(1).map(|m| m.as_str().to_string())+ }++ fn extract_object_entry(name: &str, html: &str) -> Option<serde_json::Value> {+ let pattern = format!(r#"\["{}",.*?,(\{{.*?\}}),\d+\]"#, regex::escape(name));+ let re = Regex::new(&pattern).ok()?;+ let json_str = re.captures(html)?.get(1)?.as_str();+ serde_json::from_str(json_str).ok()+ }++ fn extract_number_from_query(name: &str, html: &str) -> Option<String> {+ let pattern = format!(r"{}=(\d+)", regex::escape(name));+ let re = Regex::new(&pattern).ok()?;+ re.captures(html)?.get(1).map(|m| m.as_str().to_string())+ }++ fn random_base64url(len: usize) -> String {+ let bytes: Vec<u8> = (0..len).map(|_| rand::rng().random::<u8>()).collect();+ base64_url_encode(&bytes)+ }++ fn random_alpha_string(len: usize) -> String {+ let chars: Vec<char> = "abcdefghijklmnopqrstuvwxyz".chars().collect();+ (0..len)+ .map(|_| chars[rand::rng().random_range(0..chars.len())])+ .collect()+ }++ fn is_login_redirect(html: &str) -> bool {+ let lower = html.to_lowercase();+ lower.contains("/accounts/login")+ || lower.contains("\"loginpage\"")+ || (lower.contains("\"require_login\"") && lower.contains("true"))+ }++ async fn get_gql_params(&self, post_id: &str) -> anyhow::Result<GqlParams> {+ let url = format!("https://www.instagram.com/p/{}/", post_id);++ let response = self+ .client+ .get(&url)+ .header(+ "Accept",+ "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",+ )+ .header("Accept-Language", "en-GB,en;q=0.9")+ .header("Sec-Fetch-Dest", "document")+ .header("Sec-Fetch-Mode", "navigate")+ .header("Sec-Fetch-Site", "none")+ .header("Sec-Fetch-User", "?1")+ .send()+ .await?;++ let html = response.text().await?;++ if Self::is_login_redirect(&html) {+ return Err(anyhow!(+ "Instagram redirecionou para login — post pode ser privado"+ ));+ }++ let csrf = Self::extract_object_entry("InstagramSecurityConfig", &html)+ .and_then(|v| {+ v.get("csrf_token")+ .and_then(|t| t.as_str())+ .map(|s| s.to_string())+ })+ .unwrap_or_default();++ let polaris = Self::extract_object_entry("PolarisSiteData", &html);+ let device_id = polaris+ .as_ref()+ .and_then(|v| {+ v.get("device_id")+ .and_then(|t| t.as_str())+ .map(|s| s.to_string())+ })+ .unwrap_or_default();+ let machine_id = polaris+ .as_ref()+ .and_then(|v| {+ v.get("machine_id")+ .and_then(|t| t.as_str())+ .map(|s| s.to_string())+ })+ .unwrap_or_default();++ let site_data = Self::extract_object_entry("SiteData", &html);+ let haste_session = site_data+ .as_ref()+ .and_then(|v| {+ v.get("haste_session")+ .and_then(|t| t.as_str())+ .map(|s| s.to_string())+ })+ .unwrap_or_else(|| "20126.HYP:instagram_web_pkg.2.1...0".to_string());+ let hsi = site_data+ .as_ref()+ .and_then(|v| v.get("hsi").and_then(|t| t.as_str()).map(|s| s.to_string()))+ .unwrap_or_else(|| "7436540909012459023".to_string());+ let spin_r = site_data+ .as_ref()+ .and_then(|v| {+ v.get("__spin_r")+ .and_then(|t| t.as_str())+ .map(|s| s.to_string())+ })+ .unwrap_or_else(|| "1019933358".to_string());+ let spin_b = site_data+ .as_ref()+ .and_then(|v| {+ v.get("__spin_b")+ .and_then(|t| t.as_str())+ .map(|s| s.to_string())+ })+ .unwrap_or_else(|| "trunk".to_string());+ let spin_t = site_data+ .as_ref()+ .and_then(|v| {+ v.get("__spin_t")+ .and_then(|t| t.as_str().or_else(|| t.as_u64().map(|_| "")).map(|_| ()))+ })+ .map(|_| {+ site_data+ .as_ref()+ .and_then(|v| {+ v.get("__spin_t").and_then(|t| {+ t.as_str()+ .map(|s| s.to_string())+ .or_else(|| t.as_u64().map(|n| n.to_string()))+ })+ })+ .unwrap_or_default()+ })+ .unwrap_or_else(|| {+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs();+ now.to_string()+ });++ let web_config = Self::extract_object_entry("DGWWebConfig", &html);+ let app_id = web_config+ .as_ref()+ .and_then(|v| {+ v.get("appId").and_then(|t| {+ t.as_str()+ .map(|s| s.to_string())+ .or_else(|| t.as_u64().map(|n| n.to_string()))+ })+ })+ .unwrap_or_else(|| IG_APP_ID.to_string());++ let lsd = Self::extract_object_entry("LSD", &html)+ .and_then(|v| {+ v.get("token")+ .and_then(|t| t.as_str())+ .map(|s| s.to_string())+ })+ .unwrap_or_else(|| Self::random_base64url(8));++ let bloks_version_id = Self::extract_object_entry("WebBloksVersioningID", &html)+ .and_then(|v| {+ v.get("versioningID")+ .and_then(|t| t.as_str())+ .map(|s| s.to_string())+ })+ .unwrap_or_default();++ let push_info = Self::extract_object_entry("InstagramWebPushInfo", &html);+ let rollout_hash = push_info+ .as_ref()+ .and_then(|v| {+ v.get("rollout_hash")+ .and_then(|t| t.as_str())+ .map(|s| s.to_string())+ })+ .unwrap_or_else(|| "1019933358".to_string());++ let comet_req = Self::extract_number_from_query("__comet_req", &html)+ .unwrap_or_else(|| "7".to_string());++ let jazoest = Self::extract_number_from_query("jazoest", &html).unwrap_or_else(|| {+ let val: u32 = rand::rng().random_range(1000..10000);+ val.to_string()+ });++ Ok(GqlParams {+ csrf_token: csrf,+ device_id,+ machine_id,+ lsd_token: lsd,+ app_id,+ haste_session,+ hsi,+ rollout_hash,+ spin_r,+ spin_b,+ spin_t,+ comet_req,+ jazoest,+ bloks_version_id,+ })+ }++ async fn request_gql(&self, post_id: &str) -> anyhow::Result<serde_json::Value> {+ let params = self.get_gql_params(post_id).await?;++ let anon_cookie = [+ if !params.csrf_token.is_empty() {+ Some(format!("csrftoken={}", params.csrf_token))+ } else {+ None+ },+ if !params.device_id.is_empty() {+ Some(format!("ig_did={}", params.device_id))+ } else {+ None+ },+ Some("wd=1280x720".to_string()),+ Some("dpr=2".to_string()),+ if !params.machine_id.is_empty() {+ Some(format!("mid={}", params.machine_id))+ } else {+ None+ },+ Some("ig_nrcb=1".to_string()),+ ]+ .into_iter()+ .flatten()+ .collect::<Vec<_>>()+ .join("; ");++ let s_val = format!("::{}", Self::random_alpha_string(6));+ let dyn_val = Self::random_base64url(154);+ let csr_val = Self::random_base64url(154);++ let variables = serde_json::json!({+ "shortcode": post_id,+ "fetch_tagged_user_count": null,+ "hoisted_comment_id": null,+ "hoisted_reply_id": null+ });++ let body = format!(+ "__d=www&__a=1&__s={}&__hs={}&__req=b&__ccg=EXCELLENT&__rev={}&__hsi={}&__dyn={}&__csr={}&__user=0&__comet_req={}&av=0&dpr=2&lsd={}&jazoest={}&__spin_r={}&__spin_b={}&__spin_t={}&fb_api_caller_class=RelayModern&fb_api_req_friendly_name=PolarisPostActionLoadPostQueryQuery&variables={}&server_timestamps=true&doc_id={}",+ urlencoding::encode(&s_val),+ urlencoding::encode(¶ms.haste_session),+ urlencoding::encode(¶ms.rollout_hash),+ urlencoding::encode(¶ms.hsi),+ urlencoding::encode(&dyn_val),+ urlencoding::encode(&csr_val),+ urlencoding::encode(¶ms.comet_req),+ urlencoding::encode(¶ms.lsd_token),+ urlencoding::encode(¶ms.jazoest),+ urlencoding::encode(¶ms.spin_r),+ urlencoding::encode(¶ms.spin_b),+ urlencoding::encode(¶ms.spin_t),+ urlencoding::encode(&variables.to_string()),+ GQL_DOC_ID,+ );++ let response = self+ .client+ .post("https://www.instagram.com/graphql/query")+ .header("Accept", "*/*")+ .header("Accept-Language", "en-GB,en;q=0.9")+ .header("Content-Type", "application/x-www-form-urlencoded")+ .header("Sec-Fetch-Dest", "empty")+ .header("Sec-Fetch-Mode", "cors")+ .header("Sec-Fetch-Site", "same-origin")+ .header("X-Requested-With", "XMLHttpRequest")+ .header("x-ig-app-id", ¶ms.app_id)+ .header("X-FB-LSD", ¶ms.lsd_token)+ .header("X-CSRFToken", ¶ms.csrf_token)+ .header("X-FB-Friendly-Name", "PolarisPostActionLoadPostQueryQuery")+ .header("x-asbd-id", "129477")+ .header("X-Bloks-Version-Id", ¶ms.bloks_version_id)+ .header("Referer", "https://www.instagram.com/")+ .header("Cookie", &anon_cookie)+ .body(body)+ .send()+ .await?;++ if !response.status().is_success() {+ return Err(anyhow!("Instagram GQL retornou HTTP {}", response.status()));+ }++ let json: serde_json::Value = response.json().await?;++ let data = json+ .get("data")+ .ok_or_else(|| anyhow!("Resposta GQL sem data"))?;++ let media = data+ .get("xdt_shortcode_media")+ .or_else(|| data.get("shortcode_media"));++ match media {+ Some(m) if !m.is_null() => Ok(m.clone()),+ _ => Err(anyhow!("Post not found via GQL")),+ }+ }++ async fn request_embed(&self, post_id: &str) -> anyhow::Result<serde_json::Value> {+ let url = format!("https://www.instagram.com/p/{}/embed/captioned/", post_id);++ let response = self+ .client+ .get(&url)+ .header(+ "Accept",+ "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",+ )+ .header("Accept-Language", "en-GB,en;q=0.9")+ .header("Sec-Fetch-Dest", "iframe")+ .header("Sec-Fetch-Mode", "navigate")+ .header("Sec-Fetch-Site", "cross-site")+ .header("Referer", "https://www.instagram.com/")+ .send()+ .await?;++ let html = response.text().await?;++ if let Some(json_str) = Self::regex_extract(r#""init",\[\],\[(.*?)\]\],"#, &html) {+ if let Ok(embed_data) = serde_json::from_str::<serde_json::Value>(&json_str) {+ if let Some(context_json) = embed_data.get("contextJSON").and_then(|v| v.as_str()) {+ let context: serde_json::Value = serde_json::from_str(context_json)?;+ return Ok(context);+ }+ }+ }++ if let Some(json_str) = Self::regex_extract(+ r#"window\.__additionalDataLoaded\('extra',\s*(\{.*?\})\s*\)"#,+ &html,+ ) {+ let data: serde_json::Value = serde_json::from_str(&json_str)?;+ return Ok(data);+ }++ Err(anyhow!("Could not extract data from embed"))+ }++ async fn fallback_ytdlp(&self, url: &str, post_id: &str) -> anyhow::Result<MediaInfo> {+ let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;+ let json = crate::core::ytdlp::get_video_info(&ytdlp_path, url, &[]).await?;+ let mut info =+ crate::platforms::generic_ytdlp::GenericYtdlpDownloader::parse_video_info(&json)?;++ info.title = format!("instagram_{}", post_id);+ info.platform = "instagram".to_string();++ let post_url = format!("https://www.instagram.com/p/{}/", post_id);+ for q in &mut info.available_qualities {+ q.format = "ytdlp".to_string();+ q.url = post_url.clone();+ }++ Ok(info)+ }++ fn extract_media_from_gql(data: &serde_json::Value) -> anyhow::Result<InstagramMedia> {+ let sidecar = data.get("edge_sidecar_to_children");++ if let Some(sidecar) = sidecar {+ if let Some(edges) = sidecar.get("edges").and_then(|v| v.as_array()) {+ let items: Vec<CarouselItem> = edges+ .iter()+ .filter_map(|edge| {+ let node = edge.get("node")?;+ let is_video = node+ .get("is_video")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);++ let url = if is_video {+ node.get("video_url").and_then(|v| v.as_str())+ } else {+ node.get("display_url").and_then(|v| v.as_str())+ }?;++ Some(CarouselItem {+ url: url.to_string(),+ is_video,+ })+ })+ .collect();++ if !items.is_empty() {+ return Ok(InstagramMedia::Carousel { items });+ }+ }+ }++ if let Some(video_url) = data.get("video_url").and_then(|v| v.as_str()) {+ return Ok(InstagramMedia::Single {+ url: video_url.to_string(),+ is_video: true,+ });+ }++ if let Some(display_url) = data.get("display_url").and_then(|v| v.as_str()) {+ return Ok(InstagramMedia::Single {+ url: display_url.to_string(),+ is_video: false,+ });+ }++ Err(anyhow!("No media found in post"))+ }++ fn instagram_headers() -> reqwest::header::HeaderMap {+ let mut headers = reqwest::header::HeaderMap::new();+ headers.insert(+ reqwest::header::REFERER,+ "https://www.instagram.com/".parse().unwrap(),+ );+ headers.insert(+ reqwest::header::ORIGIN,+ "https://www.instagram.com".parse().unwrap(),+ );+ 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 resolve_fallback_post_url(info: &MediaInfo, opts: &DownloadOptions) -> Option<String> {+ if let Some(url) = Self::post_url_from_title(&info.title) {+ return Some(url);+ }+ if let Some(page_url) = opts.page_url.as_deref() {+ if Self::extract_post_id(page_url).is_some() {+ return Some(page_url.to_string());+ }+ if let Some(share_id) = Self::extract_share_id(page_url) {+ return Some(format!("https://www.instagram.com/share/{}/", share_id));+ }+ }+ None+ }++ 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<ProgressUpdate>,+ ) -> 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(),+ opts.referer+ .as_deref()+ .or(Some("https://www.instagram.com/")),+ opts.cancel_token.clone(),+ None,+ opts.concurrent_fragments,+ false,+ &[],+ opts.audio_format.as_deref(),+ )+ .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")+ .or_else(|| g.get("xdt_shortcode_media"))+ }) {+ return Self::extract_media_from_gql(video_url);+ }++ if let Some(video_url) = data.get("video_url").and_then(|v| v.as_str()) {+ return Ok(InstagramMedia::Single {+ url: video_url.to_string(),+ is_video: true,+ });+ }++ if let Some(display_url) = data+ .get("media")+ .and_then(|m| m.get("display_url"))+ .or_else(|| data.get("display_url"))+ .and_then(|v| v.as_str())+ {+ return Ok(InstagramMedia::Single {+ url: display_url.to_string(),+ is_video: false,+ });+ }++ Err(anyhow!("No media found in embed"))+ }+}++fn base64_url_encode(bytes: &[u8]) -> String {+ use base64::Engine;+ base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)+}++#[async_trait]+impl PlatformDownloader for InstagramDownloader {+ fn name(&self) -> &str {+ "instagram"+ }++ fn can_handle(&self, url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ if let Some(host) = parsed.host_str() {+ let host = host.to_lowercase();+ return host == "instagram.com"+ || host.ends_with(".instagram.com")+ || host == "ddinstagram.com"+ || host.ends_with(".ddinstagram.com");+ }+ }+ false+ }++ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {+ if Self::is_story_url(url) {+ return Err(anyhow!(+ "Instagram Stories are not supported. Only public posts, reels and carousels."+ ));+ }++ let post_id = if let Some(share_id) = Self::extract_share_id(url) {+ let resolved = self.resolve_share_link(&share_id).await?;+ Self::extract_post_id(&resolved).ok_or_else(|| anyhow!("Could not extract post ID"))?+ } else {+ Self::extract_post_id(url).ok_or_else(|| anyhow!("Could not extract post ID"))?+ };++ let filename_base = format!("instagram_{}", post_id);++ let embed_result = self.request_embed(&post_id).await;+ let media = match embed_result {+ Ok(data) => Self::extract_media_from_embed(&data),+ Err(_embed_err) => match self.request_gql(&post_id).await {+ Ok(data) => Self::extract_media_from_gql(&data),+ Err(_gql_err) => {+ return self.fallback_ytdlp(url, &post_id).await;+ }+ },+ };++ let media = match media {+ Ok(m) => m,+ Err(_) => {+ return self.fallback_ytdlp(url, &post_id).await;+ }+ };++ match media {+ InstagramMedia::Single { url, is_video } => {+ let (media_type, format) = if is_video {+ (MediaType::Video, "mp4")+ } else {+ (MediaType::Photo, "jpg")+ };++ Ok(MediaInfo {+ title: filename_base,+ author: String::new(),+ platform: "instagram".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: vec![VideoQuality {+ label: "original".to_string(),+ width: 0,+ height: 0,+ url,+ format: format.to_string(),+ }],+ media_type,+ file_size_bytes: None,+ })+ }+ InstagramMedia::Carousel { items } => {+ let qualities: Vec<VideoQuality> = items+ .iter()+ .enumerate()+ .map(|(i, item)| {+ let format = if item.is_video { "mp4" } else { "jpg" };+ VideoQuality {+ label: format!("media_{}", i + 1),+ width: 0,+ height: 0,+ url: item.url.clone(),+ format: format.to_string(),+ }+ })+ .collect();++ Ok(MediaInfo {+ title: filename_base,+ author: String::new(),+ platform: "instagram".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: qualities,+ media_type: MediaType::Carousel,+ file_size_bytes: None,+ })+ }+ }+ }++ async fn download(+ &self,+ info: &MediaInfo,+ opts: &DownloadOptions,+ progress: mpsc::Sender<ProgressUpdate>,+ ) -> anyhow::Result<DownloadResult> {+ let count = info.available_qualities.len();++ if count == 1 {+ let quality = info.available_qualities.first().unwrap();++ if quality.format == "ytdlp" {+ return Self::ytdlp_download_post(&quality.url, opts, progress).await;+ }++ let filename = format!(+ "{}.{}",+ sanitize_filename::sanitize(&info.title),+ quality.format+ );+ let output = opts.output_dir.join(&filename);++ let mut hdr_map = Self::instagram_headers();+ crate::core::http_client::inject_ua_header(&mut hdr_map, opts.user_agent.as_deref());+ let headers = Some(hdr_map);++ match download_direct_with_headers(+ &self.client,+ &quality.url,+ &output,+ progress.clone(),+ headers,+ Some(&opts.cancel_token),+ )+ .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::resolve_fallback_post_url(info, opts) {+ 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;+ let mut last_path = opts.output_dir.clone();++ for (i, quality) in info.available_qualities.iter().enumerate() {+ let filename = format!(+ "{}_{}.{}",+ sanitize_filename::sanitize(&info.title),+ i + 1,+ quality.format,+ );+ let output = opts.output_dir.join(&filename);+ let (tx, _rx) = mpsc::channel(8);++ let mut hdr_map = Self::instagram_headers();+ crate::core::http_client::inject_ua_header(&mut hdr_map, opts.user_agent.as_deref());+ let headers = Some(hdr_map);++ match download_direct_with_headers(+ &self.client,+ &quality.url,+ &output,+ tx,+ headers,+ Some(&opts.cancel_token),+ )+ .await+ {+ Ok(bytes) => {+ total_bytes += bytes;+ last_path = output;++ let percent = ((i + 1) as f64 / count as f64) * 100.0;+ let _ = progress.send(ProgressUpdate::percent(percent)).await;+ }+ Err(e) => {+ if Self::is_html_block_error(&e) {+ if let Some(post_url) = Self::resolve_fallback_post_url(info, opts) {+ 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 {+ file_path: last_path,+ file_size_bytes: total_bytes,+ duration_seconds: 0.0,+ torrent_id: None,+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::PathBuf;+ use tokio_util::sync::CancellationToken;++ fn make_opts(page_url: Option<&str>) -> DownloadOptions {+ DownloadOptions {+ quality: None,+ output_dir: PathBuf::from("."),+ filename_template: None,+ download_subtitles: false,+ include_auto_subtitles: false,+ download_mode: None,+ audio_format: None,+ format_id: None,+ referer: None,+ extra_headers: None,+ page_url: page_url.map(String::from),+ user_agent: None,+ cancel_token: CancellationToken::new(),+ concurrent_fragments: 1,+ ytdlp_path: None,+ torrent_listen_port: None,+ torrent_id_slot: None,+ custom_ytdlp_args: None,+ torrent_files: None,+ torrent_auto_trackers: false,+ torrent_upnp: false,+ }+ }++ fn make_info(title: &str) -> MediaInfo {+ MediaInfo {+ title: title.to_string(),+ author: String::new(),+ platform: "instagram".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: vec![],+ media_type: MediaType::Video,+ file_size_bytes: None,+ }+ }++ #[test]+ fn post_url_from_title_accepts_prefixed_title() {+ assert_eq!(+ InstagramDownloader::post_url_from_title("instagram_ABC123"),+ Some("https://www.instagram.com/p/ABC123/".to_string())+ );+ }++ #[test]+ fn post_url_from_title_rejects_yt_dlp_default_title() {+ assert_eq!(+ InstagramDownloader::post_url_from_title("Video by savadgee"),+ None+ );+ }++ #[test]+ fn post_url_from_title_rejects_empty_post_id() {+ assert_eq!(InstagramDownloader::post_url_from_title("instagram_"), None);+ }++ #[test]+ fn resolve_fallback_prefers_title_prefix() {+ let info = make_info("instagram_ABC123");+ let opts = make_opts(Some("https://www.instagram.com/p/XYZ999/"));+ assert_eq!(+ InstagramDownloader::resolve_fallback_post_url(&info, &opts),+ Some("https://www.instagram.com/p/ABC123/".to_string())+ );+ }++ #[test]+ fn resolve_fallback_uses_page_url_for_yt_dlp_titles() {+ let info = make_info("Video by savadgee");+ let opts = make_opts(Some("https://www.instagram.com/reel/XYZ999/"));+ assert_eq!(+ InstagramDownloader::resolve_fallback_post_url(&info, &opts),+ Some("https://www.instagram.com/reel/XYZ999/".to_string())+ );+ }++ #[test]+ fn resolve_fallback_uses_page_url_share_link() {+ let info = make_info("Video by savadgee");+ let opts = make_opts(Some("https://www.instagram.com/share/ABCxyz/"));+ assert_eq!(+ InstagramDownloader::resolve_fallback_post_url(&info, &opts),+ Some("https://www.instagram.com/share/ABCxyz/".to_string())+ );+ }++ #[test]+ fn resolve_fallback_returns_none_when_page_url_not_instagram() {+ let info = make_info("Video by savadgee");+ let opts = make_opts(Some("https://example.com/foo"));+ assert_eq!(+ InstagramDownloader::resolve_fallback_post_url(&info, &opts),+ None+ );+ }++ #[test]+ fn resolve_fallback_returns_none_when_no_sources_available() {+ let info = make_info("Video by savadgee");+ let opts = make_opts(None);+ assert_eq!(+ InstagramDownloader::resolve_fallback_post_url(&info, &opts),+ None+ );+ }++ #[test]+ fn is_html_block_error_matches_direct_downloader_message() {+ let err = anyhow!("Server returned HTML instead of media — URL may have expired");+ assert!(InstagramDownloader::is_html_block_error(&err));+ }++ #[test]+ fn is_html_block_error_rejects_unrelated_error() {+ let err = anyhow!("HTTP 404 downloading url");+ assert!(!InstagramDownloader::is_html_block_error(&err));+ }+}diff --git a/src-tauri/omniget-core/src/platforms/mod.rs b/src-tauri/omniget-core/src/platforms/mod.rsindex 422be9cc..e5926be6 100644--- a/src-tauri/omniget-core/src/platforms/mod.rs+++ b/src-tauri/omniget-core/src/platforms/mod.rs@@ -2,10 +2,13 @@ pub mod bluesky;pub mod direct_file;pub mod douyin;pub mod generic_ytdlp;-// pub mod magnet; // needs librqbit + trackers (Tauri-only for now)+pub mod instagram;+pub mod pinterest;pub mod p2p;pub mod p2p_words;+pub mod reddit;pub mod traits;+pub mod tiktok;pub mod twitch;pub mod vimeo;pub mod youtube;@@ -14,8 +17,11 @@ pub use bluesky::BlueskyDownloader;pub use direct_file::DirectFileDownloader;pub use douyin::DouyinDownloader;pub use generic_ytdlp::GenericYtdlpDownloader;-// pub use magnet::MagnetDownloader;+pub use instagram::InstagramDownloader;+pub use pinterest::PinterestDownloader;pub use p2p::P2pDownloader;+pub use reddit::RedditDownloader;+pub use tiktok::TikTokDownloader;pub use traits::PlatformDownloader;pub use twitch::TwitchClipsDownloader;pub use vimeo::VimeoDownloader;diff --git a/src-tauri/omniget-core/src/platforms/pinterest.rs b/src-tauri/omniget-core/src/platforms/pinterest.rsnew file mode 100644index 00000000..f5a9be4f--- /dev/null+++ b/src-tauri/omniget-core/src/platforms/pinterest.rs@@ -0,0 +1,326 @@+use crate::models::progress::ProgressUpdate;+use std::sync::LazyLock;++use anyhow::anyhow;+use async_trait::async_trait;+use regex::Regex;+use tokio::sync::mpsc;++use crate::core::direct_downloader;+use crate::core::redirect;+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};+use crate::platforms::traits::PlatformDownloader;++const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";++static PIN_NOT_FOUND_RE: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(r#""__typename"\s*:\s*"PinNotFound""#).expect("valid PIN_NOT_FOUND_RE")+});++static VIDEO_URL_RE: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(r#""url":"(https://v1\.pinimg\.com/videos/.*?)""#).expect("valid VIDEO_URL_RE")+});++static IMAGE_URL_RE: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(r#"src="(https://i\.pinimg\.com/.*?\.(jpg|gif))""#).expect("valid IMAGE_URL_RE")+});++pub struct PinterestDownloader {+ client: reqwest::Client,+}++impl Default for PinterestDownloader {+ fn default() -> Self {+ Self::new()+ }+}++impl PinterestDownloader {+ pub fn new() -> Self {+ let mut builder = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())+ .user_agent(USER_AGENT)+ .timeout(std::time::Duration::from_secs(120))+ .connect_timeout(std::time::Duration::from_secs(15));++ if let Some(jar) =+ crate::core::cookie_parser::load_extension_cookies_for_domain("pinterest.com")+ {+ builder = builder.cookie_provider(jar);+ }++ let client = builder.build().unwrap_or_default();+ Self { client }+ }++ fn extract_pin_id(url: &str) -> Option<String> {+ let parsed = url::Url::parse(url).ok()?;+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();++ if segments.first() == Some(&"pin") {+ let raw_id = segments.get(1)?;+ if raw_id.contains("--") {+ return raw_id.split("--").last().map(|s| s.to_string());+ }+ return Some(raw_id.to_string());+ }++ if segments.first() == Some(&"url_shortener") {+ return None;+ }++ segments.last().map(|s| {+ if s.contains("--") {+ s.split("--").last().unwrap_or(s).to_string()+ } else {+ s.to_string()+ }+ })+ }++ fn is_short_link(url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ if let Some(host) = parsed.host_str() {+ return host == "pin.it";+ }+ }+ false+ }++ async fn resolve_pin_url(&self, url: &str) -> anyhow::Result<String> {+ if Self::is_short_link(url) {+ let canonical = redirect::resolve_redirect(&self.client, url).await?;+ return Ok(canonical);+ }+ Ok(url.to_string())+ }++ async fn fetch_pin_html(&self, pin_id: &str) -> anyhow::Result<String> {+ let url = format!("https://www.pinterest.com/pin/{}/", pin_id);++ let response = self+ .client+ .get(&url)+ .header("Accept", "text/html")+ .header("Accept-Language", "en-US,en;q=0.9")+ .send()+ .await?;++ if !response.status().is_success() {+ return Err(anyhow!(+ "HTTP {} ao acessar pin {}",+ response.status(),+ pin_id+ ));+ }++ response.text().await.map_err(Into::into)+ }++ fn check_pin_not_found(html: &str) -> bool {+ PIN_NOT_FOUND_RE.is_match(html)+ }++ fn extract_video_url(html: &str) -> Option<String> {+ VIDEO_URL_RE+ .captures_iter(html)+ .filter_map(|cap| cap.get(1).map(|m| m.as_str().to_string()))+ .find(|url| url.ends_with(".mp4"))+ }++ fn extract_image_url(html: &str) -> Option<(String, bool)> {+ let mut best: Option<(String, bool)> = None;++ for cap in IMAGE_URL_RE.captures_iter(html) {+ if let Some(url_match) = cap.get(1) {+ let url = url_match.as_str().to_string();+ let is_gif = url.ends_with(".gif");+ if best.is_none() || url.contains("originals") || url.contains("1200x") {+ best = Some((url, is_gif));+ }+ }+ }++ best+ }+}++#[async_trait]+impl PlatformDownloader for PinterestDownloader {+ fn name(&self) -> &str {+ "pinterest"+ }++ fn can_handle(&self, url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ if let Some(host) = parsed.host_str() {+ let host = host.to_lowercase();+ return host == "pin.it"+ || host.contains("pinterest.com")+ || host.contains("pinterest.ca")+ || host.contains("pinterest.co.uk")+ || host.contains("pinterest.fr")+ || host.contains("pinterest.de")+ || host.contains("pinterest.es")+ || host.contains("pinterest.it")+ || host.contains("pinterest.pt")+ || host.contains("pinterest.jp")+ || host.contains("pinterest.kr")+ || host.contains("pinterest.com.br")+ || host.contains("pinterest.com.mx")+ || host.contains("pinterest.co.kr")+ || host.contains("pinterest.cl")+ || host.contains("pinterest.at")+ || host.contains("pinterest.ch")+ || host.contains("pinterest.com.au")+ || host.contains("pinterest.co.in")+ || host.contains("pinterest.nz")+ || host.contains("pinterest.ph")+ || host.contains("pinterest.ru")+ || host.contains("pinterest.se")+ || host.contains("pinterest.dk")+ || host.contains("pinterest.");+ }+ }+ false+ }++ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {+ match self.native_get_media_info(url).await {+ Ok(info) => Ok(info),+ Err(native_err) => {+ tracing::warn!(+ "[pinterest] native failed: {}, trying yt-dlp fallback",+ native_err+ );+ self.fallback_ytdlp(url).await.map_err(|_| native_err)+ }+ }+ }++ async fn download(+ &self,+ info: &MediaInfo,+ opts: &DownloadOptions,+ progress: mpsc::Sender<ProgressUpdate>,+ ) -> anyhow::Result<DownloadResult> {+ if let Some(quality) = info.available_qualities.first() {+ 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(),+ opts.referer+ .as_deref()+ .or(Some("https://www.pinterest.com/")),+ opts.cancel_token.clone(),+ None,+ opts.concurrent_fragments,+ false,+ &[],+ opts.audio_format.as_deref(),+ )+ .await;+ }+ }++ let quality = info+ .available_qualities+ .first()+ .ok_or_else(|| anyhow!("No media URL available"))?;++ let extension = &quality.format;+ let filename = format!("{}.{}", info.title, extension);+ let safe_filename = sanitize_filename::sanitize(&filename);+ let output_path = opts.output_dir.join(&safe_filename);++ let total_bytes = direct_downloader::download_direct(+ &self.client,+ &quality.url,+ &output_path,+ progress,+ Some(&opts.cancel_token),+ )+ .await?;++ Ok(DownloadResult {+ file_path: output_path,+ file_size_bytes: total_bytes,+ duration_seconds: 0.0,+ torrent_id: None,+ })+ }+}++impl PinterestDownloader {+ async fn fallback_ytdlp(&self, url: &str) -> anyhow::Result<MediaInfo> {+ let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;+ let json = crate::core::ytdlp::get_video_info(&ytdlp_path, url, &[]).await?;+ crate::platforms::generic_ytdlp::GenericYtdlpDownloader::parse_video_info(&json)+ }++ async fn native_get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {+ let canonical = self.resolve_pin_url(url).await?;++ let pin_id =+ Self::extract_pin_id(&canonical).ok_or_else(|| anyhow!("Could not extract pin ID"))?;++ let html = self.fetch_pin_html(&pin_id).await?;++ if Self::check_pin_not_found(&html) {+ return Err(anyhow!("Pin not found"));+ }++ if let Some(video_url) = Self::extract_video_url(&html) {+ return Ok(MediaInfo {+ title: format!("pinterest_{}", pin_id),+ author: String::new(),+ platform: "pinterest".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: vec![VideoQuality {+ label: "original".to_string(),+ width: 0,+ height: 0,+ url: video_url,+ format: "mp4".to_string(),+ }],+ media_type: MediaType::Video,+ file_size_bytes: None,+ });+ }++ if let Some((image_url, is_gif)) = Self::extract_image_url(&html) {+ let media_type = if is_gif {+ MediaType::Gif+ } else {+ MediaType::Photo+ };+ let format = if is_gif { "gif" } else { "jpg" };++ return Ok(MediaInfo {+ title: format!("pinterest_{}", pin_id),+ author: String::new(),+ platform: "pinterest".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: vec![VideoQuality {+ label: "original".to_string(),+ width: 0,+ height: 0,+ url: image_url,+ format: format.to_string(),+ }],+ media_type,+ file_size_bytes: None,+ });+ }++ Err(anyhow!("No media found in pin {}", pin_id))+ }+}diff --git a/src-tauri/omniget-core/src/platforms/reddit.rs b/src-tauri/omniget-core/src/platforms/reddit.rsnew file mode 100644index 00000000..2dc4518c--- /dev/null+++ b/src-tauri/omniget-core/src/platforms/reddit.rs@@ -0,0 +1,770 @@+use anyhow::anyhow;+use async_trait::async_trait;+use crate::models::progress::ProgressUpdate;+use tokio::sync::mpsc;++use crate::core::direct_downloader;+use crate::core::ffmpeg;+use crate::core::redirect;+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};+use crate::platforms::traits::PlatformDownloader;++const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36";++pub struct RedditDownloader {+ client: reqwest::Client,+}++enum RedditMedia {+ Video {+ video_url: String,+ duration: Option<f64>,+ },+ Gif {+ url: String,+ },+ Image {+ url: String,+ },+ Gallery {+ items: Vec<GalleryItem>,+ },+}++struct GalleryItem {+ url: String,+ ext: String,+}++impl Default for RedditDownloader {+ fn default() -> Self {+ Self::new()+ }+}++impl RedditDownloader {+ pub fn new() -> Self {+ let mut builder = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())+ .user_agent(USER_AGENT)+ .timeout(std::time::Duration::from_secs(120))+ .connect_timeout(std::time::Duration::from_secs(15));++ if let Some(jar) =+ crate::core::cookie_parser::load_extension_cookies_for_domain("reddit.com")+ {+ builder = builder.cookie_provider(jar);+ }++ let client = builder.build().unwrap_or_default();+ Self { client }+ }++ fn extract_post_id(url: &str) -> Option<String> {+ let parsed = url::Url::parse(url).ok()?;+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();++ if segments.len() >= 4 && segments[0] == "r" && segments[2] == "comments" {+ return Some(segments[3].to_string());+ }++ if segments.first() == Some(&"comments") {+ return segments.get(1).map(|s| s.to_string());+ }++ if segments.first() == Some(&"video") {+ return segments.get(1).map(|s| s.to_string());+ }++ None+ }++ fn extract_subreddit(url: &str) -> Option<String> {+ let parsed = url::Url::parse(url).ok()?;+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();+ if segments.first() == Some(&"r") {+ return segments.get(1).map(|s| s.to_string());+ }+ None+ }++ fn is_short_link(url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ if let Some(host) = parsed.host_str() {+ let host = host.to_lowercase();+ return host == "v.redd.it" || host == "redd.it";+ }+ }+ false+ }++ fn is_share_link(url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();+ return segments.len() >= 4 && segments[0] == "r" && segments[2] == "s";+ }+ false+ }++ async fn resolve_to_canonical(&self, url: &str) -> anyhow::Result<String> {+ if Self::is_short_link(url) {+ return redirect::resolve_redirect(&self.client, url).await;+ }++ if Self::is_share_link(url) {+ return redirect::resolve_redirect(&self.client, url).await;+ }++ Ok(url.to_string())+ }++ async fn fetch_post_data(&self, post_id: &str) -> anyhow::Result<serde_json::Value> {+ let url = format!("https://www.reddit.com/comments/{}.json", post_id);++ let response = self+ .client+ .get(&url)+ .header("Accept", "application/json")+ .send()+ .await?;++ if !response.status().is_success() {+ return Err(anyhow!("Reddit retornou HTTP {}", response.status()));+ }++ let json: serde_json::Value = response.json().await?;++ if !json.is_array() {+ return Err(anyhow!("Post not found"));+ }++ json.as_array()+ .and_then(|arr| arr.first())+ .and_then(|listing| listing.pointer("/data/children/0/data"))+ .cloned()+ .ok_or_else(|| anyhow!("Post not found"))+ }++ fn construct_audio_url(fallback_url: &str) -> Vec<String> {+ let video = fallback_url.split('?').next().unwrap_or(fallback_url);+ let mut candidates = Vec::new();++ if video.contains(".mp4") {+ if let Some(base) = video.split('_').next() {+ candidates.push(format!("{}_audio.mp4", base));+ candidates.push(format!("{}_AUDIO_128.mp4", base));+ }+ }++ if let Some(dash_pos) = video.find("DASH") {+ candidates.push(format!("{}audio", &video[..dash_pos]));+ }++ candidates+ }++ async fn find_audio_url(&self, fallback_url: &str) -> Option<String> {+ let candidates = Self::construct_audio_url(fallback_url);++ for candidate in candidates {+ let resp = tokio::time::timeout(+ std::time::Duration::from_secs(5),+ self.client.head(&candidate).send(),+ )+ .await;++ if let Ok(Ok(r)) = resp {+ if r.status().is_success() {+ return Some(candidate);+ }+ }+ }++ None+ }++ fn get_resolution_variants(video_url: &str) -> Vec<String> {+ let resolutions = [+ "DASH_720.mp4",+ "DASH_480.mp4",+ "DASH_360.mp4",+ "DASH_240.mp4",+ ];+ let mut variants = vec![video_url.to_string()];+ for res in &resolutions {+ if !video_url.contains(res) {+ if let Some(base) = video_url.rfind("DASH_") {+ let mut variant = video_url[..base].to_string();+ variant.push_str(res);+ variants.push(variant);+ }+ }+ }+ variants+ }++ async fn download_video_with_fallback(+ &self,+ video_url: &str,+ output: &std::path::Path,+ progress_tx: mpsc::Sender<ProgressUpdate>,+ cancel: Option<&tokio_util::sync::CancellationToken>,+ ) -> anyhow::Result<u64> {+ let variants = Self::get_resolution_variants(video_url);+ let mut last_err = anyhow!("No resolution available");++ for variant in &variants {+ if let Some(token) = cancel {+ if token.is_cancelled() {+ return Err(anyhow!("Download cancelled"));+ }+ }+ match direct_downloader::download_direct(+ &self.client,+ variant,+ output,+ progress_tx.clone(),+ cancel,+ )+ .await+ {+ Ok(bytes) => return Ok(bytes),+ Err(e) => {+ last_err = e;+ let _ = tokio::fs::remove_file(output).await;+ }+ }+ }++ Err(last_err)+ }++ fn parse_media(data: &serde_json::Value) -> Option<RedditMedia> {+ let is_gallery = data+ .get("is_gallery")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ if is_gallery {+ if let Some(gallery) = Self::parse_gallery(data) {+ return Some(gallery);+ }+ }++ if let Some(url) = data.get("url").and_then(|v| v.as_str()) {+ if url.ends_with(".gif") {+ return Some(RedditMedia::Gif {+ url: url.to_string(),+ });+ }+ }++ if let Some(reddit_video) = data.pointer("/secure_media/reddit_video") {+ let fallback = reddit_video.get("fallback_url").and_then(|v| v.as_str())?;+ let duration = reddit_video.get("duration").and_then(|v| v.as_f64());+ let video_url = fallback.split('?').next().unwrap_or(fallback).to_string();++ return Some(RedditMedia::Video {+ video_url,+ duration,+ });+ }++ if let Some(url) = data.get("url").and_then(|v| v.as_str()) {+ let is_media = data+ .get("is_reddit_media_domain")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ if is_media+ || url.contains("i.redd.it")+ || url.ends_with(".jpg")+ || url.ends_with(".png")+ || url.ends_with(".jpeg")+ {+ return Some(RedditMedia::Image {+ url: url.to_string(),+ });+ }+ }++ None+ }++ fn parse_gallery(data: &serde_json::Value) -> Option<RedditMedia> {+ let gallery_data = data.get("gallery_data")?.get("items")?.as_array()?;+ let media_metadata = data.get("media_metadata")?;++ let mut items = Vec::new();++ for item in gallery_data {+ let media_id = item.get("media_id").and_then(|v| v.as_str())?;+ let meta = media_metadata.get(media_id)?;++ let mime = meta+ .get("m")+ .and_then(|v| v.as_str())+ .unwrap_or("image/jpeg");+ let ext = match mime {+ "image/png" => "png",+ "image/gif" => "gif",+ "image/webp" => "webp",+ _ => "jpg",+ };++ let url = if let Some(source) = meta.get("s") {+ source+ .get("u")+ .or_else(|| source.get("gif"))+ .and_then(|v| v.as_str())+ .map(|u| u.replace("&", "&"))+ } else {+ None+ };++ if let Some(url) = url {+ items.push(GalleryItem {+ url,+ ext: ext.to_string(),+ });+ }+ }++ if items.is_empty() {+ return None;+ }++ Some(RedditMedia::Gallery { items })+ }+}++#[async_trait]+impl PlatformDownloader for RedditDownloader {+ fn name(&self) -> &str {+ "reddit"+ }++ fn can_handle(&self, url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ if let Some(host) = parsed.host_str() {+ let host = host.to_lowercase();+ return host == "reddit.com"+ || host.ends_with(".reddit.com")+ || host == "v.redd.it"+ || host == "redd.it";+ }+ }+ false+ }++ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {+ match self.native_get_media_info(url).await {+ Ok(info) => Ok(info),+ Err(native_err) => {+ tracing::warn!(+ "[reddit] native failed: {}, trying yt-dlp fallback",+ native_err+ );+ self.fallback_ytdlp(url).await.map_err(|_| native_err)+ }+ }+ }++ async fn download(+ &self,+ info: &MediaInfo,+ opts: &DownloadOptions,+ progress: mpsc::Sender<ProgressUpdate>,+ ) -> anyhow::Result<DownloadResult> {+ if let Some(quality) = info.available_qualities.first() {+ 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(),+ opts.referer.as_deref().or(Some("https://www.reddit.com/")),+ opts.cancel_token.clone(),+ None,+ opts.concurrent_fragments,+ false,+ &[],+ opts.audio_format.as_deref(),+ )+ .await;+ }+ }++ self.native_download(info, opts, progress).await+ }+}++impl RedditDownloader {+ async fn fallback_ytdlp(&self, url: &str) -> anyhow::Result<MediaInfo> {+ let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;+ let json = crate::core::ytdlp::get_video_info(&ytdlp_path, url, &[]).await?;+ crate::platforms::generic_ytdlp::GenericYtdlpDownloader::parse_video_info(&json)+ }++ async fn native_get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {+ let canonical = self.resolve_to_canonical(url).await?;++ let post_id = Self::extract_post_id(&canonical)+ .ok_or_else(|| anyhow!("Could not extract post ID"))?;++ let subreddit = Self::extract_subreddit(&canonical).unwrap_or_default();++ let data = self.fetch_post_data(&post_id).await?;++ let media = Self::parse_media(&data).ok_or_else(|| anyhow!("No media found in post"))?;++ let source_id = if subreddit.is_empty() {+ post_id.clone()+ } else {+ format!("{}_{}", subreddit.to_lowercase(), post_id)+ };++ let title = format!("reddit_{}", source_id);++ match media {+ RedditMedia::Video {+ video_url,+ duration,+ } => {+ let audio = self.find_audio_url(&video_url).await;+ let mut qualities = vec![VideoQuality {+ label: "video".to_string(),+ width: 0,+ height: 0,+ url: video_url,+ format: "mp4".to_string(),+ }];++ if let Some(audio_url) = audio {+ qualities.push(VideoQuality {+ label: "audio".to_string(),+ width: 0,+ height: 0,+ url: audio_url,+ format: "mp4_audio".to_string(),+ });+ }++ Ok(MediaInfo {+ title,+ author: subreddit,+ platform: "reddit".to_string(),+ duration_seconds: duration,+ thumbnail_url: None,+ available_qualities: qualities,+ media_type: MediaType::Video,+ file_size_bytes: None,+ })+ }+ RedditMedia::Gif { url: gif_url } => Ok(MediaInfo {+ title,+ author: subreddit,+ platform: "reddit".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: vec![VideoQuality {+ label: "original".to_string(),+ width: 0,+ height: 0,+ url: gif_url,+ format: "gif".to_string(),+ }],+ media_type: MediaType::Gif,+ file_size_bytes: None,+ }),+ RedditMedia::Image { url: image_url } => {+ let ext = if image_url.ends_with(".png") {+ "png"+ } else {+ "jpg"+ };+ Ok(MediaInfo {+ title,+ author: subreddit,+ platform: "reddit".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: vec![VideoQuality {+ label: "original".to_string(),+ width: 0,+ height: 0,+ url: image_url,+ format: ext.to_string(),+ }],+ media_type: MediaType::Photo,+ file_size_bytes: None,+ })+ }+ RedditMedia::Gallery { items } => {+ let qualities: Vec<VideoQuality> = items+ .into_iter()+ .enumerate()+ .map(|(i, item)| VideoQuality {+ label: format!("media_{}", i + 1),+ width: 0,+ height: 0,+ url: item.url,+ format: item.ext,+ })+ .collect();++ Ok(MediaInfo {+ title,+ author: subreddit,+ platform: "reddit".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: qualities,+ media_type: MediaType::Carousel,+ file_size_bytes: None,+ })+ }+ }+ }++ async fn native_download(+ &self,+ info: &MediaInfo,+ opts: &DownloadOptions,+ progress: mpsc::Sender<ProgressUpdate>,+ ) -> anyhow::Result<DownloadResult> {+ match info.media_type {+ MediaType::Video => {+ let video_quality = info+ .available_qualities+ .iter()+ .find(|q| q.label == "video")+ .ok_or_else(|| anyhow!("No video URL"))?;++ let audio_quality = info.available_qualities.iter().find(|q| q.label == "audio");++ let has_audio = audio_quality.is_some();+ let ffmpeg_available = ffmpeg::is_ffmpeg_available().await;++ if has_audio && !ffmpeg_available {+ tracing::warn!("[reddit] Video has separate audio but FFmpeg is not installed — downloading video without audio");+ }++ if has_audio {+ let video_tmp = opts.output_dir.join(format!(+ "{}_video_tmp.mp4",+ sanitize_filename::sanitize(&info.title)+ ));+ let audio_tmp = opts.output_dir.join(format!(+ "{}_audio_tmp.mp4",+ sanitize_filename::sanitize(&info.title)+ ));+ let output = opts+ .output_dir+ .join(format!("{}.mp4", sanitize_filename::sanitize(&info.title)));++ let _ = progress.send(ProgressUpdate::percent(0.0)).await;++ let (vtx, mut vrx) = mpsc::channel::<ProgressUpdate>(8);+ let progress_video = progress.clone();+ tokio::spawn(async move {+ while let Some(p) = vrx.recv().await {+ let scaled = p.percent * 0.6;+ let _ = progress_video+ .send(ProgressUpdate::rich(scaled, None, None, p.speed_bps, None))+ .await;+ }+ });++ let video_bytes = self+ .download_video_with_fallback(+ &video_quality.url,+ &video_tmp,+ vtx,+ Some(&opts.cancel_token),+ )+ .await?;++ let _ = progress.send(ProgressUpdate::percent(60.0)).await;++ let audio_url = &audio_quality.unwrap().url;+ let (atx, mut arx) = mpsc::channel::<ProgressUpdate>(8);+ let progress_audio = progress.clone();+ tokio::spawn(async move {+ while let Some(p) = arx.recv().await {+ let scaled = 60.0 + p.percent * 0.25;+ let _ = progress_audio+ .send(ProgressUpdate::rich(scaled, None, None, p.speed_bps, None))+ .await;+ }+ });++ let audio_ok = direct_downloader::download_direct(+ &self.client,+ audio_url,+ &audio_tmp,+ atx,+ Some(&opts.cancel_token),+ )+ .await+ .is_ok();++ let _ = progress.send(ProgressUpdate::percent(85.0)).await;++ if audio_ok && ffmpeg_available {+ ffmpeg::mux_video_audio(&video_tmp, &audio_tmp, &output).await?;+ let _ = tokio::fs::remove_file(&video_tmp).await;+ let _ = tokio::fs::remove_file(&audio_tmp).await;+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;++ let file_size = tokio::fs::metadata(&output).await?.len();+ Ok(DownloadResult {+ file_path: output,+ file_size_bytes: file_size,+ duration_seconds: info.duration_seconds.unwrap_or(0.0),+ torrent_id: None,+ })+ } else {+ let video_final = opts.output_dir.join(format!(+ "{}{}.mp4",+ sanitize_filename::sanitize(&info.title),+ if !audio_ok { "" } else { "_noaudio" }+ ));+ let _ = tokio::fs::rename(&video_tmp, &video_final).await;++ if audio_ok {+ let audio_final = opts.output_dir.join(format!(+ "{}_audio.mp4",+ sanitize_filename::sanitize(&info.title)+ ));+ let _ = tokio::fs::rename(&audio_tmp, &audio_final).await;+ } else {+ let _ = tokio::fs::remove_file(&audio_tmp).await;+ }++ let _ = progress.send(ProgressUpdate::percent(100.0)).await;++ Ok(DownloadResult {+ file_path: video_final,+ file_size_bytes: video_bytes,+ duration_seconds: info.duration_seconds.unwrap_or(0.0),+ torrent_id: None,+ })+ }+ } else {+ let output = opts+ .output_dir+ .join(format!("{}.mp4", sanitize_filename::sanitize(&info.title)));+ let bytes = self+ .download_video_with_fallback(+ &video_quality.url,+ &output,+ progress,+ Some(&opts.cancel_token),+ )+ .await?;++ Ok(DownloadResult {+ file_path: output,+ file_size_bytes: bytes,+ duration_seconds: info.duration_seconds.unwrap_or(0.0),+ torrent_id: None,+ })+ }+ }+ MediaType::Gif => {+ let url = &info+ .available_qualities+ .first()+ .ok_or_else(|| anyhow!("Nenhum URL GIF"))?+ .url;+ let output = opts+ .output_dir+ .join(format!("{}.gif", sanitize_filename::sanitize(&info.title)));+ let bytes = direct_downloader::download_direct(+ &self.client,+ url,+ &output,+ progress,+ Some(&opts.cancel_token),+ )+ .await?;++ Ok(DownloadResult {+ file_path: output,+ file_size_bytes: bytes,+ duration_seconds: 0.0,+ torrent_id: None,+ })+ }+ MediaType::Photo => {+ let quality = info+ .available_qualities+ .first()+ .ok_or_else(|| anyhow!("Nenhum URL de imagem"))?;+ let ext = &quality.format;+ let output = opts.output_dir.join(format!(+ "{}.{}",+ sanitize_filename::sanitize(&info.title),+ ext+ ));+ let bytes = direct_downloader::download_direct(+ &self.client,+ &quality.url,+ &output,+ progress,+ Some(&opts.cancel_token),+ )+ .await?;++ Ok(DownloadResult {+ file_path: output,+ file_size_bytes: bytes,+ duration_seconds: 0.0,+ torrent_id: None,+ })+ }+ MediaType::Carousel => {+ let count = info.available_qualities.len();+ let mut total_bytes = 0u64;+ let mut last_path = opts.output_dir.clone();++ for (i, quality) in info.available_qualities.iter().enumerate() {+ let filename = format!(+ "{}_{}.{}",+ sanitize_filename::sanitize(&info.title),+ i + 1,+ quality.format,+ );+ let output = opts.output_dir.join(&filename);+ let (tx, _rx) = mpsc::channel(8);++ let bytes = direct_downloader::download_direct(+ &self.client,+ &quality.url,+ &output,+ tx,+ Some(&opts.cancel_token),+ )+ .await?;++ total_bytes += bytes;+ last_path = output;++ let percent = ((i + 1) as f64 / count as f64) * 100.0;+ let _ = progress.send(ProgressUpdate::percent(percent)).await;+ }++ Ok(DownloadResult {+ file_path: last_path,+ file_size_bytes: total_bytes,+ duration_seconds: 0.0,+ torrent_id: None,+ })+ }+ _ => Err(anyhow!("Unsupported media type")),+ }+ }+}diff --git a/src-tauri/omniget-core/src/platforms/tiktok.rs b/src-tauri/omniget-core/src/platforms/tiktok.rsnew file mode 100644index 00000000..81d7092d--- /dev/null+++ b/src-tauri/omniget-core/src/platforms/tiktok.rs@@ -0,0 +1,672 @@+use crate::models::progress::ProgressUpdate;+use std::sync::Arc;++use anyhow::anyhow;+use async_trait::async_trait;+use reqwest::header::{HeaderMap, HeaderValue, COOKIE, REFERER};+use tokio::sync::mpsc;++use crate::core::direct_downloader;+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};+use crate::platforms::traits::PlatformDownloader;++const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";+const SHORT_LINK_UA: &str =+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)";++pub struct TikTokDownloader {+ client: reqwest::Client,+ captured_cookies: Arc<tokio::sync::Mutex<Option<String>>>,+}++impl Default for TikTokDownloader {+ fn default() -> Self {+ Self::new()+ }+}++impl TikTokDownloader {+ pub fn new() -> Self {+ let mut builder = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())+ .user_agent(USER_AGENT)+ .timeout(std::time::Duration::from_secs(30));++ if let Some(jar) =+ crate::core::cookie_parser::load_extension_cookies_for_domain("tiktok.com")+ {+ builder = builder.cookie_provider(jar);+ } else {+ builder = builder.cookie_store(true);+ }++ let client = builder.build().unwrap_or_default();+ Self {+ client,+ captured_cookies: Arc::new(tokio::sync::Mutex::new(None)),+ }+ }++ fn tiktok_headers() -> HeaderMap {+ let mut headers = HeaderMap::new();+ headers.insert(REFERER, HeaderValue::from_static("https://www.tiktok.com/"));+ headers+ }++ fn download_headers(&self, cookies: &Option<String>) -> HeaderMap {+ let mut headers = Self::tiktok_headers();+ if let Some(ref cookie_str) = cookies {+ if let Ok(val) = HeaderValue::from_str(cookie_str) {+ headers.insert(COOKIE, val);+ }+ }+ headers+ }++ fn extract_post_id(url: &str) -> Option<String> {+ let parsed = url::Url::parse(url).ok()?;+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();++ if segments.len() >= 3+ && segments[0].starts_with('@')+ && (segments[1] == "video" || segments[1] == "photo")+ {+ let id = segments[2];+ if id.chars().all(|c| c.is_ascii_digit()) {+ return Some(id.to_string());+ }+ }++ None+ }++ async fn resolve_short_link(&self, url: &str) -> anyhow::Result<String> {+ let redirect_client =+ crate::core::http_client::apply_global_proxy(reqwest::Client::builder())+ .user_agent(SHORT_LINK_UA)+ .redirect(reqwest::redirect::Policy::none())+ .build()+ .unwrap_or_default();++ let response = redirect_client.get(url).send().await?;++ if let Some(location) = response+ .headers()+ .get("location")+ .and_then(|v| v.to_str().ok())+ {+ let clean = location.split('?').next().unwrap_or(location).to_string();+ return Ok(clean);+ }++ let html = response.text().await?;++ if html.starts_with("<a href=\"https://") {+ if let Some(url_part) = html.split("<a href=\"").nth(1) {+ let full_url = url_part.split('"').next().unwrap_or(url_part);+ let clean = full_url.split('?').next().unwrap_or(full_url).to_string();+ return Ok(clean);+ }+ }++ Err(anyhow!("Could not resolve short link"))+ }++ fn is_captcha_page(html: &str) -> bool {+ html.contains("verify-bar-close")+ || html.contains("captcha_verify")+ || html.contains("tiktok-verify-page")+ || html.contains("verify/page")+ || (html.contains("Verify to continue")+ && !html.contains("__UNIVERSAL_DATA_FOR_REHYDRATION__"))+ }++ fn is_valid_play_addr(url: &str) -> bool {+ if url.is_empty() {+ return false;+ }+ if !url.starts_with("http://") && !url.starts_with("https://") {+ return false;+ }+ if url.contains("verify") || url.contains("captcha") {+ return false;+ }+ true+ }++ async fn fetch_detail(&self, post_id: &str) -> anyhow::Result<serde_json::Value> {+ let url = format!("https://www.tiktok.com/@i/video/{}", post_id);++ let response = self.client.get(&url).send().await?;++ let status = response.status();++ if !status.is_success() && status.as_u16() != 302 {+ return Err(anyhow!("TikTok retornou HTTP {}", status));+ }++ let mut cookie_parts = Vec::new();+ for cookie in response.cookies() {+ cookie_parts.push(format!("{}={}", cookie.name(), cookie.value()));+ }+ if !cookie_parts.is_empty() {+ let cookie_str = cookie_parts.join("; ");+ *self.captured_cookies.lock().await = Some(cookie_str);+ }++ let html = response.text().await?;++ if Self::is_captcha_page(&html) {+ return Err(anyhow!(+ "TikTok is blocking requests. Try again in a few minutes."+ ));+ }++ let json_str = html+ .split("<script id=\"__UNIVERSAL_DATA_FOR_REHYDRATION__\" type=\"application/json\">")+ .nth(1)+ .and_then(|s| s.split("</script>").next())+ .ok_or_else(|| anyhow!("TikTok is blocking requests. Try again in a few minutes."))?;++ let data: serde_json::Value = serde_json::from_str(json_str)+ .map_err(|_| anyhow!("Erro ao processar resposta do TikTok"))?;++ let video_detail = data+ .get("__DEFAULT_SCOPE__")+ .and_then(|s| s.get("webapp.video-detail"))+ .ok_or_else(|| anyhow!("Video data not found in TikTok response"))?;++ if let Some(status_msg) = video_detail+ .get("statusMsg")+ .and_then(|v| v.as_str())+ .filter(|s| !s.is_empty())+ {+ return Err(anyhow!("Post not available: {}", status_msg));+ }++ if let Some(status_code) = video_detail.get("statusCode").and_then(|v| v.as_u64()) {+ if status_code != 0 {+ return Err(anyhow!("Post not available (status {})", status_code));+ }+ }++ let detail = video_detail+ .pointer("/itemInfo/itemStruct")+ .ok_or_else(|| anyhow!("Video data not found in TikTok response"))?+ .clone();++ if detail+ .get("isContentClassified")+ .and_then(|v| v.as_bool())+ .unwrap_or(false)+ {+ return Err(anyhow!("Age-restricted content"));+ }++ if detail.get("author").is_none() {+ return Err(anyhow!("Post not available"));+ }++ Ok(detail)+ }++ fn extract_author(detail: &serde_json::Value) -> String {+ detail+ .pointer("/author/uniqueId")+ .or_else(|| detail.pointer("/author/unique_id"))+ .and_then(|v| v.as_str())+ .unwrap_or("unknown")+ .to_string()+ }++ fn extract_video_url(detail: &serde_json::Value) -> Option<String> {+ if let Some(play_addr) = detail.pointer("/video/playAddr") {+ if let Some(url) = play_addr.as_str() {+ if Self::is_valid_play_addr(url) {+ return Some(url.to_string());+ }+ }+ }++ if let Some(play_addr) = detail.pointer("/video/play_addr/url_list") {+ if let Some(urls) = play_addr.as_array() {+ for u in urls {+ if let Some(url) = u.as_str() {+ if Self::is_valid_play_addr(url) {+ return Some(url.to_string());+ }+ }+ }+ }+ }++ if let Some(download_addr) = detail.pointer("/video/downloadAddr") {+ if let Some(url) = download_addr.as_str() {+ if Self::is_valid_play_addr(url) {+ return Some(url.to_string());+ }+ }+ }++ if let Some(bitrate_info) = detail+ .pointer("/video/bitrateInfo")+ .and_then(|v| v.as_array())+ {+ for bitrate in bitrate_info {+ if let Some(url_list) = bitrate+ .pointer("/PlayAddr/UrlList")+ .and_then(|v| v.as_array())+ {+ for u in url_list {+ if let Some(url) = u.as_str() {+ if Self::is_valid_play_addr(url) {+ return Some(url.to_string());+ }+ }+ }+ }+ }+ }++ None+ }++ fn extract_image_urls(detail: &serde_json::Value) -> Option<Vec<String>> {+ let images = detail+ .pointer("/imagePost/images")+ .and_then(|v| v.as_array())?;++ let urls: Vec<String> = images+ .iter()+ .filter_map(|img| {+ let url_list = img.pointer("/imageURL/urlList")?.as_array()?;+ url_list+ .iter()+ .filter_map(|u| u.as_str())+ .find(|u| u.contains(".jpeg"))+ .map(|u| u.to_string())+ })+ .collect();++ if urls.is_empty() {+ return None;+ }++ Some(urls)+ }++ async fn fallback_ytdlp(&self, url: &str) -> anyhow::Result<MediaInfo> {+ let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;+ let extra_flags = vec![+ "--referer".to_string(),+ "https://www.tiktok.com/".to_string(),+ ];+ let json = crate::core::ytdlp::get_video_info(&ytdlp_path, url, &extra_flags).await?;+ let mut info =+ crate::platforms::generic_ytdlp::GenericYtdlpDownloader::parse_video_info(&json)?;+ for q in &mut info.available_qualities {+ q.url = url.to_string();+ q.format = "ytdlp".to_string();+ }+ Ok(info)+ }++ async fn get_media_info_via_ytdlp(+ &self,+ url: &str,+ post_id: &str,+ ) -> anyhow::Result<MediaInfo> {+ let ytdlp_path = crate::core::ytdlp::find_ytdlp_cached()+ .await+ .ok_or_else(|| anyhow!("yt-dlp not found — install it in Settings"))?;++ let extra_flags = vec![+ "--referer".to_string(),+ "https://www.tiktok.com/".to_string(),+ ];++ let json = crate::core::ytdlp::get_video_info(&ytdlp_path, url, &extra_flags).await?;++ let title = json+ .get("title")+ .and_then(|v| v.as_str())+ .map(|s| format!("tiktok_{}", sanitize_filename::sanitize(s)))+ .unwrap_or_else(|| format!("tiktok_{}", post_id));++ let author = json+ .get("uploader")+ .or_else(|| json.get("creator"))+ .and_then(|v| v.as_str())+ .unwrap_or("unknown")+ .to_string();++ let duration = json.get("duration").and_then(|v| v.as_f64());++ let thumbnail = json+ .get("thumbnail")+ .and_then(|v| v.as_str())+ .map(String::from);++ Ok(MediaInfo {+ title,+ author,+ platform: "tiktok".to_string(),+ duration_seconds: duration,+ thumbnail_url: thumbnail,+ available_qualities: vec![VideoQuality {+ label: "original".to_string(),+ width: 0,+ height: 0,+ url: url.to_string(),+ format: "ytdlp".to_string(),+ }],+ media_type: MediaType::Video,+ file_size_bytes: None,+ })+ }++ fn extract_music_url(detail: &serde_json::Value) -> Option<String> {+ detail+ .pointer("/music/playUrl")+ .and_then(|v| v.as_str())+ .filter(|s| !s.is_empty())+ .map(|s| s.to_string())+ }++ fn extract_duration(detail: &serde_json::Value) -> Option<f64> {+ detail.pointer("/video/duration").and_then(|v| v.as_f64())+ }+}++#[async_trait]+impl PlatformDownloader for TikTokDownloader {+ fn name(&self) -> &str {+ "tiktok"+ }++ fn can_handle(&self, url: &str) -> bool {+ if let Ok(parsed) = url::Url::parse(url) {+ if let Some(host) = parsed.host_str() {+ let host = host.to_lowercase();+ return host == "tiktok.com" || host.ends_with(".tiktok.com");+ }+ }+ false+ }++ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {+ let original_url = url.to_string();++ let post_id = match Self::extract_post_id(url) {+ Some(id) => id,+ None => {+ let canonical = self+ .resolve_short_link(url)+ .await+ .unwrap_or_else(|_| url.to_string());+ Self::extract_post_id(&canonical).unwrap_or_else(|| "unknown".to_string())+ }+ };++ let detail = match self.fetch_detail(&post_id).await {+ Ok(d) => d,+ Err(first_err) => {+ tracing::warn!("[tiktok] native failed: {}, trying yt-dlp", first_err);+ return self+ .get_media_info_via_ytdlp(&original_url, &post_id)+ .await+ .or_else(|_| Err(first_err));+ }+ };++ let author = Self::extract_author(&detail);+ let filename_base = format!(+ "tiktok_{}_{}",+ sanitize_filename::sanitize(&author),+ post_id+ );++ if let Some(image_urls) = Self::extract_image_urls(&detail) {+ let media_type = if image_urls.len() == 1 {+ MediaType::Photo+ } else {+ MediaType::Carousel+ };++ let qualities: Vec<VideoQuality> = image_urls+ .iter()+ .enumerate()+ .map(|(i, u)| VideoQuality {+ label: format!("photo_{}", i + 1),+ width: 0,+ height: 0,+ url: u.clone(),+ format: "jpg".to_string(),+ })+ .collect();++ return Ok(MediaInfo {+ title: filename_base,+ author,+ platform: "tiktok".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: qualities,+ media_type,+ file_size_bytes: None,+ });+ }++ if let Some(video_url) = Self::extract_video_url(&detail) {+ return Ok(MediaInfo {+ title: filename_base,+ author,+ platform: "tiktok".to_string(),+ duration_seconds: Self::extract_duration(&detail),+ thumbnail_url: None,+ available_qualities: vec![VideoQuality {+ label: "best".to_string(),+ width: 0,+ height: 0,+ url: video_url,+ format: "tiktok_direct".to_string(),+ }],+ media_type: MediaType::Video,+ file_size_bytes: None,+ });+ }++ if let Some(music_url) = Self::extract_music_url(&detail) {+ return Ok(MediaInfo {+ title: filename_base,+ author,+ platform: "tiktok".to_string(),+ duration_seconds: None,+ thumbnail_url: None,+ available_qualities: vec![VideoQuality {+ label: "audio".to_string(),+ width: 0,+ height: 0,+ url: music_url,+ format: "mp3".to_string(),+ }],+ media_type: MediaType::Audio,+ file_size_bytes: None,+ });+ }++ tracing::warn!("[tiktok] no media extracted natively, trying yt-dlp fallback");+ self.fallback_ytdlp(&original_url).await+ }++ async fn download(+ &self,+ info: &MediaInfo,+ opts: &DownloadOptions,+ progress: mpsc::Sender<ProgressUpdate>,+ ) -> anyhow::Result<DownloadResult> {+ if let Some(quality) = info.available_qualities.first() {+ 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(),+ opts.referer.as_deref().or(Some("https://www.tiktok.com/")),+ opts.cancel_token.clone(),+ None,+ opts.concurrent_fragments,+ false,+ &[],+ opts.audio_format.as_deref(),+ )+ .await;+ }+ }++ let cookies = self.captured_cookies.lock().await.clone();+ let mut headers = self.download_headers(&cookies);+ crate::core::http_client::inject_ua_header(&mut headers, opts.user_agent.as_deref());++ match info.media_type {+ MediaType::Video => {+ let quality = info+ .available_qualities+ .first()+ .ok_or_else(|| anyhow!("No video URL available"))?;++ if quality.format == "tiktok_direct" {+ let filename = format!("{}.mp4", sanitize_filename::sanitize(&info.title));+ let output = opts.output_dir.join(&filename);++ let result = direct_downloader::download_direct_with_headers(+ &self.client,+ &quality.url,+ &output,+ progress.clone(),+ Some(headers),+ Some(&opts.cancel_token),+ )+ .await;++ match result {+ Ok(bytes) => {+ return Ok(DownloadResult {+ file_path: output,+ file_size_bytes: bytes,+ duration_seconds: info.duration_seconds.unwrap_or(0.0),+ torrent_id: None,+ });+ }+ Err(e) => {+ tracing::warn!(+ "[tiktok] direct download failed: {}, falling back to yt-dlp",+ e+ );+ let _ = tokio::fs::remove_file(&output).await;+ }+ }+ }++ let ytdlp_path = match &opts.ytdlp_path {+ Some(p) => p.clone(),+ None => crate::core::ytdlp::find_ytdlp_cached()+ .await+ .ok_or_else(|| anyhow!("yt-dlp not found"))?,+ };++ crate::core::ytdlp::download_video(+ &ytdlp_path,+ &quality.url,+ &opts.output_dir,+ None,+ progress,+ opts.download_mode.as_deref(),+ None,+ opts.filename_template.as_deref(),+ opts.referer.as_deref().or(Some("https://www.tiktok.com/")),+ opts.cancel_token.clone(),+ None,+ opts.concurrent_fragments,+ false,+ &[],+ opts.audio_format.as_deref(),+ )+ .await+ }+ MediaType::Photo | MediaType::Carousel => {+ let mut total_bytes = 0u64;+ let count = info.available_qualities.len();+ let mut last_path = opts.output_dir.clone();++ for (i, quality) in info.available_qualities.iter().enumerate() {+ let filename = if count == 1 {+ format!("{}.jpg", sanitize_filename::sanitize(&info.title))+ } else {+ format!(+ "{}_photo_{}.jpg",+ sanitize_filename::sanitize(&info.title),+ i + 1+ )+ };+ let output = opts.output_dir.join(&filename);+ let (tx, _rx) = mpsc::channel(8);++ let bytes = direct_downloader::download_direct_with_headers(+ &self.client,+ &quality.url,+ &output,+ tx,+ Some(headers.clone()),+ Some(&opts.cancel_token),+ )+ .await?;++ total_bytes += bytes;+ last_path = output;++ let percent = ((i + 1) as f64 / count as f64) * 100.0;+ let _ = progress.send(ProgressUpdate::percent(percent)).await;+ }++ Ok(DownloadResult {+ file_path: last_path,+ file_size_bytes: total_bytes,+ duration_seconds: 0.0,+ torrent_id: None,+ })+ }+ MediaType::Audio => {+ let quality = info+ .available_qualities+ .first()+ .ok_or_else(|| anyhow!("No audio URL available"))?;++ let filename = format!("{}.mp3", sanitize_filename::sanitize(&info.title));+ let output = opts.output_dir.join(&filename);++ let bytes = direct_downloader::download_direct_with_headers(+ &self.client,+ &quality.url,+ &output,+ progress,+ Some(headers),+ Some(&opts.cancel_token),+ )+ .await?;++ Ok(DownloadResult {+ file_path: output,+ file_size_bytes: bytes,+ duration_seconds: 0.0,+ torrent_id: None,+ })+ }+ _ => Err(anyhow!("Unsupported media type for download")),+ }+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex cf8a5b14..f7aa0f61 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -42,13 +42,13 @@ pub fn run() {tracing_subscriber::fmt::init();let mut registry = core::registry::PlatformRegistry::new();- registry.register(Arc::new(platforms::instagram::InstagramDownloader::new()));- registry.register(Arc::new(platforms::pinterest::PinterestDownloader::new()));- registry.register(Arc::new(platforms::tiktok::TikTokDownloader::new()));+ registry.register(Arc::new(omniget_core::platforms::InstagramDownloader::new()));+ registry.register(Arc::new(omniget_core::platforms::PinterestDownloader::new()));+ registry.register(Arc::new(omniget_core::platforms::TikTokDownloader::new()));registry.register(Arc::new(platforms::twitter::TwitterDownloader::new()));registry.register(Arc::new(omniget_core::platforms::TwitchClipsDownloader::new()));registry.register(Arc::new(omniget_core::platforms::BlueskyDownloader::new()));- registry.register(Arc::new(platforms::reddit::RedditDownloader::new()));+ registry.register(Arc::new(omniget_core::platforms::RedditDownloader::new()));registry.register(Arc::new(omniget_core::platforms::YouTubeDownloader::new()));registry.register(Arc::new(omniget_core::platforms::VimeoDownloader::new()));registry.register(Arc::new(platforms::bilibili::BilibiliDownloader::new()));diff --git a/src-tauri/src/platforms/mod.rs b/src-tauri/src/platforms/mod.rsindex b163750e..6392b2e3 100644--- a/src-tauri/src/platforms/mod.rs+++ b/src-tauri/src/platforms/mod.rs@@ -4,15 +4,18 @@ pub use omniget_core::platforms::BlueskyDownloader;pub use omniget_core::platforms::DirectFileDownloader;pub use omniget_core::platforms::DouyinDownloader;pub use omniget_core::platforms::GenericYtdlpDownloader;+pub use omniget_core::platforms::InstagramDownloader;pub use crate::platforms::magnet::MagnetDownloader;+pub use omniget_core::platforms::PinterestDownloader;pub use omniget_core::platforms::P2pDownloader;+pub use omniget_core::platforms::RedditDownloader;+pub use omniget_core::platforms::TikTokDownloader;pub use omniget_core::platforms::TwitchClipsDownloader;pub use omniget_core::platforms::VimeoDownloader;pub use omniget_core::platforms::YouTubeDownloader;+pub mod magnet;pub mod noop;-pub mod pinterest;-pub mod tiktok;pub mod twitter;#[cfg(not(target_os = "android"))]@@ -21,9 +24,4 @@ pub mod bilibili;pub mod gallerydl;#[cfg(not(target_os = "android"))]pub mod generic_ytdlp;-#[cfg(not(target_os = "android"))]-pub mod instagram;-#[cfg(not(target_os = "android"))]-pub mod reddit;-pub mod magnet;-// Ported to omniget-core: bluesky, direct_file, douyin, p2p, twitch, vimeo, youtube+// Ported to omniget-core: bluesky, direct_file, douyin, instagram, pinterest, p2p, reddit, tiktok, twitch, vimeo, youtube