Skip to content

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

Phase 1: port 8 simple platforms to omniget-core

Hanakodc06cfec59b6
diff --git a/src-tauri/omniget-core/src/platforms/bluesky.rs b/src-tauri/omniget-core/src/platforms/bluesky.rs
new file mode 100644
index 00000000..e54b4d74
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bluesky.rs
@@ -0,0 +1,382 @@
+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::hls_downloader::HlsDownloader;
+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+const API_BASE: &str = "https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread";
+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";
+
+pub struct BlueskyDownloader {
+ client: reqwest::Client,
+}
+
+impl Default for BlueskyDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl BlueskyDownloader {
+ 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 (user, post_id) = Self::extract_user_and_post(url)
+ .ok_or_else(|| anyhow!("Could not extract user and post_id from URL"))?;
+
+ let json = self.fetch_post(&user, &post_id).await?;
+
+ let embed = json
+ .pointer("/thread/post/embed")
+ .ok_or_else(|| anyhow!("Post does not contain media"))?;
+
+ let media = extract_media(embed).ok_or_else(|| anyhow!("Unsupported media type"))?;
+
+ let filename_base = format!("bluesky_{}_{}", sanitize_filename::sanitize(&user), post_id);
+
+ match media {
+ BlueskyMedia::Video { hls_url } => Ok(MediaInfo {
+ title: filename_base,
+ author: user,
+ platform: "bluesky".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "best".to_string(),
+ width: 0,
+ height: 0,
+ url: hls_url,
+ format: "hls".to_string(),
+ }],
+ media_type: MediaType::Video,
+ file_size_bytes: None,
+ }),
+ BlueskyMedia::Images { urls } => {
+ let media_type = if urls.len() == 1 {
+ MediaType::Photo
+ } else {
+ MediaType::Carousel
+ };
+ let qualities: Vec<VideoQuality> = urls
+ .iter()
+ .enumerate()
+ .map(|(i, u)| VideoQuality {
+ label: format!("{}", i + 1),
+ width: 0,
+ height: 0,
+ url: u.clone(),
+ format: "jpg".to_string(),
+ })
+ .collect();
+ Ok(MediaInfo {
+ title: filename_base,
+ author: user,
+ platform: "bluesky".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: qualities,
+ media_type,
+ file_size_bytes: None,
+ })
+ }
+ BlueskyMedia::Gif { url: gif_url } => Ok(MediaInfo {
+ title: filename_base,
+ author: user,
+ platform: "bluesky".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,
+ }),
+ }
+ }
+
+ pub fn new() -> Self {
+ let client = 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))
+ .build()
+ .unwrap_or_default();
+ Self { client }
+ }
+
+ fn extract_user_and_post(url: &str) -> Option<(String, 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] == "profile" && segments[2] == "post" {
+ return Some((segments[1].to_string(), segments[3].to_string()));
+ }
+ None
+ }
+
+ async fn fetch_post(&self, user: &str, post_id: &str) -> anyhow::Result<serde_json::Value> {
+ let uri = format!("at://{}/app.bsky.feed.post/{}", user, post_id);
+ let url = format!(
+ "{}?depth=0&parentHeight=0&uri={}",
+ API_BASE,
+ urlencoding::encode(&uri)
+ );
+
+ let response = self.client.get(&url).send().await?;
+
+ if !response.status().is_success() {
+ return Err(anyhow!("Bluesky API retornou HTTP {}", response.status()));
+ }
+
+ let json: serde_json::Value = response.json().await?;
+
+ if let Some(error) = json.get("error").and_then(|e| e.as_str()) {
+ return match error {
+ "NotFound" | "InternalServerError" => Err(anyhow!("Post not available")),
+ "InvalidRequest" => Err(anyhow!("Unsupported link")),
+ _ => Err(anyhow!("Erro da API: {}", error)),
+ };
+ }
+
+ Ok(json)
+ }
+}
+
+enum BlueskyMedia {
+ Video { hls_url: String },
+ Images { urls: Vec<String> },
+ Gif { url: String },
+}
+
+fn extract_media(embed: &serde_json::Value) -> Option<BlueskyMedia> {
+ let embed_type = embed.get("$type")?.as_str()?;
+
+ match embed_type {
+ "app.bsky.embed.video#view" => {
+ let playlist = embed.get("playlist")?.as_str()?;
+ let hls_url = playlist.replace("video.bsky.app/watch/", "video.cdn.bsky.app/hls/");
+ Some(BlueskyMedia::Video { hls_url })
+ }
+ "app.bsky.embed.images#view" => {
+ let images = embed.get("images")?.as_array()?;
+ let urls: Vec<String> = images
+ .iter()
+ .filter_map(|img| img.get("fullsize")?.as_str().map(|s| s.to_string()))
+ .collect();
+ if urls.is_empty() {
+ return None;
+ }
+ Some(BlueskyMedia::Images { urls })
+ }
+ "app.bsky.embed.external#view" => {
+ let uri = embed.get("external")?.get("uri")?.as_str()?;
+ extract_gif_from_uri(uri)
+ }
+ "app.bsky.embed.recordWithMedia#view" => {
+ let media = embed.get("media")?;
+ let media_type = media.get("$type")?.as_str()?;
+ if media_type == "app.bsky.embed.external#view" {
+ let uri = media.get("external")?.get("uri")?.as_str()?;
+ return extract_gif_from_uri(uri);
+ }
+ if media_type == "app.bsky.embed.video#view" {
+ let playlist = media.get("playlist")?.as_str()?;
+ let hls_url = playlist.replace("video.bsky.app/watch/", "video.cdn.bsky.app/hls/");
+ return Some(BlueskyMedia::Video { hls_url });
+ }
+ None
+ }
+ _ => None,
+ }
+}
+
+fn extract_gif_from_uri(uri: &str) -> Option<BlueskyMedia> {
+ let parsed = url::Url::parse(uri).ok()?;
+ if parsed.host_str()? == "media.tenor.com" {
+ let mut clean = parsed.clone();
+ clean.set_query(None);
+ return Some(BlueskyMedia::Gif {
+ url: clean.to_string(),
+ });
+ }
+ None
+}
+
+#[async_trait]
+impl PlatformDownloader for BlueskyDownloader {
+ fn name(&self) -> &str {
+ "bluesky"
+ }
+
+ 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 == "bsky.app" || host.ends_with(".bsky.app");
+ }
+ }
+ 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!(
+ "[bluesky] 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://bsky.app")),
+ opts.cancel_token.clone(),
+ None,
+ opts.concurrent_fragments,
+ false,
+ &[],
+ opts.audio_format.as_deref(),
+ )
+ .await;
+ }
+ }
+
+ match info.media_type {
+ MediaType::Video => {
+ let hls_url = &info
+ .available_qualities
+ .first()
+ .ok_or_else(|| anyhow!("No HLS URL available"))?
+ .url;
+
+ let filename = format!("{}.mp4", sanitize_filename::sanitize(&info.title));
+ let output_path = opts.output_dir.join(&filename);
+ let output_str = output_path.to_string_lossy().to_string();
+
+ let downloader =
+ HlsDownloader::new().with_user_agent_override(opts.user_agent.clone());
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
+
+ let result = downloader
+ .download(
+ hls_url,
+ &output_str,
+ "https://bsky.app",
+ None,
+ opts.cancel_token.clone(),
+ 20,
+ 3,
+ )
+ .await?;
+
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
+
+ Ok(DownloadResult {
+ file_path: result.path,
+ file_size_bytes: result.file_size,
+ duration_seconds: 0.0,
+ torrent_id: None,
+ })
+ }
+ 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 ext = &quality.format;
+ let filename = if count == 1 {
+ format!("{}.{}", sanitize_filename::sanitize(&info.title), ext)
+ } else {
+ format!(
+ "{}_{}.{}",
+ sanitize_filename::sanitize(&info.title),
+ i + 1,
+ ext
+ )
+ };
+ 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,
+ })
+ }
+ MediaType::Gif => {
+ let gif_url = &info
+ .available_qualities
+ .first()
+ .ok_or_else(|| anyhow!("No GIF URL available"))?
+ .url;
+
+ let filename = format!("{}.gif", sanitize_filename::sanitize(&info.title));
+ let output = opts.output_dir.join(&filename);
+
+ let bytes = direct_downloader::download_direct(
+ &self.client,
+ gif_url,
+ &output,
+ progress,
+ 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/omniget-core/src/platforms/direct_file.rs b/src-tauri/omniget-core/src/platforms/direct_file.rs
new file mode 100644
index 00000000..3ba4b612
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/direct_file.rs
@@ -0,0 +1,168 @@
+use crate::models::progress::ProgressUpdate;
+use crate::platforms::traits::PlatformDownloader;
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use crate::core::direct_downloader;
+use crate::core::http_client;
+use crate::models::media::{
+ DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality,
+};
+
+pub struct DirectFileDownloader;
+
+impl Default for DirectFileDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl DirectFileDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+fn filename_from_url(url: &str) -> String {
+ url::Url::parse(url)
+ .ok()
+ .and_then(|u| {
+ let last = u.path().rsplit('/').next()?.to_string();
+ if last.is_empty() || !last.contains('.') {
+ return None;
+ }
+ Some(
+ urlencoding::decode(&last)
+ .map(|d| d.to_string())
+ .unwrap_or(last),
+ )
+ })
+ .map(|name| sanitize_filename::sanitize(&name))
+ .filter(|name| !name.is_empty())
+ .unwrap_or_else(|| "download".to_string())
+}
+
+async fn probe_file_size(url: &str) -> Option<u64> {
+ let client = http_client::apply_global_proxy(reqwest::Client::builder())
+ .timeout(std::time::Duration::from_secs(10))
+ .build()
+ .ok()?;
+ let resp = client.head(url).send().await.ok()?;
+ if !resp.status().is_success() {
+ return None;
+ }
+ resp.content_length().filter(|len| *len > 0)
+}
+
+#[async_trait]
+impl PlatformDownloader for DirectFileDownloader {
+ fn name(&self) -> &str {
+ "direct_file"
+ }
+
+ fn can_handle(&self, url: &str) -> bool {
+ crate::platforms::is_direct_file_url(url)
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ let title = filename_from_url(url);
+ let file_size_bytes = probe_file_size(url).await;
+
+ Ok(MediaInfo {
+ title,
+ author: String::new(),
+ platform: "direct_file".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "original".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "direct_file".to_string(),
+ }],
+ media_type: MediaType::File,
+ file_size_bytes,
+ })
+ }
+
+ async fn download(
+ &self,
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+ ) -> anyhow::Result<DownloadResult> {
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
+
+ let file_url = info
+ .available_qualities
+ .first()
+ .map(|q| q.url.as_str())
+ .filter(|u| !u.is_empty())
+ .ok_or_else(|| anyhow!("No URL available"))?;
+
+ let filename = sanitize_filename::sanitize(&info.title);
+ let filename = if filename.is_empty() {
+ filename_from_url(file_url)
+ } else {
+ filename
+ };
+ let output_path = opts.output_dir.join(&filename);
+
+ let mut builder = http_client::apply_global_proxy(reqwest::Client::builder())
+ .connect_timeout(std::time::Duration::from_secs(30));
+
+ if let Some(ua) = opts.user_agent.as_deref() {
+ builder = builder.user_agent(ua);
+ }
+
+ let jar = crate::core::cookie_parser::load_extension_cookies_for_url(file_url).or_else(|| {
+ opts.referer
+ .as_deref()
+ .and_then(crate::core::cookie_parser::load_extension_cookies_for_url)
+ });
+ if let Some(jar) = jar {
+ builder = builder.cookie_provider(jar);
+ }
+
+ let client = builder
+ .build()
+ .map_err(|e| anyhow!("Failed to build HTTP client: {}", e))?;
+
+ let mut headers = reqwest::header::HeaderMap::new();
+ if let Some(ref r) = opts.referer {
+ if let Ok(val) = reqwest::header::HeaderValue::from_str(r) {
+ headers.insert(reqwest::header::REFERER, val);
+ }
+ }
+ if let Some(ref hdrs) = opts.extra_headers {
+ for (name, value) in hdrs {
+ if let (Ok(hname), Ok(hval)) = (
+ reqwest::header::HeaderName::from_bytes(name.as_bytes()),
+ reqwest::header::HeaderValue::from_str(value),
+ ) {
+ headers.insert(hname, hval);
+ }
+ }
+ }
+ http_client::inject_ua_header(&mut headers, opts.user_agent.as_deref());
+
+ let bytes = direct_downloader::download_direct_with_headers(
+ &client,
+ file_url,
+ &output_path,
+ progress,
+ Some(headers),
+ Some(&opts.cancel_token),
+ )
+ .await?;
+
+ Ok(DownloadResult {
+ file_path: output_path,
+ file_size_bytes: bytes,
+ duration_seconds: 0.0,
+ torrent_id: None,
+ })
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/douyin.rs b/src-tauri/omniget-core/src/platforms/douyin.rs
new file mode 100644
index 00000000..d174e355
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/douyin.rs
@@ -0,0 +1,294 @@
+use crate::models::progress::ProgressUpdate;
+use std::collections::HashSet;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use crate::core::http_client;
+use crate::core::ytdlp;
+use crate::models::media::{
+ DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality as MediaVideoQuality,
+};
+use crate::platforms::traits::PlatformDownloader;
+
+const DOUYIN_UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36";
+const DOUYIN_REFERER: &str = "https://www.douyin.com/?recommend=1";
+
+pub struct DouyinDownloader;
+
+impl Default for DouyinDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl DouyinDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+
+ fn extra_flags() -> Vec<String> {
+ vec![
+ "--referer".to_string(),
+ DOUYIN_REFERER.to_string(),
+ "--user-agent".to_string(),
+ DOUYIN_UA.to_string(),
+ ]
+ }
+
+ fn host_matches(host: &str) -> bool {
+ let host = host.to_lowercase();
+ host == "douyin.com"
+ || host.ends_with(".douyin.com")
+ || host == "iesdouyin.com"
+ || host.ends_with(".iesdouyin.com")
+ || host == "amemv.com"
+ || host.ends_with(".amemv.com")
+ }
+
+ 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.douyin.com"
+ || host == "amemv.com"
+ || host.ends_with(".amemv.com")
+ || host == "iesdouyin.com"
+ || host.ends_with(".iesdouyin.com");
+ }
+ }
+ false
+ }
+
+ fn canonicalize(url: &str) -> String {
+ let Ok(parsed) = url::Url::parse(url) else {
+ return url.to_string();
+ };
+ let host = parsed.host_str().unwrap_or("").to_lowercase();
+ if !Self::host_matches(&host) {
+ return url.to_string();
+ }
+
+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();
+ let target = match segments.as_slice() {
+ ["share", kind @ ("video" | "note" | "slides"), id, ..] => Some((*kind, *id)),
+ [kind @ ("video" | "note"), id, ..] => Some((*kind, *id)),
+ _ => None,
+ };
+ if let Some((kind, id)) = target {
+ if !id.is_empty() && id.chars().all(|c| c.is_ascii_digit()) {
+ let kind = if kind == "slides" { "note" } else { kind };
+ return format!("https://www.douyin.com/{}/{}", kind, id);
+ }
+ }
+
+ if let Some(id) = parsed
+ .query_pairs()
+ .find(|(k, _)| k == "modal_id")
+ .map(|(_, v)| v.to_string())
+ {
+ if !id.is_empty() && id.chars().all(|c| c.is_ascii_digit()) {
+ return format!("https://www.douyin.com/video/{}", id);
+ }
+ }
+
+ url.to_string()
+ }
+
+ async fn resolve_url(url: &str) -> String {
+ if !Self::is_short_link(url) {
+ return Self::canonicalize(url);
+ }
+ let builder = reqwest::Client::builder()
+ .timeout(Duration::from_secs(10))
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .user_agent(DOUYIN_UA);
+ let client = match http_client::apply_global_proxy(builder).build() {
+ Ok(c) => c,
+ Err(_) => return Self::canonicalize(url),
+ };
+ match client.get(url).send().await {
+ Ok(resp) => Self::canonicalize(resp.url().as_str()),
+ Err(e) => {
+ tracing::warn!("[douyin] short-link resolve failed: {}", e);
+ Self::canonicalize(url)
+ }
+ }
+ }
+
+ fn build_qualities(formats: &[serde_json::Value], url: &str) -> Vec<MediaVideoQuality> {
+ let mut seen_heights = HashSet::new();
+ let mut qualities = Vec::new();
+
+ for fmt in formats {
+ let height = fmt.get("height").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
+ let vcodec = fmt.get("vcodec").and_then(|v| v.as_str()).unwrap_or("none");
+
+ if height == 0 || vcodec == "none" {
+ continue;
+ }
+ if !seen_heights.insert(height) {
+ continue;
+ }
+
+ let label = match height {
+ 2160 => "4K".to_string(),
+ 1440 => "2K".to_string(),
+ 1080 => "1080p".to_string(),
+ 720 => "720p".to_string(),
+ 480 => "480p".to_string(),
+ 360 => "360p".to_string(),
+ _ => format!("{}p", height),
+ };
+
+ qualities.push(MediaVideoQuality {
+ label,
+ width: fmt.get("width").and_then(|v| v.as_u64()).unwrap_or(0) as u32,
+ height,
+ url: url.to_string(),
+ format: "mp4".to_string(),
+ });
+ }
+
+ qualities.sort_by(|a, b| b.height.cmp(&a.height));
+
+ if qualities.is_empty() {
+ qualities.push(MediaVideoQuality {
+ label: "best".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "mp4".to_string(),
+ });
+ }
+
+ qualities
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for DouyinDownloader {
+ fn name(&self) -> &str {
+ "douyin"
+ }
+
+ fn can_handle(&self, url: &str) -> bool {
+ if let Ok(parsed) = url::Url::parse(url) {
+ if let Some(host) = parsed.host_str() {
+ return Self::host_matches(host);
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ let ytdlp_path = ytdlp::find_ytdlp_cached()
+ .await
+ .ok_or_else(|| anyhow!("yt-dlp not found"))?;
+
+ let resolved = Self::resolve_url(url).await;
+ let extra = Self::extra_flags();
+ let json = ytdlp::get_video_info(&ytdlp_path, &resolved, &extra).await?;
+
+ let title = json
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Douyin Video")
+ .to_string();
+
+ let author = json
+ .get("uploader")
+ .and_then(|v| v.as_str())
+ .or_else(|| json.get("channel").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);
+
+ let formats = json
+ .get("formats")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let qualities = Self::build_qualities(&formats, &resolved);
+
+ let has_video = formats
+ .iter()
+ .any(|f| f.get("vcodec").and_then(|v| v.as_str()).unwrap_or("none") != "none");
+
+ Ok(MediaInfo {
+ title,
+ author,
+ platform: "douyin".to_string(),
+ duration_seconds: duration,
+ thumbnail_url: thumbnail,
+ available_qualities: qualities,
+ media_type: if has_video {
+ MediaType::Video
+ } else {
+ MediaType::Audio
+ },
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+ ) -> anyhow::Result<DownloadResult> {
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
+
+ let ytdlp_path = match &opts.ytdlp_path {
+ Some(p) => p.clone(),
+ None => ytdlp::find_ytdlp_cached()
+ .await
+ .ok_or_else(|| anyhow!("yt-dlp not found"))?,
+ };
+
+ let canonical = info
+ .available_qualities
+ .first()
+ .map(|q| q.url.as_str())
+ .unwrap_or("");
+ if canonical.is_empty() {
+ return Err(anyhow!("No URL available"));
+ }
+ let canonical = Self::resolve_url(canonical).await;
+
+ let quality_height = opts
+ .quality
+ .as_ref()
+ .and_then(|q| q.trim_end_matches('p').parse::<u32>().ok());
+
+ let extra = Self::extra_flags();
+
+ ytdlp::download_video(
+ &ytdlp_path,
+ &canonical,
+ &opts.output_dir,
+ quality_height,
+ progress,
+ opts.download_mode.as_deref(),
+ opts.format_id.as_deref(),
+ opts.filename_template.as_deref(),
+ opts.referer.as_deref().or(Some(DOUYIN_REFERER)),
+ opts.cancel_token.clone(),
+ None,
+ opts.concurrent_fragments,
+ opts.download_subtitles,
+ &extra,
+ opts.audio_format.as_deref(),
+ )
+ .await
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/magnet.rs b/src-tauri/omniget-core/src/platforms/magnet.rs
new file mode 100644
index 00000000..938b28e4
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/magnet.rs
@@ -0,0 +1,310 @@
+use crate::models::progress::ProgressUpdate;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use librqbit::{api::TorrentIdOrHash, AddTorrent, AddTorrentOptions, Session, SessionOptions};
+use tokio::sync::mpsc;
+
+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+type SharedSession = Arc<tokio::sync::Mutex<Option<Arc<Session>>>>;
+
+pub struct MagnetDownloader {
+ session: SharedSession,
+ session_output_dir: Arc<tokio::sync::Mutex<Option<PathBuf>>>,
+}
+
+impl MagnetDownloader {
+ pub fn new(session: SharedSession) -> Self {
+ Self {
+ session,
+ session_output_dir: Arc::new(tokio::sync::Mutex::new(None)),
+ }
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for MagnetDownloader {
+ fn name(&self) -> &str {
+ "magnet"
+ }
+
+ fn can_handle(&self, url: &str) -> bool {
+ url.starts_with("magnet:")
+ || url.ends_with(".torrent")
+ || (std::path::Path::new(url).exists()
+ && std::path::Path::new(url)
+ .extension()
+ .map(|e| e == "torrent")
+ .unwrap_or(false))
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ let mut title = "Torrent Download".to_string();
+
+ if url.starts_with("magnet:") {
+ if let Ok(parsed_url) = url::Url::parse(url) {
+ for (key, value) in parsed_url.query_pairs() {
+ if key == "dn" {
+ title = value.to_string();
+ break;
+ }
+ }
+ }
+ } else {
+ let path = std::path::Path::new(url);
+ if path.exists() {
+ if let Some(stem) = path.file_stem() {
+ title = stem.to_string_lossy().to_string();
+ }
+ } else if url.ends_with(".torrent") {
+ if let Some(name) = url.rsplit('/').next() {
+ title = name.trim_end_matches(".torrent").to_string();
+ }
+ }
+ }
+
+ Ok(MediaInfo {
+ title,
+ author: "BitTorrent".to_string(),
+ platform: "magnet".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "Original".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "torrent".to_string(),
+ }],
+ media_type: MediaType::Video,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+ ) -> anyhow::Result<DownloadResult> {
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
+
+ let url = match info.available_qualities.first() {
+ Some(q) => &q.url,
+ None => anyhow::bail!("No URL found in MediaInfo"),
+ };
+
+ let output_dir = &opts.output_dir;
+
+ // Get or create the shared session, recreating if output_dir changed
+ let session = {
+ let mut guard = self.session.lock().await;
+ let mut dir_guard = self.session_output_dir.lock().await;
+ let need_new_session = match (&*guard, &*dir_guard) {
+ (Some(_), Some(prev_dir)) => prev_dir != output_dir,
+ (None, _) => true,
+ _ => true,
+ };
+ if need_new_session {
+ if guard.is_some() {
+ tracing::info!("[magnet] output dir changed, recreating session");
+ }
+ let listen_port = opts.torrent_listen_port.unwrap_or(6881).min(65525);
+ tracing::info!(
+ "[magnet] creating shared session, port: {}, output: {}",
+ listen_port,
+ output_dir.display()
+ );
+ let enable_upnp = opts.torrent_upnp;
+ let make_opts = |disable_dht_persistence: bool, disable_dht: bool| SessionOptions {
+ listen_port_range: Some(listen_port..listen_port.saturating_add(10)),
+ disable_dht,
+ disable_dht_persistence,
+ enable_upnp_port_forwarding: enable_upnp,
+ ..Default::default()
+ };
+ let cancel_rx = opts.cancel_token.clone();
+ let output_pb: PathBuf = output_dir.into();
+ let s = tokio::select! {
+ result = async {
+ match Session::new_with_opts(output_pb.clone(), make_opts(false, false)).await {
+ Ok(s) => Ok(s),
+ Err(e) => {
+ tracing::warn!(
+ "[magnet] persistent DHT init failed ({}); retrying without DHT persistence",
+ e
+ );
+ match Session::new_with_opts(output_pb.clone(), make_opts(true, false)).await {
+ Ok(s) => Ok(s),
+ Err(e2) => {
+ tracing::warn!(
+ "[magnet] DHT init failed ({}); retrying with DHT disabled (trackers/PEX only)",
+ e2
+ );
+ Session::new_with_opts(output_pb, make_opts(true, true)).await
+ }
+ }
+ }
+ }
+ } => {
+ result.map_err(|e| anyhow::anyhow!("Failed to initialize torrent session: {}", e))?
+ }
+ _ = cancel_rx.cancelled() => {
+ anyhow::bail!("Download cancelled during session creation");
+ }
+ };
+ *guard = Some(s.clone());
+ *dir_guard = Some(output_dir.clone());
+ s
+ } else {
+ tracing::info!("[magnet] reusing existing session");
+ guard.as_ref().unwrap().clone()
+ }
+ };
+
+ let add_torrent = if url.starts_with("magnet:")
+ || url.starts_with("http://")
+ || url.starts_with("https://")
+ {
+ AddTorrent::from_url(url)
+ } else {
+ let path = std::path::Path::new(url);
+ if path.exists() && path.extension().map(|e| e == "torrent").unwrap_or(false) {
+ let bytes = tokio::fs::read(path)
+ .await
+ .map_err(|e| anyhow::anyhow!("Failed to read .torrent file: {}", e))?;
+ AddTorrent::from_bytes(bytes)
+ } else {
+ AddTorrent::from_url(url)
+ }
+ };
+ let only_files = opts
+ .torrent_files
+ .as_ref()
+ .filter(|v| !v.is_empty())
+ .cloned();
+ if let Some(sel) = &only_files {
+ tracing::info!("[magnet] selective download: {} file(s)", sel.len());
+ }
+ let trackers = if opts.torrent_auto_trackers {
+ let list = crate::core::trackers::extra_trackers();
+ tracing::info!("[magnet] injecting {} public trackers", list.len());
+ Some(list)
+ } else {
+ None
+ };
+ let torrent_opts = AddTorrentOptions {
+ overwrite: true,
+ only_files,
+ trackers,
+ ..Default::default()
+ };
+
+ tracing::info!("[magnet] adding torrent, output: {}", output_dir.display());
+ let (torrent_id, managed_torrent) =
+ match session.add_torrent(add_torrent, Some(torrent_opts)).await {
+ Ok(resp) => match resp {
+ librqbit::AddTorrentResponse::Added(id, handle) => (id, handle),
+ librqbit::AddTorrentResponse::AlreadyManaged(id, handle) => (id, handle),
+ librqbit::AddTorrentResponse::ListOnly(_) => {
+ anyhow::bail!("Torrent was added in list-only mode");
+ }
+ },
+ Err(e) => anyhow::bail!("Failed to add torrent: {}", e),
+ };
+
+ tracing::info!(
+ "[magnet] torrent added (id={}), waiting for download...",
+ torrent_id
+ );
+
+ if let Some(slot) = &opts.torrent_id_slot {
+ *slot.lock().await = Some(torrent_id);
+ }
+
+ let completion = managed_torrent.wait_until_completed();
+ tokio::pin!(completion);
+
+ let cancel_rx = opts.cancel_token.clone();
+ let session_for_cancel = session.clone();
+
+ loop {
+ tokio::select! {
+ _ = tokio::time::sleep(std::time::Duration::from_millis(500)) => {
+ if managed_torrent.is_paused() {
+ continue;
+ }
+ let stats = managed_torrent.stats();
+ let total = stats.total_bytes;
+ let downloaded = stats.progress_bytes;
+
+ if total > 0 {
+ let pct = (downloaded as f64 / total as f64) * 100.0;
+ let _ = progress.send(ProgressUpdate::percent(pct)).await;
+ tracing::debug!(
+ "[magnet] progress: {:.1}% ({:.1} MB / {:.1} MB)",
+ pct,
+ downloaded as f64 / 1_048_576.0,
+ total as f64 / 1_048_576.0,
+ );
+ // Fallback: detect completion from stats when
+ // wait_until_completed() doesn't resolve
+ if downloaded >= total {
+ tracing::info!("[magnet] download complete from stats (id={})", torrent_id);
+ break;
+ }
+ }
+ }
+ _ = cancel_rx.cancelled() => {
+ tracing::info!("[magnet] download cancelled, removing torrent id={}", torrent_id);
+ if let Err(e) = session_for_cancel.delete(TorrentIdOrHash::Id(torrent_id), false).await {
+ tracing::warn!("[magnet] failed to delete torrent on cancel: {}", e);
+ }
+ anyhow::bail!("Download cancelled");
+ }
+ res = &mut completion => {
+ if let Err(e) = res {
+ anyhow::bail!("Torrent download failed: {}", e);
+ }
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
+ tracing::info!("[magnet] download complete (id={})", torrent_id);
+ break;
+ }
+ }
+ }
+
+ let (total_size, torrent_name) = managed_torrent
+ .with_metadata(|meta| {
+ let size = meta
+ .info
+ .iter_file_lengths()
+ .ok()
+ .map(|iter| iter.sum::<u64>())
+ .unwrap_or_else(|| meta.file_infos.iter().map(|f| f.len).sum());
+ let name = meta
+ .info
+ .name
+ .as_ref()
+ .map(|n| String::from_utf8_lossy(n.as_ref()).to_string())
+ .unwrap_or_default();
+ (size, name)
+ })
+ .unwrap_or((0, String::new()));
+
+ let file_path = if torrent_name.is_empty() {
+ output_dir.clone()
+ } else {
+ output_dir.join(&torrent_name)
+ };
+
+ Ok(DownloadResult {
+ file_path,
+ file_size_bytes: total_size,
+ duration_seconds: 0.0,
+ torrent_id: Some(torrent_id),
+ })
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/mod.rs b/src-tauri/omniget-core/src/platforms/mod.rs
index 5a73c081..422be9cc 100644
--- a/src-tauri/omniget-core/src/platforms/mod.rs
+++ b/src-tauri/omniget-core/src/platforms/mod.rs
@@ -1,9 +1,24 @@
+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 p2p;
+pub mod p2p_words;
pub mod traits;
+pub mod twitch;
+pub mod vimeo;
pub mod youtube;
+pub use bluesky::BlueskyDownloader;
+pub use direct_file::DirectFileDownloader;
+pub use douyin::DouyinDownloader;
pub use generic_ytdlp::GenericYtdlpDownloader;
+// pub use magnet::MagnetDownloader;
+pub use p2p::P2pDownloader;
pub use traits::PlatformDownloader;
+pub use twitch::TwitchClipsDownloader;
+pub use vimeo::VimeoDownloader;
pub use youtube::YouTubeDownloader;
use serde::{Deserialize, Serialize};
diff --git a/src-tauri/omniget-core/src/platforms/p2p.rs b/src-tauri/omniget-core/src/platforms/p2p.rs
new file mode 100644
index 00000000..6a82aaf7
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/p2p.rs
@@ -0,0 +1,348 @@
+
+
+use crate::models::progress::ProgressUpdate;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::fs::File;
+use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
+use tokio::net::TcpStream;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+const CHUNK_SIZE: usize = 64 * 1024;
+
+fn relay_addr() -> String {
+ std::env::var("OMNIGET_RELAY").unwrap_or_else(|_| "relay.tonho.wtf:9009".to_string())
+}
+
+async fn connect_relay() -> anyhow::Result<TcpStream> {
+ let addr = relay_addr();
+ let stream = tokio::time::timeout(
+ std::time::Duration::from_secs(10),
+ TcpStream::connect(&addr),
+ )
+ .await
+ .map_err(|_| anyhow!("Connection to relay timed out (10s)"))?
+ .map_err(|e| anyhow!("Failed to connect to relay {}: {}", addr, e))?;
+ Ok(stream)
+}
+
+async fn read_line(
+ reader: &mut BufReader<tokio::io::ReadHalf<TcpStream>>,
+) -> anyhow::Result<String> {
+ let mut line = String::new();
+ let n = reader.read_line(&mut line).await?;
+ if n == 0 {
+ anyhow::bail!("Relay closed connection unexpectedly");
+ }
+ Ok(line.trim_end().to_string())
+}
+
+fn check_relay_error(line: &str) -> anyhow::Result<()> {
+ if let Some(err) = line.strip_prefix("ERROR ") {
+ anyhow::bail!("Relay error: {}", err);
+ }
+ Ok(())
+}
+
+pub struct P2pDownloader;
+
+impl P2pDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for P2pDownloader {
+ fn name(&self) -> &str {
+ "p2p"
+ }
+
+ fn can_handle(&self, url: &str) -> bool {
+ if let Some(code) = url.strip_prefix("p2p:") {
+ return crate::platforms::p2p_words::is_valid_code(code);
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ let code = url
+ .strip_prefix("p2p:")
+ .ok_or_else(|| anyhow!("Invalid P2P URL: {}", url))?;
+
+ if !crate::platforms::p2p_words::is_valid_code(code) {
+ anyhow::bail!("Invalid share code: {}", code);
+ }
+
+ let title = format!("P2P Transfer ({})", &code[..code.len().min(30)]);
+
+ Ok(MediaInfo {
+ title,
+ author: "P2P Transfer".to_string(),
+ platform: "p2p".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "Original".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "p2p".to_string(),
+ }],
+ media_type: MediaType::Video,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+ ) -> anyhow::Result<DownloadResult> {
+ let url = match info.available_qualities.first() {
+ Some(q) => &q.url,
+ None => anyhow::bail!("No URL found in MediaInfo"),
+ };
+
+ let code = url
+ .strip_prefix("p2p:")
+ .ok_or_else(|| anyhow!("Invalid P2P URL"))?;
+
+ let _ = progress.send(ProgressUpdate::percent(-2.0)).await;
+
+ tracing::info!("[p2p] connecting to relay for code: {}", code);
+
+ let stream = connect_relay().await?;
+ let (read_half, mut write_half) = tokio::io::split(stream);
+ let mut reader = BufReader::new(read_half);
+
+ write_half
+ .write_all(format!("RECV {}\n", code).as_bytes())
+ .await?;
+ write_half.flush().await?;
+
+ let response = read_line(&mut reader).await?;
+ check_relay_error(&response)?;
+ if response != "READY" {
+ anyhow::bail!("Unexpected relay response: {}", response);
+ }
+
+ tracing::info!("[p2p] connected to sender via relay");
+
+ let file_name = read_line(&mut reader).await?;
+ let file_size_str = read_line(&mut reader).await?;
+ let file_size: u64 = file_size_str
+ .parse()
+ .map_err(|_| anyhow!("Invalid file size from sender: {}", file_size_str))?;
+
+ tracing::info!("[p2p] receiving: {} ({} bytes)", file_name, file_size);
+
+ write_half.write_all(b"OK\n").await?;
+ write_half.flush().await?;
+
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
+
+ let sanitized = sanitize_filename::sanitize(&file_name);
+ let output_path = opts.output_dir.join(&sanitized);
+ if let Some(parent) = output_path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let mut file = File::create(&output_path).await?;
+ let mut received: u64 = 0;
+ let mut buf = vec![0u8; CHUNK_SIZE];
+
+ while received < file_size {
+ if opts.cancel_token.is_cancelled() {
+ let _ = tokio::fs::remove_file(&output_path).await;
+ anyhow::bail!("Download cancelled");
+ }
+
+ let to_read = ((file_size - received) as usize).min(CHUNK_SIZE);
+ let n = reader.read(&mut buf[..to_read]).await?;
+ if n == 0 {
+ break;
+ }
+
+ file.write_all(&buf[..n]).await?;
+ received += n as u64;
+
+ if file_size > 0 {
+ let pct = (received as f64 / file_size as f64) * 100.0;
+ let _ = progress.send(ProgressUpdate::percent(pct)).await;
+ }
+ }
+
+ file.flush().await?;
+ drop(file);
+
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
+
+ tracing::info!("[p2p] download complete: {}", output_path.display());
+
+ Ok(DownloadResult {
+ file_path: output_path,
+ file_size_bytes: received,
+ duration_seconds: 0.0,
+ torrent_id: None,
+ })
+ }
+}
+
+pub struct P2pSendSession {
+ pub code: String,
+ pub file_path: PathBuf,
+ pub file_name: String,
+ pub file_size: u64,
+ pub cancel_token: CancellationToken,
+ pub progress: Arc<tokio::sync::Mutex<f64>>,
+ pub status: Arc<tokio::sync::Mutex<String>>,
+ pub sent_bytes: Arc<tokio::sync::Mutex<u64>>,
+ pub paused: Arc<std::sync::atomic::AtomicBool>,
+}
+
+pub async fn start_send(
+ file_path: PathBuf,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<P2pSendSession> {
+ let metadata = tokio::fs::metadata(&file_path)
+ .await
+ .map_err(|e| anyhow!("File not found: {}", e))?;
+
+ if !metadata.is_file() {
+ anyhow::bail!("Path is not a file: {}", file_path.display());
+ }
+
+ let file_size = metadata.len();
+ let file_name = file_path
+ .file_name()
+ .map(|n| n.to_string_lossy().to_string())
+ .unwrap_or_else(|| "file".to_string());
+
+ let code = crate::platforms::p2p_words::generate_code();
+
+ tracing::info!("[p2p] share code generated: {}", code);
+
+ Ok(P2pSendSession {
+ code,
+ file_path,
+ file_name,
+ file_size,
+ cancel_token,
+ progress: Arc::new(tokio::sync::Mutex::new(0.0)),
+ status: Arc::new(tokio::sync::Mutex::new("waiting".to_string())),
+ sent_bytes: Arc::new(tokio::sync::Mutex::new(0)),
+ paused: Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ })
+}
+
+pub async fn run_sender(session: &P2pSendSession) -> anyhow::Result<()> {
+ let cancel = session.cancel_token.clone();
+
+ *session.status.lock().await = "connecting".to_string();
+
+ tracing::info!("[p2p] connecting to relay...");
+
+ let stream = connect_relay().await?;
+ let (read_half, mut write_half) = tokio::io::split(stream);
+ let mut reader = BufReader::new(read_half);
+
+ write_half
+ .write_all(format!("SEND {}\n", session.code).as_bytes())
+ .await?;
+ write_half.flush().await?;
+
+ let response = read_line(&mut reader).await?;
+ check_relay_error(&response)?;
+ if response != "WAIT" {
+ anyhow::bail!("Unexpected relay response: {}", response);
+ }
+
+ *session.status.lock().await = "waiting_for_receiver".to_string();
+ tracing::info!("[p2p] waiting for receiver... code: {}", session.code);
+
+ let ready = tokio::select! {
+ line = read_line(&mut reader) => line?,
+ _ = cancel.cancelled() => {
+ anyhow::bail!("Send cancelled while waiting for receiver");
+ }
+ };
+
+ check_relay_error(&ready)?;
+ if ready != "READY" {
+ anyhow::bail!("Unexpected relay response: {}", ready);
+ }
+
+ *session.status.lock().await = "connected".to_string();
+ tracing::info!("[p2p] receiver connected");
+
+ let header = format!("{}\n{}\n", session.file_name, session.file_size);
+ write_half.write_all(header.as_bytes()).await?;
+ write_half.flush().await?;
+
+ let ok_response = tokio::select! {
+ line = read_line(&mut reader) => line?,
+ _ = cancel.cancelled() => {
+ anyhow::bail!("Send cancelled while waiting for OK");
+ }
+ };
+
+ if ok_response != "OK" {
+ anyhow::bail!("Receiver rejected transfer: {}", ok_response);
+ }
+
+ *session.status.lock().await = "transferring".to_string();
+ tracing::info!(
+ "[p2p] transferring: {} ({} bytes)",
+ session.file_name,
+ session.file_size
+ );
+
+ let mut file = File::open(&session.file_path).await?;
+ let mut buf = vec![0u8; CHUNK_SIZE];
+ let mut sent: u64 = 0;
+
+ loop {
+ if cancel.is_cancelled() {
+ anyhow::bail!("Send cancelled during transfer");
+ }
+
+ while session.paused.load(std::sync::atomic::Ordering::Relaxed) {
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ if cancel.is_cancelled() {
+ anyhow::bail!("Send cancelled while paused");
+ }
+ }
+
+ let n = file.read(&mut buf).await?;
+ if n == 0 {
+ break;
+ }
+
+ write_half.write_all(&buf[..n]).await?;
+ sent += n as u64;
+
+ *session.sent_bytes.lock().await = sent;
+ if session.file_size > 0 {
+ *session.progress.lock().await = (sent as f64 / session.file_size as f64) * 100.0;
+ }
+ }
+
+ write_half.flush().await?;
+ drop(write_half);
+
+ *session.progress.lock().await = 100.0;
+ *session.status.lock().await = "complete".to_string();
+
+ tracing::info!("[p2p] transfer complete: {} bytes sent", sent);
+
+ Ok(())
+}
diff --git a/src-tauri/omniget-core/src/platforms/p2p_words.rs b/src-tauri/omniget-core/src/platforms/p2p_words.rs
new file mode 100644
index 00000000..12cf3881
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/p2p_words.rs
@@ -0,0 +1,302 @@
+pub static WORDLIST: [&str; 256] = [
+ "bulbasaur",
+ "ivysaur",
+ "venusaur",
+ "charmander",
+ "charmeleon",
+ "charizard",
+ "squirtle",
+ "wartortle",
+ "blastoise",
+ "caterpie",
+ "butterfree",
+ "weedle",
+ "beedrill",
+ "pidgey",
+ "pidgeot",
+ "rattata",
+ "raticate",
+ "spearow",
+ "fearow",
+ "ekans",
+ "arbok",
+ "pikachu",
+ "raichu",
+ "sandshrew",
+ "sandslash",
+ "nidoran",
+ "nidorina",
+ "nidoqueen",
+ "nidorino",
+ "nidoking",
+ "clefairy",
+ "clefable",
+ "vulpix",
+ "ninetales",
+ "jigglypuff",
+ "wigglytuff",
+ "zubat",
+ "golbat",
+ "oddish",
+ "gloom",
+ "vileplume",
+ "paras",
+ "parasect",
+ "venonat",
+ "venomoth",
+ "diglett",
+ "dugtrio",
+ "meowth",
+ "persian",
+ "psyduck",
+ "golduck",
+ "mankey",
+ "primeape",
+ "growlithe",
+ "arcanine",
+ "poliwag",
+ "poliwhirl",
+ "poliwrath",
+ "abra",
+ "kadabra",
+ "alakazam",
+ "machop",
+ "machoke",
+ "machamp",
+ "bellsprout",
+ "weepinbell",
+ "victreebel",
+ "tentacool",
+ "tentacruel",
+ "geodude",
+ "graveler",
+ "golem",
+ "ponyta",
+ "rapidash",
+ "slowpoke",
+ "slowbro",
+ "magnemite",
+ "magneton",
+ "farfetchd",
+ "doduo",
+ "dodrio",
+ "seel",
+ "dewgong",
+ "grimer",
+ "muk",
+ "shellder",
+ "cloyster",
+ "gastly",
+ "haunter",
+ "gengar",
+ "onix",
+ "drowzee",
+ "hypno",
+ "krabby",
+ "kingler",
+ "voltorb",
+ "electrode",
+ "exeggcute",
+ "exeggutor",
+ "cubone",
+ "marowak",
+ "hitmonlee",
+ "hitmonchan",
+ "lickitung",
+ "koffing",
+ "weezing",
+ "rhyhorn",
+ "rhydon",
+ "chansey",
+ "tangela",
+ "kangaskhan",
+ "horsea",
+ "seadra",
+ "goldeen",
+ "seaking",
+ "staryu",
+ "starmie",
+ "scyther",
+ "jynx",
+ "electabuzz",
+ "magmar",
+ "pinsir",
+ "tauros",
+ "magikarp",
+ "gyarados",
+ "lapras",
+ "ditto",
+ "eevee",
+ "vaporeon",
+ "jolteon",
+ "flareon",
+ "porygon",
+ "omanyte",
+ "omastar",
+ "kabuto",
+ "kabutops",
+ "aerodactyl",
+ "snorlax",
+ "articuno",
+ "zapdos",
+ "moltres",
+ "dratini",
+ "dragonair",
+ "dragonite",
+ "mewtwo",
+ "mew",
+ "chikorita",
+ "bayleef",
+ "meganium",
+ "cyndaquil",
+ "quilava",
+ "typhlosion",
+ "totodile",
+ "croconaw",
+ "feraligatr",
+ "sentret",
+ "furret",
+ "hoothoot",
+ "noctowl",
+ "ledyba",
+ "spinarak",
+ "ariados",
+ "crobat",
+ "chinchou",
+ "lanturn",
+ "pichu",
+ "cleffa",
+ "igglybuff",
+ "togepi",
+ "togetic",
+ "natu",
+ "xatu",
+ "mareep",
+ "flaaffy",
+ "ampharos",
+ "bellossom",
+ "marill",
+ "azumarill",
+ "sudowoodo",
+ "politoed",
+ "hoppip",
+ "skiploom",
+ "jumpluff",
+ "aipom",
+ "sunkern",
+ "sunflora",
+ "yanma",
+ "wooper",
+ "quagsire",
+ "espeon",
+ "umbreon",
+ "murkrow",
+ "slowking",
+ "misdreavus",
+ "unown",
+ "wobbuffet",
+ "girafarig",
+ "pineco",
+ "forretress",
+ "dunsparce",
+ "gligar",
+ "steelix",
+ "snubbull",
+ "granbull",
+ "qwilfish",
+ "scizor",
+ "shuckle",
+ "heracross",
+ "sneasel",
+ "teddiursa",
+ "ursaring",
+ "slugma",
+ "magcargo",
+ "swinub",
+ "piloswine",
+ "corsola",
+ "remoraid",
+ "octillery",
+ "delibird",
+ "mantine",
+ "skarmory",
+ "houndour",
+ "houndoom",
+ "kingdra",
+ "phanpy",
+ "donphan",
+ "porygon2",
+ "stantler",
+ "smeargle",
+ "tyrogue",
+ "hitmontop",
+ "smoochum",
+ "elekid",
+ "magby",
+ "miltank",
+ "blissey",
+ "raikou",
+ "entei",
+ "suicune",
+ "larvitar",
+ "pupitar",
+ "tyranitar",
+ "lugia",
+ "celebi",
+ "treecko",
+ "grovyle",
+ "sceptile",
+ "torchic",
+ "combusken",
+ "blaziken",
+ "mudkip",
+ "marshtomp",
+ "swampert",
+ "ralts",
+ "gardevoir",
+ "absol",
+];
+
+pub fn generate_code() -> String {
+ use rand::RngExt;
+ let mut rng = rand::rng();
+ let mut indices = Vec::with_capacity(4);
+
+ while indices.len() < 4 {
+ let idx: usize = rng.random_range(0..256);
+ if !indices.contains(&idx) {
+ indices.push(idx);
+ }
+ }
+
+ indices
+ .iter()
+ .map(|&i| WORDLIST[i])
+ .collect::<Vec<_>>()
+ .join("-")
+}
+
+pub fn is_valid_code(s: &str) -> bool {
+ validate_words(s)
+}
+
+fn validate_words(s: &str) -> bool {
+ let parts: Vec<&str> = s.split('-').collect();
+ if parts.len() != 4 {
+ return false;
+ }
+ let mut seen = Vec::with_capacity(4);
+ for word in &parts {
+ let lower = word.to_lowercase();
+ match WORDLIST.iter().position(|w| *w == lower) {
+ Some(idx) => {
+ if seen.contains(&idx) {
+ return false;
+ }
+ seen.push(idx);
+ }
+ None => return false,
+ }
+ }
+ true
+}
diff --git a/src-tauri/omniget-core/src/platforms/twitch.rs b/src-tauri/omniget-core/src/platforms/twitch.rs
new file mode 100644
index 00000000..9ab7bedd
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/twitch.rs
@@ -0,0 +1,361 @@
+use anyhow::anyhow;
+use async_trait::async_trait;
+use crate::models::progress::ProgressUpdate;
+use tokio::sync::mpsc;
+
+use crate::core::direct_downloader;
+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+const GQL_URL: &str = "https://gql.twitch.tv/gql";
+const CLIENT_ID: &str = "kimne78kx3ncx6brgo4mv6wki5h1ko";
+const TOKEN_HASH: &str = "36b89d2507fce29e5ca551df756d27c1cfe079e2609642b4390aa4c35796eb11";
+
+struct ClipMetadata {
+ title: String,
+ duration_seconds: f64,
+ thumbnail_url: Option<String>,
+ broadcaster_login: Option<String>,
+ video_qualities: Vec<ClipQuality>,
+}
+
+struct ClipQuality {
+ quality: String,
+ source_url: String,
+}
+
+struct AccessToken {
+ signature: String,
+ value: String,
+}
+
+pub struct TwitchClipsDownloader {
+ client: reqwest::Client,
+}
+
+impl Default for TwitchClipsDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl TwitchClipsDownloader {
+ 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 slug =
+ Self::extract_clip_slug(url).ok_or_else(|| anyhow!("Could not extract clip slug"))?;
+
+ let clip = self.fetch_clip_metadata(&slug).await?;
+
+ if clip.video_qualities.is_empty() {
+ return Err(anyhow!("No video quality available"));
+ }
+
+ let broadcaster = clip
+ .broadcaster_login
+ .as_deref()
+ .ok_or_else(|| anyhow!("Dados do clip incompletos"))?;
+
+ let token = self.fetch_access_token(&slug).await?;
+
+ let clip_title = clip.title.trim().to_string();
+
+ let available_qualities: Vec<VideoQuality> = clip
+ .video_qualities
+ .iter()
+ .map(|q| {
+ let height: u32 = q.quality.parse().unwrap_or(0);
+ let authenticated_url = Self::build_authenticated_url(&q.source_url, &token);
+ VideoQuality {
+ label: format!("{}p", q.quality),
+ width: 0,
+ height,
+ url: authenticated_url,
+ format: "mp4".to_string(),
+ }
+ })
+ .collect();
+
+ Ok(MediaInfo {
+ title: sanitize_filename::sanitize(&clip_title),
+ author: broadcaster.to_string(),
+ platform: "twitch".to_string(),
+ duration_seconds: Some(clip.duration_seconds),
+ thumbnail_url: clip.thumbnail_url,
+ available_qualities,
+ media_type: MediaType::Video,
+ file_size_bytes: None,
+ })
+ }
+
+ pub fn new() -> Self {
+ let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .timeout(std::time::Duration::from_secs(120))
+ .connect_timeout(std::time::Duration::from_secs(15))
+ .build()
+ .unwrap_or_default();
+
+ Self { client }
+ }
+
+ fn extract_clip_slug(url: &str) -> Option<String> {
+ let parsed = url::Url::parse(url).ok()?;
+ let host = parsed.host_str()?.to_lowercase();
+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();
+
+ if host == "clips.twitch.tv" || host.ends_with(".clips.twitch.tv") {
+ return segments.first().map(|s| s.to_string());
+ }
+
+ if segments.len() >= 3 && segments.get(1) == Some(&"clip") {
+ return segments.get(2).map(|s| s.to_string());
+ }
+
+ None
+ }
+
+ async fn fetch_clip_metadata(&self, slug: &str) -> anyhow::Result<ClipMetadata> {
+ let query = format!(
+ r#"{{ clip(slug: "{}") {{ broadcaster {{ login }} curator {{ login }} durationSeconds id medium: thumbnailURL(width: 480, height: 272) title videoQualities {{ quality sourceURL }} }} }}"#,
+ slug
+ );
+
+ let body = serde_json::json!({ "query": query });
+
+ let response = self
+ .client
+ .post(GQL_URL)
+ .header("client-id", CLIENT_ID)
+ .json(&body)
+ .send()
+ .await?;
+
+ if !response.status().is_success() {
+ return Err(anyhow!("Twitch GQL retornou HTTP {}", response.status()));
+ }
+
+ let json: serde_json::Value = response.json().await?;
+
+ let clip = json
+ .pointer("/data/clip")
+ .ok_or_else(|| anyhow!("Clip not found: {}", slug))?;
+
+ if clip.is_null() {
+ return Err(anyhow!("Clip not found: {}", slug));
+ }
+
+ let title = clip
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Untitled")
+ .to_string();
+
+ let duration_seconds = clip
+ .get("durationSeconds")
+ .and_then(|v| v.as_f64())
+ .unwrap_or(0.0);
+
+ let thumbnail_url = clip
+ .get("medium")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+
+ let broadcaster_login = clip
+ .pointer("/broadcaster/login")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+
+ let video_qualities = clip
+ .get("videoQualities")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|q| {
+ let quality = q.get("quality")?.as_str()?.to_string();
+ let source_url = q.get("sourceURL")?.as_str()?.to_string();
+ Some(ClipQuality {
+ quality,
+ source_url,
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+
+ Ok(ClipMetadata {
+ title,
+ duration_seconds,
+ thumbnail_url,
+ broadcaster_login,
+ video_qualities,
+ })
+ }
+
+ async fn fetch_access_token(&self, slug: &str) -> anyhow::Result<AccessToken> {
+ let body = serde_json::json!([{
+ "operationName": "VideoAccessToken_Clip",
+ "variables": { "slug": slug },
+ "extensions": {
+ "persistedQuery": {
+ "version": 1,
+ "sha256Hash": TOKEN_HASH
+ }
+ }
+ }]);
+
+ let response = self
+ .client
+ .post(GQL_URL)
+ .header("client-id", CLIENT_ID)
+ .json(&body)
+ .send()
+ .await?;
+
+ if !response.status().is_success() {
+ return Err(anyhow!(
+ "Twitch GQL token retornou HTTP {}",
+ response.status()
+ ));
+ }
+
+ let json: serde_json::Value = response.json().await?;
+
+ let token_obj = json
+ .as_array()
+ .and_then(|arr| arr.first())
+ .and_then(|r| r.pointer("/data/clip/playbackAccessToken"))
+ .ok_or_else(|| anyhow!("Access token not available for clip: {}", slug))?;
+
+ let signature = token_obj
+ .get("signature")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("Token sem signature"))?
+ .to_string();
+
+ let value = token_obj
+ .get("value")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("Token sem value"))?
+ .to_string();
+
+ Ok(AccessToken { signature, value })
+ }
+
+ fn build_authenticated_url(source_url: &str, token: &AccessToken) -> String {
+ format!(
+ "{}?sig={}&token={}",
+ source_url,
+ urlencoding::encode(&token.signature),
+ urlencoding::encode(&token.value),
+ )
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for TwitchClipsDownloader {
+ fn name(&self) -> &str {
+ "twitch"
+ }
+
+ 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();
+ let is_twitch = host == "twitch.tv" || host.ends_with(".twitch.tv");
+
+ if !is_twitch {
+ return false;
+ }
+
+ return Self::extract_clip_slug(url).is_some();
+ }
+ }
+ 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!(
+ "[twitch] 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.twitch.tv/")),
+ opts.cancel_token.clone(),
+ None,
+ opts.concurrent_fragments,
+ false,
+ &[],
+ opts.audio_format.as_deref(),
+ )
+ .await;
+ }
+ }
+
+ let first = info
+ .available_qualities
+ .first()
+ .ok_or_else(|| anyhow!("No media URL available"))?;
+
+ let selected = if let Some(ref wanted) = opts.quality {
+ info.available_qualities
+ .iter()
+ .find(|q| q.label == *wanted)
+ .unwrap_or(first)
+ } else {
+ first
+ };
+
+ let filename = format!(
+ "{}_{}.mp4",
+ sanitize_filename::sanitize(&info.title),
+ selected.label
+ );
+ let output_path = opts.output_dir.join(&filename);
+
+ let total_bytes = direct_downloader::download_direct(
+ &self.client,
+ &selected.url,
+ &output_path,
+ progress,
+ Some(&opts.cancel_token),
+ )
+ .await?;
+
+ Ok(DownloadResult {
+ file_path: output_path,
+ file_size_bytes: total_bytes,
+ duration_seconds: info.duration_seconds.unwrap_or(0.0),
+ torrent_id: None,
+ })
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/vimeo.rs b/src-tauri/omniget-core/src/platforms/vimeo.rs
new file mode 100644
index 00000000..2ee6fc43
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/vimeo.rs
@@ -0,0 +1,183 @@
+use crate::models::progress::ProgressUpdate;
+use crate::platforms::traits::PlatformDownloader;
+use std::collections::HashSet;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use crate::core::ytdlp;
+use crate::models::media::{
+ DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality as MediaVideoQuality,
+};
+
+pub struct VimeoDownloader;
+
+impl Default for VimeoDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl VimeoDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+
+ fn extract_quality_height(quality_str: &str) -> Option<u32> {
+ let s = quality_str.trim().to_lowercase();
+ if s == "best" || s == "highest" {
+ return None;
+ }
+ s.trim_end_matches('p').parse::<u32>().ok()
+ }
+
+ fn parse_video_info(json: &serde_json::Value) -> anyhow::Result<MediaInfo> {
+ let title = json
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("unknown")
+ .to_string();
+
+ let author = json
+ .get("uploader")
+ .or_else(|| json.get("channel"))
+ .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(|s| s.to_string());
+
+ let webpage_url = json
+ .get("webpage_url")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let mut qualities: Vec<MediaVideoQuality> = Vec::new();
+ let mut seen_heights: HashSet<u32> = HashSet::new();
+
+ if let Some(formats) = json.get("formats").and_then(|v| v.as_array()) {
+ for f in formats {
+ let height = f.get("height").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
+ let width = f.get("width").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
+ let vcodec = f.get("vcodec").and_then(|v| v.as_str()).unwrap_or("none");
+
+ if vcodec == "none" || height == 0 {
+ continue;
+ }
+
+ if seen_heights.insert(height) {
+ qualities.push(MediaVideoQuality {
+ label: format!("{}p", height),
+ width,
+ height,
+ url: webpage_url.clone(),
+ format: "ytdlp".to_string(),
+ });
+ }
+ }
+ }
+
+ qualities.sort_by(|a, b| b.height.cmp(&a.height));
+
+ if qualities.is_empty() {
+ qualities.push(MediaVideoQuality {
+ label: "best".to_string(),
+ width: 0,
+ height: 0,
+ url: webpage_url,
+ format: "ytdlp".to_string(),
+ });
+ }
+
+ Ok(MediaInfo {
+ title,
+ author,
+ platform: "vimeo".to_string(),
+ duration_seconds: duration,
+ thumbnail_url: thumbnail,
+ available_qualities: qualities,
+ media_type: MediaType::Video,
+ file_size_bytes: None,
+ })
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for VimeoDownloader {
+ fn name(&self) -> &str {
+ "vimeo"
+ }
+
+ 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 == "vimeo.com" || host.ends_with(".vimeo.com");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ let ytdlp_path = ytdlp::ensure_ytdlp().await.map_err(|e| {
+ anyhow!("Vimeo requires yt-dlp. Failed to get yt-dlp: {}", e)
+ })?;
+
+ let json = ytdlp::get_video_info(&ytdlp_path, url, &[]).await?;
+ Self::parse_video_info(&json)
+ }
+
+ async fn download(
+ &self,
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+ ) -> anyhow::Result<DownloadResult> {
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
+
+ let ytdlp_path = ytdlp::ensure_ytdlp().await?;
+
+ let first = info
+ .available_qualities
+ .first()
+ .ok_or_else(|| anyhow!("No quality available"))?;
+
+ let selected = if let Some(ref wanted) = opts.quality {
+ info.available_qualities
+ .iter()
+ .find(|q| q.label == *wanted)
+ .unwrap_or(first)
+ } else {
+ first
+ };
+
+ let quality_height = Self::extract_quality_height(&selected.label);
+ let video_url = &selected.url;
+
+ ytdlp::download_video(
+ &ytdlp_path,
+ video_url,
+ &opts.output_dir,
+ quality_height,
+ progress,
+ opts.download_mode.as_deref(),
+ opts.format_id.as_deref(),
+ opts.filename_template.as_deref(),
+ opts.referer.as_deref(),
+ opts.cancel_token.clone(),
+ None,
+ opts.concurrent_fragments,
+ false,
+ &[],
+ opts.audio_format.as_deref(),
+ )
+ .await
+ }
+}
diff --git a/src-tauri/src/commands/p2p.rs b/src-tauri/src/commands/p2p.rs
index b8efb729..8180681b 100644
--- a/src-tauri/src/commands/p2p.rs
+++ b/src-tauri/src/commands/p2p.rs
@@ -2,7 +2,7 @@ use serde::Serialize;
use tauri::Emitter;
use tokio_util::sync::CancellationToken;
-use crate::platforms::p2p;
+use omniget_core::platforms::p2p;
use crate::{AppState, P2pSendHandle};
#[derive(Clone, Serialize)]
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 1d4b4639..cf8a5b14 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -46,21 +46,21 @@ pub fn run() {
registry.register(Arc::new(platforms::pinterest::PinterestDownloader::new()));
registry.register(Arc::new(platforms::tiktok::TikTokDownloader::new()));
registry.register(Arc::new(platforms::twitter::TwitterDownloader::new()));
- registry.register(Arc::new(platforms::twitch::TwitchClipsDownloader::new()));
- registry.register(Arc::new(platforms::bluesky::BlueskyDownloader::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::YouTubeDownloader::new()));
- registry.register(Arc::new(platforms::vimeo::VimeoDownloader::new()));
+ registry.register(Arc::new(omniget_core::platforms::VimeoDownloader::new()));
registry.register(Arc::new(platforms::bilibili::BilibiliDownloader::new()));
- registry.register(Arc::new(platforms::douyin::DouyinDownloader::new()));
+ registry.register(Arc::new(omniget_core::platforms::DouyinDownloader::new()));
let torrent_session: Arc<tokio::sync::Mutex<Option<Arc<librqbit::Session>>>> =
Arc::new(tokio::sync::Mutex::new(None));
registry.register(Arc::new(platforms::magnet::MagnetDownloader::new(
torrent_session.clone(),
)));
- registry.register(Arc::new(platforms::p2p::P2pDownloader::new()));
+ registry.register(Arc::new(omniget_core::platforms::P2pDownloader::new()));
registry.register(Arc::new(platforms::gallerydl::GalleryDlDownloader::new()));
- registry.register(Arc::new(platforms::direct_file::DirectFileDownloader::new()));
+ registry.register(Arc::new(omniget_core::platforms::DirectFileDownloader::new()));
registry.register(Arc::new(
platforms::generic_ytdlp::GenericYtdlpDownloader::new(),
));
diff --git a/src-tauri/src/platforms/mod.rs b/src-tauri/src/platforms/mod.rs
index 9a652d7e..b163750e 100644
--- a/src-tauri/src/platforms/mod.rs
+++ b/src-tauri/src/platforms/mod.rs
@@ -1,32 +1,29 @@
pub use omniget_core::platforms::traits;
pub use omniget_core::platforms::Platform;
+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 crate::platforms::magnet::MagnetDownloader;
+pub use omniget_core::platforms::P2pDownloader;
+pub use omniget_core::platforms::TwitchClipsDownloader;
+pub use omniget_core::platforms::VimeoDownloader;
pub use omniget_core::platforms::YouTubeDownloader;
-pub mod bluesky;
-pub mod direct_file;
pub mod noop;
pub mod pinterest;
pub mod tiktok;
-pub mod twitch;
pub mod twitter;
#[cfg(not(target_os = "android"))]
pub mod bilibili;
#[cfg(not(target_os = "android"))]
-pub mod douyin;
-#[cfg(not(target_os = "android"))]
pub mod gallerydl;
#[cfg(not(target_os = "android"))]
pub mod generic_ytdlp;
#[cfg(not(target_os = "android"))]
pub mod instagram;
-pub mod magnet;
-pub mod p2p;
#[cfg(not(target_os = "android"))]
pub mod reddit;
-#[cfg(not(target_os = "android"))]
-pub mod vimeo;
-// YouTube now lives in omniget-core
-// #[cfg(not(target_os = "android"))]
-// pub mod youtube;
+pub mod magnet;
+// Ported to omniget-core: bluesky, direct_file, douyin, p2p, twitch, vimeo, youtube