Skip to content

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

feat: add VoompPlay platform support with downloader and API integration

Tonhoffa06374283a
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/cakto/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/cakto/mod.rs
new file mode 100644
index 00000000..f2f1ef36
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/cakto/mod.rs
@@ -0,0 +1,70 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct CaktoDownloader;
+
+impl Default for CaktoDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl CaktoDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for CaktoDownloader {
+ fn name(&self) -> &str {
+ "cakto"
+ }
+
+ 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 == "cakto.com.br"
+ || host == "aluno.cakto.com.br"
+ || host == "app.cakto.com.br";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Cakto".to_string(),
+ author: String::new(),
+ platform: "cakto".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: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Cakto"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/api.rs
new file mode 100644
index 00000000..bf858fce
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/api.rs
@@ -0,0 +1,408 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const API_BASE: &str = "https://api.cakto.com.br";
+
+#[derive(Clone)]
+pub struct CaktoMembersSession {
+ pub cookie: String,
+ pub access_token: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub cookie: String,
+ pub access_token: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CaktoMembersCourse {
+ pub id: String,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CaktoMembersModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<CaktoMembersLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CaktoMembersLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub video_uuid: Option<String>,
+ pub description: Option<String>,
+}
+
+fn build_client(access_token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", access_token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static("https://app.cakto.com.br"),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://app.cakto.com.br/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn build_cookie_client(cookie: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Cookie",
+ HeaderValue::from_str(&format!("sessionid={}", cookie))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("caktomembers_session.json"))
+}
+
+pub async fn fetch_access_token(cookie: &str) -> anyhow::Result<String> {
+ let cookie_client = build_cookie_client(cookie)?;
+
+ let url = format!("{}/api/members/courses/token/", API_BASE);
+ let resp = cookie_client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "fetch_access_token returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let token = body
+ .get("accessToken")
+ .or_else(|| body.get("access_token"))
+ .or_else(|| body.get("token"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("No accessToken in response"))?
+ .to_string();
+
+ Ok(token)
+}
+
+pub async fn validate_token(session: &CaktoMembersSession) -> anyhow::Result<bool> {
+ let url = format!("{}/api/members/courses/", API_BASE);
+ let resp = session.client.get(&url).send().await?;
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &CaktoMembersSession) -> anyhow::Result<Vec<CaktoMembersCourse>> {
+ let url = format!("{}/api/members/courses/", API_BASE);
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let courses_arr = if body.is_array() {
+ body.as_array().cloned().unwrap_or_default()
+ } else {
+ body.get("results")
+ .or_else(|| body.get("courses"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default()
+ };
+
+ let mut courses = Vec::new();
+
+ for item in &courses_arr {
+ let id = item
+ .get("externalId")
+ .or_else(|| item.get("id"))
+ .map(|v| match v {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let name = item
+ .get("nome")
+ .or_else(|| item.get("name"))
+ .or_else(|| item.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if !id.is_empty() {
+ courses.push(CaktoMembersCourse { id, name });
+ }
+
+ if let Some(modulos) = item.get("modulos").and_then(|v| v.as_array()) {
+ let _ = modulos;
+ }
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_course_content(
+ session: &CaktoMembersSession,
+ course_id: &str,
+) -> anyhow::Result<Vec<CaktoMembersModule>> {
+ let url = format!("{}/api/members/courses/", API_BASE);
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let courses_arr = if body.is_array() {
+ body.as_array().cloned().unwrap_or_default()
+ } else {
+ body.get("results")
+ .or_else(|| body.get("courses"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default()
+ };
+
+ let course_data = courses_arr
+ .iter()
+ .find(|c| {
+ let eid = c.get("externalId").or_else(|| c.get("id"));
+ if let Some(v) = eid {
+ match v {
+ serde_json::Value::String(s) => s == course_id,
+ serde_json::Value::Number(n) => n.to_string() == course_id,
+ _ => false,
+ }
+ } else {
+ false
+ }
+ })
+ .ok_or_else(|| anyhow!("Course not found in response"))?;
+
+ let modulos = course_data
+ .get("modulos")
+ .or_else(|| course_data.get("modules"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for (mi, mod_val) in modulos.iter().enumerate() {
+ let mod_id = mod_val
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => format!("{}", mi),
+ })
+ .unwrap_or_else(|| format!("{}", mi));
+
+ let mod_name = mod_val
+ .get("nome")
+ .or_else(|| mod_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let aulas = mod_val
+ .get("aulas")
+ .or_else(|| mod_val.get("lessons"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (li, lesson_val) in aulas.iter().enumerate() {
+ let lesson_id = lesson_val
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => format!("{}", li),
+ })
+ .unwrap_or_else(|| format!("{}", li));
+
+ let lesson_name = lesson_val
+ .get("nome")
+ .or_else(|| lesson_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let video_uuid = lesson_val
+ .get("video")
+ .or_else(|| lesson_val.get("video_uuid"))
+ .or_else(|| lesson_val.get("videoUuid"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let description = lesson_val
+ .get("descricao")
+ .or_else(|| lesson_val.get("description"))
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .map(String::from);
+
+ lessons.push(CaktoMembersLesson {
+ id: lesson_id,
+ name: lesson_name,
+ order: li as i64,
+ video_uuid,
+ description,
+ });
+ }
+
+ modules.push(CaktoMembersModule {
+ id: mod_id,
+ name: mod_name,
+ order: mi as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_lesson_video_url(
+ session: &CaktoMembersSession,
+ lesson_id: &str,
+ video_uuid: Option<&str>,
+) -> anyhow::Result<Option<String>> {
+ if let Some(uuid) = video_uuid {
+ if !uuid.is_empty() {
+ let hls_url = format!("https://stream.cakto.com.br/{}/playlist.m3u8", uuid);
+ return Ok(Some(hls_url));
+ }
+ }
+
+ let url = format!(
+ "https://us-central1-cakto2.cloudfunctions.net/api/aulas/{}/assistir",
+ lesson_id
+ );
+ let resp = session.client.get(&url).send().await?;
+
+ if resp.status().is_success() {
+ let body_text = resp.text().await?;
+ if let Ok(body) = serde_json::from_str::<serde_json::Value>(&body_text) {
+ if let Some(url) = body.get("video_url")
+ .or_else(|| body.get("url"))
+ .or_else(|| body.get("videoUrl"))
+ .and_then(|v| v.as_str())
+ {
+ return Ok(Some(url.to_string()));
+ }
+ }
+ }
+
+ Ok(None)
+}
+
+pub async fn save_session(session: &CaktoMembersSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ cookie: session.cookie.clone(),
+ access_token: session.access_token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[caktomembers] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<CaktoMembersSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.access_token)?;
+
+ tracing::info!("[caktomembers] session loaded");
+
+ Ok(Some(CaktoMembersSession {
+ cookie: saved.cookie,
+ access_token: saved.access_token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/downloader.rs
new file mode 100644
index 00000000..ee5c552e
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/downloader.rs
@@ -0,0 +1,275 @@
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, CaktoMembersCourse, CaktoMembersSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct CaktoMembersDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &CaktoMembersSession,
+ course: &CaktoMembersCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, &course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[caktomembers] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &CaktoMembersDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+
+ if let Some(ref desc) = lesson.description {
+ let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_desc_dir).await?;
+ omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
+ }
+
+ let video_url = match api::get_lesson_video_url(session, &lesson.id, lesson.video_uuid.as_deref()).await {
+ Ok(Some(url)) => url,
+ Ok(None) => {
+ tracing::warn!("[caktomembers] No video found for lesson '{}'", lesson.name);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &CaktoMembersDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ Err(e) => {
+ tracing::error!("[caktomembers] Failed to get video URL for '{}': {}", lesson.name, e);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &CaktoMembersDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[caktomembers] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &CaktoMembersDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(&video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[caktomembers] HLS download failed for '{}': {}", lesson.name, e);
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[caktomembers] yt-dlp download failed for '{}': {}", lesson.name, e);
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &CaktoMembersDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://app.cakto.com.br/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = std::path::Path::new(output_dir);
+ let (tx, _rx) = tokio::sync::mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://app.cakto.com.br/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/mod.rs
new file mode 100644
index 00000000..fac3e892
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/mod.rs
@@ -0,0 +1,68 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct CaktoMembersDownloader;
+
+impl Default for CaktoMembersDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl CaktoMembersDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for CaktoMembersDownloader {
+ fn name(&self) -> &str {
+ "caktomembers"
+ }
+
+ 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 == "app.cakto.com.br";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Cakto Members".to_string(),
+ author: String::new(),
+ platform: "caktomembers".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Cakto Members courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/curseduca/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/curseduca/api.rs
new file mode 100644
index 00000000..b812d5b4
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/curseduca/api.rs
@@ -0,0 +1,514 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct CurseducaSession {
+ pub token: String,
+ pub api_key: String,
+ pub site_url: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub api_key: String,
+ pub site_url: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CurseducaCourse {
+ pub id: String,
+ pub name: String,
+ pub slug: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CurseducaModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<CurseducaLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CurseducaLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub uuid: Option<String>,
+ pub video_type: Option<i64>,
+ pub description: Option<String>,
+}
+
+fn build_client(token: &str, api_key: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert(
+ "api_key",
+ HeaderValue::from_str(api_key)?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("curseduca_session.json"))
+}
+
+pub async fn discover_api_key(site_url: &str) -> anyhow::Result<String> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let clean_url = site_url.trim_end_matches('/');
+
+ let resp = temp_client
+ .get("https://application.curseduca.pro/platform-by-url")
+ .query(&[("url", clean_url)])
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "discover_api_key returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let key = body
+ .get("key")
+ .or_else(|| body.get("apiKey"))
+ .or_else(|| body.get("api_key"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("No API key in platform discovery response"))?
+ .to_string();
+
+ Ok(key)
+}
+
+pub async fn authenticate(site_url: &str, username: &str, password: &str) -> anyhow::Result<CurseducaSession> {
+ let api_key = discover_api_key(site_url).await?;
+
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "username": username,
+ "password": password,
+ });
+
+ let resp = temp_client
+ .post("https://prof.curseduca.pro/login")
+ .header("api_key", &api_key)
+ .header("Content-Type", "application/json")
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Authentication failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let token = body
+ .get("accessToken")
+ .or_else(|| body.get("token"))
+ .or_else(|| body.get("access_token"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("No access token in login response"))?
+ .to_string();
+
+ let client = build_client(&token, &api_key)?;
+
+ Ok(CurseducaSession {
+ token,
+ api_key,
+ site_url: site_url.to_string(),
+ client,
+ })
+}
+
+pub async fn validate_token(session: &CurseducaSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://prof.curseduca.pro/me/access")
+ .send()
+ .await?;
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &CurseducaSession) -> anyhow::Result<Vec<CurseducaCourse>> {
+ let resp = session
+ .client
+ .get("https://prof.curseduca.pro/me/access")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let courses_arr = if body.is_array() {
+ body.as_array().cloned().unwrap_or_default()
+ } else {
+ body.get("courses")
+ .or_else(|| body.get("data"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default()
+ };
+
+ let mut courses = Vec::new();
+
+ for item in &courses_arr {
+ let id = item
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let name = item
+ .get("name")
+ .or_else(|| item.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let slug = item
+ .get("slug")
+ .and_then(|v| v.as_str())
+ .unwrap_or(&id)
+ .to_string();
+
+ if !id.is_empty() {
+ courses.push(CurseducaCourse { id, name, slug });
+ }
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_course_content(
+ session: &CurseducaSession,
+ course_slug: &str,
+) -> anyhow::Result<Vec<CurseducaModule>> {
+ let url = format!("{}/m/lessons/{}", session.site_url.trim_end_matches('/'), course_slug);
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let mut modules = Vec::new();
+ let mut module_order = 0i64;
+
+ let mut search_pos = 0;
+ while let Some(script_start) = body_text[search_pos..].find("<script") {
+ let abs_start = search_pos + script_start;
+ if let Some(script_end) = body_text[abs_start..].find("</script>") {
+ let script_content = &body_text[abs_start..abs_start + script_end];
+ search_pos = abs_start + script_end + 9;
+
+ if script_content.contains("modules") || script_content.contains("lessons") {
+ if let Some(json_start) = script_content.find('{') {
+ let json_str = &script_content[json_start..];
+ if let Some(end) = find_matching_brace(json_str) {
+ if let Ok(data) = serde_json::from_str::<serde_json::Value>(&json_str[..=end]) {
+ if let Some(mods) = extract_modules_from_data(&data) {
+ for m in mods {
+ modules.push(m);
+ }
+ }
+ }
+ }
+ }
+ }
+ } else {
+ break;
+ }
+ }
+
+ if modules.is_empty() {
+ if let Ok(data) = serde_json::from_str::<serde_json::Value>(&body_text) {
+ if let Some(mods) = extract_modules_from_data(&data) {
+ modules = mods;
+ }
+ }
+ }
+
+ for m in &mut modules {
+ module_order += 1;
+ m.order = module_order;
+ }
+
+ Ok(modules)
+}
+
+fn find_matching_brace(s: &str) -> Option<usize> {
+ let mut depth = 0i32;
+ for (i, ch) in s.char_indices() {
+ match ch {
+ '{' => depth += 1,
+ '}' => {
+ depth -= 1;
+ if depth == 0 {
+ return Some(i);
+ }
+ }
+ _ => {}
+ }
+ }
+ None
+}
+
+fn extract_modules_from_data(data: &serde_json::Value) -> Option<Vec<CurseducaModule>> {
+ let modules_arr = data.get("modules")
+ .or_else(|| data.get("content"))
+ .and_then(|v| v.as_array())?;
+
+ let mut modules = Vec::new();
+
+ for (mi, mod_val) in modules_arr.iter().enumerate() {
+ let mod_id = mod_val.get("id")
+ .map(|v| match v {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => format!("{}", mi),
+ })
+ .unwrap_or_else(|| format!("{}", mi));
+
+ let mod_name = mod_val.get("name")
+ .or_else(|| mod_val.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lessons_arr = mod_val.get("lessons")
+ .or_else(|| mod_val.get("aulas"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (li, lesson_val) in lessons_arr.iter().enumerate() {
+ let lesson_id = lesson_val.get("id")
+ .map(|v| match v {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => format!("{}", li),
+ })
+ .unwrap_or_else(|| format!("{}", li));
+
+ let lesson_name = lesson_val.get("name")
+ .or_else(|| lesson_val.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let uuid = lesson_val.get("uuid")
+ .or_else(|| lesson_val.get("externalId"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let video_type = lesson_val.get("type")
+ .or_else(|| lesson_val.get("videoType"))
+ .and_then(|v| v.as_i64());
+
+ let description = lesson_val.get("description")
+ .or_else(|| lesson_val.get("content"))
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .map(String::from);
+
+ lessons.push(CurseducaLesson {
+ id: lesson_id,
+ name: lesson_name,
+ order: li as i64,
+ uuid,
+ video_type,
+ description,
+ });
+ }
+
+ modules.push(CurseducaModule {
+ id: mod_id,
+ name: mod_name,
+ order: mi as i64,
+ lessons,
+ });
+ }
+
+ Some(modules)
+}
+
+pub async fn get_lesson_video_url(
+ session: &CurseducaSession,
+ lesson_uuid: &str,
+) -> anyhow::Result<Option<String>> {
+ let url = format!("https://clas.curseduca.pro/bff/aulas/{}/watch", lesson_uuid);
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lesson_video_url returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let video_url = body
+ .get("url")
+ .or_else(|| body.get("videoUrl"))
+ .or_else(|| body.get("video_url"))
+ .or_else(|| body.get("playbackUrl"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ if video_url.is_some() {
+ return Ok(video_url);
+ }
+
+ let video_type = body.get("type").and_then(|v| v.as_i64()).unwrap_or(0);
+
+ match video_type {
+ 4 => {
+ if let Some(vid_id) = body.get("externalId").or_else(|| body.get("videoId")).and_then(|v| v.as_str()) {
+ return Ok(Some(format!("https://www.youtube.com/watch?v={}", vid_id)));
+ }
+ }
+ 7 => {
+ if let Some(vid_id) = body.get("externalId").or_else(|| body.get("videoId")).and_then(|v| v.as_str()) {
+ return Ok(Some(format!("https://player.vimeo.com/video/{}", vid_id)));
+ }
+ }
+ 20 => {
+ if let Some(hls) = body.get("hlsUrl").or_else(|| body.get("streamUrl")).and_then(|v| v.as_str()) {
+ return Ok(Some(hls.to_string()));
+ }
+ }
+ 22 => {
+ if let Some(url) = body.get("scaleupUrl").or_else(|| body.get("playerUrl")).and_then(|v| v.as_str()) {
+ return Ok(Some(url.to_string()));
+ }
+ }
+ _ => {}
+ }
+
+ Ok(None)
+}
+
+pub async fn save_session(session: &CurseducaSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ api_key: session.api_key.clone(),
+ site_url: session.site_url.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[curseduca] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<CurseducaSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token, &saved.api_key)?;
+
+ tracing::info!("[curseduca] session loaded");
+
+ Ok(Some(CurseducaSession {
+ token: saved.token,
+ api_key: saved.api_key,
+ site_url: saved.site_url,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/curseduca/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/curseduca/downloader.rs
new file mode 100644
index 00000000..aa7a24eb
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/curseduca/downloader.rs
@@ -0,0 +1,279 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, CurseducaCourse, CurseducaSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct CurseducaDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &CurseducaSession,
+ course: &CurseducaCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, &course.slug).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[curseduca] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &CurseducaDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+
+ if let Some(ref desc) = lesson.description {
+ let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_desc_dir).await?;
+ omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
+ }
+
+ let lesson_uuid = lesson.uuid.as_deref().unwrap_or(&lesson.id);
+
+ let video_url = match api::get_lesson_video_url(session, lesson_uuid).await {
+ Ok(Some(url)) => url,
+ Ok(None) => {
+ tracing::warn!("[curseduca] No video found for lesson '{}'", lesson.name);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &CurseducaDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ Err(e) => {
+ tracing::error!("[curseduca] Failed to get video URL for '{}': {}", lesson.name, e);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &CurseducaDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[curseduca] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &CurseducaDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(&video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[curseduca] HLS download failed for '{}': {}", lesson.name, e);
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[curseduca] yt-dlp download failed for '{}': {}", lesson.name, e);
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &CurseducaDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ None,
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/curseduca/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/curseduca/mod.rs
new file mode 100644
index 00000000..cdc5196d
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/curseduca/mod.rs
@@ -0,0 +1,70 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct CurseducaDownloader;
+
+impl Default for CurseducaDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl CurseducaDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for CurseducaDownloader {
+ fn name(&self) -> &str {
+ "curseduca"
+ }
+
+ 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 == "curseduca.pro"
+ || host.ends_with(".curseduca.pro")
+ || host == "curseduca.com";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Curseduca Course".to_string(),
+ author: String::new(),
+ platform: "curseduca".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Curseduca courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/api.rs
new file mode 100644
index 00000000..1a940e4a
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/api.rs
@@ -0,0 +1,402 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const API_BASE: &str = "https://www.datascienceacademy.com.br";
+
+#[derive(Clone)]
+pub struct DsaSession {
+ pub token: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DsaCourse {
+ pub id: String,
+ pub name: String,
+ pub slug: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DsaModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<DsaLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DsaLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub item_type: String,
+ pub vimeo_id: Option<String>,
+ pub description: Option<String>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Token",
+ HeaderValue::from_str(token)?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static(API_BASE),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_str(&format!("{}/", API_BASE))?,
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("dsa_session.json"))
+}
+
+pub async fn validate_token(session: &DsaSession) -> anyhow::Result<bool> {
+ let url = format!("{}/api/products_all", API_BASE);
+
+ let resp = session.client.get(&url).send().await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &DsaSession) -> anyhow::Result<Vec<DsaCourse>> {
+ let url = format!("{}/api/products_all", API_BASE);
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let courses_map = body
+ .get("courses")
+ .and_then(|v| v.as_object())
+ .cloned()
+ .unwrap_or_default();
+
+ let allowed_ids: Vec<String> = body
+ .get("allowedCourseIds")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
+ .collect()
+ })
+ .unwrap_or_default();
+
+ let mut enrolled_ids: Vec<String> = Vec::new();
+ let progress_url = format!("{}/api/user/courses-progress", API_BASE);
+ if let Ok(progress_resp) = session.client.get(&progress_url).send().await {
+ if progress_resp.status().is_success() {
+ if let Ok(progress_text) = progress_resp.text().await {
+ if let Ok(progress_body) = serde_json::from_str::<serde_json::Value>(&progress_text) {
+ if let Some(user_courses) = progress_body.get("userCourses").and_then(|v| v.as_array()) {
+ for uc in user_courses {
+ let me = uc.get("me").unwrap_or(&serde_json::Value::Null);
+ let is_premium = me.get("premium").and_then(|v| v.as_bool()).unwrap_or(false);
+ let is_registered = me.get("registered").and_then(|v| v.as_bool()).unwrap_or(false);
+ if is_premium || is_registered {
+ if let Some(cid) = uc.get("courseId") {
+ enrolled_ids.push(cid.to_string().trim_matches('"').to_string());
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ let mut result = Vec::new();
+
+ for (cid, course) in &courses_map {
+ let me = course.get("me").unwrap_or(&serde_json::Value::Null);
+ let course_id = course
+ .get("id")
+ .map(|v| v.to_string().trim_matches('"').to_string())
+ .unwrap_or_else(|| cid.clone());
+
+ let is_registered = me.get("registered").and_then(|v| v.as_bool()).unwrap_or(false);
+ let is_allowed = allowed_ids.contains(&course_id) || allowed_ids.contains(cid);
+ let is_free = course.get("status").and_then(|v| v.as_str()) == Some("free");
+ let is_enrolled = enrolled_ids.contains(&course_id);
+
+ if !is_registered && !is_allowed && !is_free && !is_enrolled {
+ continue;
+ }
+
+ let name = course
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Course")
+ .to_string();
+
+ let slug = course
+ .get("titleId")
+ .and_then(|v| v.as_str())
+ .unwrap_or(cid)
+ .to_string();
+
+ result.push(DsaCourse {
+ id: course_id,
+ name,
+ slug,
+ });
+ }
+
+ result.sort_by(|a, b| a.name.cmp(&b.name));
+
+ Ok(result)
+}
+
+pub async fn get_course_content(
+ session: &DsaSession,
+ slug: &str,
+) -> anyhow::Result<Vec<DsaModule>> {
+ let url = format!("{}/api/course/{}?contents", API_BASE, slug);
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let course_data = body.get("course").unwrap_or(&body);
+ let sections = course_data.get("sections");
+ let videos = course_data
+ .get("videos")
+ .and_then(|v| v.as_object())
+ .cloned()
+ .unwrap_or_default();
+
+ let sections_list: Vec<serde_json::Value> = match sections {
+ Some(serde_json::Value::Object(map)) => map.values().cloned().collect(),
+ Some(serde_json::Value::Array(arr)) => arr.clone(),
+ _ => Vec::new(),
+ };
+
+ let mut modules = Vec::new();
+
+ for (section_index, section) in sections_list.iter().enumerate() {
+ let title = resolve_title(
+ section.get("titles").or_else(|| section.get("title")),
+ &format!("Module {}", section_index + 1),
+ );
+
+ let learning_path = section
+ .get("learningPath")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (lesson_index, item) in learning_path.iter().enumerate() {
+ let unit_id = item
+ .get("id")
+ .map(|v| v.to_string().trim_matches('"').to_string())
+ .unwrap_or_else(|| format!("{}-{}", section_index + 1, lesson_index + 1));
+
+ let unit_type = item
+ .get("type")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_lowercase();
+
+ let mut lesson_title = String::new();
+
+ if (unit_type == "ivideo" || unit_type == "video") && videos.contains_key(&unit_id) {
+ if let Some(vid) = videos.get(&unit_id) {
+ lesson_title = vid
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ }
+ }
+
+ if lesson_title.is_empty() || lesson_title == "Untitled" {
+ lesson_title = resolve_title(
+ item.get("titles").or_else(|| item.get("unitTitle")),
+ &format!("Lesson {}", lesson_index + 1),
+ );
+ }
+
+ let vimeo_id = if (unit_type == "ivideo" || unit_type == "video") && videos.contains_key(&unit_id) {
+ videos
+ .get(&unit_id)
+ .and_then(|vid| vid.get("vimeoid"))
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ } else {
+ None
+ };
+
+ let description = item
+ .get("description")
+ .or_else(|| item.get("content"))
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .map(String::from);
+
+ lessons.push(DsaLesson {
+ id: unit_id,
+ name: lesson_title,
+ order: (lesson_index + 1) as i64,
+ item_type: unit_type,
+ vimeo_id,
+ description,
+ });
+ }
+
+ let section_id = section
+ .get("titleId")
+ .or_else(|| section.get("id"))
+ .map(|v| v.to_string().trim_matches('"').to_string())
+ .unwrap_or_else(|| format!("{}", section_index + 1));
+
+ modules.push(DsaModule {
+ id: section_id,
+ name: title,
+ order: (section_index + 1) as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+fn resolve_title(raw: Option<&serde_json::Value>, fallback: &str) -> String {
+ match raw {
+ Some(serde_json::Value::Object(map)) => {
+ for key in &["pt-BR", "pt", "en", "title"] {
+ if let Some(val) = map.get(*key).and_then(|v| v.as_str()) {
+ let trimmed = val.trim();
+ if !trimmed.is_empty() {
+ return trimmed.to_string();
+ }
+ }
+ }
+ for val in map.values() {
+ if let Some(s) = val.as_str() {
+ let trimmed = s.trim();
+ if !trimmed.is_empty() {
+ return trimmed.to_string();
+ }
+ }
+ }
+ fallback.to_string()
+ }
+ Some(serde_json::Value::Array(arr)) => {
+ for entry in arr {
+ if let Some(s) = entry.as_str() {
+ let trimmed = s.trim();
+ if !trimmed.is_empty() {
+ return trimmed.to_string();
+ }
+ }
+ }
+ fallback.to_string()
+ }
+ Some(serde_json::Value::String(s)) => {
+ let trimmed = s.trim();
+ if !trimmed.is_empty() {
+ trimmed.to_string()
+ } else {
+ fallback.to_string()
+ }
+ }
+ _ => fallback.to_string(),
+ }
+}
+
+pub async fn save_session(session: &DsaSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[dsa] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<DsaSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[dsa] session loaded");
+
+ Ok(Some(DsaSession {
+ token: saved.token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/downloader.rs
new file mode 100644
index 00000000..e1ba0c22
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/downloader.rs
@@ -0,0 +1,228 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, DsaCourse, DsaSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct DsaCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &DsaSession,
+ course: &DsaCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, &course.slug).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[dsa] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &DsaCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+
+ if let Some(ref desc) = lesson.description {
+ let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_desc_dir).await?;
+ omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
+ }
+
+ if lesson.item_type == "ivideo" || lesson.item_type == "video" {
+ if let Some(ref vimeo_id) = lesson.vimeo_id {
+ if vimeo_id.is_empty() {
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &DsaCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[dsa] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &DsaCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ let vimeo_url = format!("https://player.vimeo.com/video/{}", vimeo_id);
+
+ match download_with_ytdlp(&vimeo_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[dsa] yt-dlp download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &DsaCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://www.datascienceacademy.com.br/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/mod.rs
new file mode 100644
index 00000000..14239aa6
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/mod.rs
@@ -0,0 +1,69 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct DataScienceAcademyDownloader;
+
+impl Default for DataScienceAcademyDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl DataScienceAcademyDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for DataScienceAcademyDownloader {
+ fn name(&self) -> &str {
+ "datascienceacademy"
+ }
+
+ 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 == "datascienceacademy.com.br"
+ || host == "www.datascienceacademy.com.br";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Data Science Academy".to_string(),
+ author: String::new(),
+ platform: "datascienceacademy".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: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Data Science Academy"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/api.rs
new file mode 100644
index 00000000..ed82c72f
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/api.rs
@@ -0,0 +1,582 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct NutrorSession {
+ pub token: String,
+ pub refresh_token: Option<String>,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub refresh_token: Option<String>,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct NutrorCourse {
+ pub id: String,
+ pub name: String,
+ pub hash: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct NutrorModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<NutrorLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct NutrorLesson {
+ pub id: String,
+ pub name: String,
+ pub hash: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct NutrorLessonDetail {
+ pub id: String,
+ pub name: String,
+ pub video_url: Option<String>,
+ pub files: Vec<NutrorFile>,
+ pub description: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct NutrorFile {
+ pub name: String,
+ pub url: String,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert("FrontVersion", HeaderValue::from_static("1458"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("nutror_session.json"))
+}
+
+pub async fn refresh_token(session: &NutrorSession) -> anyhow::Result<NutrorSession> {
+ let refresh = session
+ .refresh_token
+ .as_deref()
+ .ok_or_else(|| anyhow!("No refresh token available"))?;
+
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let resp = temp_client
+ .post("https://learner-api.nutror.com/oauth/refresh?startWhen=requestFailed")
+ .header("Authorization", format!("Bearer {}", session.token))
+ .header("RefreshToken", refresh)
+ .header("Accept", "application/json")
+ .header("FrontVersion", "1458")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Token refresh failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let new_token = body
+ .get("token")
+ .or_else(|| body.get("access_token"))
+ .or_else(|| body.get("newAuthToken"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("No token in refresh response"))?
+ .to_string();
+
+ let new_refresh = body
+ .get("refreshToken")
+ .or_else(|| body.get("refresh_token"))
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ .or_else(|| session.refresh_token.clone());
+
+ let client = build_client(&new_token)?;
+
+ Ok(NutrorSession {
+ token: new_token,
+ refresh_token: new_refresh,
+ client,
+ })
+}
+
+pub async fn validate_token(session: &NutrorSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://learner-api.nutror.com/learner/course/search?page=1&size=1&status=seeAll&showShelf=true")
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &NutrorSession) -> anyhow::Result<Vec<NutrorCourse>> {
+ let mut all_courses = Vec::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!(
+ "https://learner-api.nutror.com/learner/course/search?page={}&size=20&status=seeAll&showShelf=true",
+ page
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let data = body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ if data.is_empty() {
+ break;
+ }
+
+ for item in &data {
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
+ .unwrap_or_default();
+
+ let name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let hash = item
+ .get("hash")
+ .or_else(|| item.get("courseHash"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ all_courses.push(NutrorCourse {
+ id,
+ name,
+ hash,
+ });
+ }
+
+ let total_pages = body
+ .get("totalPages")
+ .or_else(|| body.get("total_pages"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(1);
+
+ if page as u64 >= total_pages {
+ break;
+ }
+
+ page += 1;
+ }
+
+ Ok(all_courses)
+}
+
+pub async fn get_modules(
+ session: &NutrorSession,
+ course_hash: &str,
+) -> anyhow::Result<Vec<NutrorModule>> {
+ let url = format!(
+ "https://learner-api.nutror.com/learner/course/{}/lessons/v2",
+ course_hash
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_modules returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let data = body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_else(|| {
+ body.as_array().cloned().unwrap_or_default()
+ });
+
+ let mut modules = Vec::new();
+
+ for (i, item) in data.iter().enumerate() {
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
+ .unwrap_or_default();
+
+ let name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let order = item
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(i as i64);
+
+ let mut lessons = Vec::new();
+
+ let lessons_arr = item
+ .get("lessons")
+ .or_else(|| item.get("items"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for (j, lesson_val) in lessons_arr.iter().enumerate() {
+ let lesson_id = lesson_val
+ .get("id")
+ .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
+ .unwrap_or_default();
+
+ let lesson_name = lesson_val
+ .get("title")
+ .or_else(|| lesson_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_hash = lesson_val
+ .get("hash")
+ .or_else(|| lesson_val.get("lessonHash"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_order = lesson_val
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(j as i64);
+
+ lessons.push(NutrorLesson {
+ id: lesson_id,
+ name: lesson_name,
+ hash: lesson_hash,
+ order: lesson_order,
+ });
+ }
+
+ lessons.sort_by_key(|l| l.order);
+
+ modules.push(NutrorModule {
+ id,
+ name,
+ order,
+ lessons,
+ });
+ }
+
+ modules.sort_by_key(|m| m.order);
+
+ Ok(modules)
+}
+
+pub async fn get_lesson_detail(
+ session: &NutrorSession,
+ lesson_hash: &str,
+) -> anyhow::Result<NutrorLessonDetail> {
+ let url = format!(
+ "https://learner-api.nutror.com/learner/lessons/{}",
+ lesson_hash
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lesson_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let lesson = body.get("data").unwrap_or(&body);
+
+ let id = lesson
+ .get("id")
+ .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
+ .unwrap_or_default();
+
+ let name = lesson
+ .get("title")
+ .or_else(|| lesson.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let mut video_url: Option<String> = None;
+ let mut files = Vec::new();
+ let mut description: Option<String> = None;
+
+ let contents = lesson
+ .get("contents")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for content in &contents {
+ let type_obj = content.get("type");
+ let type_id = type_obj
+ .and_then(|t| t.get("id").and_then(|v| v.as_i64()))
+ .unwrap_or(0);
+
+ let embed = content
+ .get("content")
+ .or_else(|| content.get("embed"))
+ .or_else(|| content.get("url"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if type_id == 4 && description.is_none() && !embed.trim().is_empty() {
+ description = Some(embed.to_string());
+ }
+
+ if video_url.is_none() {
+ match type_id {
+ 1 => {
+ let yt_id = extract_youtube_id(embed);
+ if let Some(yt_id) = yt_id {
+ video_url = Some(format!("https://www.youtube.com/watch?v={}", yt_id));
+ }
+ }
+ 9 => {
+ let safe_url = extract_safevideo_url(embed);
+ if let Some(url) = safe_url {
+ video_url = Some(url);
+ }
+ }
+ _ => {
+ if embed.contains("youtube.com") || embed.contains("youtu.be") {
+ video_url = Some(embed.to_string());
+ } else if embed.contains("vimeo.com") {
+ video_url = Some(embed.to_string());
+ } else if embed.contains(".mp4") || embed.contains(".m3u8") {
+ video_url = Some(embed.to_string());
+ }
+ }
+ }
+ }
+ }
+
+ let lesson_files = lesson
+ .get("lesson_files")
+ .or_else(|| lesson.get("files"))
+ .or_else(|| lesson.get("attachments"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for file in &lesson_files {
+ let file_name = file
+ .get("name")
+ .or_else(|| file.get("title"))
+ .or_else(|| file.get("filename"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("file")
+ .to_string();
+
+ let file_url = file
+ .get("url")
+ .or_else(|| file.get("download_url"))
+ .or_else(|| file.get("path"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if !file_url.is_empty() {
+ files.push(NutrorFile {
+ name: file_name,
+ url: file_url,
+ });
+ }
+ }
+
+ if description.is_none() {
+ description = lesson
+ .get("description")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .map(String::from);
+ }
+
+ Ok(NutrorLessonDetail {
+ id,
+ name,
+ video_url,
+ files,
+ description,
+ })
+}
+
+fn extract_youtube_id(embed: &str) -> Option<String> {
+ if let Some(pos) = embed.find("youtube.com/embed/") {
+ let rest = &embed[pos + 18..];
+ let end = rest.find(|c: char| c == '"' || c == '?' || c == '&' || c == '\'').unwrap_or(rest.len());
+ let id = &rest[..end];
+ if !id.is_empty() {
+ return Some(id.to_string());
+ }
+ }
+ if let Some(pos) = embed.find("watch?v=") {
+ let rest = &embed[pos + 8..];
+ let end = rest.find(|c: char| c == '&' || c == '"' || c == '\'').unwrap_or(rest.len());
+ let id = &rest[..end];
+ if !id.is_empty() {
+ return Some(id.to_string());
+ }
+ }
+ if let Some(pos) = embed.find("youtu.be/") {
+ let rest = &embed[pos + 9..];
+ let end = rest.find(|c: char| c == '?' || c == '"' || c == '\'').unwrap_or(rest.len());
+ let id = &rest[..end];
+ if !id.is_empty() {
+ return Some(id.to_string());
+ }
+ }
+ None
+}
+
+fn extract_safevideo_url(embed: &str) -> Option<String> {
+ if let Some(pos) = embed.find("src=\"") {
+ let rest = &embed[pos + 5..];
+ let end = rest.find('"').unwrap_or(rest.len());
+ let url = &rest[..end];
+ if !url.is_empty() {
+ return Some(url.to_string());
+ }
+ }
+ if let Some(pos) = embed.find("src='") {
+ let rest = &embed[pos + 5..];
+ let end = rest.find('\'').unwrap_or(rest.len());
+ let url = &rest[..end];
+ if !url.is_empty() {
+ return Some(url.to_string());
+ }
+ }
+ if embed.starts_with("http") && !embed.contains('<') {
+ return Some(embed.to_string());
+ }
+ None
+}
+
+pub async fn save_session(session: &NutrorSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ refresh_token: session.refresh_token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[nutror] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<NutrorSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[nutror] session loaded");
+
+ Ok(Some(NutrorSession {
+ token: saved.token,
+ refresh_token: saved.refresh_token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/downloader.rs
new file mode 100644
index 00000000..afbe38a6
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/downloader.rs
@@ -0,0 +1,349 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, NutrorCourse, NutrorSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct NutrorCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &NutrorSession,
+ course: &NutrorCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_modules(session, &course.hash).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[nutror] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &NutrorCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ let detail = match api::get_lesson_detail(session, &lesson.hash).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[nutror] Failed to get lesson detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &NutrorCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if let Some(ref desc) = detail.description {
+ omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
+ }
+
+ if let Some(ref video_url) = detail.video_url {
+ let video_ext = if video_url.contains(".m3u8") {
+ "mp4"
+ } else {
+ video_url
+ .rsplit('.')
+ .next()
+ .and_then(|e| {
+ let e = e.split('?').next().unwrap_or(e);
+ if e.len() <= 4 {
+ Some(e)
+ } else {
+ None
+ }
+ })
+ .unwrap_or("mp4")
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.{}",
+ lesson_dir,
+ li + 1,
+ lesson_name,
+ video_ext
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[nutror] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &NutrorCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[nutror] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[nutror] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[nutror] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for file in &detail.files {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let file_name = filename::sanitize_path_component(&file.name);
+ let file_path = format!("{}/{}", lesson_dir, file_name);
+
+ if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&file_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, &file.url, &file_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[nutror] File download failed for '{}': {}",
+ file.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &NutrorCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://nutror.com/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://nutror.com/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/mod.rs
new file mode 100644
index 00000000..980dcffc
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/mod.rs
@@ -0,0 +1,65 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct EduzzNutrorDownloader;
+
+impl EduzzNutrorDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+impl Default for EduzzNutrorDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for EduzzNutrorDownloader {
+ fn name(&self) -> &str {
+ "eduzznutror"
+ }
+
+ 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 == "nutror.com"
+ || host.ends_with(".nutror.com")
+ || host == "eduzz.com"
+ || host.ends_with(".eduzz.com");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Eduzz Nutror".to_string(),
+ author: String::new(),
+ platform: "eduzznutror".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Eduzz Nutror"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/api.rs
new file mode 100644
index 00000000..fa773bb8
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/api.rs
@@ -0,0 +1,437 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct EntregaDigitalSession {
+ pub token: String,
+ pub api_base: String,
+ pub app_version: String,
+ pub device_id: String,
+ pub os_value: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub api_base: String,
+ pub app_version: String,
+ pub device_id: String,
+ pub os_value: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EntregaDigitalCourse {
+ pub id: i64,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EntregaDigitalModule {
+ pub id: i64,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<EntregaDigitalLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EntregaDigitalLesson {
+ pub id: i64,
+ pub name: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EntregaDigitalLessonDetail {
+ pub id: i64,
+ pub name: String,
+ pub description: Option<String>,
+ pub video_url: Option<String>,
+ pub attachments: Vec<EntregaDigitalAttachment>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EntregaDigitalAttachment {
+ pub url: String,
+ pub name: String,
+ pub size: Option<u64>,
+}
+
+pub fn build_api_base(site_url: &str) -> anyhow::Result<String> {
+ let parsed = url::Url::parse(site_url)
+ .map_err(|e| anyhow!("Invalid site URL: {}", e))?;
+
+ let host = parsed
+ .host_str()
+ .ok_or_else(|| anyhow!("No host in URL"))?;
+
+ if !host.contains("entregadigital.app.br") {
+ return Err(anyhow!("Not an Entrega Digital URL"));
+ }
+
+ let subdomain = host
+ .strip_suffix(".entregadigital.app.br")
+ .unwrap_or(host);
+
+ Ok(format!(
+ "https://api-{}.entregadigital.app.br/api/v1/app",
+ subdomain
+ ))
+}
+
+fn build_client(
+ token: &str,
+ app_version: &str,
+ device_id: &str,
+ os_value: &str,
+) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "app-version",
+ HeaderValue::from_str(app_version)?,
+ );
+ headers.insert(
+ "device-id",
+ HeaderValue::from_str(device_id)?,
+ );
+ headers.insert(
+ "os",
+ HeaderValue::from_str(os_value)?,
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("entregadigital_session.json"))
+}
+
+pub async fn validate_token(session: &EntregaDigitalSession) -> anyhow::Result<bool> {
+ let url = format!("{}/products", session.api_base);
+
+ let resp = session
+ .client
+ .get(&url)
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &EntregaDigitalSession) -> anyhow::Result<Vec<EntregaDigitalCourse>> {
+ let url = format!("{}/products", session.api_base);
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let products = body
+ .as_array()
+ .cloned()
+ .unwrap_or_default();
+
+ let mut courses = Vec::new();
+
+ for item in &products {
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = item
+ .get("name")
+ .or_else(|| item.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ courses.push(EntregaDigitalCourse { id, name });
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_course_content(
+ session: &EntregaDigitalSession,
+ course_id: i64,
+) -> anyhow::Result<Vec<EntregaDigitalModule>> {
+ let url = format!("{}/products/{}", session.api_base, course_id);
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let modules_arr = body
+ .get("modules")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for (mi, module_val) in modules_arr.iter().enumerate() {
+ let mod_id = module_val
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let mod_name = module_val
+ .get("name")
+ .or_else(|| module_val.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let mod_order = module_val
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(mi as i64);
+
+ let lessons_arr = module_val
+ .get("lessons")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (li, lesson_val) in lessons_arr.iter().enumerate() {
+ let lesson_id = lesson_val
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let lesson_name = lesson_val
+ .get("name")
+ .or_else(|| lesson_val.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_order = lesson_val
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(li as i64);
+
+ lessons.push(EntregaDigitalLesson {
+ id: lesson_id,
+ name: lesson_name,
+ order: lesson_order,
+ });
+ }
+
+ lessons.sort_by_key(|l| l.order);
+
+ modules.push(EntregaDigitalModule {
+ id: mod_id,
+ name: mod_name,
+ order: mod_order,
+ lessons,
+ });
+ }
+
+ modules.sort_by_key(|m| m.order);
+
+ Ok(modules)
+}
+
+pub async fn get_lesson_detail(
+ session: &EntregaDigitalSession,
+ lesson_id: i64,
+) -> anyhow::Result<EntregaDigitalLessonDetail> {
+ let url = format!("{}/lessons/{}/auth", session.api_base, lesson_id);
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lesson_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let name = body
+ .get("name")
+ .or_else(|| body.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let description = body
+ .get("description")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let detail = body.get("detail");
+
+ let video_url = detail
+ .and_then(|d| {
+ d.get("panda")
+ .and_then(|p| p.get("video_hls"))
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ })
+ .or_else(|| {
+ detail.and_then(|d| {
+ d.get("panda-live")
+ .and_then(|p| p.get("video_hls"))
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ })
+ })
+ .or_else(|| {
+ body.get("video_player")
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ })
+ .or_else(|| {
+ body.get("action")
+ .and_then(|a| a.get("url"))
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ });
+
+ let attachments = body
+ .get("attachments")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|a| {
+ let att_url = a
+ .get("url")
+ .and_then(|v| v.as_str())?
+ .to_string();
+
+ let att_name = a
+ .get("name")
+ .or_else(|| a.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("attachment")
+ .to_string();
+
+ let size = a
+ .get("size")
+ .and_then(|v| v.as_u64());
+
+ Some(EntregaDigitalAttachment {
+ url: att_url,
+ name: att_name,
+ size,
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+
+ Ok(EntregaDigitalLessonDetail {
+ id: lesson_id,
+ name,
+ description,
+ video_url,
+ attachments,
+ })
+}
+
+pub async fn save_session(session: &EntregaDigitalSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ api_base: session.api_base.clone(),
+ app_version: session.app_version.clone(),
+ device_id: session.device_id.clone(),
+ os_value: session.os_value.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[entregadigital] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<EntregaDigitalSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token, &saved.app_version, &saved.device_id, &saved.os_value)?;
+
+ tracing::info!("[entregadigital] session loaded");
+
+ Ok(Some(EntregaDigitalSession {
+ token: saved.token,
+ api_base: saved.api_base,
+ app_version: saved.app_version,
+ device_id: saved.device_id,
+ os_value: saved.os_value,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/downloader.rs
new file mode 100644
index 00000000..d8785f70
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/downloader.rs
@@ -0,0 +1,348 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, EntregaDigitalCourse, EntregaDigitalSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct EntregaDigitalCourseDownloadProgress {
+ pub course_id: i64,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &EntregaDigitalSession,
+ course: &EntregaDigitalCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &EntregaDigitalCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ let detail = match api::get_lesson_detail(session, lesson.id).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[entregadigital] Failed to get lesson detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &EntregaDigitalCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if let Some(ref desc) = detail.description {
+ omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
+ }
+
+ if let Some(ref video_url) = detail.video_url {
+ let video_ext = if video_url.contains(".m3u8") {
+ "mp4"
+ } else {
+ video_url
+ .rsplit('.')
+ .next()
+ .and_then(|e| {
+ let e = e.split('?').next().unwrap_or(e);
+ if e.len() <= 4 {
+ Some(e)
+ } else {
+ None
+ }
+ })
+ .unwrap_or("mp4")
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.{}",
+ lesson_dir,
+ li + 1,
+ lesson_name,
+ video_ext
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[entregadigital] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &EntregaDigitalCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[entregadigital] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[entregadigital] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[entregadigital] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for attachment in &detail.attachments {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let att_name = filename::sanitize_path_component(&attachment.name);
+ let att_path = format!("{}/{}", lesson_dir, att_name);
+
+ if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&att_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, &attachment.url, &att_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[entregadigital] Attachment download failed for '{}': {}",
+ attachment.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &EntregaDigitalCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://entregadigital.app.br/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://entregadigital.app.br/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/mod.rs
new file mode 100644
index 00000000..1208be6a
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/mod.rs
@@ -0,0 +1,63 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct EntregaDigitalDownloader;
+
+impl EntregaDigitalDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+impl Default for EntregaDigitalDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for EntregaDigitalDownloader {
+ fn name(&self) -> &str {
+ "entregadigital"
+ }
+
+ 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 == "entregadigital.app.br"
+ || host.ends_with(".entregadigital.app.br");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Entrega Digital".to_string(),
+ author: String::new(),
+ platform: "entregadigital".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Entrega Digital"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/api.rs
new file mode 100644
index 00000000..7b6fe0e4
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/api.rs
@@ -0,0 +1,424 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const API_BASE: &str = "https://api.estrategiaconcursos.com.br/api/aluno";
+
+#[derive(Clone)]
+pub struct EstrategiaConcursosSession {
+ pub token: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaConcursosCourse {
+ pub id: i64,
+ pub name: String,
+ pub total_aulas: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaConcursosModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<EstrategiaConcursosLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaConcursosLesson {
+ pub id: i64,
+ pub name: String,
+ pub order: i64,
+ pub is_disponivel: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaConcursosLessonDetail {
+ pub id: i64,
+ pub name: String,
+ pub description: String,
+ pub videos: Vec<EstrategiaConcursosVideo>,
+ pub pdf_url: Option<String>,
+ pub pdf_grifado_url: Option<String>,
+ pub pdf_simplificado_url: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaConcursosVideo {
+ pub quality: String,
+ pub url: String,
+ pub audio_url: Option<String>,
+ pub slide_url: Option<String>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert(
+ "Cookie",
+ HeaderValue::from_str(&format!("PHPSESSID={}; __Secure-SID={}", token, token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert("Personificado", HeaderValue::from_static("false"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static("https://www.estrategiaconcursos.com.br"),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://www.estrategiaconcursos.com.br/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("estrategia_concursos_session.json"))
+}
+
+pub async fn validate_token(session: &EstrategiaConcursosSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get(format!("{}/perfil/detalhes", API_BASE))
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &EstrategiaConcursosSession) -> anyhow::Result<Vec<EstrategiaConcursosCourse>> {
+ let resp = session
+ .client
+ .get(format!("{}/curso", API_BASE))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let mut courses = Vec::new();
+
+ let concursos = body
+ .get("data")
+ .and_then(|d| d.get("concursos"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for concurso in &concursos {
+ let cursos = concurso
+ .get("cursos")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for curso in &cursos {
+ let id = curso
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = curso
+ .get("nome")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let total_aulas = curso
+ .get("total_aulas")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ courses.push(EstrategiaConcursosCourse {
+ id,
+ name,
+ total_aulas,
+ });
+ }
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_course_content(
+ session: &EstrategiaConcursosSession,
+ course_id: i64,
+) -> anyhow::Result<Vec<EstrategiaConcursosModule>> {
+ let resp = session
+ .client
+ .get(format!("{}/curso/{}", API_BASE, course_id))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let aulas = body
+ .get("data")
+ .and_then(|d| d.get("aulas"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (i, aula) in aulas.iter().enumerate() {
+ let id = aula
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = aula
+ .get("nome")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let is_disponivel = aula
+ .get("is_disponivel")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ lessons.push(EstrategiaConcursosLesson {
+ id,
+ name,
+ order: i as i64,
+ is_disponivel,
+ });
+ }
+
+ let module = EstrategiaConcursosModule {
+ id: course_id.to_string(),
+ name: "Aulas".to_string(),
+ order: 0,
+ lessons,
+ };
+
+ Ok(vec![module])
+}
+
+pub async fn get_lesson_detail(
+ session: &EstrategiaConcursosSession,
+ lesson_id: i64,
+) -> anyhow::Result<EstrategiaConcursosLessonDetail> {
+ let resp = session
+ .client
+ .get(format!("{}/aula/{}", API_BASE, lesson_id))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lesson_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let data = body.get("data").unwrap_or(&body);
+
+ let name = data
+ .get("nome")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let mut videos = Vec::new();
+
+ let videos_arr = data
+ .get("videos")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for video in &videos_arr {
+ let resolucoes = video
+ .get("resolucoes")
+ .and_then(|v| v.as_object());
+
+ if let Some(res_map) = resolucoes {
+ let best = pick_best_quality(res_map);
+ if let Some((quality, url)) = best {
+ let audio_url = video
+ .get("audio")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from);
+
+ let slide_url = video
+ .get("slide")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from);
+
+ videos.push(EstrategiaConcursosVideo {
+ quality,
+ url,
+ audio_url,
+ slide_url,
+ });
+ }
+ }
+ }
+
+ let pdf_url = data
+ .get("pdf")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from);
+
+ let pdf_grifado_url = data
+ .get("pdf_grifado")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from);
+
+ let pdf_simplificado_url = data
+ .get("pdf_simplificado")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from);
+
+ let description = extract_description(data);
+
+ Ok(EstrategiaConcursosLessonDetail {
+ id: lesson_id,
+ name,
+ description,
+ videos,
+ pdf_url,
+ pdf_grifado_url,
+ pdf_simplificado_url,
+ })
+}
+
+pub fn extract_description(data: &serde_json::Value) -> String {
+ let mut parts = Vec::new();
+
+ if let Some(desc) = data.get("descricao").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) {
+ parts.push(desc.to_string());
+ }
+
+ if let Some(conteudo) = data.get("conteudo").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) {
+ parts.push(conteudo.to_string());
+ }
+
+ if let Some(html) = data.get("html").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) {
+ if parts.is_empty() {
+ parts.push(html.to_string());
+ }
+ }
+
+ parts.join("\n\n")
+}
+
+fn pick_best_quality(resolucoes: &serde_json::Map<String, serde_json::Value>) -> Option<(String, String)> {
+ let priority = ["720", "480", "360", "1080", "240"];
+
+ for q in &priority {
+ if let Some(url) = resolucoes.get(*q).and_then(|v| v.as_str()) {
+ if !url.is_empty() {
+ return Some((q.to_string(), url.to_string()));
+ }
+ }
+ }
+
+ resolucoes.iter().next().and_then(|(k, v)| {
+ v.as_str().map(|u| (k.clone(), u.to_string()))
+ })
+}
+
+pub async fn save_session(session: &EstrategiaConcursosSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[estrategia_concursos] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<EstrategiaConcursosSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[estrategia_concursos] session loaded");
+
+ Ok(Some(EstrategiaConcursosSession {
+ token: saved.token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/downloader.rs
new file mode 100644
index 00000000..e4d75ba4
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/downloader.rs
@@ -0,0 +1,347 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, EstrategiaConcursosCourse, EstrategiaConcursosSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct EstrategiaConcursosCourseDownloadProgress {
+ pub course_id: i64,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &EstrategiaConcursosSession,
+ course: &EstrategiaConcursosCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[estrategia_concursos] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &EstrategiaConcursosCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ if !lesson.is_disponivel {
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &EstrategiaConcursosCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+
+ let detail = match api::get_lesson_detail(session, lesson.id).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_concursos] Failed to get lesson detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &EstrategiaConcursosCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if !detail.description.is_empty() {
+ let desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&desc_dir).await.ok();
+ omniget_core::core::course_utils::save_description(&desc_dir, &detail.description, "html").await.ok();
+ }
+
+ for (vi, video) in detail.videos.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let suffix = if detail.videos.len() > 1 {
+ format!(" ({})", vi + 1)
+ } else {
+ String::new()
+ };
+
+ let video_path = format!(
+ "{}/{}. {}{}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name,
+ suffix
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[estrategia_concursos] Skipping existing: {}", video_path);
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, &video.url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_concursos] Video download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+
+ if let Some(ref audio_url) = video.audio_url {
+ let audio_path = format!(
+ "{}/{}. Audio - {}{}.mp3",
+ mod_dir,
+ li + 1,
+ lesson_name,
+ suffix
+ );
+
+ if !tokio::fs::try_exists(&audio_path).await.unwrap_or(false) {
+ match download_file_direct(&session.client, audio_url, &audio_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_concursos] Audio download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+ }
+
+ if let Some(ref slide_url) = video.slide_url {
+ let slide_ext = slide_url
+ .rsplit('.')
+ .next()
+ .and_then(|e| e.split('?').next())
+ .filter(|e| e.len() <= 5)
+ .unwrap_or("pdf");
+ let slide_path = format!(
+ "{}/{}. Slide - {}{}.{}",
+ mod_dir,
+ li + 1,
+ lesson_name,
+ suffix,
+ slide_ext
+ );
+
+ if !tokio::fs::try_exists(&slide_path).await.unwrap_or(false) {
+ match download_file_direct(&session.client, slide_url, &slide_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_concursos] Slide download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+ }
+ }
+
+ if let Some(ref pdf_url) = detail.pdf_url {
+ let pdf_path = format!("{}/{}. {}.pdf", mod_dir, li + 1, lesson_name);
+ if !tokio::fs::try_exists(&pdf_path).await.unwrap_or(false) {
+ match download_file_direct(&session.client, pdf_url, &pdf_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_concursos] PDF download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+ }
+
+ if let Some(ref pdf_url) = detail.pdf_grifado_url {
+ let pdf_path = format!("{}/{}. {} (grifado).pdf", mod_dir, li + 1, lesson_name);
+ if !tokio::fs::try_exists(&pdf_path).await.unwrap_or(false) {
+ match download_file_direct(&session.client, pdf_url, &pdf_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_concursos] PDF grifado download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+ }
+
+ if let Some(ref pdf_url) = detail.pdf_simplificado_url {
+ let pdf_path = format!("{}/{}. {} (simplificado).pdf", mod_dir, li + 1, lesson_name);
+ if !tokio::fs::try_exists(&pdf_path).await.unwrap_or(false) {
+ match download_file_direct(&session.client, pdf_url, &pdf_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_concursos] PDF simplificado download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &EstrategiaConcursosCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/mod.rs
new file mode 100644
index 00000000..5255bdf5
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/mod.rs
@@ -0,0 +1,73 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct EstrategiaConcursosDownloader;
+
+impl Default for EstrategiaConcursosDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl EstrategiaConcursosDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for EstrategiaConcursosDownloader {
+ fn name(&self) -> &str {
+ "estrategia_concursos"
+ }
+
+ 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();
+ if host == "estrategiaconcursos.com.br" || host == "www.estrategiaconcursos.com.br" {
+ return true;
+ }
+ if (host == "estrategia.com" || host == "www.estrategia.com") && parsed.path().contains("concursos") {
+ return true;
+ }
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Estratégia Concursos".to_string(),
+ author: String::new(),
+ platform: "estrategia_concursos".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Estratégia Concursos courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/api.rs
new file mode 100644
index 00000000..9ee77615
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/api.rs
@@ -0,0 +1,682 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const API_BASE: &str = "https://api.estrategia.com";
+
+#[derive(Clone)]
+pub struct EstrategiaLdiSession {
+ pub token: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaLdiCourse {
+ pub id: String,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaLdiModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<EstrategiaLdiLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaLdiLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaLdiTrack {
+ pub url: String,
+ pub audio_url: Option<String>,
+ pub title: Option<String>,
+ pub duration: Option<f64>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert(
+ "Cookie",
+ HeaderValue::from_str(&format!("__Secure-SID={}", token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static("https://concursos.estrategia.com"),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://concursos.estrategia.com/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("estrategia_ldi_session.json"))
+}
+
+pub async fn validate_token(session: &EstrategiaLdiSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get(format!("{}/bff/goals/shelves?page=1&per_page=1", API_BASE))
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn search_courses(session: &EstrategiaLdiSession, query: &str) -> anyhow::Result<Vec<EstrategiaLdiCourse>> {
+ let mut courses = Vec::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!(
+ "{}/bff/goals/shelves?page={}&per_page=20&name={}",
+ API_BASE,
+ page,
+ urlencoding::encode(query)
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "search_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let goals = body
+ .get("goals")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ if goals.is_empty() {
+ break;
+ }
+
+ for goal in &goals {
+ let id = goal
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let name = goal
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if !id.is_empty() {
+ courses.push(EstrategiaLdiCourse { id, name });
+ }
+ }
+
+ page += 1;
+ if page > 50 {
+ break;
+ }
+ }
+
+ Ok(courses)
+}
+
+pub async fn list_courses(session: &EstrategiaLdiSession) -> anyhow::Result<Vec<EstrategiaLdiCourse>> {
+ search_courses(session, "").await
+}
+
+pub async fn get_course_content(
+ session: &EstrategiaLdiSession,
+ goal_id: &str,
+) -> anyhow::Result<Vec<EstrategiaLdiModule>> {
+ let url = format!("{}/bff/goals/{}/contents/ldi", API_BASE, goal_id);
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let chapters = body
+ .get("chapters")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_else(|| {
+ body.as_array().cloned().unwrap_or_default()
+ });
+
+ let mut modules = Vec::new();
+
+ for (ci, chapter) in chapters.iter().enumerate() {
+ let chapter_name = chapter
+ .get("title")
+ .or_else(|| chapter.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("Chapter")
+ .to_string();
+
+ let chapter_id = chapter
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", ci),
+ })
+ .unwrap_or_else(|| format!("{}", ci));
+
+ let items = chapter
+ .get("items")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (ii, item) in items.iter().enumerate() {
+ let item_id = item
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}-{}", ci, ii),
+ })
+ .unwrap_or_else(|| format!("{}-{}", ci, ii));
+
+ let item_name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ lessons.push(EstrategiaLdiLesson {
+ id: item_id,
+ name: item_name,
+ order: ii as i64,
+ });
+ }
+
+ modules.push(EstrategiaLdiModule {
+ id: chapter_id,
+ name: chapter_name,
+ order: ci as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_item_detail(
+ session: &EstrategiaLdiSession,
+ item_id: &str,
+) -> anyhow::Result<serde_json::Value> {
+ let mut all_sub_blocks = Vec::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!("{}/v3/mci/items/{}", API_BASE, item_id);
+
+ let resp = session.client.get(&url)
+ .query(&[
+ ("page", page.to_string().as_str()),
+ ("order", "asc"),
+ ("per_page", "30"),
+ ("view_mode", "complete"),
+ ("should_load_metadata", "true"),
+ ("video_only", "false"),
+ ("text_only", "false"),
+ ("question_only", "false"),
+ ("cast_only", "false"),
+ ("attachment_only", "false"),
+ ])
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ if all_sub_blocks.is_empty() {
+ return Err(anyhow!(
+ "get_item_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+ break;
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+ let item_data = body.get("data").unwrap_or(&body);
+
+ if let Some(blocks) = item_data.get("sub_blocks").and_then(|v| v.as_array()) {
+ all_sub_blocks.extend(blocks.clone());
+ }
+
+ let total_pages = body
+ .get("meta")
+ .and_then(|m| m.get("last_page"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(1) as u32;
+
+ if page >= total_pages {
+ break;
+ }
+ page += 1;
+ }
+
+ let result = serde_json::json!({
+ "sub_blocks": all_sub_blocks
+ });
+ Ok(result)
+}
+
+pub async fn get_track_info(
+ session: &EstrategiaLdiSession,
+ track_id: &str,
+) -> anyhow::Result<EstrategiaLdiTrack> {
+ let url = format!("{}/v2/tracks/{}", API_BASE, track_id);
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_track_info returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+ let track_data = body.get("data").unwrap_or(&body);
+
+ let mut video_files: Vec<(i64, String)> = Vec::new();
+ if let Some(files) = track_data.get("video_files").and_then(|v| v.as_array()) {
+ for vf in files {
+ let height = vf.get("height").and_then(|v| v.as_i64()).unwrap_or(0);
+ let link = vf.get("link").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ if !link.is_empty() {
+ video_files.push((height, link));
+ }
+ }
+ }
+
+ video_files.sort_by(|a, b| b.0.cmp(&a.0));
+
+ let track_url = if let Some((_, best_url)) = video_files.first() {
+ best_url.clone()
+ } else {
+ track_data
+ .get("url")
+ .or_else(|| track_data.get("source"))
+ .or_else(|| track_data.get("link"))
+ .or_else(|| body.get("url"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string()
+ };
+
+ let duration = track_data
+ .get("duration")
+ .and_then(|v| v.as_f64());
+
+ let audio_url = track_data
+ .get("audio_url")
+ .or_else(|| track_data.get("audio"))
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from);
+
+ let title = track_data
+ .get("name")
+ .or_else(|| track_data.get("title"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ if track_url.is_empty() {
+ return Err(anyhow!("No URL found in track response for track_id={}", track_id));
+ }
+
+ Ok(EstrategiaLdiTrack {
+ url: track_url,
+ audio_url,
+ title,
+ duration,
+ })
+}
+
+pub fn extract_track_ids(item_detail: &serde_json::Value) -> Vec<String> {
+ let mut track_ids = Vec::new();
+
+ let sub_blocks = item_detail
+ .get("sub_blocks")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for block in &sub_blocks {
+ let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
+
+ if block_type == "cast" {
+ let data = block.get("data")
+ .or_else(|| block.get("simple_data"))
+ .cloned()
+ .unwrap_or_default();
+
+ let track_type = data.get("type").and_then(|v| v.as_str()).unwrap_or("");
+ let track_value = data.get("value").and_then(|v| v.as_str()).unwrap_or("");
+
+ if track_type == "track" && !track_value.is_empty() {
+ track_ids.push(track_value.to_string());
+ }
+ } else if block_type == "videoMyDocuments" {
+ let data = block.get("data")
+ .or_else(|| block.get("simple_data"))
+ .cloned()
+ .unwrap_or_default();
+
+ let resolved = data.get("resolved").cloned().unwrap_or_default();
+ let video_url = resolved.get("data")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if !video_url.is_empty() {
+ track_ids.push(format!("direct:{}", video_url));
+ }
+ }
+ }
+
+ if track_ids.is_empty() {
+ let tracks = item_detail
+ .get("tracks")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for track in &tracks {
+ if let Some(id) = track.get("id").map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ }) {
+ if !id.is_empty() {
+ track_ids.push(id);
+ }
+ }
+ }
+ }
+
+ if track_ids.is_empty() {
+ if let Some(track_id) = item_detail.get("track_id").map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ }) {
+ if !track_id.is_empty() {
+ track_ids.push(track_id);
+ }
+ }
+ }
+
+ track_ids
+}
+
+pub fn extract_attachment_urls(item_detail: &serde_json::Value) -> Vec<(String, String)> {
+ let mut attachments = Vec::new();
+
+ let sub_blocks = item_detail
+ .get("sub_blocks")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for block in &sub_blocks {
+ let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
+
+ if block_type == "attachment" || block_type == "pdfMyDocuments" {
+ let data = block.get("data")
+ .or_else(|| block.get("simple_data"))
+ .cloned()
+ .unwrap_or_default();
+
+ let resolved = data.get("resolved").cloned().unwrap_or(data.clone());
+
+ let url = resolved.get("url")
+ .or_else(|| resolved.get("data"))
+ .or_else(|| resolved.get("file"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let name = resolved.get("name")
+ .or_else(|| resolved.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("attachment")
+ .to_string();
+
+ if !url.is_empty() {
+ attachments.push((name, url));
+ }
+ }
+ }
+
+ let atts = item_detail
+ .get("attachments")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for att in &atts {
+ let url = att
+ .get("url")
+ .or_else(|| att.get("file"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let name = att
+ .get("name")
+ .or_else(|| att.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("attachment")
+ .to_string();
+
+ if !url.is_empty() {
+ attachments.push((name, url));
+ }
+ }
+
+ attachments
+}
+
+pub fn extract_description(item_detail: &serde_json::Value) -> String {
+ let sub_blocks = item_detail.get("sub_blocks").and_then(|v| v.as_array()).cloned().unwrap_or_default();
+ let mut parts = Vec::new();
+
+ for block in &sub_blocks {
+ let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
+
+ if block_type == "tiptap" {
+ let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
+ if let Some(content) = data.get("content").and_then(|v| v.as_str()) {
+ parts.push(content.to_string());
+ } else if let Some(html) = data.as_str() {
+ parts.push(html.to_string());
+ }
+ } else if block_type == "question" {
+ let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
+ let resolved = data.get("resolved").cloned().unwrap_or(data.clone());
+
+ let statement = resolved.get("statement")
+ .or_else(|| resolved.get("enunciado"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if !statement.is_empty() {
+ let mut q = format!("<div class=\"question\"><p><strong>Questao:</strong> {}</p>", statement);
+
+ if let Some(alts) = resolved.get("alternatives").and_then(|v| v.as_array()) {
+ q.push_str("<ol type=\"A\">");
+ for alt in alts {
+ let text = alt.get("text")
+ .or_else(|| alt.get("content"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ let is_correct = alt.get("is_correct")
+ .or_else(|| alt.get("correct"))
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ if is_correct {
+ q.push_str(&format!("<li><strong>{}</strong></li>", text));
+ } else {
+ q.push_str(&format!("<li>{}</li>", text));
+ }
+ }
+ q.push_str("</ol>");
+ }
+
+ let answer = resolved.get("answer")
+ .or_else(|| resolved.get("resposta"))
+ .or_else(|| resolved.get("gabarito"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if !answer.is_empty() {
+ q.push_str(&format!("<p><strong>Resposta:</strong> {}</p>", answer));
+ }
+
+ let explanation = resolved.get("explanation")
+ .or_else(|| resolved.get("explicacao"))
+ .or_else(|| resolved.get("comment"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if !explanation.is_empty() {
+ q.push_str(&format!("<p><strong>Explicacao:</strong> {}</p>", explanation));
+ }
+
+ q.push_str("</div>");
+ parts.push(q);
+ }
+ }
+ }
+
+ parts.join("\n\n")
+}
+
+pub fn extract_audio_urls(item_detail: &serde_json::Value) -> Vec<(String, String)> {
+ let sub_blocks = item_detail.get("sub_blocks").and_then(|v| v.as_array()).cloned().unwrap_or_default();
+ let mut audios = Vec::new();
+
+ for block in &sub_blocks {
+ let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
+
+ if block_type == "cast" {
+ let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
+ let track_type = data.get("type").and_then(|v| v.as_str()).unwrap_or("");
+ let track_value = data.get("value").and_then(|v| v.as_str()).unwrap_or("");
+
+ if track_type == "track" && !track_value.is_empty() {
+ audios.push(("track".to_string(), track_value.to_string()));
+ }
+ }
+ }
+
+ audios
+}
+
+pub async fn save_session(session: &EstrategiaLdiSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[estrategia_ldi] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<EstrategiaLdiSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[estrategia_ldi] session loaded");
+
+ Ok(Some(EstrategiaLdiSession {
+ token: saved.token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/downloader.rs
new file mode 100644
index 00000000..b653c7ba
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/downloader.rs
@@ -0,0 +1,387 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, EstrategiaLdiCourse, EstrategiaLdiSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct EstrategiaLdiCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &EstrategiaLdiSession,
+ course: &EstrategiaLdiCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, &course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[estrategia_ldi] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &EstrategiaLdiCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+
+ let item_detail = match api::get_item_detail(session, &lesson.id).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_ldi] Failed to get item detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &EstrategiaLdiCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ let description = api::extract_description(&item_detail);
+ if !description.is_empty() {
+ omniget_core::core::course_utils::save_description(&mod_dir, &description, "html").await.ok();
+ }
+
+ let track_ids = api::extract_track_ids(&item_detail);
+
+ for (ti, track_id) in track_ids.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let (video_url, audio_url, track_title) = if let Some(direct_url) = track_id.strip_prefix("direct:") {
+ (direct_url.to_string(), None, None)
+ } else {
+ match api::get_track_info(session, track_id).await {
+ Ok(t) => (t.url, t.audio_url, t.title),
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_ldi] Failed to get track '{}': {}",
+ track_id,
+ e
+ );
+ continue;
+ }
+ }
+ };
+
+ let suffix = if track_ids.len() > 1 {
+ format!(" ({})", ti + 1)
+ } else {
+ String::new()
+ };
+
+ let video_path = format!(
+ "{}/{}. {}{}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name,
+ suffix
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[estrategia_ldi] Skipping existing: {}", video_path);
+ } else {
+ download_video_ldi(session, &video_url, &video_path, &mod_dir, &lesson.name, &cancel_token, &total_bytes).await;
+ }
+ } else {
+ download_video_ldi(session, &video_url, &video_path, &mod_dir, &lesson.name, &cancel_token, &total_bytes).await;
+ }
+
+ if let Some(ref a_url) = audio_url {
+ let audio_name = track_title.as_deref().unwrap_or(&lesson.name);
+ let safe_audio = filename::sanitize_path_component(audio_name);
+ let audio_path = format!("{}/{}. Audio - {}{}.mp3", mod_dir, li + 1, safe_audio, suffix);
+
+ if !tokio::fs::try_exists(&audio_path).await.unwrap_or(false) {
+ match download_file_direct(&session.client, a_url, &audio_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[estrategia_ldi] audio download failed: {}", e);
+ }
+ }
+ }
+ }
+ }
+
+ let attachments = api::extract_attachment_urls(&item_detail);
+ for (att_name, att_url) in &attachments {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let safe_name = filename::sanitize_path_component(att_name);
+ let ext = att_url.rsplit('.').next().unwrap_or("pdf");
+ let ext = ext.split('?').next().unwrap_or(ext);
+ let att_path = format!("{}/{}.{}", mod_dir, safe_name, ext);
+
+ if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&att_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, att_url, &att_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_ldi] Attachment download failed for '{}': {}",
+ att_name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &EstrategiaLdiCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://concursos.estrategia.com/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://concursos.estrategia.com/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
+
+async fn download_video_ldi(
+ session: &api::EstrategiaLdiSession,
+ video_url: &str,
+ video_path: &str,
+ mod_dir: &str,
+ lesson_name: &str,
+ cancel_token: &CancellationToken,
+ total_bytes: &Arc<AtomicU64>,
+) {
+ let is_direct_url = video_url.contains(".mp4")
+ || video_url.contains("vimeocdn")
+ || video_url.contains("akamaized")
+ || video_url.contains("cloudfront")
+ || video_url.contains("player.vimeo.com/progressive");
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(video_url, video_path, cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[estrategia_ldi] HLS download failed for '{}': {}", lesson_name, e);
+ let _ = tokio::fs::remove_file(video_path).await;
+ }
+ }
+ } else if is_direct_url {
+ match download_file_direct(&session.client, video_url, video_path, cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[estrategia_ldi] Direct download failed for '{}': {}, trying yt-dlp", lesson_name, e);
+ match download_with_ytdlp(video_url, mod_dir, cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!("[estrategia_ldi] All methods failed for '{}': {}", lesson_name, e2);
+ }
+ }
+ }
+ }
+ } else {
+ match download_with_ytdlp(video_url, mod_dir, cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[estrategia_ldi] yt-dlp failed for '{}': {}, trying direct", lesson_name, e);
+ match download_file_direct(&session.client, video_url, video_path, cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!("[estrategia_ldi] Direct download also failed for '{}': {}", lesson_name, e2);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/mod.rs
new file mode 100644
index 00000000..28ab7d8c
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/mod.rs
@@ -0,0 +1,68 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct EstrategiaLdiDownloader;
+
+impl Default for EstrategiaLdiDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl EstrategiaLdiDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for EstrategiaLdiDownloader {
+ fn name(&self) -> &str {
+ "estrategia_ldi"
+ }
+
+ 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 == "concursos.estrategia.com";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Estratégia LDI".to_string(),
+ author: String::new(),
+ platform: "estrategia_ldi".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Estratégia LDI courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/api.rs
new file mode 100644
index 00000000..97f8b0bb
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/api.rs
@@ -0,0 +1,811 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const API_BASE: &str = "https://api.estrategia.com";
+
+#[derive(Clone)]
+pub struct EstrategiaMilitaresSession {
+ pub token: String,
+ pub cookie_string: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub cookie_string: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaMilitaresCourse {
+ pub id: String,
+ pub name: String,
+ pub slug: String,
+ pub goal_id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaMilitaresModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<EstrategiaMilitaresLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaMilitaresLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EstrategiaMilitaresTrack {
+ pub url: String,
+ pub audio_url: Option<String>,
+ pub title: Option<String>,
+ pub duration: Option<f64>,
+}
+
+pub fn parse_token_input(input: &str) -> (String, String) {
+ let trimmed = input.trim();
+
+ if trimmed.starts_with('{') || trimmed.starts_with('[') {
+ if let Ok(val) = serde_json::from_str::<serde_json::Value>(trimmed) {
+ let cookies_arr = val.get("cookies")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .or_else(|| val.as_array().cloned())
+ .unwrap_or_default();
+
+ let mut jwt = String::new();
+ let mut cookie_parts: Vec<String> = Vec::new();
+
+ for c in &cookies_arr {
+ let name = c.get("name").and_then(|v| v.as_str()).unwrap_or("");
+ let value = c.get("value").and_then(|v| v.as_str()).unwrap_or("");
+ if !name.is_empty() && !value.is_empty() {
+ cookie_parts.push(format!("{}={}", name, value));
+ if name == "__Secure-SID" {
+ jwt = value.to_string();
+ }
+ }
+ }
+
+ if !jwt.is_empty() {
+ return (jwt, cookie_parts.join("; "));
+ }
+ }
+ }
+
+ if trimmed.contains("; ") || trimmed.contains("__Secure-SID=") || trimmed.contains("_cfuvid=") {
+ let mut jwt = String::new();
+ for part in trimmed.split("; ") {
+ if let Some(val) = part.strip_prefix("__Secure-SID=") {
+ jwt = val.to_string();
+ }
+ }
+ if !jwt.is_empty() {
+ return (jwt, trimmed.to_string());
+ }
+ return (trimmed.to_string(), format!("__Secure-SID={}", trimmed));
+ }
+
+ (trimmed.to_string(), format!("__Secure-SID={}", trimmed))
+}
+
+fn build_client(token: &str, cookie_string: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert(
+ "Cookie",
+ HeaderValue::from_str(cookie_string)?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json, text/plain, */*"));
+ headers.insert("Accept-Language", HeaderValue::from_static("pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static("https://militares.estrategia.com"),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://militares.estrategia.com/"),
+ );
+ headers.insert("x-vertical", HeaderValue::from_static("militares"));
+ headers.insert("x-requester-id", HeaderValue::from_static("front-student"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("estrategia_militares_session.json"))
+}
+
+pub async fn validate_token(session: &EstrategiaMilitaresSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get(format!("{}/bff/goals/shelves?page=1&per_page=1&name=test", API_BASE))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body = resp.text().await.unwrap_or_default();
+ tracing::info!("[estrategia_militares] validate_token status={} body_preview={}", status, &body[..body.len().min(500)]);
+
+ Ok(status.is_success())
+}
+
+async fn fetch_ldi_courses_for_goal(session: &EstrategiaMilitaresSession, goal_id: &str) -> Vec<EstrategiaMilitaresCourse> {
+ let url = format!("{}/bff/goals/{}/contents/ldi?page=1&per_page=50", API_BASE, goal_id);
+
+ let resp = match session.client.get(&url).send().await {
+ Ok(r) => r,
+ Err(e) => {
+ tracing::warn!("[estrategia_militares] failed to fetch LDI for goal {}: {}", goal_id, e);
+ return Vec::new();
+ }
+ };
+
+ let body_text = match resp.text().await {
+ Ok(t) => t,
+ Err(_) => return Vec::new(),
+ };
+
+ let body: serde_json::Value = match serde_json::from_str(&body_text) {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+
+ let contents = body
+ .get("data")
+ .and_then(|d| d.get("contents"))
+ .and_then(|c| c.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut courses = Vec::new();
+ for c in &contents {
+ let id = c.get("id").map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ }).unwrap_or_default();
+
+ let name = c.get("title")
+ .or(c.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let slug = c.get("slug")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if !id.is_empty() && !slug.is_empty() {
+ courses.push(EstrategiaMilitaresCourse {
+ id,
+ name,
+ slug,
+ goal_id: goal_id.to_string(),
+ });
+ }
+ }
+
+ courses
+}
+
+pub async fn search_courses(session: &EstrategiaMilitaresSession, query: &str) -> anyhow::Result<Vec<EstrategiaMilitaresCourse>> {
+ if query.trim().is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let url = format!(
+ "{}/bff/goals/shelves?page=1&per_page=20&name={}",
+ API_BASE,
+ urlencoding::encode(query.trim())
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ tracing::info!("[estrategia_militares] search status={} body_len={}", status, body_text.len());
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "search_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+ let mut all_goal_ids = Vec::new();
+
+ let result_data = body.get("data").unwrap_or(&body);
+
+ if let Some(shelves) = result_data.get("shelves").and_then(|v| v.as_object()) {
+ for (_shelf_name, goals_val) in shelves {
+ let goals = goals_val.as_array().cloned().unwrap_or_default();
+ for goal in &goals {
+ let goal_id = goal.get("id").map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ }).unwrap_or_default();
+
+ if !goal_id.is_empty() {
+ all_goal_ids.push(goal_id);
+ }
+ }
+ }
+ }
+
+ if let Some(highlights) = result_data.get("highlights") {
+ let highlight_goals = highlights.get("goals").and_then(|v| v.as_array()).cloned().unwrap_or_default();
+ for goal in &highlight_goals {
+ let goal_id = goal.get("id").map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ }).unwrap_or_default();
+
+ if !goal_id.is_empty() && !all_goal_ids.contains(&goal_id) {
+ all_goal_ids.push(goal_id);
+ }
+ }
+ }
+
+ let mut courses = Vec::new();
+ let mut seen_ids = std::collections::HashSet::new();
+
+ for goal_id in &all_goal_ids {
+ let ldi_courses = fetch_ldi_courses_for_goal(session, goal_id).await;
+ for c in ldi_courses {
+ if seen_ids.insert(c.id.clone()) {
+ courses.push(c);
+ }
+ }
+ }
+
+ tracing::info!("[estrategia_militares] found {} courses across {} goals for query '{}'", courses.len(), all_goal_ids.len(), query);
+ Ok(courses)
+}
+
+pub async fn list_courses(session: &EstrategiaMilitaresSession) -> anyhow::Result<Vec<EstrategiaMilitaresCourse>> {
+ search_courses(session, "militar").await
+}
+
+pub async fn get_course_content(
+ session: &EstrategiaMilitaresSession,
+ course_slug: &str,
+) -> anyhow::Result<Vec<EstrategiaMilitaresModule>> {
+ let url = format!("{}/v3/mci/courses/slug/{}", API_BASE, course_slug);
+
+ let resp = session.client.get(&url)
+ .header("cache-control", "no-cache")
+ .send()
+ .await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ tracing::info!("[estrategia_militares] get_course_content slug={} status={} len={}", course_slug, status, body_text.len());
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let course_data = body.get("data").unwrap_or(&body);
+
+ let chapters = course_data
+ .get("chapters")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for (ci, chapter) in chapters.iter().enumerate() {
+ let chapter_name = chapter
+ .get("title")
+ .or_else(|| chapter.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("Chapter")
+ .to_string();
+
+ let chapter_id = chapter
+ .get("chapter_id")
+ .or(chapter.get("id"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", ci),
+ })
+ .unwrap_or_else(|| format!("{}", ci));
+
+ let items = chapter
+ .get("items")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (ii, item) in items.iter().enumerate() {
+ let item_id = item
+ .get("item_id")
+ .or(item.get("id"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}-{}", ci, ii),
+ })
+ .unwrap_or_else(|| format!("{}-{}", ci, ii));
+
+ let item_name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ lessons.push(EstrategiaMilitaresLesson {
+ id: item_id,
+ name: item_name,
+ order: ii as i64,
+ });
+ }
+
+ modules.push(EstrategiaMilitaresModule {
+ id: chapter_id,
+ name: chapter_name,
+ order: ci as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_item_detail(
+ session: &EstrategiaMilitaresSession,
+ item_id: &str,
+) -> anyhow::Result<serde_json::Value> {
+ let mut all_sub_blocks = Vec::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!("{}/v3/mci/items/{}", API_BASE, item_id);
+
+ let resp = session.client.get(&url)
+ .query(&[
+ ("page", page.to_string().as_str()),
+ ("order", "asc"),
+ ("per_page", "30"),
+ ("view_mode", "complete"),
+ ("should_load_metadata", "true"),
+ ("video_only", "false"),
+ ("text_only", "false"),
+ ("question_only", "false"),
+ ("cast_only", "false"),
+ ("attachment_only", "false"),
+ ])
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ if all_sub_blocks.is_empty() {
+ return Err(anyhow!(
+ "get_item_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+ break;
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+ let item_data = body.get("data").unwrap_or(&body);
+
+ if let Some(blocks) = item_data.get("sub_blocks").and_then(|v| v.as_array()) {
+ all_sub_blocks.extend(blocks.clone());
+ }
+
+ let total_pages = body
+ .get("meta")
+ .and_then(|m| m.get("last_page"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(1) as u32;
+
+ if page >= total_pages {
+ break;
+ }
+ page += 1;
+ }
+
+ let result = serde_json::json!({
+ "sub_blocks": all_sub_blocks
+ });
+ Ok(result)
+}
+
+pub async fn get_track_info(
+ session: &EstrategiaMilitaresSession,
+ track_id: &str,
+) -> anyhow::Result<EstrategiaMilitaresTrack> {
+ let url = format!("{}/v2/tracks/{}", API_BASE, track_id);
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_track_info returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+ let track_data = body.get("data").unwrap_or(&body);
+
+ let mut video_files: Vec<(i64, String)> = Vec::new();
+ if let Some(files) = track_data.get("video_files").and_then(|v| v.as_array()) {
+ for vf in files {
+ let height = vf.get("height").and_then(|v| v.as_i64()).unwrap_or(0);
+ let link = vf.get("link").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ if !link.is_empty() {
+ video_files.push((height, link));
+ }
+ }
+ }
+
+ video_files.sort_by(|a, b| b.0.cmp(&a.0));
+
+ let track_url = if let Some((_, best_url)) = video_files.first() {
+ best_url.clone()
+ } else {
+ track_data
+ .get("url")
+ .or_else(|| track_data.get("source"))
+ .or_else(|| track_data.get("link"))
+ .or_else(|| body.get("url"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string()
+ };
+
+ let duration = track_data
+ .get("duration")
+ .and_then(|v| v.as_f64());
+
+ let audio_url = track_data
+ .get("audio_url")
+ .or_else(|| track_data.get("audio"))
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from);
+
+ let title = track_data
+ .get("name")
+ .or_else(|| track_data.get("title"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ tracing::info!("[estrategia_militares] track {} url_len={} has_video_files={} has_audio={}", track_id, track_url.len(), !video_files.is_empty(), audio_url.is_some());
+
+ if track_url.is_empty() {
+ return Err(anyhow!("No URL found in track response for track_id={}", track_id));
+ }
+
+ Ok(EstrategiaMilitaresTrack {
+ url: track_url,
+ audio_url,
+ title,
+ duration,
+ })
+}
+
+pub fn extract_track_ids(item_detail: &serde_json::Value) -> Vec<String> {
+ let mut track_ids = Vec::new();
+
+ let sub_blocks = item_detail
+ .get("sub_blocks")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for block in &sub_blocks {
+ let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
+
+ if block_type == "cast" {
+ let data = block.get("data")
+ .or_else(|| block.get("simple_data"))
+ .cloned()
+ .unwrap_or_default();
+
+ let track_type = data.get("type").and_then(|v| v.as_str()).unwrap_or("");
+ let track_value = data.get("value").and_then(|v| v.as_str()).unwrap_or("");
+
+ if track_type == "track" && !track_value.is_empty() {
+ track_ids.push(track_value.to_string());
+ }
+ } else if block_type == "videoMyDocuments" {
+ let data = block.get("data")
+ .or_else(|| block.get("simple_data"))
+ .cloned()
+ .unwrap_or_default();
+
+ let resolved = data.get("resolved").cloned().unwrap_or_default();
+ let video_url = resolved.get("data")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if !video_url.is_empty() {
+ track_ids.push(format!("direct:{}", video_url));
+ }
+ }
+ }
+
+ if track_ids.is_empty() {
+ let tracks = item_detail
+ .get("tracks")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for track in &tracks {
+ if let Some(id) = track.get("id").map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ }) {
+ if !id.is_empty() {
+ track_ids.push(id);
+ }
+ }
+ }
+ }
+
+ track_ids
+}
+
+pub fn extract_attachment_urls(item_detail: &serde_json::Value) -> Vec<(String, String)> {
+ let mut attachments = Vec::new();
+
+ let sub_blocks = item_detail
+ .get("sub_blocks")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for block in &sub_blocks {
+ let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
+
+ if block_type == "attachment" || block_type == "pdfMyDocuments" {
+ let data = block.get("data")
+ .or_else(|| block.get("simple_data"))
+ .cloned()
+ .unwrap_or_default();
+
+ let resolved = data.get("resolved").cloned().unwrap_or(data.clone());
+
+ let url = resolved.get("url")
+ .or_else(|| resolved.get("data"))
+ .or_else(|| resolved.get("file"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let name = resolved.get("name")
+ .or_else(|| resolved.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("attachment")
+ .to_string();
+
+ if !url.is_empty() {
+ attachments.push((name, url));
+ }
+ }
+ }
+
+ let atts = item_detail
+ .get("attachments")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for att in &atts {
+ let url = att
+ .get("url")
+ .or_else(|| att.get("file"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let name = att
+ .get("name")
+ .or_else(|| att.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("attachment")
+ .to_string();
+
+ if !url.is_empty() {
+ attachments.push((name, url));
+ }
+ }
+
+ attachments
+}
+
+pub fn extract_description(item_detail: &serde_json::Value) -> String {
+ let sub_blocks = item_detail.get("sub_blocks").and_then(|v| v.as_array()).cloned().unwrap_or_default();
+ let mut parts = Vec::new();
+
+ for block in &sub_blocks {
+ let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
+
+ if block_type == "tiptap" {
+ let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
+ if let Some(content) = data.get("content").and_then(|v| v.as_str()) {
+ parts.push(content.to_string());
+ } else if let Some(html) = data.as_str() {
+ parts.push(html.to_string());
+ }
+ } else if block_type == "question" {
+ let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
+ let resolved = data.get("resolved").cloned().unwrap_or(data.clone());
+
+ let statement = resolved.get("statement")
+ .or_else(|| resolved.get("enunciado"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if !statement.is_empty() {
+ let mut q = format!("<div class=\"question\"><p><strong>Questao:</strong> {}</p>", statement);
+
+ if let Some(alts) = resolved.get("alternatives").and_then(|v| v.as_array()) {
+ q.push_str("<ol type=\"A\">");
+ for alt in alts {
+ let text = alt.get("text")
+ .or_else(|| alt.get("content"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ let is_correct = alt.get("is_correct")
+ .or_else(|| alt.get("correct"))
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ if is_correct {
+ q.push_str(&format!("<li><strong>{}</strong> ✓</li>", text));
+ } else {
+ q.push_str(&format!("<li>{}</li>", text));
+ }
+ }
+ q.push_str("</ol>");
+ }
+
+ let answer = resolved.get("answer")
+ .or_else(|| resolved.get("resposta"))
+ .or_else(|| resolved.get("gabarito"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if !answer.is_empty() {
+ q.push_str(&format!("<p><strong>Resposta:</strong> {}</p>", answer));
+ }
+
+ let explanation = resolved.get("explanation")
+ .or_else(|| resolved.get("explicacao"))
+ .or_else(|| resolved.get("comment"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if !explanation.is_empty() {
+ q.push_str(&format!("<p><strong>Explicacao:</strong> {}</p>", explanation));
+ }
+
+ q.push_str("</div>");
+ parts.push(q);
+ }
+ }
+ }
+
+ parts.join("\n\n")
+}
+
+pub fn extract_audio_urls(item_detail: &serde_json::Value) -> Vec<(String, String)> {
+ let sub_blocks = item_detail.get("sub_blocks").and_then(|v| v.as_array()).cloned().unwrap_or_default();
+ let mut audios = Vec::new();
+
+ for block in &sub_blocks {
+ let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
+
+ if block_type == "cast" {
+ let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
+ let track_type = data.get("type").and_then(|v| v.as_str()).unwrap_or("");
+ let track_value = data.get("value").and_then(|v| v.as_str()).unwrap_or("");
+
+ if track_type == "track" && !track_value.is_empty() {
+ audios.push(("track".to_string(), track_value.to_string()));
+ }
+ }
+ }
+
+ audios
+}
+
+pub async fn save_session(session: &EstrategiaMilitaresSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ cookie_string: session.cookie_string.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[estrategia_militares] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<EstrategiaMilitaresSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token, &saved.cookie_string)?;
+
+ tracing::info!("[estrategia_militares] session loaded");
+
+ Ok(Some(EstrategiaMilitaresSession {
+ token: saved.token,
+ cookie_string: saved.cookie_string,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/downloader.rs
new file mode 100644
index 00000000..c04c342d
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/downloader.rs
@@ -0,0 +1,410 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, EstrategiaMilitaresCourse, EstrategiaMilitaresSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct EstrategiaMilitaresCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &EstrategiaMilitaresSession,
+ course: &EstrategiaMilitaresCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, &course.slug).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &EstrategiaMilitaresCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+
+ let item_detail = match api::get_item_detail(session, &lesson.id).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_militares] Failed to get item detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &EstrategiaMilitaresCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ let description = api::extract_description(&item_detail);
+ if !description.is_empty() {
+ omniget_core::core::course_utils::save_description(&mod_dir, &description, "html").await.ok();
+ }
+
+ let track_ids = api::extract_track_ids(&item_detail);
+
+ for (ti, track_id) in track_ids.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let video_url = if let Some(direct_url) = track_id.strip_prefix("direct:") {
+ direct_url.to_string()
+ } else {
+ match api::get_track_info(session, track_id).await {
+ Ok(t) => t.url,
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_militares] Failed to get track '{}': {}",
+ track_id,
+ e
+ );
+ continue;
+ }
+ }
+ };
+
+ let (audio_url, track_title) = if !track_id.starts_with("direct:") {
+ match api::get_track_info(session, track_id).await {
+ Ok(ref t) => (t.audio_url.clone(), t.title.clone()),
+ Err(_) => (None, None),
+ }
+ } else {
+ (None, None)
+ };
+
+ let track_info = api::EstrategiaMilitaresTrack {
+ url: video_url,
+ audio_url: audio_url.clone(),
+ title: track_title.clone(),
+ duration: None,
+ };
+
+ let suffix = if track_ids.len() > 1 {
+ format!(" ({})", ti + 1)
+ } else {
+ String::new()
+ };
+
+ let video_path = format!(
+ "{}/{}. {}{}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name,
+ suffix
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[estrategia_militares] Skipping existing: {}", video_path);
+ continue;
+ }
+ }
+
+ let is_direct_url = track_info.url.contains(".mp4")
+ || track_info.url.contains("vimeocdn")
+ || track_info.url.contains("akamaized")
+ || track_info.url.contains("cloudfront")
+ || track_info.url.contains("player.vimeo.com/progressive");
+
+ if track_info.url.contains(".m3u8") {
+ match download_hls_video(&track_info.url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_militares] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else if is_direct_url {
+ tracing::info!("[estrategia_militares] Direct download for '{}'", lesson.name);
+ match download_file_direct(&session.client, &track_info.url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_militares] Direct download failed for '{}': {}, trying yt-dlp",
+ lesson.name,
+ e
+ );
+ match download_with_ytdlp(&track_info.url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[estrategia_militares] All methods failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ } else {
+ match download_with_ytdlp(&track_info.url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_militares] yt-dlp failed for '{}': {}, trying direct",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, &track_info.url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[estrategia_militares] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+
+ if let Some(ref a_url) = audio_url {
+ let audio_name = track_title.as_deref().unwrap_or(&lesson.name);
+ let safe_audio = filename::sanitize_path_component(audio_name);
+ let audio_path = format!("{}/{}. Audio - {}{}.mp3", mod_dir, li + 1, safe_audio, suffix);
+
+ if !tokio::fs::try_exists(&audio_path).await.unwrap_or(false) {
+ match download_file_direct(&session.client, a_url, &audio_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[estrategia_militares] audio download failed: {}", e);
+ }
+ }
+ }
+ }
+ }
+
+ let attachments = api::extract_attachment_urls(&item_detail);
+ for (att_name, att_url) in &attachments {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let safe_name = filename::sanitize_path_component(att_name);
+ let ext = att_url.rsplit('.').next().unwrap_or("pdf");
+ let ext = ext.split('?').next().unwrap_or(ext);
+ let att_path = format!("{}/{}.{}", mod_dir, safe_name, ext);
+
+ if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&att_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, att_url, &att_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[estrategia_militares] Attachment download failed for '{}': {}",
+ att_name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &EstrategiaMilitaresCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://militares.estrategia.com/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://militares.estrategia.com/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/mod.rs
new file mode 100644
index 00000000..f3b41d3b
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/mod.rs
@@ -0,0 +1,68 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct EstrategiaMilitaresDownloader;
+
+impl Default for EstrategiaMilitaresDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl EstrategiaMilitaresDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for EstrategiaMilitaresDownloader {
+ fn name(&self) -> &str {
+ "estrategia_militares"
+ }
+
+ 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 == "militares.estrategia.com";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Estratégia Militares".to_string(),
+ author: String::new(),
+ platform: "estrategia_militares".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Estratégia Militares courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/api.rs
new file mode 100644
index 00000000..bf3066ee
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/api.rs
@@ -0,0 +1,516 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct FluencySession {
+ pub token: String,
+ pub email: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub email: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct FluencyCourse {
+ pub id: String,
+ pub name: String,
+ pub program_id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct FluencyModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<FluencyLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct FluencyLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct FluencyLessonDetail {
+ pub id: String,
+ pub name: String,
+ pub video_url: Option<String>,
+ pub description: Option<String>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static("https://academy.fluency.io"),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://academy.fluency.io/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("fluency_session.json"))
+}
+
+pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<FluencySession> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "email": email,
+ "password": password,
+ });
+
+ let resp = temp_client
+ .post("https://accounts-api.fluency.io/auth/sign-in/")
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Authentication failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let token = body
+ .get("access_token")
+ .or_else(|| body.get("accessToken"))
+ .or_else(|| body.get("token"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("access_token not found in login response"))?
+ .to_string();
+
+ let client = build_client(&token)?;
+
+ Ok(FluencySession {
+ token,
+ email: email.to_string(),
+ client,
+ })
+}
+
+pub async fn validate_token(session: &FluencySession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://bifrost.fluencyacademy.io/programs")
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &FluencySession) -> anyhow::Result<Vec<FluencyCourse>> {
+ let resp = session
+ .client
+ .get("https://bifrost.fluencyacademy.io/programs")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_programs returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let programs: serde_json::Value = serde_json::from_str(&body_text)?;
+ let programs_arr = programs.as_array().cloned().unwrap_or_default();
+
+ let mut all_courses = Vec::new();
+
+ for program in &programs_arr {
+ let program_id = program
+ .get("id")
+ .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
+ .unwrap_or_default();
+
+ let program_name = program
+ .get("name")
+ .or_else(|| program.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ for endpoint in &["main", "complement"] {
+ let url = format!(
+ "https://bifrost.fluencyacademy.io/programs/{}/courses/{}",
+ program_id, endpoint
+ );
+
+ let resp = session.client.get(&url).send().await;
+
+ if let Ok(resp) = resp {
+ if resp.status().is_success() {
+ let text = resp.text().await.unwrap_or_default();
+ let courses: serde_json::Value =
+ serde_json::from_str(&text).unwrap_or_default();
+
+ let courses_arr = courses.as_array().cloned().unwrap_or_default();
+
+ for course in &courses_arr {
+ let id = course
+ .get("id")
+ .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
+ .unwrap_or_default();
+
+ let name = course
+ .get("name")
+ .or_else(|| course.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let display_name = if program_name.is_empty() {
+ name
+ } else {
+ format!("{} - {}", program_name, name)
+ };
+
+ all_courses.push(FluencyCourse {
+ id,
+ name: display_name,
+ program_id: program_id.clone(),
+ });
+ }
+ }
+ }
+ }
+ }
+
+ Ok(all_courses)
+}
+
+pub async fn get_modules(
+ session: &FluencySession,
+ course_id: &str,
+) -> anyhow::Result<Vec<FluencyModule>> {
+ let url = format!(
+ "https://bifrost.fluencyacademy.io/courses/{}/learning-path?size=50",
+ course_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_modules returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let content_arr = body
+ .get("content")
+ .or_else(|| body.get("modules"))
+ .or_else(|| body.get("units"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_else(|| {
+ if body.is_array() {
+ body.as_array().cloned().unwrap_or_default()
+ } else {
+ Vec::new()
+ }
+ });
+
+ let mut modules = Vec::new();
+
+ for (i, item) in content_arr.iter().enumerate() {
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
+ .unwrap_or_default();
+
+ let name = item
+ .get("name")
+ .or_else(|| item.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let order = item
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(i as i64);
+
+ let mut lessons = Vec::new();
+
+ let lessons_arr = item
+ .get("lessons")
+ .or_else(|| item.get("units"))
+ .or_else(|| item.get("items"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for (j, lesson_val) in lessons_arr.iter().enumerate() {
+ let lesson_id = lesson_val
+ .get("id")
+ .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
+ .unwrap_or_default();
+
+ let lesson_name = lesson_val
+ .get("name")
+ .or_else(|| lesson_val.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_order = lesson_val
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(j as i64);
+
+ lessons.push(FluencyLesson {
+ id: lesson_id,
+ name: lesson_name,
+ order: lesson_order,
+ });
+ }
+
+ lessons.sort_by_key(|l| l.order);
+
+ modules.push(FluencyModule {
+ id,
+ name,
+ order,
+ lessons,
+ });
+ }
+
+ modules.sort_by_key(|m| m.order);
+
+ Ok(modules)
+}
+
+pub async fn get_lesson_detail(
+ session: &FluencySession,
+ lesson_id: &str,
+) -> anyhow::Result<FluencyLessonDetail> {
+ let url = format!(
+ "https://bifrost.fluencyacademy.io/lessons/{}/tasks",
+ lesson_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lesson_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let tasks = body
+ .as_array()
+ .or_else(|| body.get("tasks").and_then(|v| v.as_array()))
+ .cloned()
+ .unwrap_or_default();
+
+ let mut video_url: Option<String> = None;
+ let mut lesson_name = String::new();
+ let mut description: Option<String> = None;
+
+ for task in &tasks {
+ if lesson_name.is_empty() {
+ if let Some(n) = task.get("name").or_else(|| task.get("title")).and_then(|v| v.as_str()) {
+ lesson_name = n.to_string();
+ }
+ }
+
+ let meta = task.get("meta");
+
+ if let Some(meta) = meta {
+ let sources = meta.get("sources").and_then(|v| v.as_array());
+
+ if let Some(sources) = sources {
+ let mut best_mp4: Option<String> = None;
+ let mut best_height: u64 = 0;
+ let mut hls_url: Option<String> = None;
+
+ for source in sources {
+ let src_url = source
+ .get("src")
+ .or_else(|| source.get("url"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ let src_type = source
+ .get("type")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ let quality = source
+ .get("quality")
+ .or_else(|| source.get("label"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ let height: u64 = quality
+ .chars()
+ .filter(|c| c.is_ascii_digit())
+ .collect::<String>()
+ .parse()
+ .unwrap_or(0);
+
+ if src_type.contains("mp4") || src_url.contains(".mp4") {
+ if height > best_height {
+ best_height = height;
+ best_mp4 = Some(src_url.to_string());
+ }
+ } else if src_type.contains("m3u8")
+ || src_type.contains("hls")
+ || src_url.contains(".m3u8")
+ {
+ hls_url = Some(src_url.to_string());
+ }
+ }
+
+ if best_mp4.is_some() {
+ video_url = best_mp4;
+ } else if hls_url.is_some() {
+ video_url = hls_url;
+ }
+ }
+
+ if video_url.is_none() {
+ if let Some(url) = meta.get("url").or_else(|| meta.get("video_url")).and_then(|v| v.as_str()) {
+ if !url.is_empty() {
+ video_url = Some(url.to_string());
+ }
+ }
+ }
+ }
+
+ if description.is_none() {
+ if let Some(desc) = task.get("description") {
+ let text = desc
+ .get("content")
+ .and_then(|v| v.as_str())
+ .or_else(|| desc.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .map(String::from);
+ if text.is_some() {
+ description = text;
+ }
+ }
+ }
+
+ if video_url.is_some() && description.is_some() {
+ break;
+ }
+ }
+
+ Ok(FluencyLessonDetail {
+ id: lesson_id.to_string(),
+ name: lesson_name,
+ video_url,
+ description,
+ })
+}
+
+pub async fn save_session(session: &FluencySession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ email: session.email.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[fluency] session saved for {}", session.email);
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<FluencySession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[fluency] session loaded for {}", saved.email);
+
+ Ok(Some(FluencySession {
+ token: saved.token,
+ email: saved.email,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/downloader.rs
new file mode 100644
index 00000000..aa032bb9
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/downloader.rs
@@ -0,0 +1,320 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, FluencyCourse, FluencySession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct FluencyCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &FluencySession,
+ course: &FluencyCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_modules(session, &course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[fluency] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &FluencyCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+
+ let detail = match api::get_lesson_detail(session, &lesson.id).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[fluency] Failed to get lesson detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &FluencyCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if let Some(ref desc) = detail.description {
+ let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_desc_dir).await?;
+ omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
+ }
+
+ if let Some(ref video_url) = detail.video_url {
+ let video_ext = if video_url.contains(".m3u8") {
+ "mp4"
+ } else {
+ video_url
+ .rsplit('.')
+ .next()
+ .and_then(|e| {
+ let e = e.split('?').next().unwrap_or(e);
+ if e.len() <= 4 {
+ Some(e)
+ } else {
+ None
+ }
+ })
+ .unwrap_or("mp4")
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.{}",
+ mod_dir,
+ li + 1,
+ lesson_name,
+ video_ext
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[fluency] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &FluencyCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[fluency] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(video_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[fluency] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[fluency] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &FluencyCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://academy.fluency.io/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://academy.fluency.io/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/mod.rs
new file mode 100644
index 00000000..9ef940d3
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/mod.rs
@@ -0,0 +1,69 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct FluencyAcademyDownloader;
+
+impl Default for FluencyAcademyDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl FluencyAcademyDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for FluencyAcademyDownloader {
+ fn name(&self) -> &str {
+ "fluencyacademy"
+ }
+
+ 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 == "fluency.io"
+ || host == "academy.fluency.io";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Fluency Academy".to_string(),
+ author: String::new(),
+ platform: "fluencyacademy".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: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Fluency Academy"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/grancursos/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/grancursos/api.rs
new file mode 100644
index 00000000..4c4aa173
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/grancursos/api.rs
@@ -0,0 +1,450 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const BASE_URL: &str = "https://www.grancursosonline.com.br";
+
+#[derive(Clone)]
+pub struct GranCursosSession {
+ pub cookies: String,
+ pub contract_id: Option<String>,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub cookies: String,
+ pub contract_id: Option<String>,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GranCursosCourse {
+ pub id: i64,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GranCursosDiscipline {
+ pub id: String,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GranCursosModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<GranCursosLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GranCursosLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub video_id: Option<String>,
+}
+
+fn build_client(cookies: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Cookie",
+ HeaderValue::from_str(cookies)?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://www.grancursosonline.com.br/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("grancursos_session.json"))
+}
+
+pub async fn validate_token(session: &GranCursosSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .post(format!("{}/aluno/api/assinatura/buscar-cursos", BASE_URL))
+ .json(&serde_json::json!({"termo": ""}))
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn search_courses(session: &GranCursosSession, query: &str) -> anyhow::Result<(Vec<GranCursosCourse>, Option<String>)> {
+ let resp = session
+ .client
+ .post(format!("{}/aluno/api/assinatura/buscar-cursos", BASE_URL))
+ .json(&serde_json::json!({"termo": query}))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "search_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let mut courses = Vec::new();
+ let mut contract_id = None;
+
+ let items = body
+ .get("data")
+ .or(Some(&body))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_else(|| {
+ body.get("cursos")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default()
+ });
+
+ for item in &items {
+ let id = item
+ .get("codigo")
+ .or_else(|| item.get("id"))
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = item
+ .get("nome")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if contract_id.is_none() {
+ contract_id = item
+ .get("contrato_id")
+ .or_else(|| item.get("contratoId"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .filter(|s| !s.is_empty());
+ }
+
+ if id > 0 {
+ courses.push(GranCursosCourse { id, name });
+ }
+ }
+
+ Ok((courses, contract_id))
+}
+
+pub async fn list_courses(session: &GranCursosSession) -> anyhow::Result<Vec<GranCursosCourse>> {
+ let (courses, _) = search_courses(session, "").await?;
+ Ok(courses)
+}
+
+pub async fn get_disciplines(
+ session: &GranCursosSession,
+ course_id: i64,
+) -> anyhow::Result<Vec<GranCursosDiscipline>> {
+ let url = format!(
+ "{}/aluno/curso/listar-conteudo-aula/codigo/{}/tipo/video",
+ BASE_URL, course_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_disciplines returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let items = body
+ .get("data")
+ .or(Some(&body))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_else(|| {
+ body.get("disciplinas")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default()
+ });
+
+ let mut disciplines = Vec::new();
+
+ for item in &items {
+ let id = item
+ .get("id")
+ .or_else(|| item.get("codigo"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let name = item
+ .get("nome")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if !id.is_empty() {
+ disciplines.push(GranCursosDiscipline { id, name });
+ }
+ }
+
+ Ok(disciplines)
+}
+
+pub async fn get_discipline_content(
+ session: &GranCursosSession,
+ course_id: i64,
+ discipline_id: &str,
+) -> anyhow::Result<Vec<GranCursosModule>> {
+ let url = format!(
+ "{}/aluno/curso/listar-conteudo-aula/codigo/{}/tipo/video/disciplina/{}",
+ BASE_URL, course_id, discipline_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_discipline_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let items = body
+ .get("data")
+ .or(Some(&body))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_else(|| {
+ body.get("conteudos")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default()
+ });
+
+ let mut modules = Vec::new();
+
+ for (ci, content) in items.iter().enumerate() {
+ let content_id = content
+ .get("id")
+ .or_else(|| content.get("codigo"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", ci),
+ })
+ .unwrap_or_else(|| format!("{}", ci));
+
+ let content_name = content
+ .get("nome")
+ .or_else(|| content.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("Content")
+ .to_string();
+
+ let aulas = content
+ .get("aulas")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (ai, aula) in aulas.iter().enumerate() {
+ let aula_id = aula
+ .get("id")
+ .or_else(|| aula.get("codigo"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}-{}", ci, ai),
+ })
+ .unwrap_or_else(|| format!("{}-{}", ci, ai));
+
+ let aula_name = aula
+ .get("nome")
+ .or_else(|| aula.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let video_id = aula
+ .get("video_id")
+ .or_else(|| aula.get("videoId"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .filter(|s| !s.is_empty());
+
+ lessons.push(GranCursosLesson {
+ id: aula_id,
+ name: aula_name,
+ order: ai as i64,
+ video_id,
+ });
+ }
+
+ modules.push(GranCursosModule {
+ id: content_id,
+ name: content_name,
+ order: ci as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_video_url(
+ session: &GranCursosSession,
+ course_id: i64,
+ video_id: &str,
+ contract_id: &str,
+) -> anyhow::Result<String> {
+ let url = format!(
+ "{}/aluno/sala-de-aula/video/co/{}/a/{}/c/{}",
+ BASE_URL, course_id, video_id, contract_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_video_url returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let sources = body
+ .get("player")
+ .and_then(|p| p.get("sources"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_else(|| {
+ body.get("sources")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default()
+ });
+
+ for source in &sources {
+ let file = source
+ .get("file")
+ .or_else(|| source.get("src"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if !file.is_empty() {
+ return Ok(file.to_string());
+ }
+ }
+
+ let direct_url = body
+ .get("url")
+ .or_else(|| body.get("video_url"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if !direct_url.is_empty() {
+ return Ok(direct_url.to_string());
+ }
+
+ Err(anyhow!("No video URL found in response"))
+}
+
+pub async fn save_session(session: &GranCursosSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ cookies: session.cookies.clone(),
+ contract_id: session.contract_id.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[grancursos] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<GranCursosSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.cookies)?;
+
+ tracing::info!("[grancursos] session loaded");
+
+ Ok(Some(GranCursosSession {
+ cookies: saved.cookies,
+ contract_id: saved.contract_id,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/grancursos/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/grancursos/downloader.rs
new file mode 100644
index 00000000..473f56ad
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/grancursos/downloader.rs
@@ -0,0 +1,311 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, GranCursosCourse, GranCursosSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct GranCursosCourseDownloadProgress {
+ pub course_id: i64,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &GranCursosSession,
+ course: &GranCursosCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let contract_id = session
+ .contract_id
+ .as_deref()
+ .unwrap_or("0");
+
+ let disciplines = api::get_disciplines(session, course.id).await?;
+
+ if disciplines.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no disciplines available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[grancursos] course already complete, skipping");
+ return Ok(());
+ }
+
+ let mut all_modules = Vec::new();
+
+ for discipline in &disciplines {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let modules = api::get_discipline_content(session, course.id, &discipline.id).await?;
+
+ for module in modules {
+ let prefixed_name = format!("{} - {}", discipline.name, module.name);
+ all_modules.push(super::api::GranCursosModule {
+ id: module.id,
+ name: prefixed_name,
+ order: module.order,
+ lessons: module.lessons,
+ });
+ }
+ }
+
+ if all_modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no content available for download",
+ course.name
+ ));
+ }
+
+ let total_lessons: usize = all_modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = all_modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &GranCursosCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in all_modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+
+ if let Some(ref vid_id) = lesson.video_id {
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[grancursos] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &GranCursosCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ match api::get_video_url(session, course.id, vid_id, contract_id).await {
+ Ok(video_url) => {
+ if video_url.contains(".m3u8") {
+ match download_hls_video(&video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[grancursos] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[grancursos] yt-dlp failed for '{}': {}, trying direct",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, &video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[grancursos] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(
+ "[grancursos] Failed to get video URL for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &GranCursosCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://www.grancursosonline.com.br/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://www.grancursosonline.com.br/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/grancursos/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/grancursos/mod.rs
new file mode 100644
index 00000000..436b32e6
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/grancursos/mod.rs
@@ -0,0 +1,69 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct GrancursosDownloader;
+
+impl Default for GrancursosDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl GrancursosDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for GrancursosDownloader {
+ fn name(&self) -> &str {
+ "grancursos"
+ }
+
+ 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 == "grancursosonline.com.br"
+ || host == "www.grancursosonline.com.br";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Gran Cursos".to_string(),
+ author: String::new(),
+ platform: "grancursos".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: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Gran Cursos"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/api.rs
new file mode 100644
index 00000000..fc8cef98
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/api.rs
@@ -0,0 +1,396 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct WondriumSession {
+ pub token: String,
+ pub email: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub email: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WondriumCourse {
+ pub id: String,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WondriumModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<WondriumLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WondriumLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub video_id: Option<String>,
+ pub guidebook_url: Option<String>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("wondrium_session.json"))
+}
+
+pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<WondriumSession> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "username": email,
+ "password": password,
+ });
+
+ let resp = temp_client
+ .post("https://www.thegreatcoursesplus.com/rest/V1/integration/customer/token")
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Authentication failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let token = body_text.trim().trim_matches('"').to_string();
+
+ if token.is_empty() {
+ return Err(anyhow!("Empty token in login response"));
+ }
+
+ let client = build_client(&token)?;
+
+ Ok(WondriumSession {
+ token,
+ email: email.to_string(),
+ client,
+ })
+}
+
+pub async fn validate_token(session: &WondriumSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://www.thegreatcoursesplus.com/rest/all/V2/watchlist/mine/items")
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &WondriumSession) -> anyhow::Result<Vec<WondriumCourse>> {
+ let resp = session
+ .client
+ .get("https://www.thegreatcoursesplus.com/rest/all/V2/watchlist/mine/items")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let mut courses = Vec::new();
+
+ let items = body
+ .get("items")
+ .and_then(|v| v.as_array())
+ .or_else(|| body.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for item in &items {
+ let id = item
+ .get("product_id")
+ .or_else(|| item.get("id"))
+ .or_else(|| item.get("sku"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let name = item
+ .get("name")
+ .or_else(|| item.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if !id.is_empty() && !name.is_empty() {
+ courses.push(WondriumCourse { id, name });
+ }
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_course_content(
+ session: &WondriumSession,
+ course_id: &str,
+) -> anyhow::Result<Vec<WondriumModule>> {
+ let url = format!(
+ "https://m2api.thegreatcourses.com/rest/all/V1/dlo_products/{}",
+ course_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let lectures = body
+ .get("lectures")
+ .or_else(|| body.get("episodes"))
+ .or_else(|| body.get("items"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+ let mut current_module: Option<WondriumModule> = None;
+ let mut module_index = 0;
+
+ for (li, lecture) in lectures.iter().enumerate() {
+ let lecture_id = lecture
+ .get("id")
+ .or_else(|| lecture.get("lecture_id"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", li),
+ })
+ .unwrap_or_else(|| format!("{}", li));
+
+ let lecture_name = lecture
+ .get("title")
+ .or_else(|| lecture.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let video_id = lecture
+ .get("video_id")
+ .or_else(|| lecture.get("videoId"))
+ .or_else(|| lecture.get("media_id"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .filter(|s| !s.is_empty());
+
+ let guidebook_url = lecture
+ .get("guidebook_url")
+ .or_else(|| lecture.get("pdf_url"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let section = lecture
+ .get("section")
+ .or_else(|| lecture.get("part"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("Lectures");
+
+ let lesson = WondriumLesson {
+ id: lecture_id,
+ name: lecture_name,
+ order: li as i64,
+ video_id,
+ guidebook_url,
+ };
+
+ match &mut current_module {
+ Some(m) if m.name == section => {
+ m.lessons.push(lesson);
+ }
+ _ => {
+ if let Some(m) = current_module.take() {
+ modules.push(m);
+ }
+ module_index += 1;
+ current_module = Some(WondriumModule {
+ id: format!("{}", module_index),
+ name: section.to_string(),
+ order: module_index as i64 - 1,
+ lessons: vec![lesson],
+ });
+ }
+ }
+ }
+
+ if let Some(m) = current_module {
+ modules.push(m);
+ }
+
+ if modules.is_empty() && !lectures.is_empty() {
+ let mut all_lessons = Vec::new();
+ for (li, lecture) in lectures.iter().enumerate() {
+ let lecture_id = lecture
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", li),
+ })
+ .unwrap_or_else(|| format!("{}", li));
+
+ let lecture_name = lecture
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let video_id = lecture
+ .get("video_id")
+ .or_else(|| lecture.get("media_id"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .filter(|s| !s.is_empty());
+
+ let guidebook_url = lecture
+ .get("guidebook_url")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ all_lessons.push(WondriumLesson {
+ id: lecture_id,
+ name: lecture_name,
+ order: li as i64,
+ video_id,
+ guidebook_url,
+ });
+ }
+
+ modules.push(WondriumModule {
+ id: "1".to_string(),
+ name: "Lectures".to_string(),
+ order: 0,
+ lessons: all_lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+pub fn get_video_url(video_id: &str) -> String {
+ format!(
+ "https://link.theplatform.com/s/jESqeC/media/guid/2140042498/{}?manifest=m3u",
+ video_id
+ )
+}
+
+pub async fn save_session(session: &WondriumSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ email: session.email.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[wondrium] session saved for {}", session.email);
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<WondriumSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[wondrium] session loaded for {}", saved.email);
+
+ Ok(Some(WondriumSession {
+ token: saved.token,
+ email: saved.email,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/downloader.rs
new file mode 100644
index 00000000..e7a62c34
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/downloader.rs
@@ -0,0 +1,279 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, WondriumCourse, WondriumSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct WondriumCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &WondriumSession,
+ course: &WondriumCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, &course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[wondrium] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &WondriumCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+
+ if let Some(ref vid_id) = lesson.video_id {
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[wondrium] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &WondriumCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ let video_url = api::get_video_url(vid_id);
+
+ match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[wondrium] yt-dlp failed for '{}': {}, trying HLS",
+ lesson.name,
+ e
+ );
+ match download_hls_video(&video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[wondrium] HLS download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ }
+ }
+ }
+
+ if let Some(ref pdf_url) = lesson.guidebook_url {
+ let pdf_path = format!(
+ "{}/{}. {}.pdf",
+ mod_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if !tokio::fs::try_exists(&pdf_path).await.unwrap_or(false) {
+ match download_file_direct(&session.client, pdf_url, &pdf_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[wondrium] PDF download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &WondriumCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://www.thegreatcoursesplus.com/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://www.thegreatcoursesplus.com/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &["--force-generic-extractor".to_string()],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/mod.rs
new file mode 100644
index 00000000..b8775a70
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/mod.rs
@@ -0,0 +1,71 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct GreatCoursesDownloader;
+
+impl Default for GreatCoursesDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl GreatCoursesDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for GreatCoursesDownloader {
+ fn name(&self) -> &str {
+ "greatcourses"
+ }
+
+ 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 == "thegreatcoursesplus.com"
+ || host == "www.thegreatcoursesplus.com"
+ || host == "wondrium.com"
+ || host == "www.wondrium.com";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Wondrium Course".to_string(),
+ author: String::new(),
+ platform: "greatcourses".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Wondrium courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greennclub/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/greennclub/api.rs
new file mode 100644
index 00000000..fcf1c981
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/greennclub/api.rs
@@ -0,0 +1,396 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct GreennSession {
+ pub token: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GreennCourse {
+ pub id: i64,
+ pub name: String,
+ pub lessons_count: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GreennModule {
+ pub id: i64,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<GreennLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GreennLesson {
+ pub id: i64,
+ pub name: String,
+ pub order: i64,
+ pub media_type: Option<String>,
+ pub source: Option<String>,
+ pub content: Option<String>,
+ pub duration: Option<f64>,
+ pub attachments: Vec<GreennAttachment>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GreennAttachment {
+ pub url: String,
+ pub name: String,
+ pub size: Option<u64>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(token)?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static("https://greenn.club"),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://greenn.club/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("greenn_session.json"))
+}
+
+pub async fn validate_token(session: &GreennSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://api.greenn.club/home")
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &GreennSession) -> anyhow::Result<Vec<GreennCourse>> {
+ let resp = session
+ .client
+ .get("https://api.greenn.club/home")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let courses_arr = body
+ .get("courses")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut all_courses = Vec::new();
+
+ for item in &courses_arr {
+ let has_access = item
+ .get("has_access")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ if !has_access {
+ continue;
+ }
+
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lessons_count = item
+ .get("lessons_count")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ all_courses.push(GreennCourse {
+ id,
+ name,
+ lessons_count,
+ });
+ }
+
+ Ok(all_courses)
+}
+
+pub async fn get_modules(
+ session: &GreennSession,
+ course_id: i64,
+) -> anyhow::Result<Vec<GreennModule>> {
+ let url = format!(
+ "https://api.greenn.club/course/{}/watch?data[]=course&data[]=modules",
+ course_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_modules returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let modules_arr = body
+ .get("modules")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for item in &modules_arr {
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let order = item
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ modules.push(GreennModule {
+ id,
+ name,
+ order,
+ lessons: Vec::new(),
+ });
+ }
+
+ modules.sort_by_key(|m| m.order);
+
+ Ok(modules)
+}
+
+pub async fn get_lessons(
+ session: &GreennSession,
+ course_id: i64,
+ module_id: i64,
+) -> anyhow::Result<Vec<GreennLesson>> {
+ let url = format!(
+ "https://api.greenn.club/course/{}/watch?data[]=currentModuleLessons&current_module_id={}",
+ course_id, module_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lessons returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let lessons_arr = body
+ .get("currentModuleLessons")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for item in &lessons_arr {
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let order = item
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let media_type = item
+ .get("mediaType")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let source = item
+ .get("source")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let content = item
+ .get("content")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let duration = item
+ .get("duration")
+ .and_then(|v| v.as_f64());
+
+ let attachments = item
+ .get("attachments")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|a| {
+ let url = a
+ .get("cdn_url")
+ .or_else(|| a.get("path"))
+ .and_then(|v| v.as_str())?
+ .to_string();
+
+ let att_name = a
+ .get("title")
+ .or_else(|| a.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("attachment")
+ .to_string();
+
+ let size = a
+ .get("size")
+ .and_then(|v| v.as_u64());
+
+ Some(GreennAttachment {
+ url,
+ name: att_name,
+ size,
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+
+ lessons.push(GreennLesson {
+ id,
+ name,
+ order,
+ media_type,
+ source,
+ content,
+ duration,
+ attachments,
+ });
+ }
+
+ lessons.sort_by_key(|l| l.order);
+
+ Ok(lessons)
+}
+
+pub fn extract_panda_video_id(source: &str) -> Option<String> {
+ let re = regex::Regex::new(r"[?&]v=([a-f0-9-]+)").ok()?;
+ re.captures(source).map(|c| c[1].to_string())
+}
+
+pub async fn save_session(session: &GreennSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[greenn] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<GreennSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[greenn] session loaded");
+
+ Ok(Some(GreennSession {
+ token: saved.token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greennclub/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/greennclub/downloader.rs
new file mode 100644
index 00000000..a6526f0e
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/greennclub/downloader.rs
@@ -0,0 +1,342 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, GreennCourse, GreennSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct GreennCourseDownloadProgress {
+ pub course_id: i64,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &GreennSession,
+ course: &GreennCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let mut modules = api::get_modules(session, course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ for module in &mut modules {
+ let lessons = api::get_lessons(session, course.id, module.id).await?;
+ module.lessons = lessons;
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &GreennCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ if let Some(ref content) = lesson.content {
+ omniget_core::core::course_utils::save_description(&lesson_dir, content, "html").await.ok();
+ }
+
+ let mut video_url: Option<String> = None;
+
+ if let Some(ref source) = lesson.source {
+ if let Some(ref mt) = lesson.media_type {
+ if mt.contains("panda") {
+ if let Some(_vid) = api::extract_panda_video_id(source) {
+ video_url = Some(source.clone());
+ }
+ }
+ }
+
+ if video_url.is_none()
+ && (source.contains("http://") || source.contains("https://"))
+ {
+ video_url = Some(source.clone());
+ }
+ }
+
+ if let Some(ref url) = video_url {
+ let video_ext = if url.contains(".m3u8") {
+ "mp4"
+ } else {
+ url.rsplit('.')
+ .next()
+ .and_then(|e| {
+ let e = e.split('?').next().unwrap_or(e);
+ if e.len() <= 4 {
+ Some(e)
+ } else {
+ None
+ }
+ })
+ .unwrap_or("mp4")
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.{}",
+ lesson_dir,
+ li + 1,
+ lesson_name,
+ video_ext
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[greenn] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &GreennCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if url.contains(".m3u8") {
+ match download_hls_video(url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[greenn] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(url, &lesson_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[greenn] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[greenn] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for attachment in &lesson.attachments {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let att_name = filename::sanitize_path_component(&attachment.name);
+ let att_path = format!("{}/{}", lesson_dir, att_name);
+
+ if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&att_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, &attachment.url, &att_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[greenn] Attachment download failed for '{}': {}",
+ attachment.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &GreennCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://greenn.club/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://greenn.club/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greennclub/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/greennclub/mod.rs
new file mode 100644
index 00000000..f6180295
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/greennclub/mod.rs
@@ -0,0 +1,63 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct GreennClubDownloader;
+
+impl GreennClubDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+impl Default for GreennClubDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for GreennClubDownloader {
+ fn name(&self) -> &str {
+ "greennclub"
+ }
+
+ 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 == "greenn.club"
+ || host.ends_with(".greenn.club");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Greenn Club".to_string(),
+ author: String::new(),
+ platform: "greennclub".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Greenn Club"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/gumroad/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/gumroad/api.rs
new file mode 100644
index 00000000..2d2cdbb4
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/gumroad/api.rs
@@ -0,0 +1,353 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "okhttp/4.8.1";
+const CLIENT_ID: &str = "46410c2fb9aa741c1f03cdea099929c795d20de0282b352eac881dfa46b2b89c";
+const CLIENT_SECRET: &str = "e2fa7dc5bc347d09820a3931d4ce10e1137a02577ce647b33c60670a72b1acd5";
+const MOBILE_TOKEN: &str = "ps407sr3rno1561ro2o4n360q21248s4o24oq33770rpro59o11q9r5469ososoo";
+
+const MEDIA_EXTENSIONS: &[&str] = &[
+ "mp4", "mkv", "avi", "mov", "webm", "mp3", "wav", "flac", "aac", "ogg", "m4a", "wma",
+];
+
+#[derive(Clone)]
+pub struct GumroadSession {
+ pub token: String,
+ pub email: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub email: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GumroadProduct {
+ pub id: String,
+ pub name: String,
+ pub creator_name: String,
+ pub preview_url: Option<String>,
+ pub url_redirect_token: String,
+ pub file_count: usize,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GumroadFile {
+ pub id: String,
+ pub name: String,
+ pub filetype: String,
+ pub filegroup: String,
+ pub download_url: Option<String>,
+ pub size: u64,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("gumroad_session.json"))
+}
+
+pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<GumroadSession> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let params = [
+ ("grant_type", "password"),
+ ("username", email),
+ ("password", password),
+ ("scope", "mobile_api creator_api"),
+ ("client_id", CLIENT_ID),
+ ("client_secret", CLIENT_SECRET),
+ ];
+
+ let resp = temp_client
+ .post("https://gumroad.com/oauth/token")
+ .form(&params)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Authentication failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let token = body
+ .get("access_token")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("access_token not found in login response"))?
+ .to_string();
+
+ let client = build_client(&token)?;
+
+ Ok(GumroadSession {
+ token,
+ email: email.to_string(),
+ client,
+ })
+}
+
+pub async fn validate_token(session: &GumroadSession) -> anyhow::Result<bool> {
+ let url = format!(
+ "https://api.gumroad.com/mobile/purchases/index.json?include_subscriptions=true&include_mobile_unfriendly_products=true&mobile_token={}",
+ MOBILE_TOKEN
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ if !resp.status().is_success() {
+ return Ok(false);
+ }
+
+ let body: serde_json::Value = resp.json().await?;
+ Ok(body.get("success").and_then(|v| v.as_bool()).unwrap_or(false))
+}
+
+pub async fn list_products(session: &GumroadSession) -> anyhow::Result<Vec<GumroadProduct>> {
+ let url = format!(
+ "https://api.gumroad.com/mobile/purchases/index.json?include_subscriptions=true&include_mobile_unfriendly_products=true&mobile_token={}",
+ MOBILE_TOKEN
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_products returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let success = body.get("success").and_then(|v| v.as_bool()).unwrap_or(false);
+ if !success {
+ return Err(anyhow!("API returned success=false"));
+ }
+
+ let products = body
+ .get("products")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut result = Vec::new();
+
+ for p in &products {
+ if p.get("refunded").and_then(|v| v.as_bool()).unwrap_or(false) {
+ continue;
+ }
+ if p.get("partially_refunded").and_then(|v| v.as_bool()).unwrap_or(false) {
+ continue;
+ }
+ if p.get("chargedback").and_then(|v| v.as_bool()).unwrap_or(false) {
+ continue;
+ }
+ if p.get("is_archived").and_then(|v| v.as_bool()).unwrap_or(false) {
+ continue;
+ }
+
+ let id = p.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let name = p.get("name").and_then(|v| v.as_str()).unwrap_or("unnamed").to_string();
+ let creator_name = p.get("creator_name").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let preview_url = p.get("preview_url").and_then(|v| v.as_str()).map(String::from);
+ let url_redirect_token = p
+ .get("url_redirect_token")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let file_count = p
+ .get("file_data")
+ .and_then(|v| v.as_array())
+ .map(|a| a.len())
+ .unwrap_or(0);
+
+ result.push(GumroadProduct {
+ id,
+ name,
+ creator_name,
+ preview_url,
+ url_redirect_token,
+ file_count,
+ });
+ }
+
+ Ok(result)
+}
+
+pub async fn get_product_files(
+ _session: &GumroadSession,
+ product_json: &serde_json::Value,
+) -> Vec<GumroadFile> {
+ let file_data = product_json
+ .get("file_data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut files = Vec::new();
+
+ for f in &file_data {
+ let id = f.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let name = f.get("name").and_then(|v| v.as_str()).unwrap_or("file").to_string();
+ let filetype = f
+ .get("filetype")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_lowercase();
+ let filegroup = f
+ .get("filegroup")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_lowercase();
+ let download_url = f.get("download_url").and_then(|v| v.as_str()).map(String::from);
+ let size = f.get("size").and_then(|v| v.as_u64()).unwrap_or(0);
+
+ files.push(GumroadFile {
+ id,
+ name,
+ filetype,
+ filegroup,
+ download_url,
+ size,
+ });
+ }
+
+ files
+}
+
+pub fn is_media_file(file: &GumroadFile) -> bool {
+ if file.filegroup == "video" || file.filegroup == "audio" {
+ return true;
+ }
+ MEDIA_EXTENSIONS.contains(&file.filetype.as_str())
+}
+
+pub async fn get_stream_url(
+ session: &GumroadSession,
+ url_redirect_token: &str,
+ file_id: &str,
+) -> anyhow::Result<String> {
+ let url = format!(
+ "https://api.gumroad.com/mobile/url_redirects/stream/{}/{}?mobile_token={}",
+ url_redirect_token, file_id, MOBILE_TOKEN
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_stream_url returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let playlist_url = body
+ .get("playlist_url")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("No playlist_url in stream response"))?
+ .to_string();
+
+ Ok(playlist_url)
+}
+
+pub fn get_direct_download_url(url_redirect_token: &str, file_id: &str) -> String {
+ format!(
+ "https://api.gumroad.com/mobile/url_redirects/download/{}/{}?mobile_token={}",
+ url_redirect_token, file_id, MOBILE_TOKEN
+ )
+}
+
+pub async fn save_session(session: &GumroadSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ email: session.email.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[gumroad] session saved for {}", session.email);
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<GumroadSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[gumroad] session loaded for {}", saved.email);
+
+ Ok(Some(GumroadSession {
+ token: saved.token,
+ email: saved.email,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/gumroad/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/gumroad/downloader.rs
new file mode 100644
index 00000000..a3c3ddaa
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/gumroad/downloader.rs
@@ -0,0 +1,245 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, GumroadProduct, GumroadSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct GumroadDownloadProgress {
+ pub product_id: String,
+ pub product_name: String,
+ pub percent: f64,
+ pub current_file: String,
+ pub downloaded_bytes: u64,
+ pub total_files: u32,
+ pub completed_files: u32,
+}
+
+pub async fn download_product(
+ app: &tauri::AppHandle,
+ session: &GumroadSession,
+ product: &GumroadProduct,
+ product_raw: &serde_json::Value,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let files = api::get_product_files(session, product_raw).await;
+
+ if files.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no files available for download",
+ product.name
+ ));
+ }
+
+ let product_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&product.name)
+ );
+ tokio::fs::create_dir_all(&product_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&product_dir) {
+ return Ok(());
+ }
+
+ let total_files = files.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &GumroadDownloadProgress {
+ product_id: product.id.clone(),
+ product_name: product.name.clone(),
+ percent: 0.0,
+ current_file: "Starting...".to_string(),
+ downloaded_bytes: 0,
+ total_files: total_files as u32,
+ completed_files: 0,
+ },
+ );
+
+ for (_i, file) in files.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let file_name = filename::sanitize_path_component(&file.name);
+ let dest_path = format!("{}/{}", product_dir, file_name);
+
+ if tokio::fs::try_exists(&dest_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&dest_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[gumroad] Skipping existing: {}", dest_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &GumroadDownloadProgress {
+ product_id: product.id.clone(),
+ product_name: product.name.clone(),
+ percent: done as f64 / total_files as f64 * 100.0,
+ current_file: file.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_files: total_files as u32,
+ completed_files: done as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if api::is_media_file(file) {
+ match api::get_stream_url(session, &product.url_redirect_token, &file.id).await {
+ Ok(playlist_url) => {
+ match download_with_ytdlp(
+ &playlist_url,
+ &product_dir,
+ &session.token,
+ &cancel_token,
+ )
+ .await
+ {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[gumroad] yt-dlp download failed for '{}': {}",
+ file.name,
+ e
+ );
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(
+ "[gumroad] Failed to get stream URL for '{}': {}, trying direct download",
+ file.name,
+ e
+ );
+ let download_url = file
+ .download_url
+ .clone()
+ .unwrap_or_else(|| api::get_direct_download_url(&product.url_redirect_token, &file.id));
+ match download_file_direct(&session.client, &download_url, &dest_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[gumroad] Direct download also failed for '{}': {}",
+ file.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ } else {
+ let download_url = file
+ .download_url
+ .clone()
+ .unwrap_or_else(|| api::get_direct_download_url(&product.url_redirect_token, &file.id));
+ match download_file_direct(&session.client, &download_url, &dest_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[gumroad] File download failed for '{}': {}",
+ file.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &GumroadDownloadProgress {
+ product_id: product.id.clone(),
+ product_name: product.name.clone(),
+ percent: done as f64 / total_files as f64 * 100.0,
+ current_file: file.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_files: total_files as u32,
+ completed_files: done as u32,
+ },
+ );
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&product_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ token: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let auth_header = format!("Authorization: Bearer {}", token);
+ let extra_args: Vec<String> = vec![
+ "--add-header".to_string(),
+ auth_header,
+ "--add-header".to_string(),
+ "User-Agent: okhttp/4.8.1".to_string(),
+ ];
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://gumroad.com/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &extra_args,
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/gumroad/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/gumroad/mod.rs
new file mode 100644
index 00000000..e151c7cb
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/gumroad/mod.rs
@@ -0,0 +1,68 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct GumroadDownloader;
+
+impl Default for GumroadDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl GumroadDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for GumroadDownloader {
+ fn name(&self) -> &str {
+ "gumroad"
+ }
+
+ 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 == "gumroad.com" || host.ends_with(".gumroad.com");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Gumroad Course".to_string(),
+ author: String::new(),
+ platform: "gumroad".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Gumroad courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/hotmart/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/api.rs
new file mode 100644
index 00000000..a58bb513
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/api.rs
@@ -0,0 +1,491 @@
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+use super::auth::HotmartSession;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Course {
+ pub id: u64,
+ pub name: String,
+ pub slug: Option<String>,
+ pub seller: String,
+ pub subdomain: Option<String>,
+ pub is_hotmart_club: bool,
+ pub price: Option<f64>,
+ pub image_url: Option<String>,
+ pub category: Option<String>,
+ pub external_platform: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Module {
+ pub id: String,
+ pub name: String,
+ pub pages: Vec<PageInfo>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PageInfo {
+ pub hash: String,
+ pub name: String,
+ pub page_type: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Lesson {
+ pub hash: String,
+ pub name: String,
+ pub content: Option<String>,
+ pub has_media: bool,
+ pub medias: Vec<LessonMedia>,
+ pub attachments: Vec<Attachment>,
+ pub complementary_readings: Option<Vec<ReadingLink>>,
+ pub locked: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LessonMedia {
+ pub name: String,
+ pub code: String,
+ pub url: String,
+ pub media_type: String,
+ pub size: Option<u64>,
+ pub duration: Option<u64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Attachment {
+ pub file_membership_id: String,
+ pub file_name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ReadingLink {
+ pub title: Option<String>,
+ pub url: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AttachmentInfo {
+ pub url: String,
+ pub file_name: Option<String>,
+ pub token: Option<String>,
+ pub lambda_url: Option<String>,
+ pub is_drm: bool,
+}
+
+#[derive(Debug, Clone)]
+pub struct SubdomainInfo {
+ pub product_id: u64,
+ pub subdomain: String,
+}
+
+pub fn navigation_headers(token: &str, slug: &str, product_id: u64) -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ headers.insert("Accept", HeaderValue::from_static("application/json, text/plain, */*"));
+ headers.insert("Authorization", format!("Bearer {}", token).parse().unwrap());
+ headers.insert("Origin", HeaderValue::from_static("https://hotmart.com"));
+ headers.insert("Referer", HeaderValue::from_static("https://hotmart.com"));
+ headers.insert("Pragma", HeaderValue::from_static("no-cache"));
+ headers.insert("cache-control", HeaderValue::from_static("no-cache"));
+ headers.insert("slug", slug.parse().unwrap());
+ headers.insert("x-product-id", product_id.to_string().parse().unwrap());
+ headers
+}
+
+pub async fn get_subdomains(session: &HotmartSession) -> anyhow::Result<Vec<SubdomainInfo>> {
+ let resp = session
+ .client
+ .post("https://api-sec-vlc.hotmart.com/security/oauth/check_token")
+ .form(&[("token", &session.token)])
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!("check_token retornou status {}: {}", status, &body_text[..500.min(body_text.len())]));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let resources = body
+ .get("resources")
+ .and_then(|r| r.as_array())
+ .ok_or_else(|| anyhow!("Field 'resources' not found in check_token"))?;
+
+ let mut subdomains = Vec::new();
+ for res in resources {
+ let resource = match res.get("resource") {
+ Some(r) => r,
+ None => continue,
+ };
+ let product_id = resource
+ .get("productId")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(0);
+ let subdomain = resource
+ .get("subdomain")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if product_id > 0 && !subdomain.is_empty() {
+ subdomains.push(SubdomainInfo {
+ product_id,
+ subdomain,
+ });
+ }
+ }
+
+ Ok(subdomains)
+}
+
+pub async fn list_courses(session: &HotmartSession) -> anyhow::Result<Vec<Course>> {
+ let resp = session
+ .client
+ .get("https://api-hub.cb.hotmart.com/club-drive-api/rest/v2/purchase/?archived=UNARCHIVED")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!("list_courses retornou status {}: {}", status, &body_text[..500.min(body_text.len())]));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let purchases = body
+ .get("data")
+ .and_then(|d| d.as_array())
+ .or_else(|| body.get("purchases").and_then(|p| p.as_array()))
+ .or_else(|| body.as_array())
+ .ok_or_else(|| anyhow!("Formato inesperado na resposta de cursos: sem campo 'data', 'purchases' ou array raiz"))?;
+
+ let mut courses = Vec::new();
+ for p in purchases {
+ let product = p.get("product").unwrap_or(p);
+
+ let id = product.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
+ let name = product.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
+
+ let seller = product
+ .get("seller")
+ .and_then(|s| s.get("name").and_then(|n| n.as_str()))
+ .or_else(|| {
+ p.get("producer")
+ .or_else(|| p.get("seller"))
+ .and_then(|s| s.get("name").and_then(|n| n.as_str()))
+ })
+ .unwrap_or("")
+ .to_string();
+
+ let slug = product
+ .get("hotmartClub")
+ .and_then(|hc| hc.get("slug").and_then(|s| s.as_str()))
+ .map(String::from);
+
+ let is_hotmart_club = slug.is_some()
+ || p.get("accessRights")
+ .and_then(|a| a.get("hasClubAccess"))
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ let category = product.get("category").and_then(|v| v.as_str()).map(String::from);
+ let image_url = product.get("picture").and_then(|v| v.as_str()).map(String::from);
+
+ courses.push(Course {
+ id,
+ name,
+ slug,
+ seller,
+ subdomain: None,
+ is_hotmart_club,
+ price: None,
+ image_url,
+ category,
+ external_platform: false,
+ });
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_course_price(session: &HotmartSession, product_id: u64) -> anyhow::Result<f64> {
+ let url = format!(
+ "https://api-hub.cb.hotmart.com/club-drive-api/rest/v2/purchase/products/{}",
+ product_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ if !status.is_success() {
+ return Err(anyhow!("Price not available (status {})", status));
+ }
+
+ let body: serde_json::Value = resp.json().await?;
+
+ let price = body
+ .get("purchases")
+ .and_then(|p| p.as_array())
+ .and_then(|arr| arr.first())
+ .and_then(|purchase| purchase.get("value"))
+ .and_then(|v| v.as_f64())
+ .or_else(|| body.get("value").and_then(|v| v.as_f64()))
+ .unwrap_or(0.0);
+
+ Ok(price)
+}
+
+pub fn merge_subdomains(courses: &mut [Course], subdomains: &[SubdomainInfo]) {
+ for course in courses.iter_mut() {
+ if let Some(info) = subdomains.iter().find(|s| s.product_id == course.id) {
+ course.subdomain = Some(info.subdomain.clone());
+ if course.slug.is_none() {
+ course.slug = Some(info.subdomain.clone());
+ }
+ }
+
+ if course.slug.is_none() && course.subdomain.is_none() {
+ course.external_platform = true;
+ }
+ }
+}
+
+pub async fn get_modules(
+ session: &HotmartSession,
+ slug: &str,
+ product_id: u64,
+) -> anyhow::Result<Vec<Module>> {
+ let resp = session
+ .client
+ .get("https://api-club-course-consumption-gateway-ga.cb.hotmart.com/v1/navigation")
+ .headers(navigation_headers(&session.token, slug, product_id))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!("get_modules retornou status {}: {}", status, &body_text[..500.min(body_text.len())]));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let modules_json = body
+ .get("modules")
+ .and_then(|m| m.as_array())
+ .or_else(|| body.as_array())
+ .ok_or_else(|| anyhow!("Unexpected format in modules response"))?;
+
+ let mut modules = Vec::new();
+ for m in modules_json {
+ let id = m
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+ let name = m.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
+
+ let pages_json = m
+ .get("pages")
+ .and_then(|p| p.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let pages = pages_json
+ .iter()
+ .map(|p| PageInfo {
+ hash: p.get("hash").and_then(|v| v.as_str()).unwrap_or("").to_string(),
+ name: p.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(),
+ page_type: p
+ .get("type")
+ .or_else(|| p.get("pageType"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
+ })
+ .collect();
+
+ modules.push(Module { id, name, pages });
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_lesson(
+ session: &HotmartSession,
+ slug: &str,
+ product_id: u64,
+ page_hash: &str,
+) -> anyhow::Result<Lesson> {
+ let url = format!(
+ "https://api-club-course-consumption-gateway-ga.cb.hotmart.com/v2/web/lessons/{}",
+ page_hash
+ );
+ let resp = session
+ .client
+ .get(&url)
+ .headers(navigation_headers(&session.token, slug, product_id))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ if !status.is_success() {
+ let body_text = resp.text().await.unwrap_or_default();
+ return Err(anyhow!("get_lesson retornou status {}: {}", status, &body_text[..500.min(body_text.len())]));
+ }
+
+ let body: serde_json::Value = resp.json().await?;
+
+ if let Some(msg) = body.get("message").and_then(|v| v.as_str()) {
+ return Err(anyhow!("Lesson unavailable: {}", msg));
+ }
+
+ let hash = body.get("hash").and_then(|v| v.as_str()).unwrap_or(page_hash).to_string();
+ let name = body.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let content = body.get("content").and_then(|v| v.as_str()).map(String::from);
+ let locked = body.get("locked").and_then(|v| v.as_bool()).unwrap_or(false);
+
+ let has_media = body
+ .get("hasMedia")
+ .or_else(|| body.get("hasPlayerMedia"))
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ let medias_arr = body
+ .get("medias")
+ .or_else(|| body.get("mediasSrc"))
+ .and_then(|v| v.as_array());
+
+ let medias: Vec<LessonMedia> = medias_arr
+ .map(|arr| {
+ arr.iter()
+ .map(|m| LessonMedia {
+ name: m.get("name")
+ .or_else(|| m.get("mediaName"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
+ code: m.get("code")
+ .or_else(|| m.get("mediaCode"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
+ url: m.get("url")
+ .or_else(|| m.get("mediaSrcUrl"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
+ media_type: m.get("type")
+ .or_else(|| m.get("mediaType"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
+ size: m.get("size").and_then(|v| v.as_u64()),
+ duration: m.get("duration").and_then(|v| v.as_u64()),
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+
+ let attachments: Vec<Attachment> = body
+ .get("attachments")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .map(|a| Attachment {
+ file_membership_id: a
+ .get("fileMembershipId")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default(),
+ file_name: a.get("fileName").and_then(|v| v.as_str()).unwrap_or("").to_string(),
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+
+ let complementary_readings = body
+ .get("complementaryReadings")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .map(|r| ReadingLink {
+ title: r.get("articleName")
+ .or_else(|| r.get("title"))
+ .and_then(|v| v.as_str())
+ .map(String::from),
+ url: r.get("articleUrl")
+ .or_else(|| r.get("url"))
+ .and_then(|v| v.as_str())
+ .map(String::from),
+ })
+ .collect()
+ });
+
+ Ok(Lesson {
+ hash,
+ name,
+ content,
+ has_media,
+ medias,
+ attachments,
+ complementary_readings,
+ locked,
+ })
+}
+
+pub async fn get_attachment_url(
+ session: &HotmartSession,
+ id: &str,
+) -> anyhow::Result<AttachmentInfo> {
+ let url = format!(
+ "https://api-club-hot-club-api.cb.hotmart.com/rest/v3/attachment/{}/download",
+ id
+ );
+ let resp = session
+ .client
+ .get(&url)
+ .header("Accept", "application/json, text/plain, */*")
+ .header("Origin", "https://hotmart.com")
+ .header("Referer", "https://hotmart.com")
+ .send()
+ .await?
+ .error_for_status()?;
+
+ let body: serde_json::Value = resp.json().await?;
+ let body_str = body.to_string();
+ let is_drm = body_str.contains("drm-protection");
+
+ let download_url = body
+ .get("directDownloadUrl")
+ .or_else(|| body.get("url"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let file_name = body.get("fileName").and_then(|v| v.as_str()).map(String::from);
+ let token = body.get("token").and_then(|v| v.as_str()).map(String::from);
+ let lambda_url = body.get("lambdaUrl").and_then(|v| v.as_str()).map(String::from);
+
+ Ok(AttachmentInfo {
+ url: download_url,
+ file_name,
+ token,
+ lambda_url,
+ is_drm,
+ })
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/hotmart/auth.rs b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/auth.rs
new file mode 100644
index 00000000..a89f31ab
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/auth.rs
@@ -0,0 +1,456 @@
+#[cfg(windows)]
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::cookie::Jar;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+use tauri::Manager;
+
+#[derive(Clone)]
+pub struct HotmartSession {
+ pub token: String,
+ pub email: String,
+ pub client: reqwest::Client,
+ pub cookies: Vec<(String, String)>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub email: String,
+ pub cookies: Vec<(String, String)>,
+ pub saved_at: u64,
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir = dirs::data_dir()
+ .ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("hotmart_session.json"))
+}
+
+pub fn build_client_from_saved(saved: &SavedSession) -> anyhow::Result<reqwest::Client> {
+ let jar = Jar::default();
+ let domains = [
+ "https://hotmart.com",
+ "https://api-sec-vlc.hotmart.com",
+ "https://api-hub.cb.hotmart.com",
+ "https://api-club-course-consumption-gateway-ga.cb.hotmart.com",
+ "https://consumer.hotmart.com",
+ "https://api-club-hot-club-api.cb.hotmart.com",
+ ];
+ for (name, value) in &saved.cookies {
+ let cookie_str = format!("{}={}; Domain=.hotmart.com; Path=/", name, value);
+ for domain in &domains {
+ jar.add_cookie_str(&cookie_str, &domain.parse().unwrap());
+ }
+ }
+
+ let mut default_headers = HeaderMap::new();
+ default_headers.insert(
+ "Accept",
+ HeaderValue::from_static("application/json, text/plain, */*"),
+ );
+ default_headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", saved.token))?,
+ );
+ default_headers.insert(
+ "Origin",
+ HeaderValue::from_static("https://consumer.hotmart.com"),
+ );
+ default_headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://consumer.hotmart.com"),
+ );
+ default_headers.insert("Pragma", HeaderValue::from_static("no-cache"));
+ default_headers.insert("cache-control", HeaderValue::from_static("no-cache"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
+ .cookie_provider(Arc::new(jar))
+ .default_headers(default_headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(300))
+ .build()?;
+
+ Ok(client)
+}
+
+pub async fn save_session(session: &HotmartSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ email: session.email.clone(),
+ cookies: session.cookies.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[session] saved for {}, {} cookies", session.email, session.cookies.len());
+ Ok(())
+}
+
+pub async fn load_saved_session() -> anyhow::Result<HotmartSession> {
+ let path = session_file_path()?;
+ let json = tokio::fs::read_to_string(&path).await?;
+ let saved: SavedSession = serde_json::from_str(&json)?;
+
+ tracing::info!("[session] loaded for {}, {} cookies", saved.email, saved.cookies.len());
+
+ let client = build_client_from_saved(&saved)?;
+
+ Ok(HotmartSession {
+ token: saved.token,
+ email: saved.email,
+ cookies: saved.cookies,
+ client,
+ })
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if path.exists() {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
+
+#[cfg(windows)]
+const COOKIE_URIS: &[&str] = &[
+ "https://hotmart.com",
+ "https://sso.hotmart.com",
+ "https://consumer.hotmart.com",
+ "https://api-sec-vlc.hotmart.com",
+];
+
+#[cfg(windows)]
+async fn extract_webview_cookies_for_uri(
+ window: &tauri::WebviewWindow,
+ uri: &str,
+) -> anyhow::Result<Vec<(String, String)>> {
+ use webview2_com::GetCookiesCompletedHandler;
+ use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2_2;
+ use windows_core::{Interface, HSTRING, PCWSTR, PWSTR};
+
+ let (tx, rx) = tokio::sync::oneshot::channel::<Vec<(String, String)>>();
+ let uri_owned = uri.to_string();
+
+ window
+ .with_webview(move |webview| {
+ unsafe {
+ let core = webview.controller().CoreWebView2().unwrap();
+ let core2: ICoreWebView2_2 = core.cast().unwrap();
+ let manager = core2.CookieManager().unwrap();
+ let uri_hstring = HSTRING::from(uri_owned);
+
+ let _ = manager.GetCookies(
+ PCWSTR::from_raw(uri_hstring.as_ptr()),
+ &GetCookiesCompletedHandler::create(Box::new(
+ move |error_code, cookie_list| {
+ let mut result = Vec::new();
+ if error_code.is_ok() {
+ if let Some(list) = cookie_list {
+ let mut count = 0u32;
+ list.Count(&mut count)?;
+ for i in 0..count {
+ let cookie = list.GetValueAtIndex(i)?;
+ let mut name = PWSTR::null();
+ let mut value = PWSTR::null();
+ cookie.Name(&mut name)?;
+ cookie.Value(&mut value)?;
+ result.push((
+ webview2_com::take_pwstr(name),
+ webview2_com::take_pwstr(value),
+ ));
+ }
+ }
+ }
+ let _ = tx.send(result);
+ Ok(())
+ },
+ )),
+ );
+ }
+ })
+ .map_err(|e| anyhow!("{}", e))?;
+
+ let cookies = tokio::time::timeout(Duration::from_secs(10), rx)
+ .await
+ .map_err(|_| anyhow!("Timeout ao obter cookies do WebView."))?
+ .map_err(|_| anyhow!("Canal de cookies fechado."))?;
+
+ Ok(cookies)
+}
+
+#[cfg(windows)]
+async fn extract_webview_cookies(
+ window: &tauri::WebviewWindow,
+) -> anyhow::Result<Vec<(String, String)>> {
+ let mut seen = HashMap::<String, String>::new();
+
+ for uri in COOKIE_URIS {
+ match extract_webview_cookies_for_uri(window, uri).await {
+ Ok(cookies) => {
+ let names: Vec<&str> = cookies.iter().map(|(n, _)| n.as_str()).collect();
+ tracing::info!("[cookies] {} → {} cookies: {:?}", uri, cookies.len(), names);
+ for (name, value) in cookies {
+ seen.insert(name, value);
+ }
+ }
+ Err(e) => {
+ tracing::warn!("[cookies] {} → error: {}", uri, e);
+ }
+ }
+ }
+
+ let cookies: Vec<(String, String)> = seen.into_iter().collect();
+ tracing::info!("[cookies] total unique: {}", cookies.len());
+
+ Ok(cookies)
+}
+
+#[allow(dead_code)]
+fn parse_document_cookie(s: &str) -> Vec<(String, String)> {
+ s.split(';')
+ .filter_map(|pair| {
+ let pair = pair.trim();
+ if pair.is_empty() {
+ return None;
+ }
+ let (name, value) = pair.split_once('=')?;
+ Some((name.trim().to_string(), value.trim().to_string()))
+ })
+ .collect()
+}
+
+#[cfg(not(windows))]
+async fn extract_webview_cookies_js(
+ window: &tauri::WebviewWindow,
+ cookie_data: &Arc<std::sync::Mutex<Option<String>>>,
+) -> anyhow::Result<Vec<(String, String)>> {
+ *cookie_data.lock().unwrap() = None;
+
+ window
+ .eval(
+ "window.location.href = 'https://omniget-cookie-extract.local/?cookies=' + encodeURIComponent(document.cookie)",
+ )
+ .map_err(|e| anyhow!("JS eval failed: {}", e))?;
+
+ let start = std::time::Instant::now();
+ let timeout = Duration::from_secs(5);
+ loop {
+ if let Some(cookie_str) = cookie_data.lock().unwrap().take() {
+ let cookies = parse_document_cookie(&cookie_str);
+ let names: Vec<&str> = cookies.iter().map(|(n, _)| n.as_str()).collect();
+ tracing::info!("[cookies] document.cookie → {} cookies: {:?}", cookies.len(), names);
+ return Ok(cookies);
+ }
+ if start.elapsed() > timeout {
+ tracing::warn!("[cookies] timeout waiting for document.cookie response");
+ return Ok(Vec::new());
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
+pub async fn authenticate(
+ app: &tauri::AppHandle,
+ email: &str,
+ password: &str,
+) -> anyhow::Result<HotmartSession> {
+ use tauri::Emitter;
+
+ let post_login_detected = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let post_login_flag = post_login_detected.clone();
+
+ let captcha_detected = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let captcha_flag = captcha_detected.clone();
+
+ #[cfg(not(windows))]
+ let cookie_data = Arc::new(std::sync::Mutex::new(Option::<String>::None));
+ #[cfg(not(windows))]
+ let cookie_data_nav = cookie_data.clone();
+
+ let email_json = serde_json::to_string(email)?;
+ let password_json = serde_json::to_string(password)?;
+
+ let init_script = format!(
+ r#"(function() {{
+ if (window.location.hostname !== 'sso.hotmart.com') return;
+ var filled = false;
+ function dismissCookies() {{
+ try {{
+ var el = document.querySelector('#hotmart-cookie-policy');
+ if (el && el.shadowRoot) {{
+ var btn = el.shadowRoot.querySelector('button.cookie-policy-accept-all');
+ if (btn) btn.click();
+ }}
+ }} catch(e) {{}}
+ }}
+ function fillForm() {{
+ if (filled) return;
+ var u = document.querySelector('#username');
+ var p = document.querySelector('#password');
+ if (!u || !p) return;
+ filled = true;
+ var s = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
+ s.call(u, {email_json});
+ u.dispatchEvent(new Event('input', {{ bubbles: true }}));
+ u.dispatchEvent(new Event('change', {{ bubbles: true }}));
+ s.call(p, {password_json});
+ p.dispatchEvent(new Event('input', {{ bubbles: true }}));
+ p.dispatchEvent(new Event('change', {{ bubbles: true }}));
+ setTimeout(function() {{
+ var btn = document.querySelector('[name=submit]');
+ if (btn) btn.click();
+ }}, 500);
+ }}
+ dismissCookies();
+ setTimeout(dismissCookies, 1000);
+ setTimeout(fillForm, 1500);
+ setInterval(fillForm, 500);
+ }})()"#
+ );
+
+ if let Some(existing) = app.get_webview_window("hotmart-login") {
+ let _ = existing.close();
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+
+ let login_url = "https://sso.hotmart.com/login?redirect=https%3A%2F%2Fconsumer.hotmart.com";
+
+ let login_window = tauri::WebviewWindowBuilder::new(
+ app,
+ "hotmart-login",
+ tauri::WebviewUrl::External(login_url.parse().unwrap()),
+ )
+ .title("Hotmart Login")
+ .inner_size(500.0, 700.0)
+ .initialization_script(&init_script)
+ .on_navigation(move |url| {
+ let host = url.host_str().unwrap_or("");
+ let url_str = url.as_str();
+
+ tracing::info!("[auth] navigation → {} (host={})", url_str, host);
+
+ if host == "consumer.hotmart.com"
+ || host.ends_with(".club.hotmart.com")
+ || url_str.contains("dashboard")
+ || (host.ends_with(".hotmart.com") && host != "sso.hotmart.com")
+ {
+ post_login_flag.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+
+ if url_str.contains("captcha") || url_str.contains("challenge") {
+ captcha_flag.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+
+ #[cfg(not(windows))]
+ {
+ if host == "omniget-cookie-extract.local" {
+ for (key, value) in url.query_pairs() {
+ if key == "cookies" {
+ *cookie_data_nav.lock().unwrap() = Some(value.to_string());
+ break;
+ }
+ }
+ return false;
+ }
+ }
+
+ true
+ })
+ .build()
+ .map_err(|e| anyhow!("Falha ao criar janela de login: {}", e))?;
+
+ let start = std::time::Instant::now();
+ let timeout = Duration::from_secs(120);
+ let poll_start_delay = Duration::from_secs(5);
+ let mut last_log_secs: u64 = 0;
+
+ loop {
+ if start.elapsed() > timeout {
+ let _ = login_window.close();
+ return Err(anyhow!("Timeout esperando login. Verifique credenciais."));
+ }
+
+ if captcha_detected.swap(false, std::sync::atomic::Ordering::Relaxed) {
+ let _ = app.emit("hotmart-auth-captcha", ());
+ }
+
+ let nav_detected = post_login_detected.load(std::sync::atomic::Ordering::Relaxed);
+ let should_poll = nav_detected || start.elapsed() > poll_start_delay;
+
+ if should_poll {
+ #[cfg(windows)]
+ let cookies = extract_webview_cookies(&login_window).await?;
+ #[cfg(not(windows))]
+ let cookies = extract_webview_cookies_js(&login_window, &cookie_data).await?;
+
+ let has_token = cookies.iter().any(|(name, _)| name == "hmVlcIntegration");
+
+ if has_token {
+ tracing::info!(
+ "[auth] hmVlcIntegration found after {:.1}s (nav_detected={})",
+ start.elapsed().as_secs_f64(),
+ nav_detected
+ );
+ let _ = login_window.close();
+
+ let token = cookies
+ .iter()
+ .find(|(name, _)| name == "hmVlcIntegration")
+ .map(|(_, value)| value.clone())
+ .unwrap();
+
+ let saved = SavedSession {
+ token: token.clone(),
+ email: email.to_string(),
+ cookies: cookies.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let client = build_client_from_saved(&saved)?;
+
+ return Ok(HotmartSession {
+ token,
+ email: email.to_string(),
+ client,
+ cookies,
+ });
+ }
+
+ let elapsed_secs = start.elapsed().as_secs();
+ if elapsed_secs >= last_log_secs + 5 {
+ last_log_secs = elapsed_secs;
+ let cookie_names: Vec<&str> =
+ cookies.iter().map(|(n, _)| n.as_str()).collect();
+ tracing::info!(
+ "[auth] polling at {}s, {} cookies: {:?}",
+ elapsed_secs,
+ cookies.len(),
+ cookie_names
+ );
+ }
+ }
+
+ let sleep_ms = if nav_detected { 500 } else { 2000 };
+ tokio::time::sleep(Duration::from_millis(sleep_ms)).await;
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/hotmart/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/downloader.rs
new file mode 100644
index 00000000..2faa1f47
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/downloader.rs
@@ -0,0 +1,832 @@
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use futures::stream::{self, StreamExt};
+use tokio::sync::{mpsc, Mutex};
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+use omniget_core::core::media_processor::MediaProcessor;
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
+use omniget_core::models::settings::{self, DownloadSettings};
+use crate::platforms::traits::PlatformDownloader;
+
+use super::api::{self, Course, Lesson};
+use super::auth::HotmartSession;
+use super::parser::{self, DetectedPlayer};
+
+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";
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct CourseDownloadProgress {
+ pub course_id: u64,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ pub current_page: String,
+ pub downloaded_bytes: u64,
+ pub total_pages: u32,
+ pub completed_pages: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct DoneManifest {
+ file: String,
+ size: u64,
+ segments: usize,
+ completed_at: String,
+}
+
+fn done_path(file_path: &str) -> PathBuf {
+ let p = PathBuf::from(file_path);
+ let file_name = p.file_name().unwrap_or_default().to_string_lossy();
+ let manifest_name = format!("{}.omniget.done", file_name);
+ p.with_file_name(manifest_name)
+}
+
+async fn write_done_manifest(file_path: &str, size: u64, segments: usize) -> anyhow::Result<()> {
+ let p = PathBuf::from(file_path);
+ let file_name = p
+ .file_name()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .to_string();
+ let manifest = DoneManifest {
+ file: file_name,
+ size,
+ segments,
+ completed_at: chrono::Utc::now().to_rfc3339(),
+ };
+ let json = serde_json::to_string_pretty(&manifest)?;
+ tokio::fs::write(done_path(file_path), json).await?;
+ Ok(())
+}
+
+async fn is_hls_file_valid(file_path: &str) -> bool {
+ let dp = done_path(file_path);
+
+ let manifest_bytes = match tokio::fs::read(&dp).await {
+ Ok(b) => b,
+ Err(_) => return false,
+ };
+
+ let manifest: DoneManifest = match serde_json::from_slice(&manifest_bytes) {
+ Ok(m) => m,
+ Err(_) => return false,
+ };
+
+ let meta = match tokio::fs::metadata(file_path).await {
+ Ok(m) => m,
+ Err(_) => return false,
+ };
+
+ meta.len() == manifest.size
+}
+
+const CONCURRENT_LESSONS: usize = 3;
+
+#[derive(Clone)]
+pub struct HotmartDownloader {
+ session: Arc<Mutex<Option<HotmartSession>>>,
+ download_settings: DownloadSettings,
+ max_concurrent_segments: u32,
+ max_retries: u32,
+ concurrent_fragments: u32,
+ hls_client: reqwest::Client,
+}
+
+impl HotmartDownloader {
+ pub fn new(
+ session: Arc<Mutex<Option<HotmartSession>>>,
+ download_settings: DownloadSettings,
+ max_concurrent_segments: u32,
+ max_retries: u32,
+ concurrent_fragments: u32,
+ ) -> Self {
+ let hls_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .danger_accept_invalid_certs(true)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(300))
+ .pool_max_idle_per_host(50)
+ .pool_idle_timeout(Duration::from_secs(30))
+ .build()
+ .unwrap();
+
+ Self {
+ session,
+ download_settings,
+ max_concurrent_segments,
+ max_retries,
+ concurrent_fragments,
+ hls_client,
+ }
+ }
+
+ fn filename_prefix(&self) -> &str {
+ if self.download_settings.filename_template == settings::default_filename_template() {
+ "omniget-"
+ } else {
+ ""
+ }
+ }
+
+ pub async fn download_lesson(
+ &self,
+ session: &HotmartSession,
+ lesson: &Lesson,
+ output_dir: &str,
+ referer: &str,
+ bytes_tx: tokio::sync::mpsc::UnboundedSender<u64>,
+ cancel_token: &CancellationToken,
+ ) -> anyhow::Result<Vec<PathBuf>> {
+ let mut results = Vec::new();
+
+ tokio::fs::create_dir_all(output_dir).await?;
+
+ if lesson.has_media {
+ let prefix = self.filename_prefix().to_string();
+ let media_futures: Vec<_> = lesson.medias.iter().enumerate().map(|(i, media)| {
+ let media = media.clone();
+ let session = session.clone();
+ let output_dir = output_dir.to_string();
+ let bytes_tx = bytes_tx.clone();
+ let cancel_token = cancel_token.clone();
+ let hls_client = self.hls_client.clone();
+ let max_concurrent_segments = self.max_concurrent_segments;
+ let max_retries = self.max_retries;
+ let prefix = prefix.clone();
+
+ async move {
+ let mut paths: Vec<PathBuf> = Vec::new();
+
+ if cancel_token.is_cancelled() {
+ return paths;
+ }
+
+ let assets = match parser::fetch_player_media_assets(&media.url, &session).await {
+ Ok(a) => a,
+ Err(_) => return paths,
+ };
+
+ if media.media_type.to_uppercase().contains("VIDEO") {
+ let m3u8_url = match assets.first().and_then(|a| a.get("url")).and_then(|v| v.as_str()) {
+ Some(url) => url.to_string(),
+ None => return paths,
+ };
+
+ let out = format!("{}/{}{}. Aula.mp4", output_dir, prefix, i + 1);
+
+ if is_hls_file_valid(&out).await {
+ return paths;
+ }
+
+ if tokio::fs::try_exists(done_path(&out)).await.unwrap_or(false) {
+ let _ = tokio::fs::remove_file(&out).await;
+ let _ = tokio::fs::remove_file(done_path(&out)).await;
+ }
+
+ let hls_result = retry_hls_download(
+ &m3u8_url,
+ &out,
+ "https://cf-embed.play.hotmart.com/",
+ Some(bytes_tx.clone()),
+ &cancel_token,
+ max_concurrent_segments,
+ max_retries,
+ 3,
+ Some(hls_client),
+ )
+ .await;
+
+ match hls_result {
+ Ok(hls_result) => {
+ let _ = write_done_manifest(&out, hls_result.file_size, hls_result.segments).await;
+ paths.push(hls_result.path);
+ }
+ Err(e) => {
+ tracing::error!("[download] Falha ao baixar vídeo '{}': {}", out, e);
+ let _ = tokio::fs::remove_file(&out).await;
+ }
+ }
+ } else if media.media_type.to_uppercase().contains("AUDIO") {
+ for asset in &assets {
+ let content_type = asset
+ .get("contentType")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if !content_type.to_lowercase().contains("audio") {
+ continue;
+ }
+ let audio_url = match asset.get("url").and_then(|v| v.as_str()) {
+ Some(url) => url,
+ None => continue,
+ };
+
+ let safe_name = filename::sanitize_path_component(&media.name);
+ let out = format!(
+ "{}/{}{}. {}",
+ output_dir,
+ prefix,
+ i + 1,
+ if safe_name.is_empty() { "Audio.mp4".to_string() } else { safe_name }
+ );
+
+ if tokio::fs::try_exists(&out).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&out).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match session.client.get(audio_url).send().await {
+ Ok(resp) => match resp.bytes().await {
+ Ok(bytes) => {
+ let _ = bytes_tx.send(bytes.len() as u64);
+ if tokio::fs::write(&out, &bytes).await.is_ok() {
+ paths.push(PathBuf::from(out));
+ }
+ }
+ Err(e) => tracing::error!("[download] Falha ao baixar áudio: {}", e),
+ },
+ Err(e) => tracing::error!("[download] Falha ao baixar áudio: {}", e),
+ }
+ }
+ }
+
+ paths
+ }
+ }).collect();
+
+ let all_media_results = futures::future::join_all(media_futures).await;
+ for media_result in all_media_results {
+ results.extend(media_result);
+ }
+ }
+
+ if let Some(html) = &lesson.content {
+ let players = parser::detect_players_from_html(html);
+ let prefix2 = self.filename_prefix().to_string();
+ let player_futures: Vec<_> = players.into_iter().enumerate().map(|(i, player)| {
+ let bytes_tx = bytes_tx.clone();
+ let cancel_token = cancel_token.clone();
+ let hls_client = self.hls_client.clone();
+ let max_concurrent_segments = self.max_concurrent_segments;
+ let max_retries = self.max_retries;
+ let concurrent_fragments = self.concurrent_fragments;
+ let output_dir = output_dir.to_string();
+ let referer = referer.to_string();
+ let prefix = prefix2.clone();
+
+ async move {
+ let mut paths: Vec<PathBuf> = Vec::new();
+
+ if cancel_token.is_cancelled() {
+ return paths;
+ }
+
+ let out = format!("{}/{}{}. Aula.mp4", output_dir, prefix, i + 1);
+
+ match player {
+ DetectedPlayer::Vimeo { embed_url } => {
+ if tokio::fs::try_exists(&out).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&out).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ return paths;
+ }
+ }
+
+ match omniget_core::core::ytdlp::ensure_ytdlp().await {
+ Ok(ytdlp_path) => {
+ let out_dir = std::path::Path::new(&out).parent()
+ .unwrap_or(std::path::Path::new("."));
+ let (vtx, _vrx) = mpsc::channel(8);
+ match omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ &embed_url,
+ out_dir,
+ None,
+ vtx,
+ None,
+ None,
+ None,
+ Some(&referer),
+ cancel_token.clone(),
+ None,
+ concurrent_fragments,
+ false,
+ &[],
+ ).await {
+ Ok(result) => {
+ let _ = bytes_tx.send(result.file_size_bytes);
+ paths.push(result.file_path);
+ }
+ Err(e) => {
+ tracing::error!("[download] Falha Vimeo: {}", e);
+ cleanup_part_files(out_dir).await;
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!("[download] yt-dlp indisponível para Vimeo: {}", e);
+ }
+ }
+ }
+ DetectedPlayer::PandaVideo { m3u8_url, .. } => {
+ if is_hls_file_valid(&out).await {
+ return paths;
+ }
+
+ if tokio::fs::try_exists(done_path(&out)).await.unwrap_or(false) {
+ let _ = tokio::fs::remove_file(&out).await;
+ let _ = tokio::fs::remove_file(done_path(&out)).await;
+ }
+
+ let panda_referer = m3u8_url
+ .split("com.br")
+ .next()
+ .unwrap_or("")
+ .to_string()
+ + "com.br";
+ match retry_hls_download(&m3u8_url, &out, &panda_referer, Some(bytes_tx.clone()), &cancel_token, max_concurrent_segments, max_retries, 3, Some(hls_client)).await {
+ Ok(hls_result) => {
+ let _ = write_done_manifest(&out, hls_result.file_size, hls_result.segments).await;
+ paths.push(hls_result.path);
+ }
+ Err(e) => {
+ tracing::error!("[download] Falha PandaVideo: {}", e);
+ let _ = tokio::fs::remove_file(&out).await;
+ }
+ }
+ }
+ DetectedPlayer::YouTube { video_id, .. } => {
+ if tokio::fs::try_exists(&out).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&out).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ return paths;
+ }
+ }
+
+ let yt_url = format!("https://www.youtube.com/watch?v={}", video_id);
+ match omniget_core::core::ytdlp::ensure_ytdlp().await {
+ Ok(ytdlp_path) => {
+ let out_dir = std::path::Path::new(&out).parent()
+ .unwrap_or(std::path::Path::new("."));
+ let (ytx, _yrx) = mpsc::channel(8);
+ match omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ &yt_url,
+ out_dir,
+ None,
+ ytx,
+ None,
+ None,
+ None,
+ None,
+ cancel_token.clone(),
+ None,
+ concurrent_fragments,
+ false,
+ &[],
+ ).await {
+ Ok(result) => {
+ let _ = bytes_tx.send(result.file_size_bytes);
+ paths.push(result.file_path);
+ }
+ Err(e) => {
+ tracing::error!("[download] Falha YouTube: {}", e);
+ cleanup_part_files(out_dir).await;
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!("[download] yt-dlp indisponível: {}", e);
+ }
+ }
+ }
+ DetectedPlayer::HotmartNative { .. } => {}
+ DetectedPlayer::Unknown { .. } => {}
+ }
+
+ paths
+ }
+ }).collect();
+
+ let all_player_results = futures::future::join_all(player_futures).await;
+ for player_result in all_player_results {
+ results.extend(player_result);
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ anyhow::bail!("Download cancelled by user");
+ }
+
+ if self.download_settings.download_attachments && !lesson.attachments.is_empty() {
+ let mat_dir = format!("{}/Materiais", output_dir);
+ tokio::fs::create_dir_all(&mat_dir).await?;
+
+ let att_futures: Vec<_> = lesson.attachments.iter().map(|att| {
+ let session = session.clone();
+ let safe_name = filename::sanitize_path_component(&att.file_name);
+ let att_path = format!("{}/{}", mat_dir, safe_name);
+ let file_membership_id = att.file_membership_id.clone();
+
+ async move {
+ if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
+ return None;
+ }
+ match download_attachment(&session, &file_membership_id, &att_path).await {
+ Ok(()) => Some(PathBuf::from(att_path)),
+ Err(_) => None,
+ }
+ }
+ }).collect();
+
+ let att_results = futures::future::join_all(att_futures).await;
+ for path in att_results.into_iter().flatten() {
+ results.push(path);
+ }
+ }
+
+ if self.download_settings.download_descriptions {
+ if let Some(content) = &lesson.content {
+ if !content.trim().is_empty() {
+ let desc_path = format!("{}/Description.html", output_dir);
+ if !tokio::fs::try_exists(&desc_path).await.unwrap_or(false) {
+ tokio::fs::write(&desc_path, content).await?;
+ }
+ }
+ }
+
+ if let Some(readings) = &lesson.complementary_readings {
+ if !readings.is_empty() {
+ let reading_path = format!("{}/Leitura complementar.html", output_dir);
+ if !tokio::fs::try_exists(&reading_path).await.unwrap_or(false) {
+ let mut html = String::new();
+ for link in readings {
+ let title = link.title.as_deref().unwrap_or("");
+ let url = link.url.as_deref().unwrap_or("#");
+ html.push_str(&format!("<a href=\"{}\">{}</a><br>\n", url, title));
+ }
+ tokio::fs::write(&reading_path, &html).await?;
+ }
+ }
+ }
+ }
+
+ Ok(results)
+ }
+
+ pub async fn download_full_course(
+ &self,
+ course: &Course,
+ base_dir: &str,
+ progress: mpsc::Sender<CourseDownloadProgress>,
+ cancel_token: CancellationToken,
+ ) -> anyhow::Result<()> {
+ if course.external_platform {
+ return Err(anyhow!("Curso hospedado em plataforma externa"));
+ }
+
+ let slug = course
+ .slug
+ .as_deref()
+ .or(course.subdomain.as_deref())
+ .ok_or_else(|| anyhow!("Curso sem slug/subdomain: {}", course.name))?;
+
+ let session = {
+ let guard = self.session.lock().await;
+ guard
+ .as_ref()
+ .ok_or_else(|| anyhow!("Not authenticated"))?
+ .clone()
+ };
+
+ let modules = api::get_modules(&session, slug, course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!("'{}' has no modules available for download", course.name));
+ }
+
+ let course_dir = format!(
+ "{}/{} - {}",
+ base_dir,
+ filename::sanitize_path_component(&course.name),
+ filename::sanitize_path_component(&course.seller)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ let total_pages: usize = modules.iter().map(|m| m.pages.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let done = Arc::new(AtomicUsize::new(0));
+
+ let _ = progress
+ .send(CourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Iniciando...".to_string(),
+ current_page: String::new(),
+ downloaded_bytes: 0,
+ total_pages: total_pages as u32,
+ completed_pages: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ })
+ .await;
+
+ let referer = format!("https://{}.club.hotmart.com/", slug);
+ let slug_owned = slug.to_string();
+
+ struct PageTask {
+ module_index: usize,
+ module_name: String,
+ page_hash: String,
+ page_name: String,
+ page_dir: String,
+ }
+
+ let mut all_pages = Vec::new();
+ for (mi, module) in modules.iter().enumerate() {
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ for (pi, page) in module.pages.iter().enumerate() {
+ let page_name_sanitized = filename::sanitize_path_component(&page.name);
+ let page_dir = format!("{}/{}. {}", mod_dir, pi + 1, page_name_sanitized);
+ all_pages.push(PageTask {
+ module_index: mi,
+ module_name: module.name.clone(),
+ page_hash: page.hash.clone(),
+ page_name: page.name.clone(),
+ page_dir,
+ });
+ }
+ }
+
+ stream::iter(all_pages)
+ .for_each_concurrent(CONCURRENT_LESSONS, |task| {
+ let downloader = self.clone();
+ let session = session.clone();
+ let cancel_token = cancel_token.clone();
+ let progress = progress.clone();
+ let total_bytes = total_bytes.clone();
+ let done = done.clone();
+ let course_id = course.id;
+ let course_name = course.name.clone();
+ let referer = referer.clone();
+ let slug = slug_owned.clone();
+
+ async move {
+ if cancel_token.is_cancelled() {
+ return;
+ }
+
+ if let Err(e) = tokio::fs::create_dir_all(&task.page_dir).await {
+ tracing::error!("Falha ao criar diretório '{}': {}", task.page_dir, e);
+ done.fetch_add(1, Ordering::Relaxed);
+ return;
+ }
+
+ let lesson = match api::get_lesson(&session, &slug, course_id, &task.page_hash).await {
+ Ok(l) => l,
+ Err(e) => {
+ tracing::error!("Falha ao carregar lição '{}': {}. Continuando...", task.page_name, e);
+ let completed = done.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = progress
+ .send(CourseDownloadProgress {
+ course_id,
+ course_name,
+ percent: completed as f64 / total_pages as f64 * 100.0,
+ current_module: task.module_name,
+ current_page: task.page_name,
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_pages: total_pages as u32,
+ completed_pages: completed as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (task.module_index + 1) as u32,
+ })
+ .await;
+ return;
+ }
+ };
+
+ let (lesson_bytes_tx, mut lesson_bytes_rx) =
+ tokio::sync::mpsc::unbounded_channel::<u64>();
+ let total_bytes_ref = total_bytes.clone();
+ let accumulator = tokio::spawn(async move {
+ while let Some(n) = lesson_bytes_rx.recv().await {
+ total_bytes_ref.fetch_add(n, Ordering::Relaxed);
+ }
+ });
+
+ let lesson_result = downloader
+ .download_lesson(&session, &lesson, &task.page_dir, &referer, lesson_bytes_tx, &cancel_token)
+ .await;
+
+ let _ = accumulator.await;
+
+ if let Err(e) = lesson_result {
+ if !cancel_token.is_cancelled() {
+ tracing::error!(
+ "Error downloading page '{}': {}. Continuing...",
+ task.page_name,
+ e
+ );
+ }
+ }
+
+ let completed = done.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = progress
+ .send(CourseDownloadProgress {
+ course_id,
+ course_name,
+ percent: completed as f64 / total_pages as f64 * 100.0,
+ current_module: task.module_name,
+ current_page: task.page_name,
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_pages: total_pages as u32,
+ completed_pages: completed as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (task.module_index + 1) as u32,
+ })
+ .await;
+ }
+ })
+ .await;
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ Ok(())
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn retry_hls_download(
+ m3u8_url: &str,
+ output_path: &str,
+ referer: &str,
+ bytes_tx: Option<tokio::sync::mpsc::UnboundedSender<u64>>,
+ cancel_token: &CancellationToken,
+ max_concurrent_segments: u32,
+ max_retries: u32,
+ max_attempts: u32,
+ hls_client: Option<reqwest::Client>,
+) -> anyhow::Result<omniget_core::core::hls_downloader::HlsDownloadResult> {
+ let mut last_err = None;
+ for attempt in 0..max_attempts {
+ if cancel_token.is_cancelled() {
+ anyhow::bail!("Download cancelled by user");
+ }
+ match MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ referer,
+ bytes_tx.clone(),
+ cancel_token.clone(),
+ max_concurrent_segments,
+ max_retries,
+ hls_client.clone(),
+ )
+ .await
+ {
+ Ok(result) => {
+ let meta = tokio::fs::metadata(output_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ return Ok(result);
+ }
+ last_err = Some(anyhow!("Output file empty after HLS download"));
+ }
+ Err(e) => {
+ if cancel_token.is_cancelled() {
+ return Err(e);
+ }
+ last_err = Some(e);
+ }
+ }
+ if attempt < max_attempts - 1 {
+ let _ = tokio::fs::remove_file(output_path).await;
+ let backoff = std::time::Duration::from_secs(2u64.pow(attempt));
+ tracing::warn!(
+ "[hls-retry] Tentativa {}/{} falhou para '{}', retentando em {:?}",
+ attempt + 1,
+ max_attempts,
+ output_path,
+ backoff
+ );
+ tokio::time::sleep(backoff).await;
+ }
+ }
+ Err(last_err.unwrap_or_else(|| anyhow!("HLS download failed after {} attempts", max_attempts)))
+}
+
+async fn cleanup_part_files(dir: &std::path::Path) {
+ let mut entries = match tokio::fs::read_dir(dir).await {
+ Ok(e) => e,
+ Err(_) => return,
+ };
+ while let Ok(Some(entry)) = entries.next_entry().await {
+ let path = entry.path();
+ if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
+ if name.ends_with(".part") || name.ends_with(".ytdl") {
+ let _ = tokio::fs::remove_file(&path).await;
+ }
+ }
+ }
+}
+
+async fn download_attachment(
+ session: &HotmartSession,
+ file_membership_id: &str,
+ output_path: &str,
+) -> anyhow::Result<()> {
+ let info = api::get_attachment_url(session, file_membership_id).await?;
+
+ if !info.is_drm {
+ if info.url.is_empty() {
+ return Err(anyhow!("URL de download vazia para attachment {}", file_membership_id));
+ }
+ let bytes = reqwest::get(&info.url).await?.bytes().await?;
+ tokio::fs::write(output_path, &bytes).await?;
+ } else {
+ let lambda_url = info
+ .lambda_url
+ .as_deref()
+ .ok_or_else(|| anyhow!("lambdaUrl not found for DRM"))?;
+ let drm_token = info
+ .token
+ .as_deref()
+ .ok_or_else(|| anyhow!("DRM token not found"))?;
+
+ let signed_url = session
+ .client
+ .get(lambda_url)
+ .header("token", drm_token)
+ .header("User-Agent", USER_AGENT)
+ .send()
+ .await?
+ .text()
+ .await?;
+
+ if signed_url.is_empty() || signed_url.contains("500") {
+ return Err(anyhow!("DRM attachment unavailable (empty response or error 500)"));
+ }
+
+ let bytes = reqwest::get(&signed_url).await?.bytes().await?;
+ let drm_output = format!(
+ "{}/drm_{}",
+ std::path::Path::new(output_path)
+ .parent()
+ .map(|p| p.to_str().unwrap_or("."))
+ .unwrap_or("."),
+ std::path::Path::new(output_path)
+ .file_name()
+ .map(|f| f.to_str().unwrap_or("file"))
+ .unwrap_or("file")
+ );
+ tokio::fs::write(&drm_output, &bytes).await?;
+ }
+
+ Ok(())
+}
+
+#[async_trait]
+impl PlatformDownloader for HotmartDownloader {
+ fn name(&self) -> &str {
+ "hotmart"
+ }
+
+ fn can_handle(&self, url: &str) -> bool {
+ url.contains("hotmart.com") || url.contains("club.hotmart.com")
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: format!("Hotmart course: {}", url),
+ author: String::new(),
+ platform: "hotmart".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Hotmart downloads use start_course_download, not the generic download trait"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/hotmart/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/mod.rs
new file mode 100644
index 00000000..aea8d9ab
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/mod.rs
@@ -0,0 +1,4 @@
+pub mod auth;
+pub mod api;
+pub mod parser;
+pub mod downloader;
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/hotmart/parser.rs b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/parser.rs
new file mode 100644
index 00000000..10fd2e84
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/parser.rs
@@ -0,0 +1,104 @@
+use regex::Regex;
+use scraper::{Html, Selector};
+use serde::{Deserialize, Serialize};
+
+use super::auth::HotmartSession;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "type")]
+pub enum DetectedPlayer {
+ HotmartNative { m3u8_url: String, name: String },
+ Vimeo { embed_url: String },
+ PandaVideo { embed_url: String, m3u8_url: String },
+ YouTube { video_url: String, video_id: String },
+ Unknown { src: String },
+}
+
+pub fn detect_players_from_html(html: &str) -> Vec<DetectedPlayer> {
+ let doc = Html::parse_document(html);
+ let sel = Selector::parse("iframe").unwrap();
+
+ let allowlist = ["vimeo", "youtu", "pandavideo", "liquid", "wistia", "videodelivery"];
+
+ doc.select(&sel)
+ .filter_map(|el| {
+ let src = el.value().attr("src")?;
+ if !allowlist.iter().any(|kw| src.contains(kw)) {
+ return None;
+ }
+
+ if src.contains("vimeo.com") {
+ Some(DetectedPlayer::Vimeo {
+ embed_url: src.to_string(),
+ })
+ } else if src.contains("pandavideo") {
+ let m3u8 = build_panda_m3u8(src)?;
+ Some(DetectedPlayer::PandaVideo {
+ embed_url: src.to_string(),
+ m3u8_url: m3u8,
+ })
+ } else if src.contains("youtu") {
+ let id = extract_youtube_id(src);
+ Some(DetectedPlayer::YouTube {
+ video_url: src.to_string(),
+ video_id: id,
+ })
+ } else {
+ Some(DetectedPlayer::Unknown {
+ src: src.to_string(),
+ })
+ }
+ })
+ .collect()
+}
+
+fn build_panda_m3u8(src: &str) -> Option<String> {
+ let base = src.replace("player-vz-", "b-vz-");
+ let base_part = base.split("/embed/").next()?;
+ let video_id = src.split("v=").nth(1)?.split('&').next()?;
+ Some(format!("{}/{}/playlist.m3u8", base_part, video_id))
+}
+
+fn extract_youtube_id(url: &str) -> String {
+ let re = Regex::new(
+ r"(?:youtube\.com/(?:watch\?v=|embed/|v/|shorts/)|youtu\.be/)([a-zA-Z0-9_-]{11})",
+ )
+ .unwrap();
+ re.captures(url)
+ .and_then(|c| c.get(1))
+ .map(|m| m.as_str().to_string())
+ .unwrap_or_default()
+}
+
+pub async fn fetch_player_media_assets(
+ player_url: &str,
+ session: &HotmartSession,
+) -> anyhow::Result<Vec<serde_json::Value>> {
+ let resp = session
+ .client
+ .get(player_url)
+ .header("Referer", "https://hotmart.com")
+ .send()
+ .await?
+ .error_for_status()?;
+
+ let html_text = resp.text().await?;
+ let doc = Html::parse_document(&html_text);
+ let sel = Selector::parse("script#__NEXT_DATA__").unwrap();
+
+ let script_el = doc
+ .select(&sel)
+ .next()
+ .ok_or_else(|| anyhow::anyhow!("__NEXT_DATA__ not found in player HTML"))?;
+
+ let json_text = script_el.text().collect::<String>();
+ let data: serde_json::Value = serde_json::from_str(&json_text)?;
+
+ let assets = data
+ .pointer("/props/pageProps/applicationData/mediaAssets")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ Ok(assets)
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kajabi/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/kajabi/api.rs
new file mode 100644
index 00000000..4a1e415d
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/kajabi/api.rs
@@ -0,0 +1,645 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "KajabiMobileApp";
+const BASE_URL: &str = "https://mobile-api.kajabi.com/api/mobile/v3";
+const AUTH_BASE: &str = "https://app.kajabi.com/api/mobile/v2";
+
+#[derive(Clone)]
+pub struct KajabiSession {
+ pub token: String,
+ pub site_id: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub site_id: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KajabiSite {
+ pub id: String,
+ pub title: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KajabiCourse {
+ pub id: String,
+ pub name: String,
+ pub thumbnail_url: Option<String>,
+ pub site_id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KajabiModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<KajabiLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KajabiLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KajabiLessonDetail {
+ pub id: String,
+ pub name: String,
+ pub video_url: Option<String>,
+ pub files: Vec<KajabiFile>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KajabiFile {
+ pub id: String,
+ pub name: String,
+ pub url: Option<String>,
+}
+
+fn build_client(token: &str, site_id: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert(
+ "Kjb-App-Id",
+ HeaderValue::from_static("Kajabi"),
+ );
+ headers.insert(
+ "KJB-DP",
+ HeaderValue::from_static("ANDROID"),
+ );
+ headers.insert(
+ "KJB-SITE-ID",
+ HeaderValue::from_str(site_id)?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn build_auth_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert(
+ "Kjb-App-Id",
+ HeaderValue::from_static("Kajabi"),
+ );
+ headers.insert(
+ "KJB-DP",
+ HeaderValue::from_static("ANDROID"),
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("kajabi_session.json"))
+}
+
+pub async fn request_login_link(email: &str) -> anyhow::Result<String> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "email": email,
+ });
+
+ let resp = temp_client
+ .post(&format!("{}/login_links", AUTH_BASE))
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Login link request failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let login_token = body
+ .get("token")
+ .or_else(|| body.get("login_token"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("token not found in login_links response"))?
+ .to_string();
+
+ Ok(login_token)
+}
+
+pub async fn verify_login(email: &str, confirmation_code: &str, login_token: &str) -> anyhow::Result<String> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "email": email,
+ "confirmation_code": confirmation_code,
+ "token": login_token,
+ });
+
+ let resp = temp_client
+ .post(&format!("{}/authentication", AUTH_BASE))
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Authentication failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let bearer_token = body
+ .get("bearerToken")
+ .or_else(|| body.get("bearer_token"))
+ .or_else(|| body.get("token"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("bearerToken not found in authentication response"))?
+ .to_string();
+
+ Ok(bearer_token)
+}
+
+pub async fn validate_token(session: &KajabiSession) -> anyhow::Result<bool> {
+ let client = build_auth_client(&session.token)?;
+
+ let resp = client
+ .get(&format!("{}/sites", AUTH_BASE))
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_sites(token: &str) -> anyhow::Result<Vec<KajabiSite>> {
+ let client = build_auth_client(token)?;
+
+ let resp = client
+ .get(&format!("{}/sites", AUTH_BASE))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_sites returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let sites_arr = body
+ .as_array()
+ .or_else(|| body.get("sites").and_then(|v| v.as_array()))
+ .cloned()
+ .unwrap_or_default();
+
+ let mut sites = Vec::new();
+
+ for item in &sites_arr {
+ let id = item
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let title = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ sites.push(KajabiSite { id, title });
+ }
+
+ Ok(sites)
+}
+
+pub async fn list_courses(session: &KajabiSession) -> anyhow::Result<Vec<KajabiCourse>> {
+ let mut all_courses = Vec::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!(
+ "{}/sites/{}/courses?page={}&per_page=50",
+ BASE_URL, session.site_id, page
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let courses_arr = body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .or_else(|| body.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ if courses_arr.is_empty() {
+ break;
+ }
+
+ for item in &courses_arr {
+ let id = item
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let name = item
+ .get("name")
+ .or_else(|| item.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let thumbnail_url = item
+ .get("thumbnail_url")
+ .or_else(|| item.get("image_url"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ all_courses.push(KajabiCourse {
+ id,
+ name,
+ thumbnail_url,
+ site_id: session.site_id.clone(),
+ });
+ }
+
+ page += 1;
+ }
+
+ Ok(all_courses)
+}
+
+pub async fn get_categories(
+ session: &KajabiSession,
+ product_id: &str,
+) -> anyhow::Result<Vec<KajabiModule>> {
+ let url = format!(
+ "{}/sites/{}/products/{}/categories",
+ BASE_URL, session.site_id, product_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_categories returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let categories_arr = body
+ .get("data")
+ .and_then(|v| v.get("categories"))
+ .and_then(|v| v.as_array())
+ .or_else(|| body.get("categories").and_then(|v| v.as_array()))
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for (i, cat) in categories_arr.iter().enumerate() {
+ let cat_id = cat
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", i),
+ })
+ .unwrap_or_else(|| format!("{}", i));
+
+ let cat_name = cat
+ .get("name")
+ .or_else(|| cat.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let posts_arr = cat
+ .get("posts")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (j, post) in posts_arr.iter().enumerate() {
+ let post_id = post
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", j),
+ })
+ .unwrap_or_else(|| format!("{}", j));
+
+ let post_name = post
+ .get("name")
+ .or_else(|| post.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ lessons.push(KajabiLesson {
+ id: post_id,
+ name: post_name,
+ order: j as i64,
+ });
+ }
+
+ modules.push(KajabiModule {
+ id: cat_id,
+ name: cat_name,
+ order: i as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_post_detail(
+ session: &KajabiSession,
+ product_id: &str,
+ post_id: &str,
+) -> anyhow::Result<KajabiLessonDetail> {
+ let url = format!(
+ "{}/sites/{}/products/{}/posts/{}",
+ BASE_URL, session.site_id, product_id, post_id
+ );
+
+ let mut last_err = anyhow!("Failed after retries");
+
+ for attempt in 0..3u32 {
+ if attempt > 0 {
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ }
+
+ let resp = match session.client.get(&url).send().await {
+ Ok(r) => r,
+ Err(e) => {
+ last_err = e.into();
+ continue;
+ }
+ };
+
+ let status = resp.status();
+
+ if status.as_u16() == 403 || status.as_u16() == 429 {
+ let body_text = resp.text().await.unwrap_or_default();
+ last_err = anyhow!(
+ "get_post_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ );
+ continue;
+ }
+
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_post_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let data = body.get("data").unwrap_or(&body);
+
+ let id = data
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => post_id.to_string(),
+ })
+ .unwrap_or_else(|| post_id.to_string());
+
+ let name = data
+ .get("name")
+ .or_else(|| data.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let video_url = data
+ .get("video_url")
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ .or_else(|| {
+ data.get("video")
+ .and_then(|v| v.get("url"))
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ })
+ .or_else(|| {
+ data.get("wistia_video")
+ .and_then(|v| v.get("url"))
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ })
+ .or_else(|| {
+ data.get("content_videos")
+ .and_then(|v| v.as_array())
+ .and_then(|arr| arr.first())
+ .and_then(|v| v.get("url"))
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ })
+ .or_else(|| {
+ data.get("media")
+ .and_then(|m| m.get("assets"))
+ .and_then(|a| a.as_array())
+ .and_then(|arr| {
+ arr.iter().find(|a| {
+ a.get("type")
+ .and_then(|v| v.as_str())
+ .map(|t| t == "HdMp4VideoFile")
+ .unwrap_or(false)
+ })
+ })
+ .and_then(|a| a.get("url"))
+ .and_then(|v| v.as_str())
+ .map(String::from)
+ });
+
+ let mut files = Vec::new();
+
+ if let Some(downloads) = data.get("downloads").and_then(|v| v.as_array()) {
+ for dl in downloads {
+ let file_id = dl
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let file_name = dl
+ .get("name")
+ .or_else(|| dl.get("filename"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("file")
+ .to_string();
+
+ let file_url = dl
+ .get("url")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ files.push(KajabiFile {
+ id: file_id,
+ name: file_name,
+ url: file_url,
+ });
+ }
+ }
+
+ return Ok(KajabiLessonDetail {
+ id,
+ name,
+ video_url,
+ files,
+ });
+ }
+
+ Err(last_err)
+}
+
+pub async fn save_session(session: &KajabiSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ site_id: session.site_id.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[kajabi] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<KajabiSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token, &saved.site_id)?;
+
+ tracing::info!("[kajabi] session loaded");
+
+ Ok(Some(KajabiSession {
+ token: saved.token,
+ site_id: saved.site_id,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kajabi/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/kajabi/downloader.rs
new file mode 100644
index 00000000..1f7d9837
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/kajabi/downloader.rs
@@ -0,0 +1,347 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, KajabiCourse, KajabiSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct KajabiCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &KajabiSession,
+ course: &KajabiCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_categories(session, &course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[kajabi] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &KajabiCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ let detail = match api::get_post_detail(session, &course.id, &lesson.id).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[kajabi] Failed to get post detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &KajabiCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if let Some(ref video_url) = detail.video_url {
+ let video_ext = if video_url.contains(".m3u8") {
+ "mp4"
+ } else {
+ video_url
+ .rsplit('.')
+ .next()
+ .and_then(|e| {
+ let e = e.split('?').next().unwrap_or(e);
+ if e.len() <= 4 {
+ Some(e)
+ } else {
+ None
+ }
+ })
+ .unwrap_or("mp4")
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.{}",
+ lesson_dir,
+ li + 1,
+ lesson_name,
+ video_ext
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[kajabi] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &KajabiCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[kajabi] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[kajabi] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[kajabi] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for file in &detail.files {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let file_name = filename::sanitize_path_component(&file.name);
+ let file_path = format!("{}/{}", lesson_dir, file_name);
+
+ if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&file_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ if let Some(ref url) = file.url {
+ match download_file_direct(&session.client, url, &file_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[kajabi] File download failed for '{}': {}",
+ file.name,
+ e
+ );
+ }
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &KajabiCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://app.kajabi.com/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://app.kajabi.com/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kajabi/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/kajabi/mod.rs
new file mode 100644
index 00000000..4aaa81a2
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/kajabi/mod.rs
@@ -0,0 +1,70 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct KajabiDownloader;
+
+impl Default for KajabiDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl KajabiDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for KajabiDownloader {
+ fn name(&self) -> &str {
+ "kajabi"
+ }
+
+ 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 == "kajabi.com"
+ || host.ends_with(".kajabi.com")
+ || host == "app.kajabi.com";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Kajabi Course".to_string(),
+ author: String::new(),
+ platform: "kajabi".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Kajabi courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kirvano/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/kirvano/api.rs
new file mode 100644
index 00000000..6bb720fd
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/kirvano/api.rs
@@ -0,0 +1,514 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct KirvanoSession {
+ pub token: String,
+ pub email: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub email: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KirvanoCourse {
+ pub id: String,
+ pub name: String,
+ pub seller: String,
+ pub image_url: Option<String>,
+ pub course_uuid: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KirvanoModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<KirvanoLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KirvanoLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub available: bool,
+ pub video_url: Option<String>,
+ pub description: Option<String>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static("https://app.kirvano.com"),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://app.kirvano.com/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("kirvano_session.json"))
+}
+
+pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<KirvanoSession> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "email": email,
+ "password": password,
+ "source": "app-web",
+ "fingerprint": null,
+ });
+
+ let resp = temp_client
+ .post("https://app-api.kirvano.com/users/login/otp")
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Authentication failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let token = body
+ .get("token")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("token not found in login response"))?
+ .to_string();
+
+ let client = build_client(&token)?;
+
+ Ok(KirvanoSession {
+ token,
+ email: email.to_string(),
+ client,
+ })
+}
+
+pub async fn validate_token(session: &KirvanoSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://app-api.kirvano.com/purchases?page=1&pageSize=1")
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &KirvanoSession) -> anyhow::Result<Vec<KirvanoCourse>> {
+ let mut all_courses = Vec::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!(
+ "https://app-api.kirvano.com/purchases?page={}&pageSize=99",
+ page
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let items = body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ if items.is_empty() {
+ break;
+ }
+
+ for item in &items {
+ let purchase_uuid = item
+ .get("uuid")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let name = item
+ .get("product")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Unnamed")
+ .to_string();
+
+ let image_url = item.get("photo").and_then(|v| v.as_str()).map(String::from);
+
+ let seller = item
+ .get("sellerName")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let course_uuid = item
+ .get("courseUuid")
+ .or_else(|| item.get("productUuid"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if course_uuid.is_empty() {
+ let detail_url = format!(
+ "https://app-api.kirvano.com/purchases/{}",
+ purchase_uuid
+ );
+ if let Ok(detail_resp) = session.client.get(&detail_url).send().await {
+ if detail_resp.status().is_success() {
+ if let Ok(detail_text) = detail_resp.text().await {
+ if let Ok(detail_body) = serde_json::from_str::<serde_json::Value>(&detail_text) {
+ let resolved_uuid = detail_body
+ .get("courseUuid")
+ .or_else(|| detail_body.get("productUuid"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let resolved_seller = detail_body
+ .get("sellerName")
+ .and_then(|v| v.as_str())
+ .unwrap_or(&seller)
+ .to_string();
+
+ if !resolved_uuid.is_empty() {
+ all_courses.push(KirvanoCourse {
+ id: purchase_uuid,
+ name: name.clone(),
+ seller: resolved_seller,
+ image_url: image_url.clone(),
+ course_uuid: resolved_uuid,
+ });
+ continue;
+ }
+ }
+ }
+ }
+ }
+ continue;
+ }
+
+ all_courses.push(KirvanoCourse {
+ id: purchase_uuid,
+ name,
+ seller,
+ image_url,
+ course_uuid,
+ });
+ }
+
+ let meta = body.get("meta");
+ let current_page = meta
+ .and_then(|m| m.get("page"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(page as u64);
+ let total_pages = meta
+ .and_then(|m| m.get("pages"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(1);
+
+ if current_page >= total_pages {
+ break;
+ }
+
+ page += 1;
+ }
+
+ Ok(all_courses)
+}
+
+pub async fn get_course_modules(
+ session: &KirvanoSession,
+ course_uuid: &str,
+) -> anyhow::Result<Vec<KirvanoModule>> {
+ let mut all_modules = Vec::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!(
+ "https://members-api.kirvano.com/v1/courses/{}/lessons/modules?page={}&pageSize=99",
+ course_uuid, page
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_modules returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let items = body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ if items.is_empty() {
+ break;
+ }
+
+ for item in &items {
+ let mod_uuid = item
+ .get("uuid")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let mod_name = item
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Module")
+ .to_string();
+
+ let mod_order = item
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let lessons = get_module_lessons(session, course_uuid, &mod_uuid).await?;
+
+ all_modules.push(KirvanoModule {
+ id: mod_uuid,
+ name: mod_name,
+ order: mod_order,
+ lessons,
+ });
+ }
+
+ let meta = body.get("meta");
+ let current_page = meta
+ .and_then(|m| m.get("page"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(page as u64);
+ let total_pages = meta
+ .and_then(|m| m.get("pages"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(1);
+
+ if current_page >= total_pages {
+ break;
+ }
+
+ page += 1;
+ }
+
+ all_modules.sort_by_key(|m| m.order);
+
+ Ok(all_modules)
+}
+
+async fn get_module_lessons(
+ session: &KirvanoSession,
+ course_uuid: &str,
+ module_uuid: &str,
+) -> anyhow::Result<Vec<KirvanoLesson>> {
+ let mut all_lessons = Vec::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!(
+ "https://members-api.kirvano.com/v1/courses/{}/lessons/modules/{}/contents?page={}&pageSize=99",
+ course_uuid, module_uuid, page
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_module_lessons returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let items = body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ if items.is_empty() {
+ break;
+ }
+
+ for item in &items {
+ let lesson_uuid = item
+ .get("uuid")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_name = item
+ .get("name")
+ .or_else(|| item.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("Lesson")
+ .to_string();
+
+ let lesson_order = item
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let available = item
+ .get("available")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(true);
+
+ let video_url = item
+ .get("videoUrl")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let description = item
+ .get("description")
+ .or_else(|| item.get("content"))
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .map(String::from);
+
+ all_lessons.push(KirvanoLesson {
+ id: lesson_uuid,
+ name: lesson_name,
+ order: lesson_order,
+ available,
+ video_url,
+ description,
+ });
+ }
+
+ let meta = body.get("meta");
+ let current_page = meta
+ .and_then(|m| m.get("page"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(page as u64);
+ let total_pages = meta
+ .and_then(|m| m.get("pages"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(1);
+
+ if current_page >= total_pages {
+ break;
+ }
+
+ page += 1;
+ }
+
+ all_lessons.sort_by_key(|l| l.order);
+
+ Ok(all_lessons)
+}
+
+pub async fn save_session(session: &KirvanoSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ email: session.email.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[kirvano] session saved for {}", session.email);
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<KirvanoSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[kirvano] session loaded for {}", saved.email);
+
+ Ok(Some(KirvanoSession {
+ token: saved.token,
+ email: saved.email,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kirvano/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/kirvano/downloader.rs
new file mode 100644
index 00000000..cf0d8fd7
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/kirvano/downloader.rs
@@ -0,0 +1,275 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, KirvanoCourse, KirvanoSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct KirvanoCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &KirvanoSession,
+ course: &KirvanoCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_modules(session, &course.course_uuid).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[kirvano] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &KirvanoCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ if !lesson.available {
+ tracing::info!("[kirvano] Skipping unavailable lesson: {}", lesson.name);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &KirvanoCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+
+ if let Some(ref desc) = lesson.description {
+ let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, filename::sanitize_path_component(&lesson.name));
+ tokio::fs::create_dir_all(&lesson_desc_dir).await?;
+ omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
+ }
+
+ if let Some(ref video_url) = lesson.video_url {
+ if video_url.is_empty() {
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &KirvanoCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[kirvano] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &KirvanoCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ match download_with_ytdlp(video_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[kirvano] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[kirvano] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &KirvanoCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://app.kirvano.com/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kirvano/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/kirvano/mod.rs
new file mode 100644
index 00000000..add839ad
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/kirvano/mod.rs
@@ -0,0 +1,70 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct KirvanoDownloader;
+
+impl Default for KirvanoDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl KirvanoDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for KirvanoDownloader {
+ fn name(&self) -> &str {
+ "kirvano"
+ }
+
+ 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 == "kirvano.com"
+ || host == "app-api.kirvano.com"
+ || host == "members-api.kirvano.com";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Kirvano".to_string(),
+ author: String::new(),
+ platform: "kirvano".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: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Kirvano"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kiwify/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/kiwify/api.rs
new file mode 100644
index 00000000..1fe29c21
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/kiwify/api.rs
@@ -0,0 +1,672 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const CDN_BASE: &str = "https://d3pjuhbfoxhm7c.cloudfront.net";
+
+#[derive(Clone)]
+pub struct KiwifySession {
+ pub token: String,
+ pub email: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub email: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KiwifyCourse {
+ pub id: i64,
+ pub name: String,
+ pub seller: String,
+ pub image_url: Option<String>,
+ pub is_school: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KiwifyModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<KiwifyLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KiwifyLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KiwifyLessonDetail {
+ pub id: String,
+ pub name: String,
+ pub description: Option<String>,
+ pub video_url: Option<String>,
+ pub files: Vec<KiwifyFile>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct KiwifyFile {
+ pub id: String,
+ pub name: String,
+ pub url: Option<String>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static("https://admin.kiwify.com.br"),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://admin.kiwify.com.br/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("kiwify_session.json"))
+}
+
+pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<KiwifySession> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "email": email,
+ "password": password,
+ "returnSecureToken": true,
+ });
+
+ let resp = temp_client
+ .post("https://admin-api.kiwify.com.br/v1/handleAuth/login")
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Authentication failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let token = body
+ .get("idToken")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("idToken not found in login response"))?
+ .to_string();
+
+ let client = build_client(&token)?;
+
+ Ok(KiwifySession {
+ token,
+ email: email.to_string(),
+ client,
+ })
+}
+
+pub async fn validate_token(session: &KiwifySession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://admin-api.kiwify.com.br/v1/viewer/schools/courses?page=1&archived=false")
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &KiwifySession) -> anyhow::Result<Vec<KiwifyCourse>> {
+ let mut all_courses = Vec::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!(
+ "https://admin-api.kiwify.com.br/v1/viewer/schools/courses?page={}&archived=false",
+ page
+ );
+
+ tracing::info!("[kiwify] fetching courses page {}", page);
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ tracing::info!("[kiwify] page {} status={} body_len={}", page, status, body_text.len());
+
+ if !status.is_success() {
+ if all_courses.is_empty() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+ break;
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let courses_arr = body
+ .get("courses")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let total_count = body.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
+ let page_size = body.get("page_size").and_then(|v| v.as_i64()).unwrap_or(10);
+
+ tracing::info!("[kiwify] page {} returned {} courses (total={}, page_size={})", page, courses_arr.len(), total_count, page_size);
+
+ if courses_arr.is_empty() {
+ break;
+ }
+
+ for item in &courses_arr {
+ let course_in_school = item
+ .get("course_in_school")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ let (info_obj, is_school) = if course_in_school {
+ (
+ item.get("school_info").unwrap_or(item),
+ true,
+ )
+ } else {
+ (
+ item.get("course_info").unwrap_or(item),
+ false,
+ )
+ };
+
+ let id = info_obj
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .or_else(|| item.get("id").and_then(|v| v.as_i64()))
+ .unwrap_or(0);
+
+ let name = info_obj
+ .get("name")
+ .and_then(|v| v.as_str())
+ .or_else(|| item.get("name").and_then(|v| v.as_str()))
+ .unwrap_or("")
+ .to_string();
+
+ let seller = info_obj
+ .get("producer")
+ .and_then(|p| p.get("name").and_then(|n| n.as_str()))
+ .or_else(|| {
+ item.get("producer")
+ .and_then(|p| p.get("name").and_then(|n| n.as_str()))
+ })
+ .unwrap_or("")
+ .to_string();
+
+ let image_url = info_obj
+ .get("image")
+ .and_then(|v| v.as_str())
+ .or_else(|| info_obj.get("thumbnail").and_then(|v| v.as_str()))
+ .map(String::from);
+
+ all_courses.push(KiwifyCourse {
+ id,
+ name,
+ seller,
+ image_url,
+ is_school,
+ });
+ }
+
+ if total_count > 0 && (page as i64 * page_size) >= total_count {
+ break;
+ }
+
+ if page >= 50 {
+ tracing::warn!("[kiwify] safety limit reached at page 50");
+ break;
+ }
+
+ page += 1;
+ }
+
+ tracing::info!("[kiwify] total courses found: {}", all_courses.len());
+ Ok(all_courses)
+}
+
+pub async fn get_course_content(
+ session: &KiwifySession,
+ course_id: i64,
+) -> anyhow::Result<Vec<KiwifyModule>> {
+ let club_url = format!(
+ "https://admin-api.kiwify.com/v1/viewer/clubs/{}/content?caipirinha=true",
+ course_id
+ );
+
+ let body = match session.client.get(&club_url).send().await {
+ Ok(resp) if resp.status().is_success() => {
+ let text = resp.text().await?;
+ serde_json::from_str::<serde_json::Value>(&text)?
+ }
+ _ => {
+ let fallback_url = format!(
+ "https://admin-api.kiwify.com.br/v1/viewer/courses/{}",
+ course_id
+ );
+ let resp = session.client.get(&fallback_url).send().await?;
+ let status = resp.status();
+ let text = resp.text().await?;
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &text[..text.len().min(300)]
+ ));
+ }
+ serde_json::from_str::<serde_json::Value>(&text)?
+ }
+ };
+
+ let modules_obj = body
+ .get("modules")
+ .or_else(|| body.get("content"))
+ .ok_or_else(|| anyhow!("No modules found in course content response"))?;
+
+ let mut modules = Vec::new();
+
+ match modules_obj {
+ serde_json::Value::Object(map) => {
+ let mut entries: Vec<_> = map.iter().collect();
+ entries.sort_by_key(|(_, v)| {
+ v.get("order").and_then(|o| o.as_i64()).unwrap_or(0)
+ });
+
+ for (key, module_val) in entries {
+ let module_name = module_val
+ .get("title")
+ .or_else(|| module_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or(key)
+ .to_string();
+
+ let module_order = module_val
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let mut lessons = Vec::new();
+
+ let lessons_obj = module_val
+ .get("lessons")
+ .or_else(|| module_val.get("classes"));
+
+ if let Some(serde_json::Value::Object(lessons_map)) = lessons_obj {
+ let mut lesson_entries: Vec<_> = lessons_map.iter().collect();
+ lesson_entries.sort_by_key(|(_, v)| {
+ v.get("order").and_then(|o| o.as_i64()).unwrap_or(0)
+ });
+
+ for (lesson_key, lesson_val) in lesson_entries {
+ let lesson_name = lesson_val
+ .get("title")
+ .or_else(|| lesson_val.get("name"))
+ .or_else(|| lesson_val.get("ref"))
+ .and_then(|v| v.as_str())
+ .unwrap_or(lesson_key)
+ .to_string();
+
+ let lesson_order = lesson_val
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ lessons.push(KiwifyLesson {
+ id: lesson_key.clone(),
+ name: lesson_name,
+ order: lesson_order,
+ });
+ }
+ } else if let Some(serde_json::Value::Array(lessons_arr)) = lessons_obj {
+ for (i, lesson_val) in lessons_arr.iter().enumerate() {
+ let lesson_id = lesson_val
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_name = lesson_val
+ .get("title")
+ .or_else(|| lesson_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_order = lesson_val
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(i as i64);
+
+ lessons.push(KiwifyLesson {
+ id: if lesson_id.is_empty() {
+ format!("{}", i)
+ } else {
+ lesson_id
+ },
+ name: lesson_name,
+ order: lesson_order,
+ });
+ }
+ }
+
+ modules.push(KiwifyModule {
+ id: key.clone(),
+ name: module_name,
+ order: module_order,
+ lessons,
+ });
+ }
+ }
+ serde_json::Value::Array(arr) => {
+ for (i, module_val) in arr.iter().enumerate() {
+ let module_id = module_val
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let module_name = module_val
+ .get("title")
+ .or_else(|| module_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let module_order = module_val
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(i as i64);
+
+ let mut lessons = Vec::new();
+
+ if let Some(serde_json::Value::Array(lessons_arr)) =
+ module_val.get("lessons").or_else(|| module_val.get("classes"))
+ {
+ for (j, lesson_val) in lessons_arr.iter().enumerate() {
+ let lesson_id = lesson_val
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_name = lesson_val
+ .get("title")
+ .or_else(|| lesson_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_order = lesson_val
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(j as i64);
+
+ lessons.push(KiwifyLesson {
+ id: if lesson_id.is_empty() {
+ format!("{}", j)
+ } else {
+ lesson_id
+ },
+ name: lesson_name,
+ order: lesson_order,
+ });
+ }
+ }
+
+ modules.push(KiwifyModule {
+ id: if module_id.is_empty() {
+ format!("{}", i)
+ } else {
+ module_id
+ },
+ name: module_name,
+ order: module_order,
+ lessons,
+ });
+ }
+ }
+ _ => {
+ return Err(anyhow!("Unexpected modules format in course content"));
+ }
+ }
+
+ modules.sort_by_key(|m| m.order);
+ for m in &mut modules {
+ m.lessons.sort_by_key(|l| l.order);
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_lesson_detail(
+ session: &KiwifySession,
+ course_id: i64,
+ lesson_id: &str,
+) -> anyhow::Result<KiwifyLessonDetail> {
+ let url = format!(
+ "https://admin-api.kiwify.com/v1/viewer/courses/{}/lesson/{}",
+ course_id, lesson_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lesson_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let lesson = body.get("lesson").unwrap_or(&body);
+
+ let id = lesson
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or(lesson_id)
+ .to_string();
+
+ let name = lesson
+ .get("title")
+ .or_else(|| lesson.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let description = lesson
+ .get("description")
+ .or_else(|| lesson.get("content"))
+ .or_else(|| lesson.get("body"))
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .map(String::from);
+
+ let video_url = lesson
+ .get("stream_link")
+ .or_else(|| lesson.get("video_url"))
+ .or_else(|| lesson.get("video"))
+ .and_then(|v| v.as_str())
+ .map(|url| {
+ if url.starts_with('/') {
+ format!("{}{}", CDN_BASE, url)
+ } else {
+ url.to_string()
+ }
+ });
+
+ let files = lesson
+ .get("files")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .map(|f| {
+ let file_id = f
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let file_name = f
+ .get("name")
+ .or_else(|| f.get("filename"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("file")
+ .to_string();
+
+ let file_url = f.get("url").and_then(|v| v.as_str()).map(String::from);
+
+ KiwifyFile {
+ id: file_id,
+ name: file_name,
+ url: file_url,
+ }
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+
+ Ok(KiwifyLessonDetail {
+ id,
+ name,
+ description,
+ video_url,
+ files,
+ })
+}
+
+pub async fn get_file_download_url(
+ session: &KiwifySession,
+ course_id: i64,
+ file_id: &str,
+) -> anyhow::Result<String> {
+ let url = format!(
+ "https://admin-api.kiwify.com.br/v1/viewer/courses/{}/files/{}?forceDownload=true",
+ course_id, file_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_file_download_url returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let download_url = body
+ .get("url")
+ .or_else(|| body.get("download_url"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("No download URL in file response"))?
+ .to_string();
+
+ Ok(download_url)
+}
+
+pub async fn save_session(session: &KiwifySession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ email: session.email.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[kiwify] session saved for {}", session.email);
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<KiwifySession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[kiwify] session loaded for {}", saved.email);
+
+ Ok(Some(KiwifySession {
+ token: saved.token,
+ email: saved.email,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kiwify/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/kiwify/downloader.rs
new file mode 100644
index 00000000..3ef5ce4d
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/kiwify/downloader.rs
@@ -0,0 +1,364 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, KiwifyCourse, KiwifySession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct KiwifyCourseDownloadProgress {
+ pub course_id: i64,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &KiwifySession,
+ course: &KiwifyCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &KiwifyCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ let detail = match api::get_lesson_detail(session, course.id, &lesson.id).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[kiwify] Failed to get lesson detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &KiwifyCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if let Some(ref desc) = detail.description {
+ omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
+ }
+
+ if let Some(ref video_url) = detail.video_url {
+ let video_ext = if video_url.contains(".m3u8") {
+ "mp4"
+ } else {
+ video_url
+ .rsplit('.')
+ .next()
+ .and_then(|e| {
+ let e = e.split('?').next().unwrap_or(e);
+ if e.len() <= 4 {
+ Some(e)
+ } else {
+ None
+ }
+ })
+ .unwrap_or("mp4")
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.{}",
+ lesson_dir,
+ li + 1,
+ lesson_name,
+ video_ext
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[kiwify] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &KiwifyCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[kiwify] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[kiwify] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[kiwify] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for file in &detail.files {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let file_name = filename::sanitize_path_component(&file.name);
+ let file_path = format!("{}/{}", lesson_dir, file_name);
+
+ if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&file_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ let download_url = if let Some(ref url) = file.url {
+ url.clone()
+ } else {
+ match api::get_file_download_url(session, course.id, &file.id).await {
+ Ok(url) => url,
+ Err(e) => {
+ tracing::error!(
+ "[kiwify] Failed to get download URL for file '{}': {}",
+ file.name,
+ e
+ );
+ continue;
+ }
+ }
+ };
+
+ match download_file_direct(&session.client, &download_url, &file_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[kiwify] File download failed for '{}': {}",
+ file.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &KiwifyCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://admin.kiwify.com.br/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://admin.kiwify.com.br/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kiwify/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/kiwify/mod.rs
new file mode 100644
index 00000000..e4686333
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/kiwify/mod.rs
@@ -0,0 +1,72 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct KiwifyDownloader;
+
+impl Default for KiwifyDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl KiwifyDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for KiwifyDownloader {
+ fn name(&self) -> &str {
+ "kiwify"
+ }
+
+ 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 == "kiwify.com.br"
+ || host.ends_with(".kiwify.com.br")
+ || host == "admin.kiwify.com.br";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Kiwify Course".to_string(),
+ author: String::new(),
+ platform: "kiwify".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!(
+ "Use the courses interface to download Kiwify courses"
+ ))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/masterclass/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/masterclass/api.rs
new file mode 100644
index 00000000..c81ea5d1
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/masterclass/api.rs
@@ -0,0 +1,430 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const MC_API_KEY: &str = "b9517f7d8d1f48c2de88100f2c13e77a9d8e524aed204651acca65202ff5c6cb9244c045795b1fafda617ac5eb0a6c50";
+
+#[derive(Clone)]
+pub struct MasterClassSession {
+ pub cookies: String,
+ pub profile_id: Option<String>,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub cookies: String,
+ pub profile_id: Option<String>,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MasterClassCourse {
+ pub id: String,
+ pub name: String,
+ pub instructor: String,
+ pub slug: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MasterClassModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<MasterClassLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MasterClassLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub media_uuid: Option<String>,
+}
+
+fn build_client(cookies: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert("Cookie", HeaderValue::from_str(cookies)?);
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("masterclass_session.json"))
+}
+
+pub async fn authenticate_cookies(cookies: &str) -> anyhow::Result<MasterClassSession> {
+ let client = build_client(cookies)?;
+
+ let session = MasterClassSession {
+ cookies: cookies.to_string(),
+ profile_id: None,
+ client,
+ };
+
+ let profile_id = fetch_profile_id(&session).await.ok();
+
+ Ok(MasterClassSession {
+ cookies: cookies.to_string(),
+ profile_id,
+ client: session.client,
+ })
+}
+
+async fn fetch_profile_id(session: &MasterClassSession) -> anyhow::Result<String> {
+ let resp = session
+ .client
+ .get("https://www.masterclass.com/jsonapi/v1/watch-list-items?deep=true&page%5Bsize%5D=1")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!("Failed to fetch profile: status {}", status));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let profile_id = body
+ .get("meta")
+ .and_then(|m| m.get("profile_id").or_else(|| m.get("profileId")))
+ .or_else(|| body.get("profile_id"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .filter(|s| !s.is_empty())
+ .ok_or_else(|| anyhow!("profile_id not found in response"))?;
+
+ Ok(profile_id)
+}
+
+pub async fn validate_token(session: &MasterClassSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://www.masterclass.com/jsonapi/v1/watch-list-items?deep=true&page%5Bsize%5D=1")
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &MasterClassSession) -> anyhow::Result<Vec<MasterClassCourse>> {
+ let resp = session
+ .client
+ .get("https://www.masterclass.com/jsonapi/v1/watch-list-items?deep=true")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let mut courses = Vec::new();
+
+ let items = body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for item in &items {
+ let attrs = item.get("attributes").unwrap_or(item);
+
+ let id = item
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let name = attrs
+ .get("title")
+ .or_else(|| attrs.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let instructor = attrs
+ .get("instructor_name")
+ .or_else(|| attrs.get("instructor"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let slug = attrs
+ .get("slug")
+ .or_else(|| attrs.get("url_slug"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if !id.is_empty() && !name.is_empty() {
+ courses.push(MasterClassCourse {
+ id,
+ name,
+ instructor,
+ slug,
+ });
+ }
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_course_uuid(
+ session: &MasterClassSession,
+ slug: &str,
+) -> anyhow::Result<String> {
+ let url = format!(
+ "https://www.masterclass.com/api/v3/unique-identifiers/courses/{}",
+ slug
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_uuid returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let uuid = body
+ .get("uuid")
+ .or_else(|| body.get("id"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("uuid not found in response"))?
+ .to_string();
+
+ Ok(uuid)
+}
+
+pub async fn get_course_content(
+ session: &MasterClassSession,
+ slug: &str,
+) -> anyhow::Result<Vec<MasterClassModule>> {
+ let uuid = get_course_uuid(session, slug).await?;
+
+ let url = format!(
+ "https://www.masterclass.com/api/v3/watch-bundles/{}",
+ uuid
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let chapters = body
+ .get("chapters")
+ .or_else(|| body.get("episodes"))
+ .or_else(|| body.get("lessons"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for (ci, chapter) in chapters.iter().enumerate() {
+ let chapter_id = chapter
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", ci),
+ })
+ .unwrap_or_else(|| format!("{}", ci));
+
+ let chapter_name = chapter
+ .get("title")
+ .or_else(|| chapter.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let media_uuid = chapter
+ .get("media_uuid")
+ .or_else(|| chapter.get("mediaUuid"))
+ .or_else(|| chapter.get("video_uuid"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let lessons = vec![MasterClassLesson {
+ id: chapter_id.clone(),
+ name: chapter_name.clone(),
+ order: ci as i64,
+ media_uuid,
+ }];
+
+ modules.push(MasterClassModule {
+ id: chapter_id,
+ name: chapter_name,
+ order: ci as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_video_metadata(
+ session: &MasterClassSession,
+ media_uuid: &str,
+) -> anyhow::Result<String> {
+ let url = format!(
+ "https://edge.masterclass.com/api/v1/media/metadata/{}",
+ media_uuid
+ );
+
+ let profile_id = session
+ .profile_id
+ .as_deref()
+ .unwrap_or("");
+
+ let resp = session
+ .client
+ .get(&url)
+ .header("X-Api-Key", MC_API_KEY)
+ .header("Mc-Profile-Id", profile_id)
+ .header("Origin", "https://www.masterclass.com")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_video_metadata returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let sources = body
+ .get("sources")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for source in &sources {
+ let src = source
+ .get("src")
+ .or_else(|| source.get("url"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if !src.is_empty() {
+ return Ok(src.to_string());
+ }
+ }
+
+ let direct_url = body
+ .get("url")
+ .or_else(|| body.get("src"))
+ .or_else(|| body.get("source"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if !direct_url.is_empty() {
+ return Ok(direct_url.to_string());
+ }
+
+ Err(anyhow!("No video URL found in metadata response"))
+}
+
+pub async fn save_session(session: &MasterClassSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ cookies: session.cookies.clone(),
+ profile_id: session.profile_id.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[masterclass] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<MasterClassSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.cookies)?;
+
+ tracing::info!("[masterclass] session loaded");
+
+ Ok(Some(MasterClassSession {
+ cookies: saved.cookies,
+ profile_id: saved.profile_id,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/masterclass/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/masterclass/downloader.rs
new file mode 100644
index 00000000..a43f6291
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/masterclass/downloader.rs
@@ -0,0 +1,286 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, MasterClassCourse, MasterClassSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct MasterClassCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &MasterClassSession,
+ course: &MasterClassCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let slug = if course.slug.is_empty() {
+ &course.id
+ } else {
+ &course.slug
+ };
+
+ let modules = api::get_course_content(session, slug).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_label = if course.instructor.is_empty() {
+ course.name.clone()
+ } else {
+ format!("{} - {}", course.instructor, course.name)
+ };
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course_label)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[masterclass] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &MasterClassCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ for (_li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ course_dir,
+ mi + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[masterclass] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MasterClassCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if let Some(ref media_uuid) = lesson.media_uuid {
+ match api::get_video_metadata(session, media_uuid).await {
+ Ok(video_url) => {
+ if video_url.contains(".m3u8") {
+ match download_hls_video(&video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[masterclass] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(&video_url, &course_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[masterclass] yt-dlp failed for '{}': {}, trying direct",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, &video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[masterclass] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(
+ "[masterclass] Failed to get video URL for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MasterClassCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://www.masterclass.com/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://www.masterclass.com/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/masterclass/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/masterclass/mod.rs
new file mode 100644
index 00000000..7beb38ea
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/masterclass/mod.rs
@@ -0,0 +1,68 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct MasterClassDownloader;
+
+impl Default for MasterClassDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl MasterClassDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for MasterClassDownloader {
+ fn name(&self) -> &str {
+ "masterclass"
+ }
+
+ 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 == "masterclass.com" || host == "www.masterclass.com";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "MasterClass Course".to_string(),
+ author: String::new(),
+ platform: "masterclass".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download MasterClass courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/matematicaprapassar/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/matematicaprapassar/mod.rs
new file mode 100644
index 00000000..05aeaa98
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/matematicaprapassar/mod.rs
@@ -0,0 +1,65 @@
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct MatematicaPraPassarDownloader;
+
+impl Default for MatematicaPraPassarDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl MatematicaPraPassarDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for MatematicaPraPassarDownloader {
+ fn name(&self) -> &str {
+ "matematicaprapassar"
+ }
+
+ 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 == "matematicaprapassar.com.br" || host == "www.matematicaprapassar.com.br";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Matemática Pra Passar".to_string(),
+ author: String::new(),
+ platform: "matematicaprapassar".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Matemática Pra Passar courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcel/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcel/api.rs
new file mode 100644
index 00000000..bef27a25
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/medcel/api.rs
@@ -0,0 +1,583 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const API_BASE: &str = "https://service.medcel.com.br";
+const ORIGIN_URL: &str = "https://areaaluno.medcel.com.br";
+
+#[derive(Clone)]
+pub struct MedcelSession {
+ pub token: String,
+ pub api_key: String,
+ pub student_id: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub api_key: String,
+ pub student_id: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MedcelCourse {
+ pub id: String,
+ pub name: String,
+ pub product_id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MedcelModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<MedcelLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MedcelLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub type_id: String,
+ pub product_id: String,
+ pub materials: Vec<MedcelMaterial>,
+ pub description: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MedcelMaterial {
+ pub key: String,
+ pub title: String,
+ pub url: String,
+}
+
+fn build_client(token: &str, api_key: &str, origin: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert(
+ "X-Api-Key",
+ HeaderValue::from_str(api_key)?,
+ );
+ headers.insert(
+ "X-Amz-User-Agent",
+ HeaderValue::from_static(USER_AGENT),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_str(&format!("{}/", origin))?,
+ );
+ headers.insert(
+ "Origin",
+ HeaderValue::from_str(origin)?,
+ );
+ headers.insert(
+ "Accept",
+ HeaderValue::from_static("application/json, text/plain, */*"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+pub fn build_client_with_origin(token: &str, api_key: &str, origin: &str) -> anyhow::Result<reqwest::Client> {
+ build_client(token, api_key, origin)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("medcel_session.json"))
+}
+
+pub async fn authenticate(email: &str, password: &str, api_key: &str) -> anyhow::Result<MedcelSession> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "X-Api-Key",
+ HeaderValue::from_str(api_key)?,
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_str(&format!("{}/", ORIGIN_URL))?,
+ );
+ headers.insert(
+ "Origin",
+ HeaderValue::from_str(ORIGIN_URL)?,
+ );
+
+ let payload = serde_json::json!({
+ "email": email,
+ "password": password,
+ });
+
+ let resp = temp_client
+ .post(format!("{}/m1/students/auth", API_BASE))
+ .headers(headers)
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Authentication failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let student_id = body
+ .get("_id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let session_token = body
+ .get("sessionToken")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("sessionToken not found in auth response"))?
+ .to_string();
+
+ let client = build_client(&session_token, api_key, ORIGIN_URL)?;
+
+ Ok(MedcelSession {
+ token: session_token,
+ api_key: api_key.to_string(),
+ student_id,
+ client,
+ })
+}
+
+pub async fn validate_token(session: &MedcelSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get(format!("{}/m1/contracts/getContractsByStudent?_id=me", API_BASE))
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn fetch_student_id(session: &MedcelSession) -> anyhow::Result<String> {
+ let resp = session
+ .client
+ .get(format!("{}/m1/contracts/getContractsByStudent?_id=me", API_BASE))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!("fetch_student_id failed (status {})", status));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let id = body
+ .get("_id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ Ok(id)
+}
+
+pub async fn list_courses(session: &MedcelSession) -> anyhow::Result<Vec<MedcelCourse>> {
+ let url = format!(
+ "{}/m1/contracts/getContractsByStudent?_id={}",
+ API_BASE, session.student_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let contracts = body
+ .get("contracts")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut courses = Vec::new();
+
+ for contract in &contracts {
+ let product = match contract.get("product") {
+ Some(p) => p,
+ None => continue,
+ };
+
+ let product_id = match product.get("_id").and_then(|v| v.as_str()) {
+ Some(id) => id.to_string(),
+ None => continue,
+ };
+
+ let product_name = product
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Curso")
+ .to_string();
+
+ let content_available = contract
+ .get("overallStatus")
+ .and_then(|s| s.get("content"))
+ .and_then(|c| c.get("available"))
+ .and_then(|v| v.as_bool())
+ .unwrap_or(true);
+
+ if !content_available {
+ continue;
+ }
+
+ courses.push(MedcelCourse {
+ id: product_id.clone(),
+ name: product_name,
+ product_id,
+ });
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_modules(session: &MedcelSession, product_id: &str) -> anyhow::Result<Vec<MedcelModule>> {
+ let mut all_playlists = Vec::new();
+ let mut page = 1u32;
+ let limit = 100u32;
+
+ loop {
+ let url = format!(
+ "{}/m9/subjectPlaylists/getSubjectPlaylists?studentId={}&productId={}&specialtyId=&sortMode=incidence&trial=false&page={}&limit={}",
+ API_BASE, session.student_id, product_id, page, limit
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_modules returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let items = body
+ .get("items")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ if items.is_empty() {
+ break;
+ }
+
+ all_playlists.extend(items);
+
+ let total_pages = body
+ .get("pagination")
+ .and_then(|p| p.get("pageTotal"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(1);
+
+ if page as u64 >= total_pages {
+ break;
+ }
+ page += 1;
+ }
+
+ let mut modules = Vec::new();
+
+ for (i, playlist) in all_playlists.iter().enumerate() {
+ let playlist_id = match playlist.get("_id").and_then(|v| v.as_str()) {
+ Some(id) => id.to_string(),
+ None => continue,
+ };
+
+ let name = playlist
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .trim()
+ .to_string();
+
+ let order = playlist
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(i as i64 + 1);
+
+ let lessons = get_playlist_lessons(session, &playlist_id, product_id).await?;
+
+ modules.push(MedcelModule {
+ id: playlist_id,
+ name,
+ order,
+ lessons,
+ });
+ }
+
+ modules.sort_by_key(|m| m.order);
+
+ Ok(modules)
+}
+
+async fn get_playlist_lessons(
+ session: &MedcelSession,
+ playlist_id: &str,
+ product_id: &str,
+) -> anyhow::Result<Vec<MedcelLesson>> {
+ let url = format!(
+ "{}/m9/subjectPlaylists/getPlaylistContents?playlistId={}&studentId={}",
+ API_BASE, playlist_id, session.student_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_playlist_lessons returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let playlist_contents = body
+ .get("playlistContents")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (ci, content) in playlist_contents.iter().enumerate() {
+ let content_name = content
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .trim()
+ .to_string();
+
+ let classes = content
+ .get("classes")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ if classes.is_empty() {
+ continue;
+ }
+
+ let mut video_class: Option<&serde_json::Value> = None;
+ let mut all_materials = Vec::new();
+
+ for class_item in &classes {
+ let type_id = class_item
+ .get("subTypeLearningObject")
+ .and_then(|s| s.get("id"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if let Some(mats) = class_item.get("complementMaterial").and_then(|v| v.as_array()) {
+ for mat in mats {
+ let mat_url = mat.get("location").and_then(|v| v.as_str()).unwrap_or("");
+ let mat_title = mat.get("title").and_then(|v| v.as_str()).unwrap_or("Material");
+ let mat_key = mat.get("key").and_then(|v| v.as_str()).unwrap_or("");
+
+ if !mat_url.is_empty() {
+ all_materials.push(MedcelMaterial {
+ key: mat_key.to_string(),
+ title: mat_title.to_string(),
+ url: mat_url.to_string(),
+ });
+ }
+ }
+ }
+
+ if type_id == "videoClass" && video_class.is_none() {
+ video_class = Some(class_item);
+ }
+ }
+
+ let chosen = video_class.unwrap_or(&classes[0]);
+
+ let class_id = chosen
+ .get("id")
+ .or_else(|| chosen.get("_id"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if class_id.is_empty() {
+ continue;
+ }
+
+ let type_id = chosen
+ .get("subTypeLearningObject")
+ .and_then(|s| s.get("id"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let description = content
+ .get("description")
+ .or_else(|| chosen.get("description"))
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .map(String::from);
+
+ lessons.push(MedcelLesson {
+ id: class_id,
+ name: content_name,
+ order: (ci + 1) as i64,
+ type_id,
+ product_id: product_id.to_string(),
+ materials: all_materials,
+ description,
+ });
+ }
+
+ Ok(lessons)
+}
+
+pub async fn get_video_url(
+ session: &MedcelSession,
+ class_id: &str,
+ product_id: &str,
+) -> anyhow::Result<String> {
+ let url = format!(
+ "{}/m2/videos/getVideoToPlay?id={}&student={}&product={}",
+ API_BASE, class_id, session.student_id, product_id
+ );
+
+ let resp = session
+ .client
+ .get(&url)
+ .header("X-Host-Origin", ORIGIN_URL)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_video_url returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let data = body.get("data").unwrap_or(&body);
+
+ let uri = data
+ .get("uri")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ let signature = data
+ .get("signature")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ let video_url = format!("{}{}", uri, signature);
+
+ if video_url.is_empty() {
+ return Err(anyhow!("No video URL found in response"));
+ }
+
+ Ok(video_url)
+}
+
+pub async fn save_session(session: &MedcelSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ api_key: session.api_key.clone(),
+ student_id: session.student_id.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[medcel] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<MedcelSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token, &saved.api_key, ORIGIN_URL)?;
+
+ tracing::info!("[medcel] session loaded");
+
+ Ok(Some(MedcelSession {
+ token: saved.token,
+ api_key: saved.api_key,
+ student_id: saved.student_id,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcel/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcel/downloader.rs
new file mode 100644
index 00000000..bf144657
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/medcel/downloader.rs
@@ -0,0 +1,316 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, MedcelCourse, MedcelSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct MedcelCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &MedcelSession,
+ course: &MedcelCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_modules(session, &course.product_id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[medcel] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &MedcelCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ if let Some(ref desc) = lesson.description {
+ omniget_core::core::course_utils::save_description(&lesson_dir, desc, "txt").await.ok();
+ }
+
+ if lesson.type_id == "videoClass" || lesson.type_id.contains("video") {
+ match api::get_video_url(session, &lesson.id, &lesson.product_id).await {
+ Ok(video_url) => {
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ lesson_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[medcel] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MedcelCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(&video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[medcel] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(&video_url, &lesson_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[medcel] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, &video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[medcel] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(
+ "[medcel] Failed to get video URL for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+
+ for material in &lesson.materials {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let ext = material.url.rsplit('.').next().unwrap_or("pdf");
+ let ext = ext.split('?').next().unwrap_or(ext);
+ let mat_name = filename::sanitize_path_component(&material.title);
+ let mat_path = format!("{}/{}.{}", lesson_dir, mat_name, ext);
+
+ if tokio::fs::try_exists(&mat_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&mat_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, &material.url, &mat_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[medcel] Material download failed for '{}': {}",
+ material.title,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MedcelCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://areaaluno.medcel.com.br/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://areaaluno.medcel.com.br/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcel/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcel/mod.rs
new file mode 100644
index 00000000..db0c72a0
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/medcel/mod.rs
@@ -0,0 +1,72 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct MedcelDownloader;
+
+impl Default for MedcelDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl MedcelDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for MedcelDownloader {
+ fn name(&self) -> &str {
+ "medcel"
+ }
+
+ 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 == "medcel.com.br"
+ || host == "areaaluno.medcel.com.br"
+ || host == "service.medcel.com.br";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Medcel Course".to_string(),
+ author: String::new(),
+ platform: "medcel".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!(
+ "Use the courses interface to download Medcel courses"
+ ))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcof/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcof/api.rs
new file mode 100644
index 00000000..a425a328
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/medcof/api.rs
@@ -0,0 +1,391 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const API_BASE: &str = "https://lms-api.medcof.tech";
+
+#[derive(Clone)]
+pub struct MedcofSession {
+ pub token: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MedcofCourse {
+ pub id: String,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MedcofModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<MedcofLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MedcofLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub vimeo_id: Option<String>,
+ pub description: Option<String>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("medcof_session.json"))
+}
+
+pub async fn validate_token(session: &MedcofSession) -> anyhow::Result<bool> {
+ let url = format!("{}/auth/v1/me", API_BASE);
+ let resp = session.client.get(&url).send().await?;
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &MedcofSession) -> anyhow::Result<Vec<MedcofCourse>> {
+ let url = format!("{}/auth/v1/me", API_BASE);
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let products = body
+ .get("products")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut courses = Vec::new();
+
+ for item in &products {
+ let is_active = item
+ .get("isActive")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ if !is_active {
+ continue;
+ }
+
+ let id = item
+ .get("identifier")
+ .or_else(|| item.get("id"))
+ .map(|v| match v {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let name = item
+ .get("name")
+ .or_else(|| item.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if !id.is_empty() {
+ courses.push(MedcofCourse { id, name });
+ }
+ }
+
+ Ok(courses)
+}
+
+pub async fn switch_product(session: &MedcofSession, product_id: &str) -> anyhow::Result<()> {
+ let url = format!("{}/user/use/product", API_BASE);
+ let payload = serde_json::json!({
+ "productId": product_id,
+ });
+
+ let resp = session.client.patch(&url).json(&payload).send().await?;
+
+ if !resp.status().is_success() {
+ let body_text = resp.text().await?;
+ return Err(anyhow!(
+ "switch_product failed: {}",
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ Ok(())
+}
+
+pub async fn get_course_content(session: &MedcofSession, product_id: &str) -> anyhow::Result<Vec<MedcofModule>> {
+ switch_product(session, product_id).await?;
+
+ let url = format!("{}/product/user/progress", API_BASE);
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let blocks = body
+ .get("blocks")
+ .or_else(|| body.get("data"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_else(|| {
+ if body.is_array() {
+ body.as_array().cloned().unwrap_or_default()
+ } else {
+ Vec::new()
+ }
+ });
+
+ let mut modules = Vec::new();
+
+ for (bi, block) in blocks.iter().enumerate() {
+ let block_number = block
+ .get("blockNumber")
+ .or_else(|| block.get("number"))
+ .or_else(|| block.get("id"))
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", bi + 1),
+ })
+ .unwrap_or_else(|| format!("{}", bi + 1));
+
+ let block_name = block
+ .get("name")
+ .or_else(|| block.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or(&block_number)
+ .to_string();
+
+ let aqfm_url = format!("{}/aqfm/by-block-number/{}", API_BASE, block_number);
+ let aqfm_resp = match session.client.get(&aqfm_url).send().await {
+ Ok(r) => r,
+ Err(e) => {
+ tracing::error!("[medcof] Failed to fetch block {}: {}", block_number, e);
+ continue;
+ }
+ };
+
+ if !aqfm_resp.status().is_success() {
+ continue;
+ }
+
+ let aqfm_text = aqfm_resp.text().await?;
+ let aqfm_body: serde_json::Value = match serde_json::from_str(&aqfm_text) {
+ Ok(v) => v,
+ Err(_) => continue,
+ };
+
+ let specialties = aqfm_body
+ .get("specialties")
+ .or_else(|| aqfm_body.get("data"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_else(|| {
+ if aqfm_body.is_array() {
+ aqfm_body.as_array().cloned().unwrap_or_default()
+ } else {
+ Vec::new()
+ }
+ });
+
+ let mut lessons = Vec::new();
+ let mut lesson_order = 0i64;
+
+ for specialty in &specialties {
+ let aqfms = specialty
+ .get("aqfms")
+ .or_else(|| specialty.get("items"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for aqfm in &aqfms {
+ let videos = aqfm
+ .get("videos")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for video in &videos {
+ lesson_order += 1;
+
+ let vid_id = video
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => format!("{}", lesson_order),
+ })
+ .unwrap_or_else(|| format!("{}", lesson_order));
+
+ let vid_name = video
+ .get("name")
+ .or_else(|| video.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let vimeo_id = video
+ .get("vimeoId")
+ .or_else(|| video.get("externalId"))
+ .map(|v| match v {
+ serde_json::Value::String(s) => s.clone(),
+ serde_json::Value::Number(n) => n.to_string(),
+ _ => String::new(),
+ })
+ .filter(|s| !s.is_empty());
+
+ let description = video
+ .get("description")
+ .or_else(|| video.get("content"))
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .map(String::from);
+
+ lessons.push(MedcofLesson {
+ id: vid_id,
+ name: vid_name,
+ order: lesson_order,
+ vimeo_id,
+ description,
+ });
+ }
+ }
+ }
+
+ if !lessons.is_empty() {
+ modules.push(MedcofModule {
+ id: block_number,
+ name: block_name,
+ order: (bi + 1) as i64,
+ lessons,
+ });
+ }
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_vimeo_playback_url(session: &MedcofSession, vimeo_id: &str) -> anyhow::Result<String> {
+ let url = format!("{}/vimeo/get/{}", API_BASE, vimeo_id);
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_vimeo_playback_url returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let playback_url = body
+ .get("playbackUrl")
+ .or_else(|| body.get("url"))
+ .or_else(|| body.get("link"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("No playback URL in vimeo response"))?
+ .to_string();
+
+ Ok(playback_url)
+}
+
+pub async fn save_session(session: &MedcofSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[medcof] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<MedcofSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[medcof] session loaded");
+
+ Ok(Some(MedcofSession {
+ token: saved.token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcof/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcof/downloader.rs
new file mode 100644
index 00000000..a5302d93
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/medcof/downloader.rs
@@ -0,0 +1,273 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, MedcofCourse, MedcofSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct MedcofDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &MedcofSession,
+ course: &MedcofCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, &course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[medcof] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &MedcofDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+
+ if let Some(ref desc) = lesson.description {
+ let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_desc_dir).await?;
+ omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "txt").await.ok();
+ }
+
+ if lesson.vimeo_id.is_none() {
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MedcofDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+
+ let vimeo_id = lesson.vimeo_id.as_ref().unwrap();
+
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[medcof] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MedcofDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ let video_url = match api::get_vimeo_playback_url(session, vimeo_id).await {
+ Ok(url) => url,
+ Err(e) => {
+ tracing::error!("[medcof] Failed to get playback URL for '{}': {}", lesson.name, e);
+ let vimeo_url = format!("https://player.vimeo.com/video/{}", vimeo_id);
+ vimeo_url
+ }
+ };
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(&video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[medcof] HLS download failed for '{}': {}, trying yt-dlp", lesson.name, e);
+ let _ = tokio::fs::remove_file(&video_path).await;
+ let vimeo_url = format!("https://player.vimeo.com/video/{}", vimeo_id);
+ match download_with_ytdlp(&vimeo_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!("[medcof] yt-dlp fallback also failed for '{}': {}", lesson.name, e2);
+ }
+ }
+ }
+ }
+ } else {
+ match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!("[medcof] yt-dlp download failed for '{}': {}", lesson.name, e);
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MedcofDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ None,
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcof/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcof/mod.rs
new file mode 100644
index 00000000..56313521
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/medcof/mod.rs
@@ -0,0 +1,69 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct MedcofDownloader;
+
+impl Default for MedcofDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl MedcofDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for MedcofDownloader {
+ fn name(&self) -> &str {
+ "medcof"
+ }
+
+ 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 == "medcof.com.br"
+ || host == "aulas-prime.medcof.com.br";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Medcof".to_string(),
+ author: String::new(),
+ platform: "medcof".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: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Medcof"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medway/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/medway/api.rs
new file mode 100644
index 00000000..a03ac0d4
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/medway/api.rs
@@ -0,0 +1,435 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const API_BASE: &str = "https://cms.medway.com.br/api/v2";
+
+#[derive(Clone)]
+pub struct MedwaySession {
+ pub token: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MedwayCourse {
+ pub id: i64,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MedwayModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<MedwayLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MedwayLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub item_type: String,
+ pub video_url: Option<String>,
+ pub document_id: Option<String>,
+ pub description: Option<String>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("medway_session.json"))
+}
+
+pub async fn validate_token(session: &MedwaySession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get(format!("{}/student_group/", API_BASE))
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &MedwaySession) -> anyhow::Result<Vec<MedwayCourse>> {
+ let mut courses = Vec::new();
+ let mut next_url: Option<String> = Some(format!("{}/student_group/", API_BASE));
+
+ while let Some(url) = next_url {
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let results = body
+ .get("results")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for item in &results {
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = item
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Curso")
+ .to_string();
+
+ courses.push(MedwayCourse { id, name });
+ }
+
+ next_url = body
+ .get("next")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_modules(session: &MedwaySession, course_id: i64) -> anyhow::Result<Vec<MedwayModule>> {
+ let subjects = fetch_subjects(session, course_id).await?;
+ let mut modules = Vec::new();
+
+ for (si, subject) in subjects.iter().enumerate() {
+ let subject_id = subject
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let subject_name = subject
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let subject_order = subject
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(si as i64 + 1);
+
+ let sub_modules = fetch_subject_modules(session, subject_id).await?;
+
+ for module in &sub_modules {
+ let module_id = module
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let module_name = module
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Module")
+ .to_string();
+
+ let module_order = module
+ .get("order")
+ .or_else(|| module.get("lesson_order"))
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let title = if module_order > 0 {
+ format!("{}. {} - {}. {}", subject_order, subject_name, module_order, module_name)
+ } else {
+ format!("{}. {} - {}", subject_order, subject_name, module_name)
+ };
+
+ let lessons = fetch_module_lessons(session, module_id).await?;
+
+ modules.push(MedwayModule {
+ id: module_id.to_string(),
+ name: title,
+ order: subject_order * 1000 + module_order,
+ lessons,
+ });
+ }
+ }
+
+ modules.sort_by_key(|m| m.order);
+
+ Ok(modules)
+}
+
+async fn fetch_subjects(session: &MedwaySession, course_id: i64) -> anyhow::Result<Vec<serde_json::Value>> {
+ let mut subjects = Vec::new();
+ let mut next_url: Option<String> = Some(format!(
+ "{}/lesson-subject/?ordering=order&studentgroup={}",
+ API_BASE, course_id
+ ));
+
+ while let Some(url) = next_url {
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "fetch_subjects returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let results = body
+ .get("results")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ subjects.extend(results);
+
+ next_url = body
+ .get("next")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+ }
+
+ Ok(subjects)
+}
+
+async fn fetch_subject_modules(session: &MedwaySession, subject_id: i64) -> anyhow::Result<Vec<serde_json::Value>> {
+ let url = format!("{}/lesson-subject/{}/modules/", API_BASE, subject_id);
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "fetch_subject_modules returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ match body {
+ serde_json::Value::Array(arr) => Ok(arr),
+ _ => Ok(vec![body]),
+ }
+}
+
+async fn fetch_module_lessons(session: &MedwaySession, module_id: i64) -> anyhow::Result<Vec<MedwayLesson>> {
+ let url = format!("{}/lesson-module/{}/", API_BASE, module_id);
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "fetch_module_lessons returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let items = body
+ .get("module_items")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (i, item) in items.iter().enumerate() {
+ let id = item
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}-{}", module_id, i),
+ })
+ .unwrap_or_else(|| format!("{}-{}", module_id, i));
+
+ let name = item
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let order = item
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(i as i64 + 1);
+
+ let item_type = item
+ .get("type")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let video_url = item
+ .get("url_lesson")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let document_id = item
+ .get("object_id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ });
+
+ let description = item
+ .get("description")
+ .or_else(|| item.get("content"))
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .map(String::from);
+
+ lessons.push(MedwayLesson {
+ id,
+ name,
+ order,
+ item_type,
+ video_url,
+ document_id,
+ description,
+ });
+ }
+
+ lessons.sort_by_key(|l| l.order);
+
+ Ok(lessons)
+}
+
+pub async fn get_document_url(session: &MedwaySession, document_id: &str) -> anyhow::Result<(String, String)> {
+ let url = format!("{}/lesson-document/{}/", API_BASE, document_id);
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_document_url returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let doc_url = body
+ .get("document")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let doc_name = body
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Document")
+ .to_string();
+
+ if doc_url.is_empty() {
+ return Err(anyhow!("No document URL found in response"));
+ }
+
+ Ok((doc_url, doc_name))
+}
+
+pub fn resolve_video_url(url: &str) -> String {
+ if url.contains("vimeo.com") && !url.contains("player.vimeo.com") {
+ let video_id = url.trim_end_matches('/').rsplit('/').next().unwrap_or("");
+ if !video_id.is_empty() {
+ return format!("https://player.vimeo.com/video/{}?autoplay=1&app_id=122963", video_id);
+ }
+ }
+ url.to_string()
+}
+
+pub async fn save_session(session: &MedwaySession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[medway] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<MedwaySession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[medway] session loaded");
+
+ Ok(Some(MedwaySession {
+ token: saved.token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medway/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/medway/downloader.rs
new file mode 100644
index 00000000..a2e2e840
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/medway/downloader.rs
@@ -0,0 +1,297 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, MedwayCourse, MedwaySession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct MedwayCourseDownloadProgress {
+ pub course_id: i64,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &MedwaySession,
+ course: &MedwayCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_modules(session, course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[medway] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &MedwayCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ if let Some(ref desc) = lesson.description {
+ let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_desc_dir).await?;
+ omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
+ }
+
+ let item_type = lesson.item_type.to_lowercase();
+
+ if item_type.contains("v\u{00ed}deoaula") || item_type.contains("video") {
+ if let Some(ref raw_url) = lesson.video_url {
+ if !raw_url.is_empty() {
+ let video_url = api::resolve_video_url(raw_url);
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[medway] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MedwayCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[medway] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, &video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[medway] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+ } else if item_type.contains("documento") {
+ if let Some(ref doc_id) = lesson.document_id {
+ if !doc_id.is_empty() {
+ match api::get_document_url(session, doc_id).await {
+ Ok((doc_url, doc_name)) => {
+ let ext = doc_url.rsplit('.').next().unwrap_or("pdf");
+ let ext = ext.split('?').next().unwrap_or(ext);
+ let safe_name = filename::sanitize_path_component(&doc_name);
+ let doc_path = format!("{}/{}. {}.{}", mod_dir, li + 1, safe_name, ext);
+
+ if tokio::fs::try_exists(&doc_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&doc_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MedwayCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, &doc_url, &doc_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[medway] Document download failed for '{}': {}",
+ doc_name,
+ e
+ );
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(
+ "[medway] Failed to get document URL for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MedwayCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://app.medway.com.br/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medway/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/medway/mod.rs
new file mode 100644
index 00000000..86a955b6
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/medway/mod.rs
@@ -0,0 +1,71 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct MedwayDownloader;
+
+impl MedwayDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+impl Default for MedwayDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for MedwayDownloader {
+ fn name(&self) -> &str {
+ "medway"
+ }
+
+ 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 == "medway.com.br"
+ || host.ends_with(".medway.com.br");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Medway Course".to_string(),
+ author: String::new(),
+ platform: "medway".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!(
+ "Use the courses interface to download Medway courses"
+ ))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/memberkit/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/memberkit/api.rs
new file mode 100644
index 00000000..2958c83e
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/memberkit/api.rs
@@ -0,0 +1,555 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct MemberkitSession {
+ pub cookies: String,
+ pub site_url: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub cookies: String,
+ pub site_url: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MemberkitCourse {
+ pub id: String,
+ pub name: String,
+ pub slug: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MemberkitModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<MemberkitLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MemberkitLesson {
+ pub id: String,
+ pub name: String,
+ pub url: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MemberkitLessonDetail {
+ pub id: String,
+ pub name: String,
+ pub video_url: Option<String>,
+ pub attachments: Vec<MemberkitAttachment>,
+ pub description: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MemberkitAttachment {
+ pub name: String,
+ pub url: String,
+}
+
+fn build_client(cookies: &str, site_url: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Cookie",
+ HeaderValue::from_str(&format!("_memberkit_session={}", cookies))?,
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_str(&format!("{}/", site_url))?,
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("memberkit_session.json"))
+}
+
+pub async fn authenticate(
+ email: &str,
+ password: &str,
+ site_url: &str,
+) -> anyhow::Result<MemberkitSession> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .cookie_store(true)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let login_page_url = format!("{}/users/sign_in", site_url.trim_end_matches('/'));
+ let resp = temp_client.get(&login_page_url).send().await?;
+ let login_html = resp.text().await?;
+
+ let csrf_token = extract_meta_csrf(&login_html)
+ .or_else(|| extract_input_value(&login_html, "authenticity_token"))
+ .ok_or_else(|| anyhow!("Could not find CSRF token on login page"))?;
+
+ let form_url = format!("{}/users/sign_in", site_url.trim_end_matches('/'));
+ let resp = temp_client
+ .post(&form_url)
+ .form(&[
+ ("authenticity_token", csrf_token.as_str()),
+ ("user[email]", email),
+ ("user[password]", password),
+ ])
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let resp_url = resp.url().to_string();
+ let _body = resp.text().await?;
+
+ if resp_url.contains("/sign_in") {
+ if !status.is_success() && !status.is_redirection() {
+ return Err(anyhow!("Authentication failed (status {})", status));
+ }
+ return Err(anyhow!("Authentication failed - invalid credentials"));
+ }
+
+ let root_resp = temp_client
+ .get(site_url.trim_end_matches('/'))
+ .send()
+ .await?;
+
+ if !root_resp.status().is_success() {
+ return Err(anyhow!("Authentication failed - cannot access member area"));
+ }
+
+ let cookies_header = root_resp
+ .headers()
+ .get_all("set-cookie")
+ .iter()
+ .filter_map(|v| v.to_str().ok())
+ .filter_map(|s| {
+ if s.contains("_memberkit_session=") {
+ let start = s.find("_memberkit_session=")? + 19;
+ let end = s[start..].find(';').map(|e| e + start).unwrap_or(s.len());
+ Some(s[start..end].to_string())
+ } else {
+ None
+ }
+ })
+ .last();
+
+ let session_cookie = cookies_header
+ .ok_or_else(|| anyhow!("Could not extract session cookie after login"))?;
+
+ let client = build_client(&session_cookie, site_url)?;
+
+ Ok(MemberkitSession {
+ cookies: session_cookie,
+ site_url: site_url.trim_end_matches('/').to_string(),
+ client,
+ })
+}
+
+pub async fn validate_token(session: &MemberkitSession) -> anyhow::Result<bool> {
+ let resp = session.client.get(&session.site_url).send().await?;
+
+ let url = resp.url().to_string();
+ if url.contains("/sign_in") || url.contains("/login") {
+ return Ok(false);
+ }
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &MemberkitSession) -> anyhow::Result<Vec<MemberkitCourse>> {
+ let resp = session.client.get(&session.site_url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let mut courses = Vec::new();
+
+ let card_re = regex::Regex::new(
+ r#"(?s)data-id="(\d+)"[^>]*>.*?<a[^>]+class="[^"]*text-base[^"]*"[^>]+href="([^"]+)"[^>]*>([^<]+)"#
+ )?;
+
+ for cap in card_re.captures_iter(&body_text) {
+ let id = cap[1].to_string();
+ let href = cap[2].to_string();
+ let name = cap[3].trim().to_string();
+
+ let slug = href
+ .rsplit('/')
+ .next()
+ .unwrap_or("")
+ .to_string();
+
+ if courses.iter().any(|c: &MemberkitCourse| c.id == id) {
+ continue;
+ }
+
+ courses.push(MemberkitCourse { id, name, slug });
+ }
+
+ if courses.is_empty() {
+ let link_re = regex::Regex::new(
+ r#"<a[^>]+href="([^"]*(/courses?/[^"]+))"[^>]*>([^<]+)"#
+ )?;
+
+ for cap in link_re.captures_iter(&body_text) {
+ let href = cap[1].to_string();
+ let name = cap[3].trim().to_string();
+
+ let slug = href
+ .rsplit('/')
+ .next()
+ .unwrap_or("")
+ .to_string();
+
+ let id = slug.clone();
+
+ if courses.iter().any(|c: &MemberkitCourse| c.slug == slug) {
+ continue;
+ }
+
+ courses.push(MemberkitCourse { id, name, slug });
+ }
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_modules(
+ session: &MemberkitSession,
+ course_slug: &str,
+) -> anyhow::Result<Vec<MemberkitModule>> {
+ let url = format!("{}/courses/{}", session.site_url, course_slug);
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_modules returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let mut modules = Vec::new();
+
+ let section_re = regex::Regex::new(
+ r#"(?s)<div[^>]+id="([^"]+)"[^>]*class="[^"]*section[^"]*"[^>]*>.*?<span[^>]*>([^<]+)</span>"#
+ )?;
+
+ let lesson_re = regex::Regex::new(
+ r#"(?s)<li[^>]+data-id="(\d+)"[^>]*>.*?<a[^>]+class="[^"]*lesson__title[^"]*"[^>]+href="([^"]+)"[^>]*>([^<]+)"#
+ )?;
+
+ let sections: Vec<(String, String, usize)> = section_re
+ .captures_iter(&body_text)
+ .enumerate()
+ .map(|(i, cap)| (cap[1].to_string(), cap[2].trim().to_string(), i))
+ .collect();
+
+ if sections.is_empty() {
+ let mut lessons = Vec::new();
+ for (i, cap) in lesson_re.captures_iter(&body_text).enumerate() {
+ let lesson_id = cap[1].to_string();
+ let lesson_url = cap[2].to_string();
+ let lesson_name = cap[3].trim().to_string();
+
+ if lessons.iter().any(|l: &MemberkitLesson| l.id == lesson_id) {
+ continue;
+ }
+
+ let full_url = if lesson_url.starts_with("http") {
+ lesson_url
+ } else {
+ format!("{}{}", session.site_url, lesson_url)
+ };
+
+ lessons.push(MemberkitLesson {
+ id: lesson_id,
+ name: lesson_name,
+ url: full_url,
+ order: i as i64,
+ });
+ }
+
+ if !lessons.is_empty() {
+ modules.push(MemberkitModule {
+ id: "0".to_string(),
+ name: "Content".to_string(),
+ order: 0,
+ lessons,
+ });
+ }
+ } else {
+ for (section_id, section_name, idx) in &sections {
+ let section_start = body_text
+ .find(&format!("id=\"{}\"", section_id))
+ .unwrap_or(0);
+
+ let section_end = if idx + 1 < sections.len() {
+ body_text
+ .find(&format!("id=\"{}\"", sections[idx + 1].0))
+ .unwrap_or(body_text.len())
+ } else {
+ body_text.len()
+ };
+
+ let section_html = &body_text[section_start..section_end];
+
+ let mut lessons = Vec::new();
+ for (i, cap) in lesson_re.captures_iter(section_html).enumerate() {
+ let lesson_id = cap[1].to_string();
+ let lesson_url = cap[2].to_string();
+ let lesson_name = cap[3].trim().to_string();
+
+ if lessons.iter().any(|l: &MemberkitLesson| l.id == lesson_id) {
+ continue;
+ }
+
+ let full_url = if lesson_url.starts_with("http") {
+ lesson_url
+ } else {
+ format!("{}{}", session.site_url, lesson_url)
+ };
+
+ lessons.push(MemberkitLesson {
+ id: lesson_id,
+ name: lesson_name,
+ url: full_url,
+ order: i as i64,
+ });
+ }
+
+ modules.push(MemberkitModule {
+ id: section_id.clone(),
+ name: section_name.clone(),
+ order: *idx as i64,
+ lessons,
+ });
+ }
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_lesson_detail(
+ session: &MemberkitSession,
+ lesson_url: &str,
+) -> anyhow::Result<MemberkitLessonDetail> {
+ let resp = session.client.get(lesson_url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lesson_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let title_re = regex::Regex::new(r#"<title>([^<]+)</title>"#)?;
+ let name = title_re
+ .captures(&body_text)
+ .map(|c| c[1].trim().to_string())
+ .unwrap_or_default();
+
+ let id = lesson_url
+ .rsplit('/')
+ .next()
+ .unwrap_or("")
+ .to_string();
+
+ let mut video_url: Option<String> = None;
+
+ let yt_re = regex::Regex::new(r#"data-youtube-uid-value="([^"]+)""#)?;
+ if let Some(cap) = yt_re.captures(&body_text) {
+ video_url = Some(format!("https://www.youtube.com/watch?v={}", &cap[1]));
+ }
+
+ if video_url.is_none() {
+ let vimeo_re = regex::Regex::new(r#"data-vimeo-uid-value="([^"]+)""#)?;
+ if let Some(cap) = vimeo_re.captures(&body_text) {
+ video_url = Some(format!("https://vimeo.com/{}", &cap[1]));
+ }
+ }
+
+ if video_url.is_none() {
+ let panda_re = regex::Regex::new(r#"data-panda-url-value="([^"]+)""#)?;
+ if let Some(cap) = panda_re.captures(&body_text) {
+ video_url = Some(cap[1].to_string());
+ }
+ }
+
+ if video_url.is_none() {
+ let iframe_re = regex::Regex::new(r#"<iframe[^>]+src="([^"]+)"[^>]*>"#)?;
+ for cap in iframe_re.captures_iter(&body_text) {
+ let src = &cap[1];
+ if src.contains("scaleup")
+ || src.contains("youtube")
+ || src.contains("vimeo")
+ || src.contains("pandavideo")
+ || src.contains("player")
+ {
+ video_url = Some(src.to_string());
+ break;
+ }
+ }
+ }
+
+ if video_url.is_none() {
+ let video_re = regex::Regex::new(r#"<video[^>]+src="([^"]+)""#)?;
+ if let Some(cap) = video_re.captures(&body_text) {
+ video_url = Some(cap[1].to_string());
+ }
+ }
+
+ let mut attachments = Vec::new();
+
+ let dl_re = regex::Regex::new(
+ r#"<a[^>]+href="([^"]*downloads/[^"]+)"[^>]*>([^<]+)"#
+ )?;
+
+ for cap in dl_re.captures_iter(&body_text) {
+ let att_url = cap[1].to_string();
+ let att_name = cap[2].trim().to_string();
+
+ let full_url = if att_url.starts_with("http") {
+ att_url
+ } else {
+ format!("{}{}", session.site_url, att_url)
+ };
+
+ attachments.push(MemberkitAttachment {
+ name: att_name,
+ url: full_url,
+ });
+ }
+
+ let mut description: Option<String> = None;
+ let body_re = regex::Regex::new(r#"(?s)class="[^"]*content__body[^"]*"[^>]*>(.*?)</div>"#)?;
+ if let Some(cap) = body_re.captures(&body_text) {
+ let text = cap[1].trim();
+ if !text.is_empty() {
+ description = Some(text.to_string());
+ }
+ }
+ if description.is_none() {
+ let lesson_re = regex::Regex::new(r#"(?s)class="[^"]*lesson__content[^"]*"[^>]*>(.*?)</div>"#)?;
+ if let Some(cap) = lesson_re.captures(&body_text) {
+ let text = cap[1].trim();
+ if !text.is_empty() {
+ description = Some(text.to_string());
+ }
+ }
+ }
+
+ Ok(MemberkitLessonDetail {
+ id,
+ name,
+ video_url,
+ attachments,
+ description,
+ })
+}
+
+fn extract_meta_csrf(html: &str) -> Option<String> {
+ let re = regex::Regex::new(r#"<meta\s+name="csrf-token"\s+content="([^"]+)""#).ok()?;
+ re.captures(html).map(|c| c[1].to_string())
+}
+
+fn extract_input_value(html: &str, name: &str) -> Option<String> {
+ let pattern = format!(r#"name="{}"\s+value="([^"]*)""#, regex::escape(name));
+ let re = regex::Regex::new(&pattern).ok()?;
+ if let Some(cap) = re.captures(html) {
+ return Some(cap[1].to_string());
+ }
+
+ let pattern2 = format!(r#"value="([^"]*)"\s+name="{}""#, regex::escape(name));
+ let re2 = regex::Regex::new(&pattern2).ok()?;
+ if let Some(cap) = re2.captures(html) {
+ return Some(cap[1].to_string());
+ }
+
+ None
+}
+
+pub async fn save_session(session: &MemberkitSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ cookies: session.cookies.clone(),
+ site_url: session.site_url.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[memberkit] session saved for {}", session.site_url);
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<MemberkitSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.cookies, &saved.site_url)?;
+
+ tracing::info!("[memberkit] session loaded for {}", saved.site_url);
+
+ Ok(Some(MemberkitSession {
+ cookies: saved.cookies,
+ site_url: saved.site_url,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/memberkit/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/memberkit/downloader.rs
new file mode 100644
index 00000000..c1f8ea2b
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/memberkit/downloader.rs
@@ -0,0 +1,292 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, MemberkitCourse, MemberkitSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct MemberkitCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &MemberkitSession,
+ course: &MemberkitCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_modules(session, &course.slug).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[memberkit] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &MemberkitCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ let detail = match api::get_lesson_detail(session, &lesson.url).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[memberkit] Failed to get lesson detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MemberkitCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if let Some(ref desc) = detail.description {
+ omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
+ }
+
+ if let Some(ref video_url) = detail.video_url {
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ lesson_dir,
+ li + 1,
+ lesson_name,
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[memberkit] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MemberkitCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[memberkit] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[memberkit] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+
+ for attachment in &detail.attachments {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let att_name = filename::sanitize_path_component(&attachment.name);
+ let att_path = format!("{}/{}", lesson_dir, att_name);
+
+ if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&att_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, &attachment.url, &att_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[memberkit] Attachment download failed for '{}': {}",
+ attachment.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &MemberkitCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ None,
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/memberkit/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/memberkit/mod.rs
new file mode 100644
index 00000000..9c1cdc15
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/memberkit/mod.rs
@@ -0,0 +1,68 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct MemberkitDownloader;
+
+impl Default for MemberkitDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl MemberkitDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for MemberkitDownloader {
+ fn name(&self) -> &str {
+ "memberkit"
+ }
+
+ 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 == "memberkit.com.br" || host.ends_with(".memberkit.com.br");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Memberkit".to_string(),
+ author: String::new(),
+ platform: "memberkit".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: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Memberkit"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/api.rs
new file mode 100644
index 00000000..084f47f1
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/api.rs
@@ -0,0 +1,361 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct PluralsightSession {
+ pub cookies: String,
+ pub xsrf_token: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub cookies: String,
+ pub xsrf_token: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PluralsightCourse {
+ pub id: String,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PluralsightModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<PluralsightLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PluralsightLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub clip_id: String,
+ pub version_id: String,
+}
+
+fn extract_xsrf_token(cookies: &str) -> Option<String> {
+ for part in cookies.split(';') {
+ let trimmed = part.trim();
+ if let Some(val) = trimmed.strip_prefix("XSRF-TOKEN=") {
+ let decoded = urlencoding::decode(val.trim()).ok()?;
+ return Some(decoded.to_string());
+ }
+ }
+ None
+}
+
+fn build_client(cookies: &str, xsrf_token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert("Cookie", HeaderValue::from_str(cookies)?);
+ headers.insert("x-xsrf-token", HeaderValue::from_str(xsrf_token)?);
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("pluralsight_session.json"))
+}
+
+pub fn authenticate_cookies(cookies: &str) -> anyhow::Result<PluralsightSession> {
+ let xsrf_token = extract_xsrf_token(cookies)
+ .ok_or_else(|| anyhow!("XSRF-TOKEN not found in cookies. Make sure to include the full Cookie header from browser DevTools."))?;
+
+ let client = build_client(cookies, &xsrf_token)?;
+
+ Ok(PluralsightSession {
+ cookies: cookies.to_string(),
+ xsrf_token,
+ client,
+ })
+}
+
+pub async fn validate_token(session: &PluralsightSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://app.pluralsight.com/learner/user/user-content-history?dataSource=v2&limit=1")
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &PluralsightSession) -> anyhow::Result<Vec<PluralsightCourse>> {
+ let resp = session
+ .client
+ .get("https://app.pluralsight.com/learner/user/user-content-history?dataSource=v2&limit=300")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let mut courses = Vec::new();
+
+ let items = body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .or_else(|| body.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for item in &items {
+ let id = item
+ .get("contentId")
+ .or_else(|| item.get("id"))
+ .or_else(|| item.get("courseId"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .or_else(|| item.get("contentTitle"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if !id.is_empty() && !name.is_empty() {
+ if !courses.iter().any(|c: &PluralsightCourse| c.id == id) {
+ courses.push(PluralsightCourse { id, name });
+ }
+ }
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_course_content(
+ session: &PluralsightSession,
+ course_id: &str,
+) -> anyhow::Result<Vec<PluralsightModule>> {
+ let url = format!(
+ "https://app.pluralsight.com/course-player/api/v1/table-of-contents/course/{}",
+ course_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let modules_arr = body
+ .get("modules")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for (mi, module_val) in modules_arr.iter().enumerate() {
+ let module_id = module_val
+ .get("id")
+ .or_else(|| module_val.get("moduleId"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let module_name = module_val
+ .get("title")
+ .or_else(|| module_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let clips = module_val
+ .get("contentItems")
+ .or_else(|| module_val.get("clips"))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (ci, clip_val) in clips.iter().enumerate() {
+ let clip_id = clip_val
+ .get("id")
+ .or_else(|| clip_val.get("clipId"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let clip_name = clip_val
+ .get("title")
+ .or_else(|| clip_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let version_id = clip_val
+ .get("version")
+ .or_else(|| clip_val.get("versionId"))
+ .and_then(|v| match v {
+ serde_json::Value::Number(n) => Some(n.to_string()),
+ serde_json::Value::String(s) => Some(s.clone()),
+ _ => None,
+ })
+ .unwrap_or_else(|| "1".to_string());
+
+ if !clip_id.is_empty() {
+ lessons.push(PluralsightLesson {
+ id: format!("{}-{}", module_id, ci),
+ name: clip_name,
+ order: ci as i64,
+ clip_id,
+ version_id,
+ });
+ }
+ }
+
+ modules.push(PluralsightModule {
+ id: if module_id.is_empty() {
+ format!("{}", mi)
+ } else {
+ module_id
+ },
+ name: module_name,
+ order: mi as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_clip_url(
+ session: &PluralsightSession,
+ clip_id: &str,
+ version_id: &str,
+) -> anyhow::Result<String> {
+ let url = format!(
+ "https://app.pluralsight.com/video/delivery/api/v1/clips/{}/versions/{}",
+ clip_id, version_id
+ );
+
+ let resp = session
+ .client
+ .post(&url)
+ .header("x-team", "video-services")
+ .json(&serde_json::json!({
+ "online": true,
+ "boundedContext": "course",
+ "preferredAudioLanguage": "en"
+ }))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_clip_url returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let m3u8_url = body
+ .get("urls")
+ .and_then(|u| u.as_array())
+ .and_then(|arr| arr.first())
+ .and_then(|v| v.get("url").or_else(|| v.get("src")))
+ .and_then(|v| v.as_str())
+ .or_else(|| body.get("url").and_then(|v| v.as_str()))
+ .ok_or_else(|| anyhow!("No video URL found in clip response"))?
+ .to_string();
+
+ Ok(m3u8_url)
+}
+
+pub async fn save_session(session: &PluralsightSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ cookies: session.cookies.clone(),
+ xsrf_token: session.xsrf_token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[pluralsight] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<PluralsightSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.cookies, &saved.xsrf_token)?;
+
+ tracing::info!("[pluralsight] session loaded");
+
+ Ok(Some(PluralsightSession {
+ cookies: saved.cookies,
+ xsrf_token: saved.xsrf_token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/downloader.rs
new file mode 100644
index 00000000..0e4995be
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/downloader.rs
@@ -0,0 +1,276 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, PluralsightCourse, PluralsightSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct PluralsightCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &PluralsightSession,
+ course: &PluralsightCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, &course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[pluralsight] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &PluralsightCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ mod_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[pluralsight] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &PluralsightCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ match api::get_clip_url(session, &lesson.clip_id, &lesson.version_id).await {
+ Ok(clip_url) => {
+ if clip_url.contains(".m3u8") {
+ match download_hls_video(&clip_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[pluralsight] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(&clip_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[pluralsight] yt-dlp failed for '{}': {}, trying direct",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, &clip_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[pluralsight] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(
+ "[pluralsight] Failed to get clip URL for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &PluralsightCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://app.pluralsight.com/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://app.pluralsight.com/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/mod.rs
new file mode 100644
index 00000000..98f4b2c1
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/mod.rs
@@ -0,0 +1,68 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct PluralsightDownloader;
+
+impl Default for PluralsightDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl PluralsightDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for PluralsightDownloader {
+ fn name(&self) -> &str {
+ "pluralsight"
+ }
+
+ 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 == "pluralsight.com" || host == "app.pluralsight.com";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Pluralsight Course".to_string(),
+ author: String::new(),
+ platform: "pluralsight".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Pluralsight courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/api.rs
new file mode 100644
index 00000000..c6f31cd6
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/api.rs
@@ -0,0 +1,475 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+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 BASE_URL: &str = "https://app.rocketseat.com.br";
+const API_URL: &str = "https://skylab-api.rocketseat.com.br";
+const BUNNY_LIBRARY_ID: &str = "212524";
+
+#[derive(Clone)]
+pub struct RocketseatSession {
+ pub token: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RocketseatCourse {
+ pub id: String,
+ pub name: String,
+ pub slug: String,
+ pub description: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RocketseatModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<RocketseatLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RocketseatLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub slug: String,
+ pub lesson_type: String,
+ pub video_id: Option<String>,
+ pub duration: Option<i64>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static(BASE_URL),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://app.rocketseat.com.br/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("rocketseat_session.json"))
+}
+
+pub fn create_session(token: &str) -> anyhow::Result<RocketseatSession> {
+ let client = build_client(token)?;
+ Ok(RocketseatSession {
+ token: token.to_string(),
+ client,
+ })
+}
+
+pub async fn validate_token(session: &RocketseatSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get(&format!("{}/v2/search/multi-search", API_URL))
+ .query(&[("query", "test"), ("page", "1")])
+ .header("Host", "skylab-api.rocketseat.com.br")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ tracing::info!("[rocketseat] validate_token status={}", status);
+
+ Ok(status.is_success())
+}
+
+pub async fn search_courses(
+ session: &RocketseatSession,
+ query: &str,
+) -> anyhow::Result<Vec<RocketseatCourse>> {
+ let mut all_courses = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!("{}/v2/search/multi-search", API_URL);
+ let resp = session
+ .client
+ .get(&url)
+ .query(&[("query", query), ("page", &page.to_string())])
+ .header("Host", "skylab-api.rocketseat.com.br")
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ if all_courses.is_empty() {
+ return Err(anyhow!(
+ "search_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+ break;
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let journeys = body
+ .get("journeys")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ if journeys.is_empty() {
+ break;
+ }
+
+ let mut new_count = 0;
+ for item in &journeys {
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if id.is_empty() || seen.contains(&id) {
+ continue;
+ }
+ seen.insert(id.clone());
+ new_count += 1;
+
+ let name = item
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let slug = item
+ .get("slug")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let description = item
+ .get("description")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ all_courses.push(RocketseatCourse {
+ id,
+ name,
+ slug,
+ description,
+ });
+ }
+
+ if new_count == 0 {
+ break;
+ }
+
+ let has_more = body
+ .pointer("/meta/journeys/hasMore")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ if !has_more || page > 50 {
+ break;
+ }
+
+ page += 1;
+ }
+
+ Ok(all_courses)
+}
+
+pub async fn list_courses(
+ session: &RocketseatSession,
+) -> anyhow::Result<Vec<RocketseatCourse>> {
+ search_courses(session, "rocketseat").await
+}
+
+fn parse_rsc_response(text: &str) -> serde_json::Value {
+ for line in text.lines() {
+ if line.is_empty() {
+ continue;
+ }
+ let parts: Vec<&str> = line.splitn(2, ':').collect();
+ if parts.len() < 2 {
+ continue;
+ }
+
+ if let Ok(data) = serde_json::from_str::<serde_json::Value>(parts[1]) {
+ if let Some(arr) = data.as_array() {
+ if arr.len() > 3 {
+ if let Some(payload) = arr.get(3).and_then(|v| v.as_object()) {
+ let payload_val = serde_json::Value::Object(payload.clone());
+ if payload_val.get("journeyContents").is_some()
+ || payload_val.get("lessonGroups").is_some()
+ {
+ return payload_val;
+ }
+ if let Some(inner) = payload_val.get("data").and_then(|v| v.as_object()) {
+ let inner_val = serde_json::Value::Object(inner.clone());
+ if inner_val.get("journeyContents").is_some()
+ || inner_val.get("lessonGroups").is_some()
+ {
+ return inner_val;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ serde_json::Value::Object(serde_json::Map::new())
+}
+
+pub async fn get_course_content(
+ session: &RocketseatSession,
+ course: &RocketseatCourse,
+) -> anyhow::Result<Vec<RocketseatModule>> {
+ let url = format!("{}/jornada/{}/conteudos", BASE_URL, course.slug);
+
+ let resp = session
+ .client
+ .get(&url)
+ .query(&[("_rsc", "1")])
+ .header("RSC", "1")
+ .header("Accept", "*/*")
+ .header("Host", "app.rocketseat.com.br")
+ .send()
+ .await?;
+
+ if !resp.status().is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}",
+ resp.status()
+ ));
+ }
+
+ let text = resp.text().await?;
+ let data = parse_rsc_response(&text);
+
+ let nodes = data
+ .pointer("/journeyContents/nodes")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+ let mut module_idx = 0i64;
+
+ for node in &nodes {
+ let sub_contents = node
+ .get("contents")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_else(|| vec![node.clone()]);
+
+ for sub in &sub_contents {
+ let module_slug = sub
+ .get("slug")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if module_slug.is_empty() {
+ continue;
+ }
+
+ let module_title = sub
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or(module_slug)
+ .to_string();
+
+ let lessons = fetch_module_lessons(session, &course.slug, module_slug).await?;
+
+ if !lessons.is_empty() {
+ module_idx += 1;
+ modules.push(RocketseatModule {
+ id: sub
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or(module_slug)
+ .to_string(),
+ name: module_title,
+ order: module_idx,
+ lessons,
+ });
+ }
+ }
+ }
+
+ Ok(modules)
+}
+
+async fn fetch_module_lessons(
+ session: &RocketseatSession,
+ journey_slug: &str,
+ module_slug: &str,
+) -> anyhow::Result<Vec<RocketseatLesson>> {
+ let url = format!("{}/jornada/{}/sala/{}", BASE_URL, journey_slug, module_slug);
+
+ let resp = session
+ .client
+ .get(&url)
+ .query(&[("_rsc", "1")])
+ .header("RSC", "1")
+ .header("Accept", "*/*")
+ .header("Host", "app.rocketseat.com.br")
+ .send()
+ .await?;
+
+ if !resp.status().is_success() {
+ return Ok(Vec::new());
+ }
+
+ let text = resp.text().await?;
+ let data = parse_rsc_response(&text);
+
+ let lesson_groups = data
+ .get("lessonGroups")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+ let mut order = 0i64;
+
+ for group in &lesson_groups {
+ let group_lessons = group
+ .get("lessons")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for lesson in &group_lessons {
+ order += 1;
+
+ let id = lesson
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let title = lesson
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let slug = lesson
+ .get("slug")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_type = lesson
+ .get("type")
+ .and_then(|v| v.as_str())
+ .unwrap_or("VIDEO")
+ .to_string();
+
+ let video_id = lesson
+ .get("video")
+ .and_then(|v| v.get("jupiterVideoId"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let duration = lesson
+ .get("duration")
+ .and_then(|v| v.as_i64());
+
+ lessons.push(RocketseatLesson {
+ id,
+ name: title,
+ order,
+ slug,
+ lesson_type,
+ video_id,
+ duration,
+ });
+ }
+ }
+
+ Ok(lessons)
+}
+
+pub fn get_video_embed_url(video_id: &str) -> String {
+ format!(
+ "https://iframe.mediadelivery.net/embed/{}/{}",
+ BUNNY_LIBRARY_ID, video_id
+ )
+}
+
+pub async fn save_session(session: &RocketseatSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[rocketseat] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<RocketseatSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[rocketseat] session loaded");
+
+ Ok(Some(RocketseatSession {
+ token: saved.token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/downloader.rs
new file mode 100644
index 00000000..5997506f
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/downloader.rs
@@ -0,0 +1,196 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, RocketseatCourse, RocketseatSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct RocketseatCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &RocketseatSession,
+ course: &RocketseatCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, course).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[rocketseat] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &RocketseatCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let safe_name = format!("{}. {}", li + 1, lesson_name);
+
+ if let Some(ref vid_id) = lesson.video_id {
+ let video_path = format!("{}/{}.mp4", mod_dir, safe_name);
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[rocketseat] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &RocketseatCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ let embed_url = api::get_video_embed_url(vid_id);
+
+ match download_with_ytdlp(&embed_url, &mod_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[rocketseat] yt-dlp download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &RocketseatCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://app.rocketseat.com.br/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/mod.rs
new file mode 100644
index 00000000..aed53331
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/mod.rs
@@ -0,0 +1,69 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct RocketseatDownloader;
+
+impl Default for RocketseatDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl RocketseatDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for RocketseatDownloader {
+ fn name(&self) -> &str {
+ "rocketseat"
+ }
+
+ 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 == "rocketseat.com.br"
+ || host == "app.rocketseat.com.br";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Rocketseat".to_string(),
+ author: String::new(),
+ platform: "rocketseat".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: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Rocketseat"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/skool/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/skool/api.rs
new file mode 100644
index 00000000..d035a280
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/skool/api.rs
@@ -0,0 +1,540 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct SkoolSession {
+ pub cookie_token: String,
+ pub build_id: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub cookie_token: String,
+ pub build_id: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SkoolGroup {
+ pub id: String,
+ pub slug: String,
+ pub name: String,
+ pub image_url: Option<String>,
+ pub num_courses: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SkoolModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<SkoolLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SkoolLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SkoolLessonDetail {
+ pub id: String,
+ pub name: String,
+ pub description: Option<String>,
+ pub video_url: Option<String>,
+ pub files: Vec<SkoolFile>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SkoolFile {
+ pub id: String,
+ pub name: String,
+ pub url: Option<String>,
+}
+
+fn build_client(cookie_token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Cookie",
+ HeaderValue::from_str(&format!("skooltok={}", cookie_token))?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://www.skool.com/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("skool_session.json"))
+}
+
+async fn fetch_build_id(client: &reqwest::Client) -> anyhow::Result<String> {
+ let resp = client
+ .get("https://www.skool.com")
+ .send()
+ .await?;
+
+ let html = resp.text().await?;
+
+ let re = regex::Regex::new(r#""buildId"\s*:\s*"([^"]+)""#)?;
+ let build_id = re
+ .captures(&html)
+ .and_then(|c| c.get(1))
+ .map(|m| m.as_str().to_string())
+ .ok_or_else(|| anyhow!("Could not extract buildId from Skool HTML"))?;
+
+ Ok(build_id)
+}
+
+pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<SkoolSession> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .cookie_store(true)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "email": email,
+ "password": password,
+ });
+
+ let resp = temp_client
+ .post("https://api2.skool.com/auth/login")
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+
+ let mut cookie_token = String::new();
+ for cookie in resp.cookies() {
+ if cookie.name() == "skooltok" {
+ cookie_token = cookie.value().to_string();
+ }
+ }
+
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Authentication failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ if cookie_token.is_empty() {
+ let body: serde_json::Value = serde_json::from_str(&body_text).unwrap_or_default();
+ cookie_token = body
+ .get("token")
+ .or_else(|| body.get("skooltok"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ }
+
+ if cookie_token.is_empty() {
+ return Err(anyhow!("No skooltok cookie or token in login response"));
+ }
+
+ let client = build_client(&cookie_token)?;
+ let build_id = fetch_build_id(&client).await?;
+
+ Ok(SkoolSession {
+ cookie_token,
+ build_id,
+ client,
+ })
+}
+
+pub async fn validate_token(session: &SkoolSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://api2.skool.com/self/groups?limit=1&prefs=false")
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_groups(session: &SkoolSession) -> anyhow::Result<Vec<SkoolGroup>> {
+ let mut all_groups = Vec::new();
+
+ let url = "https://api2.skool.com/self/groups?limit=50&prefs=false";
+
+ let resp = session.client.get(url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_groups returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let groups_arr = body
+ .get("groups")
+ .or_else(|| body.as_array().map(|_| &body))
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ for item in &groups_arr {
+ let metadata = item.get("metadata").unwrap_or(item);
+
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let slug = item
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let name = metadata
+ .get("display_name")
+ .and_then(|v| v.as_str())
+ .or_else(|| item.get("display_name").and_then(|v| v.as_str()))
+ .unwrap_or(&slug)
+ .to_string();
+
+ let image_url = metadata
+ .get("cover_small_url")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let num_courses = metadata
+ .get("num_courses")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ all_groups.push(SkoolGroup {
+ id,
+ slug,
+ name,
+ image_url,
+ num_courses,
+ });
+ }
+
+ Ok(all_groups)
+}
+
+pub async fn get_group_courses(
+ session: &SkoolSession,
+ group_slug: &str,
+) -> anyhow::Result<Vec<SkoolModule>> {
+ let url = format!(
+ "https://www.skool.com/_next/data/{}/{}/classroom.json?group={}",
+ session.build_id, group_slug, group_slug
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_group_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let courses_arr = body
+ .pointer("/pageProps/allCourses")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for (i, course) in courses_arr.iter().enumerate() {
+ let course_id = course
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let course_slug = course
+ .get("slug")
+ .or_else(|| course.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let metadata = course.get("metadata").unwrap_or(course);
+
+ let course_name = metadata
+ .get("title")
+ .or_else(|| metadata.get("display_name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or(&course_slug)
+ .to_string();
+
+ let lessons = get_course_lessons(session, group_slug, &course_slug).await.unwrap_or_default();
+
+ modules.push(SkoolModule {
+ id: if course_id.is_empty() { course_slug } else { course_id },
+ name: course_name,
+ order: i as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+async fn get_course_lessons(
+ session: &SkoolSession,
+ group_slug: &str,
+ course_slug: &str,
+) -> anyhow::Result<Vec<SkoolLesson>> {
+ let url = format!(
+ "https://www.skool.com/_next/data/{}/{}/classroom/{}.json?group={}&course={}",
+ session.build_id, group_slug, course_slug, group_slug, course_slug
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_lessons returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let children = body
+ .pointer("/pageProps/course/children")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (i, child) in children.iter().enumerate() {
+ let metadata = child.get("metadata").unwrap_or(child);
+
+ let lesson_id = child
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_name = metadata
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ lessons.push(SkoolLesson {
+ id: if lesson_id.is_empty() { format!("{}", i) } else { lesson_id },
+ name: lesson_name,
+ order: i as i64,
+ });
+ }
+
+ Ok(lessons)
+}
+
+pub async fn get_lesson_detail(
+ _session: &SkoolSession,
+ _group_slug: &str,
+ _course_slug: &str,
+ lesson_id: &str,
+ children: &[serde_json::Value],
+) -> anyhow::Result<SkoolLessonDetail> {
+ let child = children
+ .iter()
+ .find(|c| {
+ c.get("id")
+ .and_then(|v| v.as_str())
+ .map(|id| id == lesson_id)
+ .unwrap_or(false)
+ })
+ .cloned();
+
+ let metadata = child
+ .as_ref()
+ .and_then(|c| c.get("metadata"))
+ .unwrap_or(&serde_json::Value::Null);
+
+ let name = metadata
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let description = metadata
+ .get("description")
+ .or_else(|| metadata.get("content"))
+ .or_else(|| metadata.get("body"))
+ .and_then(|v| {
+ if v.is_string() {
+ v.as_str().map(String::from)
+ } else {
+ Some(serde_json::to_string_pretty(v).unwrap_or_default())
+ }
+ })
+ .filter(|s| !s.trim().is_empty());
+
+ let video_url = metadata
+ .get("videoLink")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let mut files = Vec::new();
+
+ if let Some(attachments) = metadata.get("attachments").and_then(|v| v.as_array()) {
+ for att in attachments {
+ let file_id = att
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let file_name = att
+ .get("name")
+ .or_else(|| att.get("filename"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("file")
+ .to_string();
+
+ files.push(SkoolFile {
+ id: file_id,
+ name: file_name,
+ url: None,
+ });
+ }
+ }
+
+ Ok(SkoolLessonDetail {
+ id: lesson_id.to_string(),
+ name,
+ description,
+ video_url,
+ files,
+ })
+}
+
+pub async fn get_file_download_url(
+ session: &SkoolSession,
+ file_id: &str,
+) -> anyhow::Result<String> {
+ let url = format!(
+ "https://api2.skool.com/files/{}/download-url?expire=28800",
+ file_id
+ );
+
+ let resp = session.client.post(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_file_download_url returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let download_url = body
+ .get("url")
+ .or_else(|| body.get("download_url"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("No download URL in file response"))?
+ .to_string();
+
+ Ok(download_url)
+}
+
+pub async fn save_session(session: &SkoolSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ cookie_token: session.cookie_token.clone(),
+ build_id: session.build_id.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[skool] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<SkoolSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.cookie_token)?;
+
+ tracing::info!("[skool] session loaded");
+
+ Ok(Some(SkoolSession {
+ cookie_token: saved.cookie_token,
+ build_id: saved.build_id,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/skool/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/skool/downloader.rs
new file mode 100644
index 00000000..69325cc2
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/skool/downloader.rs
@@ -0,0 +1,295 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, SkoolGroup, SkoolSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct SkoolCourseDownloadProgress {
+ pub group_id: String,
+ pub group_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &SkoolSession,
+ group: &SkoolGroup,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_group_courses(session, &group.slug).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ group.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&group.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &SkoolCourseDownloadProgress {
+ group_id: group.id.clone(),
+ group_name: group.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ let detail = match api::get_lesson_detail(session, &group.slug, &module.id, &lesson.id, &[]).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[skool] Failed to get lesson detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &SkoolCourseDownloadProgress {
+ group_id: group.id.clone(),
+ group_name: group.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if let Some(ref desc) = detail.description {
+ omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
+ }
+
+ if let Some(ref video_url) = detail.video_url {
+ let video_path = format!(
+ "{}/{}. {}.mp4",
+ lesson_dir,
+ li + 1,
+ lesson_name
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[skool] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &SkoolCourseDownloadProgress {
+ group_id: group.id.clone(),
+ group_name: group.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[skool] yt-dlp download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+
+ for file in &detail.files {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let file_name = filename::sanitize_path_component(&file.name);
+ let file_path = format!("{}/{}", lesson_dir, file_name);
+
+ if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&file_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ let download_url = if let Some(ref url) = file.url {
+ url.clone()
+ } else {
+ match api::get_file_download_url(session, &file.id).await {
+ Ok(url) => url,
+ Err(e) => {
+ tracing::error!(
+ "[skool] Failed to get download URL for file '{}': {}",
+ file.name,
+ e
+ );
+ continue;
+ }
+ }
+ };
+
+ match download_file_direct(&session.client, &download_url, &file_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[skool] File download failed for '{}': {}",
+ file.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &SkoolCourseDownloadProgress {
+ group_id: group.id.clone(),
+ group_name: group.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://www.skool.com/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/skool/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/skool/mod.rs
new file mode 100644
index 00000000..fbe03741
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/skool/mod.rs
@@ -0,0 +1,68 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct SkoolDownloader;
+
+impl Default for SkoolDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl SkoolDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for SkoolDownloader {
+ fn name(&self) -> &str {
+ "skool"
+ }
+
+ 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 == "skool.com" || host == "www.skool.com";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Skool Course".to_string(),
+ author: String::new(),
+ platform: "skool".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Skool courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/teachable/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/teachable/api.rs
new file mode 100644
index 00000000..4589dd3c
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/teachable/api.rs
@@ -0,0 +1,575 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "ktor-client";
+const CLIENT_TOKEN: &str = "9e44e885ac601aae4ee7109baec9ee0a503bfbb4fd11cbcb7d1de9d5e84f395b37d1521b08add19c2604dbe3c1d6c986bbd62a2513884e04e5b40704e77944e4";
+const BASE_URL: &str = "https://mobile-service.learning.teachable.com/api/v1";
+
+#[derive(Clone)]
+pub struct TeachableSession {
+ pub token: String,
+ pub school_id: Option<String>,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub school_id: Option<String>,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TeachableSchool {
+ pub id: String,
+ pub name: String,
+ pub image_url: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TeachableCourse {
+ pub id: String,
+ pub name: String,
+ pub image_url: Option<String>,
+ pub school_id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TeachableModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<TeachableLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TeachableLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TeachableLessonDetail {
+ pub id: String,
+ pub name: String,
+ pub video_url: Option<String>,
+ pub video_referer: Option<String>,
+ pub files: Vec<TeachableFile>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TeachableFile {
+ pub id: String,
+ pub name: String,
+ pub url: Option<String>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert(
+ "CLIENT-TOKEN",
+ HeaderValue::from_static(CLIENT_TOKEN),
+ );
+ headers.insert(
+ "X-APP-VERSION",
+ HeaderValue::from_static("2.3.0"),
+ );
+ headers.insert(
+ "X-DEVICE-OS",
+ HeaderValue::from_static("Android 35"),
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("teachable_session.json"))
+}
+
+pub async fn request_otp(email: &str) -> anyhow::Result<()> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "email": email,
+ });
+
+ let resp = temp_client
+ .post("https://sso.teachable.com/api/v2/auth/otp/request")
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+
+ if !status.is_success() {
+ let body_text = resp.text().await?;
+ return Err(anyhow!(
+ "OTP request failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ Ok(())
+}
+
+pub async fn verify_otp(email: &str, otp_code: &str) -> anyhow::Result<TeachableSession> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "email": email,
+ "otp_code": otp_code,
+ });
+
+ let resp = temp_client
+ .post("https://sso.teachable.com/api/v2/auth/otp/verify")
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "OTP verification failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let token = body
+ .get("token")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("token not found in OTP verify response"))?
+ .to_string();
+
+ let client = build_client(&token)?;
+
+ Ok(TeachableSession {
+ token,
+ school_id: None,
+ client,
+ })
+}
+
+pub async fn validate_token(session: &TeachableSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get(&format!("{}/schools", BASE_URL))
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_schools(session: &TeachableSession) -> anyhow::Result<Vec<TeachableSchool>> {
+ let resp = session
+ .client
+ .get(&format!("{}/schools", BASE_URL))
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_schools returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let schools_arr = body
+ .get("schools")
+ .and_then(|v| v.as_array())
+ .or_else(|| body.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut schools = Vec::new();
+
+ for item in &schools_arr {
+ let id = item
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let name = item
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let image_url = item
+ .get("image_url")
+ .or_else(|| item.get("logo_url"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ schools.push(TeachableSchool {
+ id,
+ name,
+ image_url,
+ });
+ }
+
+ Ok(schools)
+}
+
+pub async fn list_courses(
+ session: &TeachableSession,
+ school_id: &str,
+) -> anyhow::Result<Vec<TeachableCourse>> {
+ let url = format!("{}/schools/{}/courses", BASE_URL, school_id);
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let courses_arr = body
+ .get("courses")
+ .and_then(|v| v.as_array())
+ .or_else(|| body.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut courses = Vec::new();
+
+ for item in &courses_arr {
+ let id = item
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let name = item
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let image_url = item
+ .get("image_url")
+ .or_else(|| item.get("thumbnail_url"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ courses.push(TeachableCourse {
+ id,
+ name,
+ image_url,
+ school_id: school_id.to_string(),
+ });
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_syllabus(
+ session: &TeachableSession,
+ school_id: &str,
+ course_id: &str,
+) -> anyhow::Result<Vec<TeachableModule>> {
+ let url = format!(
+ "{}/schools/{}/courses/{}/syllabus",
+ BASE_URL, school_id, course_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_syllabus returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let sections_arr = body
+ .get("sections")
+ .and_then(|v| v.as_array())
+ .or_else(|| body.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for (i, section) in sections_arr.iter().enumerate() {
+ let section_id = section
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", i),
+ })
+ .unwrap_or_else(|| format!("{}", i));
+
+ let section_name = section
+ .get("name")
+ .or_else(|| section.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lectures_arr = section
+ .get("lectures")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for (j, lecture) in lectures_arr.iter().enumerate() {
+ let lecture_id = lecture
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => format!("{}", j),
+ })
+ .unwrap_or_else(|| format!("{}", j));
+
+ let lecture_name = lecture
+ .get("name")
+ .or_else(|| lecture.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ lessons.push(TeachableLesson {
+ id: lecture_id,
+ name: lecture_name,
+ order: j as i64,
+ });
+ }
+
+ modules.push(TeachableModule {
+ id: section_id,
+ name: section_name,
+ order: i as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_lecture_detail(
+ session: &TeachableSession,
+ school_id: &str,
+ course_id: &str,
+ lecture_id: &str,
+) -> anyhow::Result<TeachableLessonDetail> {
+ let url = format!(
+ "{}/schools/{}/courses/{}/lectures/{}",
+ BASE_URL, school_id, course_id, lecture_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lecture_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let lecture = body.get("lecture").unwrap_or(&body);
+
+ let id = lecture
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => lecture_id.to_string(),
+ })
+ .unwrap_or_else(|| lecture_id.to_string());
+
+ let name = lecture
+ .get("name")
+ .or_else(|| lecture.get("title"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let attachments = lecture
+ .get("attachments")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut video_url = None;
+ let mut video_referer = None;
+ let mut files = Vec::new();
+
+ for att in &attachments {
+ let kind = att
+ .get("kind")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ match kind {
+ "video" => {
+ let data = att.get("data").unwrap_or(att);
+ video_url = data
+ .get("url")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+ video_referer = data
+ .get("referer")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+ }
+ "pdf_embed" | "generic" => {
+ let data = att.get("data").unwrap_or(att);
+ let file_id = att
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let file_name = data
+ .get("name")
+ .or_else(|| data.get("filename"))
+ .or_else(|| att.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("file")
+ .to_string();
+
+ let file_url = data
+ .get("url")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ files.push(TeachableFile {
+ id: file_id,
+ name: file_name,
+ url: file_url,
+ });
+ }
+ _ => {}
+ }
+ }
+
+ Ok(TeachableLessonDetail {
+ id,
+ name,
+ video_url,
+ video_referer,
+ files,
+ })
+}
+
+pub async fn save_session(session: &TeachableSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ school_id: session.school_id.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[teachable] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<TeachableSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[teachable] session loaded");
+
+ Ok(Some(TeachableSession {
+ token: saved.token,
+ school_id: saved.school_id,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/teachable/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/teachable/downloader.rs
new file mode 100644
index 00000000..b56dc8be
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/teachable/downloader.rs
@@ -0,0 +1,351 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, TeachableCourse, TeachableSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct TeachableCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &TeachableSession,
+ course: &TeachableCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_syllabus(session, &course.school_id, &course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[teachable] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &TeachableCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ let detail = match api::get_lecture_detail(session, &course.school_id, &course.id, &lesson.id).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[teachable] Failed to get lecture detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &TeachableCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if let Some(ref video_url) = detail.video_url {
+ let video_ext = if video_url.contains(".m3u8") {
+ "mp4"
+ } else {
+ video_url
+ .rsplit('.')
+ .next()
+ .and_then(|e| {
+ let e = e.split('?').next().unwrap_or(e);
+ if e.len() <= 4 {
+ Some(e)
+ } else {
+ None
+ }
+ })
+ .unwrap_or("mp4")
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.{}",
+ lesson_dir,
+ li + 1,
+ lesson_name,
+ video_ext
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[teachable] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &TeachableCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if video_url.contains(".m3u8") {
+ let referer = detail.video_referer.as_deref().unwrap_or("https://teachable.com/");
+ match download_hls_video(video_url, &video_path, referer, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[teachable] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ let referer = detail.video_referer.as_deref().unwrap_or("https://teachable.com/");
+ match download_with_ytdlp(video_url, &lesson_dir, referer, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[teachable] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[teachable] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for file in &detail.files {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let file_name = filename::sanitize_path_component(&file.name);
+ let file_path = format!("{}/{}", lesson_dir, file_name);
+
+ if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&file_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ if let Some(ref url) = file.url {
+ match download_file_direct(&session.client, url, &file_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[teachable] File download failed for '{}': {}",
+ file.name,
+ e
+ );
+ }
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &TeachableCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ referer: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ referer,
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ referer: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some(referer),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/teachable/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/teachable/mod.rs
new file mode 100644
index 00000000..e4ddf56c
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/teachable/mod.rs
@@ -0,0 +1,70 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct TeachableDownloader;
+
+impl Default for TeachableDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl TeachableDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for TeachableDownloader {
+ fn name(&self) -> &str {
+ "teachable"
+ }
+
+ 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 == "teachable.com"
+ || host.ends_with(".teachable.com")
+ || host == "sso.teachable.com";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Teachable Course".to_string(),
+ author: String::new(),
+ platform: "teachable".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Teachable courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/themembers/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/themembers/api.rs
new file mode 100644
index 00000000..f13855a7
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/themembers/api.rs
@@ -0,0 +1,586 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+const API_BASE: &str = "https://api.themembers.com.br/api";
+
+#[derive(Clone)]
+pub struct TheMembersSession {
+ pub token: String,
+ pub tenant_id: String,
+ pub org_id: String,
+ pub domain: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub tenant_id: String,
+ pub org_id: String,
+ pub domain: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TheMembersCourse {
+ pub id: i64,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TheMembersModule {
+ pub id: i64,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<TheMembersLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TheMembersLesson {
+ pub id: i64,
+ pub name: String,
+ pub order: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TheMembersLessonDetail {
+ pub id: i64,
+ pub name: String,
+ pub description: Option<String>,
+ pub video_url: Option<String>,
+ pub url_pdf: Option<String>,
+ pub host: String,
+ pub files: Vec<TheMembersFile>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TheMembersFile {
+ pub name: String,
+ pub url: String,
+}
+
+fn build_client(token: &str, tenant_id: &str, org_id: &str, domain: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&format!("Bearer {}", token))?,
+ );
+ headers.insert("x-platform-id", HeaderValue::from_str(tenant_id)?);
+ headers.insert("x-tenant-id", HeaderValue::from_str(tenant_id)?);
+ headers.insert("Tenant-ID", HeaderValue::from_str(tenant_id)?);
+ headers.insert("orgId", HeaderValue::from_str(org_id)?);
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_str(&format!("https://{}", domain))?,
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_str(&format!("https://{}/", domain))?,
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("themembers_session.json"))
+}
+
+pub async fn resolve_tenant(domain: &str) -> anyhow::Result<(String, String)> {
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let url = format!("{}/getTenant?domain={}", API_BASE, domain);
+ let resp = temp_client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "resolve_tenant returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let tenant = body.get("tenant").unwrap_or(&body);
+
+ let tenant_id = tenant
+ .get("id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ let org_id = tenant
+ .get("organization_id")
+ .map(|v| match v {
+ serde_json::Value::Number(n) => n.to_string(),
+ serde_json::Value::String(s) => s.clone(),
+ _ => String::new(),
+ })
+ .unwrap_or_default();
+
+ if tenant_id.is_empty() {
+ return Err(anyhow!("Could not resolve tenant_id for domain {}", domain));
+ }
+
+ Ok((tenant_id, org_id))
+}
+
+pub async fn authenticate(email: &str, password: &str, domain: &str) -> anyhow::Result<TheMembersSession> {
+ let (tenant_id, org_id) = resolve_tenant(domain).await?;
+
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let payload = serde_json::json!({
+ "email": email,
+ "password": password,
+ "tenant_id": tenant_id,
+ });
+
+ let resp = temp_client
+ .post(format!("{}/auth/login", API_BASE))
+ .json(&payload)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "Authentication failed (status {}): {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let token = body
+ .get("access_token")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("access_token not found in login response"))?
+ .to_string();
+
+ let client = build_client(&token, &tenant_id, &org_id, domain)?;
+
+ Ok(TheMembersSession {
+ token,
+ tenant_id,
+ org_id,
+ domain: domain.to_string(),
+ client,
+ })
+}
+
+pub async fn authenticate_token(token: &str, domain: &str) -> anyhow::Result<TheMembersSession> {
+ let (tenant_id, org_id) = resolve_tenant(domain).await?;
+ let client = build_client(token, &tenant_id, &org_id, domain)?;
+
+ let session = TheMembersSession {
+ token: token.to_string(),
+ tenant_id,
+ org_id,
+ domain: domain.to_string(),
+ client,
+ };
+
+ let valid = validate_token(&session).await?;
+ if !valid {
+ return Err(anyhow!("Invalid token"));
+ }
+
+ Ok(session)
+}
+
+pub async fn validate_token(session: &TheMembersSession) -> anyhow::Result<bool> {
+ let url = format!(
+ "{}/auth/sideList/{}/courses",
+ API_BASE, session.tenant_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &TheMembersSession) -> anyhow::Result<Vec<TheMembersCourse>> {
+ let url = format!(
+ "{}/auth/sideList/{}/courses",
+ API_BASE, session.tenant_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let data_arr = body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut courses = Vec::new();
+ for item in &data_arr {
+ let id = item.get("id").and_then(|v| v.as_i64()).unwrap_or(0);
+ let name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if id != 0 {
+ courses.push(TheMembersCourse { id, name });
+ }
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_course_content(
+ session: &TheMembersSession,
+ course_id: i64,
+) -> anyhow::Result<Vec<TheMembersModule>> {
+ let modules_url = format!(
+ "{}/auth/sideList/{}/modules",
+ API_BASE, course_id
+ );
+
+ let resp = session.client.get(&modules_url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_course_content returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let modules_arr = body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for (mi, module_val) in modules_arr.iter().enumerate() {
+ let module_id = module_val.get("id").and_then(|v| v.as_i64()).unwrap_or(0);
+ let module_name = module_val
+ .get("title")
+ .or_else(|| module_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lessons_url = format!(
+ "{}/auth/sideList/{}/lessons",
+ API_BASE, module_id
+ );
+
+ let lessons = match session.client.get(&lessons_url).send().await {
+ Ok(resp) if resp.status().is_success() => {
+ let lessons_text = resp.text().await.unwrap_or_default();
+ let lessons_body: serde_json::Value =
+ serde_json::from_str(&lessons_text).unwrap_or(serde_json::Value::Null);
+
+ let lessons_arr = lessons_body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ lessons_arr
+ .iter()
+ .enumerate()
+ .map(|(li, lesson_val)| {
+ let lesson_id = lesson_val
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let lesson_name = lesson_val
+ .get("title")
+ .or_else(|| lesson_val.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ TheMembersLesson {
+ id: lesson_id,
+ name: lesson_name,
+ order: li as i64,
+ }
+ })
+ .collect()
+ }
+ _ => vec![],
+ };
+
+ modules.push(TheMembersModule {
+ id: module_id,
+ name: module_name,
+ order: mi as i64,
+ lessons,
+ });
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_lesson_detail(
+ session: &TheMembersSession,
+ lesson_id: i64,
+) -> anyhow::Result<TheMembersLessonDetail> {
+ let url = format!(
+ "{}/auth/home/class/{}/{}",
+ API_BASE, lesson_id, session.tenant_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lesson_detail returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let class_obj = body.get("class").unwrap_or(&body);
+
+ let name = class_obj
+ .get("title")
+ .or_else(|| class_obj.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let description = class_obj
+ .get("description")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let url_pdf = class_obj
+ .get("url_pdf")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())
+ .map(String::from);
+
+ let host = class_obj
+ .get("host")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let raw_video_url = class_obj
+ .get("url_video")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let video_url = match (host.as_str(), &raw_video_url) {
+ ("the-player-ai", Some(url)) => {
+ resolve_the_player_ai_url(url).await.ok()
+ }
+ (_, Some(url)) if !url.is_empty() => Some(url.clone()),
+ _ => None,
+ };
+
+ let materials_url = format!(
+ "{}/auth/home/materials/{}",
+ API_BASE, lesson_id
+ );
+
+ let files = match session.client.get(&materials_url).send().await {
+ Ok(resp) if resp.status().is_success() => {
+ let files_text = resp.text().await.unwrap_or_default();
+ let files_body: serde_json::Value =
+ serde_json::from_str(&files_text).unwrap_or(serde_json::Value::Array(vec![]));
+
+ let files_arr = match &files_body {
+ serde_json::Value::Array(arr) => arr.clone(),
+ _ => files_body
+ .get("data")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default(),
+ };
+
+ files_arr
+ .iter()
+ .filter_map(|f| {
+ let file_name = f
+ .get("title")
+ .or_else(|| f.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("file")
+ .to_string();
+
+ let file_url = f
+ .get("url")
+ .or_else(|| f.get("file_url"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ file_url.map(|url| TheMembersFile {
+ name: file_name,
+ url,
+ })
+ })
+ .collect()
+ }
+ _ => vec![],
+ };
+
+ Ok(TheMembersLessonDetail {
+ id: lesson_id,
+ name,
+ description,
+ video_url,
+ url_pdf,
+ host,
+ files,
+ })
+}
+
+async fn resolve_the_player_ai_url(video_url: &str) -> anyhow::Result<String> {
+ let video_id = video_url
+ .rsplit('/')
+ .next()
+ .unwrap_or(video_url)
+ .split('?')
+ .next()
+ .unwrap_or(video_url);
+
+ let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(60))
+ .build()?;
+
+ let url = format!("https://player.themembers.com.br/api/video/{}", video_id);
+ let resp = temp_client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "resolve_the_player_ai_url returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let hls_url = body
+ .get("data")
+ .and_then(|d| d.get("urls"))
+ .and_then(|u| u.get("hls"))
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("No HLS URL found in the-player-ai response"))?
+ .to_string();
+
+ Ok(hls_url)
+}
+
+pub async fn save_session(session: &TheMembersSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ tenant_id: session.tenant_id.clone(),
+ org_id: session.org_id.clone(),
+ domain: session.domain.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[themembers] session saved for {}", session.domain);
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<TheMembersSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token, &saved.tenant_id, &saved.org_id, &saved.domain)?;
+
+ tracing::info!("[themembers] session loaded for {}", saved.domain);
+
+ Ok(Some(TheMembersSession {
+ token: saved.token,
+ tenant_id: saved.tenant_id,
+ org_id: saved.org_id,
+ domain: saved.domain,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/themembers/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/themembers/downloader.rs
new file mode 100644
index 00000000..fa70f70d
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/themembers/downloader.rs
@@ -0,0 +1,362 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, TheMembersCourse, TheMembersSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct TheMembersCourseDownloadProgress {
+ pub course_id: i64,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &TheMembersSession,
+ course: &TheMembersCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &TheMembersCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ let detail = match api::get_lesson_detail(session, lesson.id).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[themembers] Failed to get lesson detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &TheMembersCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if let Some(ref desc) = detail.description {
+ omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
+ }
+
+ if let Some(ref pdf_url) = detail.url_pdf {
+ omniget_core::core::course_utils::download_attachment(
+ &session.client,
+ pdf_url,
+ &lesson_dir,
+ &format!("{}.pdf", lesson_name),
+ &cancel_token,
+ ).await.ok();
+ }
+
+ if let Some(ref video_url) = detail.video_url {
+ let video_ext = if video_url.contains(".m3u8") {
+ "mp4"
+ } else {
+ video_url
+ .rsplit('.')
+ .next()
+ .and_then(|e| {
+ let e = e.split('?').next().unwrap_or(e);
+ if e.len() <= 4 {
+ Some(e)
+ } else {
+ None
+ }
+ })
+ .unwrap_or("mp4")
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.{}",
+ lesson_dir,
+ li + 1,
+ lesson_name,
+ video_ext
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[themembers] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &TheMembersCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ let referer = format!("https://{}/", session.domain);
+
+ if video_url.contains(".m3u8") {
+ match download_hls_video(video_url, &video_path, &referer, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[themembers] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(video_url, &lesson_dir, &referer, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[themembers] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[themembers] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for file in &detail.files {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let file_name = filename::sanitize_path_component(&file.name);
+ let file_path = format!("{}/{}", lesson_dir, file_name);
+
+ if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&file_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, &file.url, &file_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[themembers] File download failed for '{}': {}",
+ file.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &TheMembersCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ referer: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ referer,
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ referer: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some(referer),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/themembers/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/themembers/mod.rs
new file mode 100644
index 00000000..79ddf36b
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/themembers/mod.rs
@@ -0,0 +1,63 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct TheMembersDownloader;
+
+impl TheMembersDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+impl Default for TheMembersDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for TheMembersDownloader {
+ fn name(&self) -> &str {
+ "themembers"
+ }
+
+ 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 == "themembers.com.br"
+ || host.ends_with(".themembers.com.br");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "TheMembers".to_string(),
+ author: String::new(),
+ platform: "themembers".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from TheMembers"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/thinkific/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/thinkific/api.rs
new file mode 100644
index 00000000..9e0f27e9
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/thinkific/api.rs
@@ -0,0 +1,681 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use regex::Regex;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+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";
+
+#[derive(Clone)]
+pub struct ThinkificSession {
+ pub cookies: String,
+ pub site_url: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub cookies: String,
+ pub site_url: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ThinkificCourse {
+ pub id: String,
+ pub name: String,
+ pub slug: String,
+ pub image_url: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ThinkificModule {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<ThinkificLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ThinkificLesson {
+ pub id: String,
+ pub name: String,
+ pub order: i64,
+ pub contentable_type: String,
+ pub contentable_id: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ThinkificLessonDetail {
+ pub id: String,
+ pub name: String,
+ pub video_url: Option<String>,
+ pub html_text: Option<String>,
+ pub files: Vec<ThinkificFile>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ThinkificFile {
+ pub name: String,
+ pub url: String,
+}
+
+fn normalise_site_url(raw: &str) -> String {
+ let mut url = raw.trim().to_string();
+ if !url.starts_with("http://") && !url.starts_with("https://") {
+ url = format!("https://{}", url);
+ }
+ if let Ok(parsed) = reqwest::Url::parse(&url) {
+ format!("{}://{}", parsed.scheme(), parsed.host_str().unwrap_or(""))
+ } else {
+ url.trim_end_matches('/').to_string()
+ }
+}
+
+fn build_client(cookies: &str, site_url: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert("Cookie", HeaderValue::from_str(cookies)?);
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Referer",
+ HeaderValue::from_str(&format!("{}/", site_url))?,
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("thinkific_session.json"))
+}
+
+pub fn create_session(cookies: &str, site_url: &str) -> anyhow::Result<ThinkificSession> {
+ let site_url = normalise_site_url(site_url);
+ let client = build_client(cookies, &site_url)?;
+ Ok(ThinkificSession {
+ cookies: cookies.to_string(),
+ site_url,
+ client,
+ })
+}
+
+pub async fn validate_session(session: &ThinkificSession) -> anyhow::Result<bool> {
+ let url = format!(
+ "{}/api/course_player/v2/enrollments",
+ session.site_url
+ );
+ let resp = session.client.get(&url).send().await?;
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &ThinkificSession) -> anyhow::Result<Vec<ThinkificCourse>> {
+ let mut courses = Vec::new();
+
+ for endpoint in &[
+ "/api/course_player/v2/enrollments",
+ "/api/course_player/v2/courses",
+ "/api/v0/enrollments",
+ "/api/v0/courses",
+ ] {
+ let url = format!("{}{}", session.site_url, endpoint);
+ let resp = match session.client.get(&url).send().await {
+ Ok(r) if r.status().is_success() => r,
+ _ => continue,
+ };
+
+ let body_text = resp.text().await.unwrap_or_default();
+ let parsed = parse_enrollments(&body_text, session).await;
+ if !parsed.is_empty() {
+ courses = parsed;
+ break;
+ }
+ }
+
+ if courses.is_empty() {
+ courses = scrape_enrollments(session).await.unwrap_or_default();
+ }
+
+ Ok(courses)
+}
+
+async fn parse_enrollments(
+ body: &str,
+ session: &ThinkificSession,
+) -> Vec<ThinkificCourse> {
+ let raw: serde_json::Value = match serde_json::from_str(body) {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+
+ let items = match &raw {
+ serde_json::Value::Array(arr) => arr.clone(),
+ serde_json::Value::Object(map) => {
+ for key in &["items", "enrollments", "courses"] {
+ if let Some(serde_json::Value::Array(arr)) = map.get(*key) {
+ return parse_items_array(arr, session).await;
+ }
+ }
+ return Vec::new();
+ }
+ _ => return Vec::new(),
+ };
+
+ parse_items_array(&items, session).await
+}
+
+async fn parse_items_array(
+ items: &[serde_json::Value],
+ session: &ThinkificSession,
+) -> Vec<ThinkificCourse> {
+ let mut courses = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+
+ for item in items {
+ let slug = item
+ .get("slug")
+ .or_else(|| item.get("course_slug"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ if slug.is_empty() || seen.contains(&slug) {
+ continue;
+ }
+ seen.insert(slug.clone());
+
+ let mut name = item
+ .get("name")
+ .or_else(|| item.get("course_name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or(&slug)
+ .to_string();
+
+ let mut image_url = extract_image(item);
+
+ if name == slug || image_url.is_none() {
+ if let Ok(detail) = fetch_course_detail(session, &slug).await {
+ if let Some(co) = detail.get("course").and_then(|v| v.as_object()) {
+ let co_val = serde_json::Value::Object(co.clone());
+ if let Some(n) = co_val.get("name").and_then(|v| v.as_str()) {
+ if !n.is_empty() {
+ name = n.to_string();
+ }
+ }
+ if image_url.is_none() {
+ image_url = extract_image(&co_val);
+ }
+ } else {
+ if let Some(n) = detail.get("name").and_then(|v| v.as_str()) {
+ if !n.is_empty() && name == slug {
+ name = n.to_string();
+ }
+ }
+ if image_url.is_none() {
+ image_url = extract_image(&detail);
+ }
+ }
+ }
+ }
+
+ courses.push(ThinkificCourse {
+ id: slug.clone(),
+ name,
+ slug,
+ image_url,
+ });
+ }
+
+ courses
+}
+
+fn extract_image(obj: &serde_json::Value) -> Option<String> {
+ for field in &[
+ "logo",
+ "course_card_image_url",
+ "card_image_url",
+ "banner_image_url",
+ "image_url",
+ "thumbnail_url",
+ "cover_image_url",
+ "image",
+ ] {
+ if let Some(v) = obj.get(*field).and_then(|v| v.as_str()) {
+ if !v.is_empty() {
+ return Some(v.to_string());
+ }
+ }
+ }
+ None
+}
+
+async fn fetch_course_detail(
+ session: &ThinkificSession,
+ slug: &str,
+) -> anyhow::Result<serde_json::Value> {
+ let url = format!(
+ "{}/api/course_player/v2/courses/{}",
+ session.site_url, slug
+ );
+ let resp = session.client.get(&url).send().await?;
+ if !resp.status().is_success() {
+ return Err(anyhow!("HTTP {}", resp.status()));
+ }
+ let body: serde_json::Value = resp.json().await?;
+ Ok(body)
+}
+
+async fn scrape_enrollments(
+ session: &ThinkificSession,
+) -> anyhow::Result<Vec<ThinkificCourse>> {
+ let url = format!("{}/enrollments", session.site_url);
+ let resp = session.client.get(&url).send().await?;
+ if !resp.status().is_success() {
+ return Ok(Vec::new());
+ }
+
+ let html = resp.text().await?;
+ let slug_re = Regex::new(r#"href=["']/?courses/(?:take/|enrolled/|enroll/)?([a-zA-Z][a-zA-Z0-9_-]{2,})["']"#)?;
+
+ let skip_set: std::collections::HashSet<&str> = [
+ "take", "new", "edit", "enroll", "preview", "sign_in", "sign_up",
+ "enrolled", "progress", "admin", "users", "bundle", "checkout",
+ "cart", "payment",
+ ]
+ .into();
+
+ let mut courses = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+
+ for cap in slug_re.captures_iter(&html) {
+ let slug = &cap[1];
+ let lower = slug.to_lowercase();
+ if seen.contains(&lower) || skip_set.contains(lower.as_str()) {
+ continue;
+ }
+ seen.insert(lower);
+
+ let mut name = slug.to_string();
+ let mut image_url = None;
+
+ if let Ok(detail) = fetch_course_detail(session, slug).await {
+ if let Some(co) = detail.get("course").and_then(|v| v.as_object()) {
+ let co_val = serde_json::Value::Object(co.clone());
+ if let Some(n) = co_val.get("name").and_then(|v| v.as_str()) {
+ if !n.is_empty() {
+ name = n.to_string();
+ }
+ }
+ image_url = extract_image(&co_val);
+ } else {
+ if let Some(n) = detail.get("name").and_then(|v| v.as_str()) {
+ if !n.is_empty() {
+ name = n.to_string();
+ }
+ }
+ image_url = extract_image(&detail);
+ }
+ }
+
+ courses.push(ThinkificCourse {
+ id: slug.to_string(),
+ name,
+ slug: slug.to_string(),
+ image_url,
+ });
+ }
+
+ Ok(courses)
+}
+
+pub async fn get_course_content(
+ session: &ThinkificSession,
+ slug: &str,
+) -> anyhow::Result<Vec<ThinkificModule>> {
+ let data = fetch_course_detail(session, slug).await?;
+
+ let chapters = data
+ .get("chapters")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let contents = data
+ .get("contents")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut ch_map: std::collections::HashMap<i64, (String, i64)> = std::collections::HashMap::new();
+ for (i, ch) in chapters.iter().enumerate() {
+ let id = ch.get("id").and_then(|v| v.as_i64()).unwrap_or(0);
+ let name = ch
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Chapter")
+ .to_string();
+ let pos = ch
+ .get("position")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(i as i64 + 1);
+ ch_map.insert(id, (name, pos));
+ }
+
+ let mut modules_map: std::collections::HashMap<i64, ThinkificModule> =
+ std::collections::HashMap::new();
+
+ for (i, content) in contents.iter().enumerate() {
+ let ch_id = content.get("chapter_id").and_then(|v| v.as_i64()).unwrap_or(0);
+ let (ch_name, ch_order) = ch_map
+ .get(&ch_id)
+ .cloned()
+ .unwrap_or(("Extras".to_string(), 999));
+
+ let contentable_id = content
+ .get("contentable_id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let contentable_type = content
+ .get("contentable_type")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson_name = content
+ .get("name")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lesson = ThinkificLesson {
+ id: format!("{}", contentable_id),
+ name: if lesson_name.is_empty() {
+ format!("Lesson {}", i + 1)
+ } else {
+ lesson_name
+ },
+ order: i as i64,
+ contentable_type,
+ contentable_id,
+ };
+
+ modules_map
+ .entry(ch_id)
+ .or_insert_with(|| ThinkificModule {
+ id: format!("{}", ch_id),
+ name: ch_name,
+ order: ch_order,
+ lessons: Vec::new(),
+ })
+ .lessons
+ .push(lesson);
+ }
+
+ let mut modules: Vec<ThinkificModule> = modules_map.into_values().collect();
+ modules.sort_by_key(|m| m.order);
+ for m in &mut modules {
+ m.lessons.sort_by_key(|l| l.order);
+ }
+
+ Ok(modules)
+}
+
+pub async fn get_lesson_detail(
+ session: &ThinkificSession,
+ lesson: &ThinkificLesson,
+) -> anyhow::Result<ThinkificLessonDetail> {
+ let lesson_id = lesson.contentable_id;
+
+ match lesson.contentable_type.as_str() {
+ "Download" => {
+ let files = fetch_download_files(session, lesson_id).await?;
+ Ok(ThinkificLessonDetail {
+ id: lesson.id.clone(),
+ name: lesson.name.clone(),
+ video_url: None,
+ html_text: None,
+ files,
+ })
+ }
+ "HtmlItem" => {
+ let html = fetch_html_item(session, lesson_id).await?;
+ Ok(ThinkificLessonDetail {
+ id: lesson.id.clone(),
+ name: lesson.name.clone(),
+ video_url: None,
+ html_text: Some(html),
+ files: Vec::new(),
+ })
+ }
+ _ => {
+ let url = format!(
+ "{}/api/course_player/v2/lessons/{}",
+ session.site_url, lesson_id
+ );
+ let resp = session.client.get(&url).send().await?;
+ if !resp.status().is_success() {
+ return Ok(ThinkificLessonDetail {
+ id: lesson.id.clone(),
+ name: lesson.name.clone(),
+ video_url: None,
+ html_text: None,
+ files: Vec::new(),
+ });
+ }
+
+ let body: serde_json::Value = resp.json().await?;
+ let lesson_obj = body.get("lesson").unwrap_or(&body);
+
+ let video_url = lesson_obj
+ .get("video_url")
+ .or_else(|| lesson_obj.get("video_embed_url"))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let html_text = lesson_obj
+ .get("html_text")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let files = body
+ .get("download_files")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|f| {
+ let dl_url = f.get("download_url").and_then(|v| v.as_str())?;
+ let fname = f
+ .get("file_name")
+ .or_else(|| f.get("label"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("attachment")
+ .to_string();
+ Some(ThinkificFile {
+ name: fname,
+ url: dl_url.to_string(),
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+
+ Ok(ThinkificLessonDetail {
+ id: lesson.id.clone(),
+ name: lesson.name.clone(),
+ video_url,
+ html_text,
+ files,
+ })
+ }
+ }
+}
+
+async fn fetch_download_files(
+ session: &ThinkificSession,
+ lesson_id: i64,
+) -> anyhow::Result<Vec<ThinkificFile>> {
+ let url = format!(
+ "{}/api/course_player/v2/downloads/{}",
+ session.site_url, lesson_id
+ );
+
+ let resp = session.client.get(&url).send().await;
+ let body: serde_json::Value = match resp {
+ Ok(r) if r.status().is_success() => r.json().await?,
+ _ => {
+ let fallback = format!(
+ "{}/api/course_player/v2/lessons/{}",
+ session.site_url, lesson_id
+ );
+ let r = session.client.get(&fallback).send().await?;
+ if !r.status().is_success() {
+ return Ok(Vec::new());
+ }
+ r.json().await?
+ }
+ };
+
+ let files = body
+ .get("download_files")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|f| {
+ let dl_url = f.get("download_url").and_then(|v| v.as_str())?;
+ let fname = f
+ .get("file_name")
+ .or_else(|| f.get("label"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("file")
+ .to_string();
+ Some(ThinkificFile {
+ name: fname,
+ url: dl_url.to_string(),
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+
+ Ok(files)
+}
+
+async fn fetch_html_item(
+ session: &ThinkificSession,
+ lesson_id: i64,
+) -> anyhow::Result<String> {
+ let url = format!(
+ "{}/api/course_player/v2/html_items/{}",
+ session.site_url, lesson_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+ if !resp.status().is_success() {
+ return Ok(String::new());
+ }
+
+ let body: serde_json::Value = resp.json().await?;
+ let item = body.get("html_item").unwrap_or(&body);
+
+ let content = item
+ .get("html_text")
+ .or_else(|| item.get("body"))
+ .or_else(|| item.get("content"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ Ok(content)
+}
+
+pub fn resolve_video_url(page_html: &str, fallback_url: &str) -> String {
+ let player_re = Regex::new(r"player\.thinkific\.com/embed/([a-f0-9-]+)").ok();
+ let mp4_re = Regex::new(r#"https?://[^\s"']+\.mp4"#).ok();
+ let wistia_re = Regex::new(r#"(?i)(?:wistia_async_|fast\.wistia\.com/embed/(?:medias|iframe)/|hashedId["']?\s*[:=]\s*["'])([a-z0-9]+)"#).ok();
+ let cdn_re = Regex::new(r#"(https://(?:d2p6ecj15pyavq|d1fto35gcfffzn)\.cloudfront\.net/[^\s"']+\.(?:mp4|m3u8)|https://player-api\.thinkific\.com/(?:hls|api/video)/[^\s"']+)"#).ok();
+
+ if let Some(re) = wistia_re {
+ if let Some(cap) = re.captures(page_html) {
+ return format!("https://fast.wistia.com/embed/iframe/{}", &cap[1]);
+ }
+ }
+
+ if let Some(re) = cdn_re {
+ if let Some(cap) = re.captures(page_html) {
+ return cap[1].to_string();
+ }
+ }
+
+ if let Some(re) = player_re {
+ if let Some(cap) = re.captures(page_html) {
+ return format!("https://player.thinkific.com/embed/{}", &cap[1]);
+ }
+ }
+
+ if let Some(re) = mp4_re {
+ if let Some(m) = re.find(page_html) {
+ return m.as_str().to_string();
+ }
+ }
+
+ fallback_url.to_string()
+}
+
+pub async fn save_session(session: &ThinkificSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ cookies: session.cookies.clone(),
+ site_url: session.site_url.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[thinkific] session saved for {}", session.site_url);
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<ThinkificSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.cookies, &saved.site_url)?;
+
+ tracing::info!("[thinkific] session loaded for {}", saved.site_url);
+
+ Ok(Some(ThinkificSession {
+ cookies: saved.cookies,
+ site_url: saved.site_url,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/thinkific/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/thinkific/downloader.rs
new file mode 100644
index 00000000..5aa0297f
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/thinkific/downloader.rs
@@ -0,0 +1,308 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, ThinkificCourse, ThinkificSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct ThinkificCourseDownloadProgress {
+ pub course_id: String,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &ThinkificSession,
+ course: &ThinkificCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let modules = api::get_course_content(session, &course.slug).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ tracing::info!("[thinkific] course already complete, skipping");
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &ThinkificCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let safe_name = format!("{}. {}", li + 1, lesson_name);
+
+ let detail = match api::get_lesson_detail(session, lesson).await {
+ Ok(d) => d,
+ Err(e) => {
+ tracing::error!(
+ "[thinkific] Failed to get lesson detail '{}': {}. Continuing...",
+ lesson.name,
+ e
+ );
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &ThinkificCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ };
+
+ if let Some(ref video_url) = detail.video_url {
+ if !video_url.is_empty() {
+ let video_path = format!("{}/{}.mp4", mod_dir, safe_name);
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[thinkific] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &ThinkificCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ let resolved_url = resolve_video_url_with_fetch(session, video_url).await;
+
+ match download_with_ytdlp(&resolved_url, &mod_dir, &session.cookies, &session.site_url, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[thinkific] yt-dlp download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ }
+ }
+ }
+ }
+
+ if let Some(ref html) = detail.html_text {
+ if !html.trim().is_empty() {
+ let html_path = format!("{}/{}.html", mod_dir, safe_name);
+ if !tokio::fs::try_exists(&html_path).await.unwrap_or(false) {
+ let doc = format!(
+ "<!DOCTYPE html>\n<html><head><meta charset=\"UTF-8\"><title>{}</title>\n<style>body {{ font-family: system-ui, sans-serif; max-width: 800px; margin: 40px auto; padding: 0 20px; line-height: 1.6; }} img {{ max-width: 100%; }}</style>\n</head><body>\n<h1>{}</h1>\n{}\n</body></html>",
+ lesson.name, lesson.name, html
+ );
+ let _ = tokio::fs::write(&html_path, doc).await;
+ }
+ }
+ }
+
+ for file in &detail.files {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let file_name = filename::sanitize_path_component(&file.name);
+ let file_path = format!("{}/{}", mod_dir, file_name);
+
+ if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&file_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, &file.url, &file_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[thinkific] File download failed for '{}': {}",
+ file.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &ThinkificCourseDownloadProgress {
+ course_id: course.id.clone(),
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn resolve_video_url_with_fetch(session: &ThinkificSession, video_url: &str) -> String {
+ let page_resp = session
+ .client
+ .get(video_url)
+ .header("Accept", "text/html,*/*")
+ .send()
+ .await;
+
+ if let Ok(resp) = page_resp {
+ if let Ok(text) = resp.text().await {
+ return api::resolve_video_url(&text, video_url);
+ }
+ }
+
+ video_url.to_string()
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cookies: &str,
+ site_url: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let cookie_header = format!("Cookie:{}", cookies);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some(&format!("{}/", site_url)),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &["--add-headers".to_string(), cookie_header],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/thinkific/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/thinkific/mod.rs
new file mode 100644
index 00000000..218b9370
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/thinkific/mod.rs
@@ -0,0 +1,68 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct ThinkificDownloader;
+
+impl Default for ThinkificDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl ThinkificDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for ThinkificDownloader {
+ fn name(&self) -> &str {
+ "thinkific"
+ }
+
+ 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 == "thinkific.com" || host.ends_with(".thinkific.com");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Thinkific Course".to_string(),
+ author: String::new(),
+ platform: "thinkific".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "course".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "course".to_string(),
+ }],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download Thinkific courses"))
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/udemy/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/udemy/api.rs
new file mode 100644
index 00000000..a022ff5b
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/udemy/api.rs
@@ -0,0 +1,441 @@
+use std::time::Duration;
+
+use anyhow::{anyhow, Result};
+use regex::Regex;
+use serde::{Deserialize, Serialize};
+
+use super::auth::UdemySession;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UdemyCourse {
+ pub id: u64,
+ pub title: String,
+ pub published_title: String,
+ pub url: Option<String>,
+ pub image_url: Option<String>,
+ pub num_published_lectures: Option<u32>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UdemyChapter {
+ pub id: u64,
+ pub title: String,
+ pub object_index: u32,
+ pub lectures: Vec<UdemyLecture>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UdemyLecture {
+ pub id: u64,
+ pub title: String,
+ pub object_index: u32,
+ pub lecture_class: String,
+ pub asset: Option<serde_json::Value>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UdemyCurriculum {
+ pub course_id: u64,
+ pub title: String,
+ pub chapters: Vec<UdemyChapter>,
+ pub total_lectures: u32,
+ pub total_video_lectures: u32,
+ pub drm_video_lectures: u32,
+}
+
+pub fn extract_course_name(url: &str) -> Option<(String, String)> {
+ let re = Regex::new(
+ r"(?i)://(.+?)\.udemy\.com/(?:course(?:/draft)*/)?([a-zA-Z0-9_-]+)"
+ ).ok()?;
+ let caps = re.captures(url)?;
+ let portal_name = caps.get(1)?.as_str().to_string();
+ let course_slug = caps.get(2)?.as_str().to_string();
+ Some((portal_name, course_slug))
+}
+
+async fn api_get_with_retry(
+ client: &reqwest::Client,
+ url: &str,
+ params: Option<&[(&str, &str)]>,
+) -> Result<reqwest::Response> {
+ let max_attempts: u32 = 3;
+ let mut last_err = None;
+
+ for attempt in 0..max_attempts {
+ let mut req = client.get(url);
+ if let Some(p) = params {
+ req = req.query(p);
+ }
+
+ match req.send().await {
+ Ok(resp) => {
+ let status = resp.status();
+ tracing::info!("[udemy-api] {} → {}", url, status);
+ if status.is_success() {
+ return Ok(resp);
+ }
+ if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
+ let body = resp.text().await.unwrap_or_default();
+ tracing::error!("[udemy-api] auth error for {}: {} — {}", url, status, &body[..body.len().min(500)]);
+ return Err(anyhow!("API auth error ({}): {}", status, body));
+ }
+ let body = resp.text().await.unwrap_or_default();
+ tracing::warn!("[udemy-api] non-success for {}: {} — {}", url, status, &body[..body.len().min(500)]);
+ last_err = Some(anyhow!("API returned {}: {}", status, body));
+ }
+ Err(e) => {
+ last_err = Some(anyhow!("Request failed: {}", e));
+ }
+ }
+
+ if attempt < max_attempts - 1 {
+ let backoff = Duration::from_millis(500 * 2u64.pow(attempt));
+ tracing::warn!(
+ "[udemy-api] attempt {}/{} failed, retrying in {:?}",
+ attempt + 1,
+ max_attempts,
+ backoff
+ );
+ tokio::time::sleep(backoff).await;
+ }
+ }
+
+ Err(last_err.unwrap_or_else(|| anyhow!("All retry attempts failed")))
+}
+
+async fn handle_pagination(
+ session: &UdemySession,
+ initial_url: &str,
+ params: Option<&[(&str, &str)]>,
+) -> Result<serde_json::Value> {
+ let resp = api_get_with_retry(&session.client, initial_url, params).await?;
+
+ let resp_text = resp.text().await
+ .map_err(|e| anyhow!("Failed to read response body: {}", e))?;
+
+ let mut data: serde_json::Value = serde_json::from_str(&resp_text)
+ .map_err(|e| {
+ let preview = if resp_text.len() > 500 { &resp_text[..500] } else { &resp_text };
+ tracing::error!("[udemy-api] JSON parse failed. Body preview: {}", preview);
+ anyhow!("Failed to parse JSON: {} — body starts with: {}", e, &resp_text[..resp_text.len().min(200)])
+ })?;
+
+ let count = data.get("count").and_then(|c| c.as_u64());
+ if count.is_none() {
+ tracing::warn!("[udemy-api] response missing 'count' field. Keys: {:?}",
+ data.as_object().map(|o| o.keys().collect::<Vec<_>>()));
+ return Ok(data);
+ }
+
+ let mut page = 1u32;
+ loop {
+ let next_url = data.get("next").and_then(|n| n.as_str()).map(|s| s.to_string());
+ match next_url {
+ Some(url) if !url.is_empty() => {
+ page += 1;
+ tracing::info!("[udemy-api] fetching page {}", page);
+
+ tokio::time::sleep(Duration::from_millis(200)).await;
+
+ let resp = match api_get_with_retry(&session.client, &url, None).await {
+ Ok(r) => r,
+ Err(e) => {
+ tracing::error!("[udemy-api] page {} failed: {}", page, e);
+ break;
+ }
+ };
+
+ let page_data: serde_json::Value = resp.json().await
+ .map_err(|e| anyhow!("Failed to parse page JSON: {}", e))?;
+
+ if let Some(new_results) = page_data.get("results").and_then(|r| r.as_array()) {
+ if let Some(existing) = data.get_mut("results").and_then(|r| r.as_array_mut()) {
+ existing.extend(new_results.iter().cloned());
+ }
+ }
+
+ if let Some(next) = page_data.get("next") {
+ data["next"] = next.clone();
+ } else {
+ data["next"] = serde_json::Value::Null;
+ }
+ }
+ _ => break,
+ }
+ }
+
+ Ok(data)
+}
+
+fn parse_course_from_json(item: &serde_json::Value) -> Option<UdemyCourse> {
+ let id = item.get("id")?.as_u64()?;
+ let title = item.get("title")?.as_str().unwrap_or("").to_string();
+ let published_title = item.get("published_title")?.as_str().unwrap_or("").to_string();
+ let url = item.get("url").and_then(|v| v.as_str()).map(|s| s.to_string());
+
+ let image_url = item.get("image_240x135")
+ .or_else(|| item.get("image_480x270"))
+ .or_else(|| item.get("image_url"))
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+
+ let num_published_lectures = item.get("num_published_lectures")
+ .and_then(|v| v.as_u64())
+ .map(|n| n as u32);
+
+ Some(UdemyCourse {
+ id,
+ title,
+ published_title,
+ url,
+ image_url,
+ num_published_lectures,
+ })
+}
+
+pub async fn list_my_courses(
+ session: &UdemySession,
+ portal_name: &str,
+) -> Result<Vec<UdemyCourse>> {
+ let url = format!(
+ "https://{}.udemy.com/api-2.0/users/me/subscribed-courses?fields[course]=id,url,title,published_title,image_240x135,num_published_lectures&ordering=-last_accessed,-access_time&page=1&page_size=10000",
+ portal_name
+ );
+
+ tracing::info!("[udemy-api] fetching subscribed courses from {}", portal_name);
+
+ let data = handle_pagination(session, &url, None).await?;
+
+ let results = data.get("results")
+ .and_then(|r| r.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let courses: Vec<UdemyCourse> = results
+ .iter()
+ .filter_map(parse_course_from_json)
+ .collect();
+
+ tracing::info!("[udemy-api] found {} subscribed courses", courses.len());
+ Ok(courses)
+}
+
+pub async fn list_subscription_courses(
+ session: &UdemySession,
+ portal_name: &str,
+) -> Result<Vec<UdemyCourse>> {
+ let url = format!(
+ "https://{}.udemy.com/api-2.0/users/me/subscription-course-enrollments?fields[course]=title,published_title,image_240x135,num_published_lectures&page=1&page_size=50",
+ portal_name
+ );
+
+ tracing::info!("[udemy-api] fetching subscription course enrollments from {}", portal_name);
+
+ let data = handle_pagination(session, &url, None).await?;
+
+ let results = data.get("results")
+ .and_then(|r| r.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let courses: Vec<UdemyCourse> = results
+ .iter()
+ .filter_map(parse_course_from_json)
+ .collect();
+
+ tracing::info!("[udemy-api] found {} subscription courses", courses.len());
+ Ok(courses)
+}
+
+pub async fn list_all_courses(
+ session: &UdemySession,
+ portal_name: &str,
+) -> Result<Vec<UdemyCourse>> {
+ let my_courses_result = list_my_courses(session, portal_name).await;
+ let sub_courses_result = list_subscription_courses(session, portal_name).await;
+
+ if let (Err(err), Err(_)) = (&my_courses_result, &sub_courses_result) {
+ tracing::error!("[udemy-api] both course fetches failed: {}", err);
+ return Err(my_courses_result.unwrap_err());
+ }
+
+ let mut my_courses = match my_courses_result {
+ Ok(c) => c,
+ Err(e) => {
+ tracing::warn!("[udemy-api] subscribed courses failed (continuing with subscription): {}", e);
+ Vec::new()
+ }
+ };
+
+ let sub_courses = match sub_courses_result {
+ Ok(c) => c,
+ Err(e) => {
+ tracing::warn!("[udemy-api] subscription enrollments failed (continuing with subscribed): {}", e);
+ Vec::new()
+ }
+ };
+
+ let existing_ids: std::collections::HashSet<u64> = my_courses.iter().map(|c| c.id).collect();
+ for course in sub_courses {
+ if !existing_ids.contains(&course.id) {
+ my_courses.push(course);
+ }
+ }
+
+ tracing::info!("[udemy-api] total unique courses: {}", my_courses.len());
+ Ok(my_courses)
+}
+
+pub fn parse_curriculum(course_id: u64, results: &[serde_json::Value]) -> Result<UdemyCurriculum> {
+ let mut chapters: Vec<UdemyChapter> = Vec::new();
+ let mut current_chapter: Option<UdemyChapter> = None;
+ let mut total_lectures: u32 = 0;
+ let mut total_video_lectures: u32 = 0;
+ let mut drm_video_lectures: u32 = 0;
+ let mut course_title = String::new();
+
+ for item in results {
+ let class = item.get("_class").and_then(|c| c.as_str()).unwrap_or("");
+
+ match class {
+ "chapter" => {
+ if let Some(ch) = current_chapter.take() {
+ chapters.push(ch);
+ }
+
+ let id = item.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
+ let title = item.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let object_index = item.get("object_index").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
+
+ if course_title.is_empty() && !title.is_empty() {
+ course_title = title.clone();
+ }
+
+ current_chapter = Some(UdemyChapter {
+ id,
+ title,
+ object_index,
+ lectures: Vec::new(),
+ });
+ }
+ "lecture" | "quiz" | "practice" => {
+ let id = item.get("id").and_then(|v| v.as_u64()).unwrap_or(0);
+ let title = item.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string();
+ let object_index = item.get("object_index").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
+ let asset = item.get("asset").cloned();
+
+ if class == "lecture" {
+ total_lectures += 1;
+
+ if let Some(ref a) = asset {
+ let asset_type = a.get("asset_type")
+ .or_else(|| a.get("assetType"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_lowercase();
+
+ if asset_type == "video" {
+ total_video_lectures += 1;
+ let has_stream_urls = a.get("stream_urls")
+ .map(|v| !v.is_null())
+ .unwrap_or(false);
+ let has_media_sources = a.get("media_sources")
+ .map(|v| !v.is_null())
+ .unwrap_or(false);
+
+ if !has_stream_urls && has_media_sources {
+ let is_drm = a.get("course_is_drmed")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false)
+ || a.get("media_license_token").is_some();
+
+ let has_downloadable = a.get("media_sources")
+ .and_then(|v| v.as_array())
+ .map(|sources| sources.iter().any(|s| {
+ let t = s.get("type").and_then(|v| v.as_str()).unwrap_or("");
+ t == "video/mp4" || t == "application/x-mpegURL"
+ }))
+ .unwrap_or(false);
+
+ if is_drm && !has_downloadable {
+ drm_video_lectures += 1;
+ }
+ }
+ }
+ }
+ }
+
+ let lecture = UdemyLecture {
+ id,
+ title,
+ object_index,
+ lecture_class: class.to_string(),
+ asset,
+ };
+
+ if let Some(ref mut ch) = current_chapter {
+ ch.lectures.push(lecture);
+ } else {
+ let mut implicit_chapter = UdemyChapter {
+ id: 0,
+ title: "Introduction".to_string(),
+ object_index: 0,
+ lectures: Vec::new(),
+ };
+ implicit_chapter.lectures.push(lecture);
+ current_chapter = Some(implicit_chapter);
+ }
+ }
+ _ => {}
+ }
+ }
+
+ if let Some(ch) = current_chapter.take() {
+ chapters.push(ch);
+ }
+
+ tracing::info!(
+ "[udemy-api] curriculum: {} chapters, {} lectures, {} video, {} drm",
+ chapters.len(), total_lectures, total_video_lectures, drm_video_lectures
+ );
+
+ Ok(UdemyCurriculum {
+ course_id,
+ title: course_title,
+ chapters,
+ total_lectures,
+ total_video_lectures,
+ drm_video_lectures,
+ })
+}
+
+pub async fn get_course_curriculum(
+ session: &UdemySession,
+ portal_name: &str,
+ course_id: u64,
+) -> Result<UdemyCurriculum> {
+ let url = format!(
+ "https://{}.udemy.com/api-2.0/courses/{}/subscriber-curriculum-items/",
+ portal_name, course_id
+ );
+
+ let params: &[(&str, &str)] = &[
+ ("fields[lecture]", "title,object_index,asset,supplementary_assets"),
+ ("fields[quiz]", "title,object_index,type"),
+ ("fields[practice]", "title,object_index"),
+ ("fields[chapter]", "title,object_index"),
+ ("fields[asset]", "title,filename,asset_type,status,is_external,media_license_token,course_is_drmed,media_sources,captions,stream_urls,download_urls,external_url,body"),
+ ("page_size", "200"),
+ ];
+
+ tracing::info!("[udemy-api] fetching curriculum for course {}", course_id);
+
+ let data = handle_pagination(session, &url, Some(params)).await?;
+
+ let results = data.get("results")
+ .and_then(|r| r.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ parse_curriculum(course_id, &results)
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/udemy/auth.rs b/src-tauri/omniget-plugin-courses/src/platforms/udemy/auth.rs
new file mode 100644
index 00000000..7bfebb29
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/udemy/auth.rs
@@ -0,0 +1,626 @@
+#[cfg(windows)]
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+use tauri::Manager;
+
+#[derive(Clone)]
+pub struct UdemySession {
+ pub access_token: String,
+ pub email: String,
+ pub client: reqwest::Client,
+ pub cookies: Vec<(String, String)>,
+ pub portal_name: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub access_token: String,
+ pub email: String,
+ pub cookies: Vec<(String, String)>,
+ pub saved_at: u64,
+ #[serde(default = "default_portal")]
+ pub portal_name: String,
+}
+
+fn default_portal() -> String {
+ "www".into()
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir = dirs::data_dir()
+ .ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("udemy_session.json"))
+}
+
+const UDEMY_CLIENT_ID: &str = "TH96Ov3Ebo3OtgoSH5mOYzYolcowM3ycedWQDDce";
+const UDEMY_CLIENT_SECRET: &str = "f2lgDUDxjFiOlVHUpwQNFUfCQPyMO0tJQMaud53PF01UKueW8enYjeEYoyVeP0bb2XVEDkJ5GLJaVTfM5QgMVz6yyXyydZdA5QhzgvG9UmCPUYaCrIVf7VpmiilfbLJc";
+
+pub fn build_client_from_saved(saved: &SavedSession) -> anyhow::Result<reqwest::Client> {
+ if saved.portal_name != "www" {
+ return build_enterprise_client(saved);
+ }
+
+ let mut default_headers = HeaderMap::new();
+
+ if !saved.access_token.is_empty() {
+ let bearer = format!("Bearer {}", saved.access_token);
+ default_headers.insert(
+ "Authorization",
+ HeaderValue::from_str(&bearer)?,
+ );
+ default_headers.insert(
+ "X-Udemy-Authorization",
+ HeaderValue::from_str(&bearer)?,
+ );
+ }
+
+ default_headers.insert(
+ "Accept",
+ HeaderValue::from_static("application/json, text/plain, */*"),
+ );
+ default_headers.insert(
+ "x-udemy-client-id",
+ HeaderValue::from_static(UDEMY_CLIENT_ID),
+ );
+ default_headers.insert(
+ "x-udemy-client-secret",
+ HeaderValue::from_static(UDEMY_CLIENT_SECRET),
+ );
+ default_headers.insert(
+ "accept-language",
+ HeaderValue::from_static("en_US"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent("okhttp/4.12.0 UdemyAndroid 9.51.2(594) (phone)")
+ .default_headers(default_headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(300))
+ .build()?;
+
+ Ok(client)
+}
+
+fn build_enterprise_client(saved: &SavedSession) -> anyhow::Result<reqwest::Client> {
+ let mut default_headers = HeaderMap::new();
+
+ let cookie_header = saved
+ .cookies
+ .iter()
+ .map(|(name, value)| format!("{}={}", name, value))
+ .collect::<Vec<_>>()
+ .join("; ");
+
+ if !cookie_header.is_empty() {
+ default_headers.insert("Cookie", HeaderValue::from_str(&cookie_header)?);
+ }
+
+ if let Some(csrf) = saved.cookies.iter().find(|(n, _)| n == "csrftoken") {
+ default_headers.insert("X-CSRFToken", HeaderValue::from_str(&csrf.1)?);
+ }
+
+ let origin = format!("https://{}.udemy.com", saved.portal_name);
+ default_headers.insert("Referer", HeaderValue::from_str(&format!("{}/", origin))?);
+ default_headers.insert("Origin", HeaderValue::from_str(&origin)?);
+ default_headers.insert(
+ "x-requested-with",
+ HeaderValue::from_static("XMLHttpRequest"),
+ );
+ default_headers.insert(
+ "Accept",
+ HeaderValue::from_static("application/json, text/plain, */*"),
+ );
+ default_headers.insert(
+ "accept-language",
+ HeaderValue::from_static("en_US"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
+ .default_headers(default_headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(300))
+ .build()?;
+
+ Ok(client)
+}
+
+pub async fn save_session(session: &UdemySession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ access_token: session.access_token.clone(),
+ email: session.email.clone(),
+ cookies: session.cookies.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ portal_name: session.portal_name.clone(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[udemy] session saved for {}, {} cookies", session.email, session.cookies.len());
+ Ok(())
+}
+
+pub async fn load_saved_session() -> anyhow::Result<UdemySession> {
+ let path = session_file_path()?;
+ let json = tokio::fs::read_to_string(&path).await?;
+ let saved: SavedSession = serde_json::from_str(&json)?;
+
+ tracing::info!("[udemy] session loaded for {}, {} cookies", saved.email, saved.cookies.len());
+
+ let client = build_client_from_saved(&saved)?;
+
+ Ok(UdemySession {
+ access_token: saved.access_token,
+ email: saved.email,
+ cookies: saved.cookies,
+ client,
+ portal_name: saved.portal_name,
+ })
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if path.exists() {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
+
+#[cfg(windows)]
+const COOKIE_URIS: &[&str] = &[
+ "https://www.udemy.com",
+ "https://udemy.com",
+];
+
+#[cfg(windows)]
+async fn extract_webview_cookies_for_uri(
+ window: &tauri::WebviewWindow,
+ uri: &str,
+) -> anyhow::Result<Vec<(String, String)>> {
+ use webview2_com::GetCookiesCompletedHandler;
+ use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2_2;
+ use windows_core::{Interface, HSTRING, PCWSTR, PWSTR};
+
+ let (tx, rx) = tokio::sync::oneshot::channel::<Vec<(String, String)>>();
+ let uri_owned = uri.to_string();
+
+ window
+ .with_webview(move |webview| {
+ unsafe {
+ let core = webview.controller().CoreWebView2().unwrap();
+ let core2: ICoreWebView2_2 = core.cast().unwrap();
+ let manager = core2.CookieManager().unwrap();
+ let uri_hstring = HSTRING::from(uri_owned);
+
+ let _ = manager.GetCookies(
+ PCWSTR::from_raw(uri_hstring.as_ptr()),
+ &GetCookiesCompletedHandler::create(Box::new(
+ move |error_code, cookie_list| {
+ let mut result = Vec::new();
+ if error_code.is_ok() {
+ if let Some(list) = cookie_list {
+ let mut count = 0u32;
+ list.Count(&mut count)?;
+ for i in 0..count {
+ let cookie = list.GetValueAtIndex(i)?;
+ let mut name = PWSTR::null();
+ let mut value = PWSTR::null();
+ cookie.Name(&mut name)?;
+ cookie.Value(&mut value)?;
+ result.push((
+ webview2_com::take_pwstr(name),
+ webview2_com::take_pwstr(value),
+ ));
+ }
+ }
+ }
+ let _ = tx.send(result);
+ Ok(())
+ },
+ )),
+ );
+ }
+ })
+ .map_err(|e| anyhow!("{}", e))?;
+
+ let cookies = tokio::time::timeout(Duration::from_secs(10), rx)
+ .await
+ .map_err(|_| anyhow!("Timeout getting cookies from WebView"))?
+ .map_err(|_| anyhow!("Cookie channel closed"))?;
+
+ Ok(cookies)
+}
+
+#[cfg(windows)]
+async fn extract_webview_cookies(
+ window: &tauri::WebviewWindow,
+) -> anyhow::Result<Vec<(String, String)>> {
+ let mut seen = HashMap::<String, String>::new();
+
+ for uri in COOKIE_URIS {
+ match extract_webview_cookies_for_uri(window, uri).await {
+ Ok(cookies) => {
+ let names: Vec<&str> = cookies.iter().map(|(n, _)| n.as_str()).collect();
+ tracing::info!("[udemy] cookies {} → {} cookies: {:?}", uri, cookies.len(), names);
+ for (name, value) in cookies {
+ seen.insert(name, value);
+ }
+ }
+ Err(e) => {
+ tracing::warn!("[udemy] cookies {} → error: {}", uri, e);
+ }
+ }
+ }
+
+ let cookies: Vec<(String, String)> = seen.into_iter().collect();
+ tracing::info!("[udemy] total unique cookies: {}", cookies.len());
+
+ Ok(cookies)
+}
+
+#[allow(dead_code)]
+fn parse_document_cookie(s: &str) -> Vec<(String, String)> {
+ s.split(';')
+ .filter_map(|pair| {
+ let pair = pair.trim();
+ if pair.is_empty() {
+ return None;
+ }
+ let (name, value) = pair.split_once('=')?;
+ Some((name.trim().to_string(), value.trim().to_string()))
+ })
+ .collect()
+}
+
+#[cfg(not(windows))]
+async fn extract_webview_cookies_js(
+ window: &tauri::WebviewWindow,
+ cookie_data: &Arc<std::sync::Mutex<Option<String>>>,
+) -> anyhow::Result<Vec<(String, String)>> {
+ *cookie_data.lock().unwrap() = None;
+
+ window
+ .eval(
+ "window.location.href = 'https://omniget-udemy-cookie-extract.local/?cookies=' + encodeURIComponent(document.cookie)",
+ )
+ .map_err(|e| anyhow!("JS eval failed: {}", e))?;
+
+ let start = std::time::Instant::now();
+ let timeout = Duration::from_secs(5);
+ loop {
+ if let Some(cookie_str) = cookie_data.lock().unwrap().take() {
+ let cookies = parse_document_cookie(&cookie_str);
+ let names: Vec<&str> = cookies.iter().map(|(n, _)| n.as_str()).collect();
+ tracing::info!("[udemy] document.cookie → {} cookies: {:?}", cookies.len(), names);
+ return Ok(cookies);
+ }
+ if start.elapsed() > timeout {
+ tracing::warn!("[udemy] timeout waiting for document.cookie response");
+ return Ok(Vec::new());
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
+fn strip_cookie_quotes(value: &str) -> &str {
+ let v = value.trim();
+ if v.starts_with('"') && v.ends_with('"') && v.len() >= 2 {
+ &v[1..v.len() - 1]
+ } else {
+ v
+ }
+}
+
+pub async fn authenticate(
+ app: &tauri::AppHandle,
+ email: &str,
+) -> anyhow::Result<UdemySession> {
+ use tauri::Emitter;
+
+ let post_login_detected = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let post_login_flag = post_login_detected.clone();
+
+ #[cfg(not(windows))]
+ let cookie_data = Arc::new(std::sync::Mutex::new(Option::<String>::None));
+ #[cfg(not(windows))]
+ let cookie_data_nav = cookie_data.clone();
+
+ let email_json = serde_json::to_string(email)?;
+
+ let init_script = format!(
+ r#"(function() {{
+ if (window.location.hostname !== 'www.udemy.com') return;
+ var filled = false;
+ function fillEmail() {{
+ if (filled) return;
+ var input = document.querySelector('input[name="email"], input[name="Email"], input[type="email"]');
+ if (!input) return;
+ filled = true;
+ var s = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
+ s.call(input, {email_json});
+ input.dispatchEvent(new Event('input', {{ bubbles: true }}));
+ input.dispatchEvent(new Event('change', {{ bubbles: true }}));
+ setTimeout(function() {{
+ var btn = document.querySelector('button[type="submit"], form button');
+ if (btn) btn.click();
+ }}, 500);
+ }}
+ setTimeout(fillEmail, 1500);
+ setInterval(fillEmail, 500);
+ }})()"#
+ );
+
+ if let Some(existing) = app.get_webview_window("udemy-login") {
+ let _ = existing.close();
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+
+ let login_url = "https://www.udemy.com/join/passwordless-auth/?locale=en_US&next=https%3A%2F%2Fwww.udemy.com%2F&response_type=html&action=login";
+
+ let login_window = tauri::WebviewWindowBuilder::new(
+ app,
+ "udemy-login",
+ tauri::WebviewUrl::External(login_url.parse().unwrap()),
+ )
+ .title("Udemy Login")
+ .inner_size(500.0, 700.0)
+ .initialization_script(&init_script)
+ .on_navigation(move |url| {
+ let host = url.host_str().unwrap_or("");
+ let url_str = url.as_str();
+
+ tracing::info!("[udemy] navigation → {} (host={})", url_str, host);
+
+ if (host == "www.udemy.com" || host == "udemy.com")
+ && !url_str.contains("/join/")
+ && !url_str.contains("/passwordless-auth/")
+ {
+ post_login_flag.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+
+ #[cfg(not(windows))]
+ {
+ if host == "omniget-udemy-cookie-extract.local" {
+ for (key, value) in url.query_pairs() {
+ if key == "cookies" {
+ *cookie_data_nav.lock().unwrap() = Some(value.to_string());
+ break;
+ }
+ }
+ return false;
+ }
+ }
+
+ true
+ })
+ .build()
+ .map_err(|e| anyhow!("Failed to create login window: {}", e))?;
+
+ let _ = app.emit("udemy-auth-waiting-code", ());
+
+ let start = std::time::Instant::now();
+ let timeout = Duration::from_secs(180);
+ let poll_start_delay = Duration::from_secs(5);
+ let mut last_log_secs: u64 = 0;
+
+ loop {
+ if start.elapsed() > timeout {
+ let _ = login_window.close();
+ return Err(anyhow!("Timeout waiting for login. Check your email for the verification code."));
+ }
+
+ let nav_detected = post_login_detected.load(std::sync::atomic::Ordering::Relaxed);
+ let should_poll = nav_detected || start.elapsed() > poll_start_delay;
+
+ if should_poll {
+ #[cfg(windows)]
+ let cookies = extract_webview_cookies(&login_window).await?;
+ #[cfg(not(windows))]
+ let cookies = extract_webview_cookies_js(&login_window, &cookie_data).await?;
+
+ let has_access_token = cookies.iter().any(|(name, _)| name == "access_token");
+ let has_logged_in = cookies
+ .iter()
+ .any(|(name, value)| name == "ud_cache_logged_in" && value == "1");
+
+ if has_access_token || has_logged_in {
+ tracing::info!(
+ "[udemy] login detected after {:.1}s (access_token={}, ud_cache_logged_in={}, nav_detected={})",
+ start.elapsed().as_secs_f64(),
+ has_access_token,
+ has_logged_in,
+ nav_detected
+ );
+ let _ = login_window.close();
+
+ let access_token = cookies
+ .iter()
+ .find(|(name, _)| name == "access_token")
+ .map(|(_, value)| strip_cookie_quotes(value).to_string())
+ .unwrap_or_default();
+
+ let saved = SavedSession {
+ access_token: access_token.clone(),
+ email: email.to_string(),
+ cookies: cookies.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ portal_name: "www".into(),
+ };
+
+ let client = build_client_from_saved(&saved)?;
+
+ return Ok(UdemySession {
+ access_token,
+ email: email.to_string(),
+ client,
+ cookies,
+ portal_name: "www".into(),
+ });
+ }
+
+ let elapsed_secs = start.elapsed().as_secs();
+ if elapsed_secs >= last_log_secs + 5 {
+ last_log_secs = elapsed_secs;
+ let cookie_names: Vec<&str> =
+ cookies.iter().map(|(n, _)| n.as_str()).collect();
+ tracing::info!(
+ "[udemy] polling at {}s, {} cookies: {:?}",
+ elapsed_secs,
+ cookies.len(),
+ cookie_names
+ );
+ }
+ }
+
+ let sleep_ms = if nav_detected { 500 } else { 2000 };
+ tokio::time::sleep(Duration::from_millis(sleep_ms)).await;
+ }
+}
+
+pub async fn authenticate_with_cookie_json(cookie_json_str: &str) -> anyhow::Result<UdemySession> {
+ #[derive(Deserialize)]
+ struct CookieEntry {
+ name: String,
+ value: String,
+ #[allow(dead_code)]
+ domain: Option<String>,
+ }
+
+ #[derive(Deserialize)]
+ struct CookieExport {
+ url: Option<String>,
+ cookies: Vec<CookieEntry>,
+ }
+
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ enum CookieInput {
+ Export(CookieExport),
+ CookieArray(Vec<CookieEntry>),
+ }
+
+ let input: CookieInput = serde_json::from_str(cookie_json_str).map_err(|e| anyhow!("Invalid cookie JSON: {}", e))?;
+
+ let export = match input {
+ CookieInput::Export(export) => export,
+ CookieInput::CookieArray(cookies) => CookieExport { url: None, cookies },
+ };
+
+ if export.cookies.is_empty() {
+ return Err(anyhow!("No cookies provided"));
+ }
+
+ // Detect portal from URL or cookie domains
+ let portal_name = if let Some(ref url) = export.url {
+ detect_portal_from_url(url)
+ } else {
+ export
+ .cookies
+ .iter()
+ .filter_map(|c| c.domain.as_deref())
+ .find_map(|d| {
+ let d = d.trim_start_matches('.');
+ d.strip_suffix(".udemy.com")
+ .map(|sub| sub.to_string())
+ })
+ .unwrap_or_else(|| "www".into())
+ };
+
+ let cookies: Vec<(String, String)> = export
+ .cookies
+ .iter()
+ .map(|c| (c.name.clone(), c.value.clone()))
+ .collect();
+
+ let access_token = cookies
+ .iter()
+ .find(|(name, _)| name == "access_token")
+ .map(|(_, value)| strip_cookie_quotes(value).to_string())
+ .unwrap_or_default();
+
+ // Try to extract email from ud_user_jwt cookie (base64url-encoded JWT)
+ let email = cookies
+ .iter()
+ .find(|(name, _)| name == "ud_user_jwt")
+ .and_then(|(_, value)| decode_jwt_email(value))
+ .unwrap_or_else(|| format!("enterprise@{}.udemy.com", portal_name));
+
+ let saved = SavedSession {
+ access_token: access_token.clone(),
+ email: email.clone(),
+ cookies: cookies.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ portal_name: portal_name.clone(),
+ };
+
+ let client = build_client_from_saved(&saved)?;
+
+ tracing::info!(
+ "[udemy] cookie login for portal={}, email={}, {} cookies",
+ portal_name,
+ email,
+ cookies.len()
+ );
+
+ Ok(UdemySession {
+ access_token,
+ email,
+ client,
+ cookies,
+ portal_name,
+ })
+}
+
+fn detect_portal_from_url(url: &str) -> String {
+ url::Url::parse(url)
+ .ok()
+ .and_then(|u| u.host_str().map(|h| h.to_string()))
+ .and_then(|host| {
+ host.strip_suffix(".udemy.com")
+ .map(|sub| sub.to_string())
+ })
+ .unwrap_or_else(|| "www".into())
+}
+
+fn decode_jwt_email(jwt: &str) -> Option<String> {
+ use base64::Engine;
+
+ // JWT has 3 parts: header.payload.signature
+ let parts: Vec<&str> = jwt.split('.').collect();
+ if parts.len() < 2 {
+ return None;
+ }
+
+ let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
+ .decode(parts[1])
+ .or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(parts[1]))
+ .ok()?;
+
+ let claims: serde_json::Value = serde_json::from_slice(&payload).ok()?;
+ claims
+ .get("email")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/udemy/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/udemy/downloader.rs
new file mode 100644
index 00000000..709909e6
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/udemy/downloader.rs
@@ -0,0 +1,719 @@
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use futures::StreamExt;
+use tokio::sync::{mpsc, Mutex};
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::media_processor::MediaProcessor;
+
+use super::api::{self, UdemyCourse};
+use super::auth::UdemySession;
+
+const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0";
+const MAX_FILENAME_BYTES: usize = 200;
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct UdemyCourseDownloadProgress {
+ pub course_id: u64,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_chapter: String,
+ pub current_lecture: String,
+ pub downloaded_bytes: u64,
+ pub total_lectures: u32,
+ pub completed_lectures: u32,
+}
+
+pub struct UdemyDownloader {
+ session: Arc<Mutex<Option<UdemySession>>>,
+ hls_client: reqwest::Client,
+ max_concurrent_segments: u32,
+ max_retries: u32,
+}
+
+fn safe_filename(name: &str) -> String {
+ let sanitized = sanitize_filename::sanitize(name);
+ if sanitized.len() <= MAX_FILENAME_BYTES {
+ return sanitized;
+ }
+ let mut end = MAX_FILENAME_BYTES;
+ while !sanitized.is_char_boundary(end) && end > 0 {
+ end -= 1;
+ }
+ sanitized[..end].to_string()
+}
+
+impl UdemyDownloader {
+ pub fn new(
+ session: Arc<Mutex<Option<UdemySession>>>,
+ max_concurrent_segments: u32,
+ max_retries: u32,
+ ) -> Self {
+ let hls_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(300))
+ .build()
+ .unwrap_or_default();
+
+ Self {
+ session,
+ hls_client,
+ max_concurrent_segments,
+ max_retries,
+ }
+ }
+
+ pub async fn download_full_course(
+ &self,
+ course: &UdemyCourse,
+ output_dir: &str,
+ curriculum: api::UdemyCurriculum,
+ progress_tx: mpsc::Sender<UdemyCourseDownloadProgress>,
+ cancel_token: CancellationToken,
+ ) -> anyhow::Result<u32> {
+ let session = {
+ let guard = self.session.lock().await;
+ guard.clone().ok_or_else(|| anyhow!("Not authenticated"))?
+ };
+
+ let _ = progress_tx.send(UdemyCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.title.clone(),
+ percent: 0.0,
+ current_chapter: String::new(),
+ current_lecture: String::new(),
+ downloaded_bytes: 0,
+ total_lectures: curriculum.total_lectures,
+ completed_lectures: 0,
+ }).await;
+
+ let course_dir_name = safe_filename(&course.title);
+ let course_dir = PathBuf::from(output_dir).join(&course_dir_name);
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ let total_lectures = curriculum.total_lectures;
+ let mut completed_lectures: u32 = 0;
+ let mut downloaded_bytes: u64 = 0;
+ let mut drm_skipped: u32 = 0;
+
+ for (ch_idx, chapter) in curriculum.chapters.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled"));
+ }
+
+ let chapter_dir_name = format!(
+ "{:02} - {}",
+ ch_idx + 1,
+ safe_filename(&chapter.title)
+ );
+ let chapter_dir = course_dir.join(&chapter_dir_name);
+ tokio::fs::create_dir_all(&chapter_dir).await?;
+
+ for (lec_idx, lecture) in chapter.lectures.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled"));
+ }
+
+ let lecture_num = (lec_idx + 1) as u32;
+
+ let _ = progress_tx.send(UdemyCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.title.clone(),
+ percent: if total_lectures > 0 {
+ (completed_lectures as f64 / total_lectures as f64) * 100.0
+ } else {
+ 0.0
+ },
+ current_chapter: chapter.title.clone(),
+ current_lecture: format!("{}/{} - {}", lecture_num, chapter.lectures.len(), lecture.title),
+ downloaded_bytes,
+ total_lectures,
+ completed_lectures,
+ }).await;
+
+ let result = self.download_lecture(
+ &session,
+ lecture,
+ &chapter_dir,
+ &cancel_token,
+ lecture_num,
+ ).await;
+
+ match result {
+ Ok((b, drm)) => {
+ downloaded_bytes += b;
+ drm_skipped += drm;
+ }
+ Err(e) => {
+ tracing::error!(
+ "[udemy] failed to download lecture '{}': {}",
+ lecture.title, e
+ );
+ }
+ }
+
+ if lecture.lecture_class == "lecture" {
+ completed_lectures += 1;
+ }
+ }
+ }
+
+ let _ = progress_tx.send(UdemyCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.title.clone(),
+ percent: 100.0,
+ current_chapter: String::new(),
+ current_lecture: String::new(),
+ downloaded_bytes,
+ total_lectures,
+ completed_lectures,
+ }).await;
+
+ tracing::info!(
+ "[udemy] course '{}' download complete: {} lectures, {} bytes, {} drm-skipped",
+ course.title, completed_lectures, downloaded_bytes, drm_skipped
+ );
+
+ Ok(drm_skipped)
+ }
+
+ async fn download_lecture(
+ &self,
+ session: &UdemySession,
+ lecture: &api::UdemyLecture,
+ chapter_dir: &Path,
+ cancel_token: &CancellationToken,
+ lecture_num: u32,
+ ) -> anyhow::Result<(u64, u32)> {
+ if lecture.lecture_class == "quiz" || lecture.lecture_class == "practice" {
+ tracing::info!("[udemy] skipping {}: {}", lecture.lecture_class, lecture.title);
+ return Ok((0, 0));
+ }
+
+ let asset = match &lecture.asset {
+ Some(a) => a,
+ None => return Ok((0, 0)),
+ };
+
+ let asset_type = asset.get("asset_type")
+ .or_else(|| asset.get("assetType"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_lowercase();
+
+ let mut total_bytes: u64 = 0;
+ let mut drm_skipped: u32 = 0;
+
+ match asset_type.as_str() {
+ "video" => {
+ let (bytes, drm) = self.download_video_asset(
+ session, asset, &lecture.title, chapter_dir, cancel_token, lecture_num
+ ).await?;
+ total_bytes += bytes;
+ drm_skipped += drm;
+ }
+ "article" => {
+ let body = asset.get("body").and_then(|v| v.as_str()).unwrap_or("");
+ if !body.is_empty() {
+ let file_name = format!(
+ "{:02} - {}.html",
+ lecture_num,
+ safe_filename(&lecture.title)
+ );
+ let file_path = chapter_dir.join(&file_name);
+ if !file_exists_with_content(&file_path).await {
+ tokio::fs::write(&file_path, body.as_bytes()).await?;
+ tracing::info!("[udemy] saved article: {}", file_name);
+ }
+ }
+ }
+ "file" | "e-book" | "presentation" | "audio" => {
+ total_bytes += self.download_downloadable_asset(
+ session, asset, &lecture.title, chapter_dir, lecture_num
+ ).await?;
+ }
+ _ => {
+ if !asset_type.is_empty() {
+ tracing::warn!("[udemy] unknown asset type '{}' for '{}'", asset_type, lecture.title);
+ }
+ }
+ }
+
+ let captions = asset.get("captions").and_then(|v| v.as_array());
+ if let Some(tracks) = captions {
+ for track in tracks {
+ let class = track.get("_class").and_then(|v| v.as_str()).unwrap_or("");
+ if class != "caption" {
+ continue;
+ }
+ let url = match track.get("url").and_then(|v| v.as_str()) {
+ Some(u) => u,
+ None => continue,
+ };
+ let lang = track.get("language")
+ .or_else(|| track.get("srclang"))
+ .or_else(|| track.get("label"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("unknown");
+
+ let ext = if url.contains(".vtt") { "vtt" } else { "srt" };
+ let caption_name = format!(
+ "{:02} - {}_{}.{}",
+ lecture_num,
+ safe_filename(&lecture.title),
+ lang,
+ ext
+ );
+ let caption_path = chapter_dir.join(&caption_name);
+
+ if !file_exists_with_content(&caption_path).await {
+ match download_file_simple(&session.client, url, &caption_path).await {
+ Ok(b) => {
+ total_bytes += b;
+ tracing::info!("[udemy] saved caption: {}", caption_name);
+ }
+ Err(e) => {
+ tracing::warn!("[udemy] failed to download caption '{}': {}", caption_name, e);
+ }
+ }
+ }
+ }
+ }
+
+ let supp_assets = asset.get("supplementary_assets").and_then(|v| v.as_array());
+ if let Some(assets) = supp_assets {
+ for supp in assets {
+ total_bytes += self.download_supplementary_asset(
+ session, supp, chapter_dir, lecture_num
+ ).await.unwrap_or(0);
+ }
+ }
+
+ Ok((total_bytes, drm_skipped))
+ }
+
+ async fn download_video_asset(
+ &self,
+ session: &UdemySession,
+ asset: &serde_json::Value,
+ title: &str,
+ chapter_dir: &Path,
+ cancel_token: &CancellationToken,
+ lecture_num: u32,
+ ) -> anyhow::Result<(u64, u32)> {
+ let file_name = format!("{:02} - {}.mp4", lecture_num, safe_filename(title));
+ let file_path = chapter_dir.join(&file_name);
+
+ if file_exists_with_content(&file_path).await {
+ tracing::info!("[udemy] skipping existing video: {}", file_name);
+ return Ok((0, 0));
+ }
+
+ let stream_urls = asset.get("stream_urls");
+ if let Some(streams) = stream_urls {
+ if let Some(videos) = streams.get("Video").and_then(|v| v.as_array()) {
+ match self.download_from_stream_urls(
+ session, videos, &file_path, title, cancel_token
+ ).await {
+ Ok(bytes) => return Ok((bytes, 0)),
+ Err(e) if e.to_string().contains("SAMPLE-AES") => {
+ tracing::warn!("[udemy] DRM-protected (SAMPLE-AES) via stream_urls: '{}'", title);
+ return Ok((0, 1));
+ }
+ Err(e) => return Err(e),
+ }
+ }
+ }
+
+ if let Some(sources) = asset.get("media_sources").and_then(|v| v.as_array()) {
+ let result = self.download_from_media_sources(
+ session, sources, &file_path, title, cancel_token
+ ).await;
+
+ match result {
+ Ok(bytes) if bytes > 0 => return Ok((bytes, 0)),
+ Ok(_) => {}
+ Err(e) => {
+ let is_drm = asset.get("course_is_drmed")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ if is_drm || e.to_string().contains("SAMPLE-AES") {
+ tracing::warn!("[udemy] DRM-protected video skipped: '{}'", title);
+ return Ok((0, 1));
+ }
+ tracing::warn!("[udemy] media_sources download failed for '{}': {}", title, e);
+ return Err(e);
+ }
+ }
+
+ let is_drm = asset.get("course_is_drmed")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ if is_drm {
+ tracing::warn!(
+ "[udemy] DRM-protected video skipped: '{}' (no downloadable sources available)",
+ title
+ );
+ return Ok((0, 1));
+ }
+
+ tracing::warn!(
+ "[udemy] no usable video sources in media_sources for '{}' (types: {})",
+ title,
+ sources.iter()
+ .filter_map(|s| s.get("type").and_then(|t| t.as_str()))
+ .collect::<Vec<_>>()
+ .join(", ")
+ );
+ return Ok((0, 0));
+ }
+
+ tracing::warn!("[udemy] no video sources found for '{}'", title);
+ Ok((0, 0))
+ }
+
+ async fn download_from_stream_urls(
+ &self,
+ session: &UdemySession,
+ videos: &[serde_json::Value],
+ file_path: &Path,
+ title: &str,
+ cancel_token: &CancellationToken,
+ ) -> anyhow::Result<u64> {
+ let mut sources: Vec<(&str, u32)> = Vec::new();
+ for v in videos {
+ let label = v.get("label").and_then(|l| l.as_str()).unwrap_or("0");
+ let url = match v.get("file").and_then(|f| f.as_str()) {
+ Some(u) => u,
+ None => continue,
+ };
+ if label.to_lowercase() == "audio" {
+ continue;
+ }
+ let height: u32 = label.parse().unwrap_or(0);
+ sources.push((url, height));
+ }
+
+ if sources.is_empty() {
+ tracing::warn!("[udemy] no valid video sources for '{}'", title);
+ return Ok(0);
+ }
+
+ sources.sort_by(|a, b| b.1.cmp(&a.1));
+ let (best_url, best_height) = sources[0];
+
+ tracing::info!("[udemy] downloading '{}' at {}p", title, best_height);
+
+ let url_str = best_url.to_string();
+ let is_hls = url_str.contains(".m3u8");
+
+ if is_hls {
+ self.download_hls_and_remux(&url_str, file_path, title, cancel_token).await
+ } else {
+ let bytes = download_file_simple(&session.client, &url_str, file_path).await?;
+ tracing::info!("[udemy] direct download complete: {} ({}p, {} bytes)", title, best_height, bytes);
+ Ok(bytes)
+ }
+ }
+
+ async fn download_from_media_sources(
+ &self,
+ session: &UdemySession,
+ sources: &[serde_json::Value],
+ file_path: &Path,
+ title: &str,
+ cancel_token: &CancellationToken,
+ ) -> anyhow::Result<u64> {
+ let mut mp4_sources: Vec<(&str, u32)> = Vec::new();
+ let mut hls_source: Option<&str> = None;
+
+ for source in sources {
+ let src = match source.get("src").and_then(|v| v.as_str()) {
+ Some(s) => s,
+ None => continue,
+ };
+ let media_type = source.get("type").and_then(|v| v.as_str()).unwrap_or("");
+
+ match media_type {
+ "video/mp4" => {
+ let label = source.get("label").and_then(|v| v.as_str()).unwrap_or("0");
+ let height: u32 = label.parse().unwrap_or(0);
+ mp4_sources.push((src, height));
+ }
+ "application/x-mpegURL" => {
+ if hls_source.is_none() {
+ hls_source = Some(src);
+ }
+ }
+ _ => {}
+ }
+ }
+
+ if !mp4_sources.is_empty() {
+ mp4_sources.sort_by(|a, b| b.1.cmp(&a.1));
+ let (best_url, best_height) = mp4_sources[0];
+
+ tracing::info!("[udemy] downloading '{}' at {}p (via media_sources mp4)", title, best_height);
+
+ let bytes = download_file_simple(&session.client, best_url, file_path).await?;
+ tracing::info!("[udemy] direct download complete: {} ({}p, {} bytes)", title, best_height, bytes);
+ return Ok(bytes);
+ }
+
+ if let Some(hls_url) = hls_source {
+ tracing::info!("[udemy] downloading '{}' via HLS (media_sources)", title);
+ return self.download_hls_and_remux(hls_url, file_path, title, cancel_token).await;
+ }
+
+ Ok(0)
+ }
+
+ async fn download_hls_and_remux(
+ &self,
+ hls_url: &str,
+ file_path: &Path,
+ title: &str,
+ cancel_token: &CancellationToken,
+ ) -> anyhow::Result<u64> {
+ let temp_ts_path = file_path.with_extension("ts");
+ let output_str_ts = temp_ts_path.to_string_lossy().to_string();
+ let output_str_mp4 = file_path.to_string_lossy().to_string();
+
+ let result = MediaProcessor::download_hls(
+ hls_url,
+ &output_str_ts,
+ "https://www.udemy.com/",
+ None,
+ cancel_token.clone(),
+ self.max_concurrent_segments,
+ self.max_retries,
+ Some(self.hls_client.clone()),
+ ).await;
+
+ match result {
+ Ok(r) => {
+ tracing::info!("[udemy] HLS download complete ({} bytes), remuxing...", r.file_size);
+ if let Err(e) = MediaProcessor::remux(&output_str_ts, &output_str_mp4).await {
+ tracing::error!("[udemy] Remuxing failed: {}", e);
+ let _ = tokio::fs::remove_file(&temp_ts_path).await;
+ return Err(e);
+ }
+ let _ = tokio::fs::remove_file(&temp_ts_path).await;
+ let final_size = tokio::fs::metadata(file_path).await?.len();
+ tracing::info!("[udemy] Remux complete: {}", title);
+ Ok(final_size)
+ }
+ Err(e) => {
+ let _ = tokio::fs::remove_file(&temp_ts_path).await;
+ Err(e)
+ }
+ }
+ }
+
+ async fn download_downloadable_asset(
+ &self,
+ session: &UdemySession,
+ asset: &serde_json::Value,
+ title: &str,
+ chapter_dir: &Path,
+ lecture_num: u32,
+ ) -> anyhow::Result<u64> {
+ let filename = asset.get("filename")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ let download_url = asset.get("download_urls")
+ .and_then(|d| {
+ if let Some(obj) = d.as_object() {
+ for (_key, val) in obj {
+ if let Some(arr) = val.as_array() {
+ if let Some(first) = arr.first() {
+ if let Some(url) = first.get("file").and_then(|f| f.as_str()) {
+ return Some(url.to_string());
+ }
+ }
+ }
+ }
+ }
+ None
+ });
+
+ let url = match download_url {
+ Some(u) => u,
+ None => {
+ tracing::warn!("[udemy] no download URL for asset '{}'", title);
+ return Ok(0);
+ }
+ };
+
+ let safe_name = if filename.is_empty() {
+ format!("{:02} - {}.bin", lecture_num, safe_filename(title))
+ } else {
+ format!("{:02} - {}", lecture_num, safe_filename(filename))
+ };
+
+ let file_path = chapter_dir.join(&safe_name);
+
+ if file_exists_with_content(&file_path).await {
+ tracing::info!("[udemy] skipping existing file: {}", safe_name);
+ return Ok(0);
+ }
+
+ match download_file_simple(&session.client, &url, &file_path).await {
+ Ok(b) => {
+ tracing::info!("[udemy] downloaded asset: {}", safe_name);
+ Ok(b)
+ }
+ Err(e) => {
+ tracing::error!("[udemy] failed to download '{}': {}", safe_name, e);
+ Ok(0)
+ }
+ }
+ }
+
+ async fn download_supplementary_asset(
+ &self,
+ session: &UdemySession,
+ supp: &serde_json::Value,
+ chapter_dir: &Path,
+ lecture_num: u32,
+ ) -> anyhow::Result<u64> {
+ let asset_type = supp.get("asset_type")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_lowercase();
+ let filename = supp.get("filename")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ let title = supp.get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ match asset_type.as_str() {
+ "file" | "sourcecode" => {
+ let download_url = supp.get("download_urls")
+ .and_then(|d| {
+ if let Some(obj) = d.as_object() {
+ for (_key, val) in obj {
+ if let Some(arr) = val.as_array() {
+ if let Some(first) = arr.first() {
+ return first.get("file").and_then(|f| f.as_str()).map(|s| s.to_string());
+ }
+ }
+ }
+ }
+ None
+ });
+
+ let url = match download_url {
+ Some(u) => u,
+ None => return Ok(0),
+ };
+
+ let base = if filename.is_empty() {
+ safe_filename(title)
+ } else {
+ safe_filename(filename)
+ };
+ let safe_name = format!("{:02} - {}", lecture_num, base);
+ let file_path = chapter_dir.join(&safe_name);
+
+ if file_exists_with_content(&file_path).await {
+ return Ok(0);
+ }
+
+ download_file_simple(&session.client, &url, &file_path).await.ok();
+ }
+ "externallink" => {
+ let external_url = supp.get("external_url")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if !external_url.is_empty() {
+ let base = if filename.is_empty() {
+ safe_filename(title)
+ } else {
+ safe_filename(filename)
+ };
+ let safe_name = format!("{:02} - {}.url", lecture_num, base);
+ let file_path = chapter_dir.join(&safe_name);
+ if !file_exists_with_content(&file_path).await {
+ let content = format!("[InternetShortcut]\nURL={}", external_url);
+ tokio::fs::write(&file_path, content.as_bytes()).await?;
+ }
+ }
+ }
+ _ => {}
+ }
+
+ Ok(0)
+ }
+}
+
+async fn file_exists_with_content(path: &Path) -> bool {
+ match tokio::fs::metadata(path).await {
+ Ok(m) => m.len() > 0,
+ Err(_) => false,
+ }
+}
+
+async fn download_file_simple(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &Path,
+) -> anyhow::Result<u64> {
+ let part_path = output_path.with_extension(
+ format!(
+ "{}.part",
+ output_path.extension().unwrap_or_default().to_string_lossy()
+ )
+ );
+
+ let result = download_file_inner(client, url, output_path, &part_path).await;
+ if result.is_err() {
+ let _ = tokio::fs::remove_file(&part_path).await;
+ }
+ result
+}
+
+async fn download_file_inner(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &Path,
+ part_path: &Path,
+) -> anyhow::Result<u64> {
+ let resp = client.get(url)
+ .timeout(Duration::from_secs(600))
+ .send()
+ .await
+ .map_err(|e| anyhow!("Download request failed: {}", e))?;
+
+ let status = resp.status();
+ if !status.is_success() {
+ if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
+ return Err(anyhow!("Auth error ({}), session may have expired", status));
+ }
+ return Err(anyhow!("Download returned status {}", status));
+ }
+
+ let mut total: u64 = 0;
+ let mut stream = resp.bytes_stream();
+ let mut file = tokio::fs::File::create(part_path).await?;
+
+ while let Some(chunk) = stream.next().await {
+ let chunk = chunk.map_err(|e| anyhow!("Stream error: {}", e))?;
+ tokio::io::AsyncWriteExt::write_all(&mut file, &chunk).await?;
+ total += chunk.len() as u64;
+ }
+
+ tokio::io::AsyncWriteExt::flush(&mut file).await?;
+ drop(file);
+
+ tokio::fs::rename(part_path, output_path).await?;
+
+ Ok(total)
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/udemy/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/udemy/mod.rs
new file mode 100644
index 00000000..40571cdd
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/udemy/mod.rs
@@ -0,0 +1,4 @@
+pub mod auth;
+pub mod api;
+pub mod downloader;
+pub mod webview_api;
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/udemy/webview_api.rs b/src-tauri/omniget-plugin-courses/src/platforms/udemy/webview_api.rs
new file mode 100644
index 00000000..c8261c35
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/udemy/webview_api.rs
@@ -0,0 +1,103 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use tauri::Manager;
+
+pub async fn ensure_api_webview(
+ app: &tauri::AppHandle,
+ result_store: &Arc<std::sync::Mutex<Option<String>>>,
+ portal_name: &str,
+) -> anyhow::Result<tauri::WebviewWindow> {
+ if let Some(existing) = app.get_webview_window("udemy-api") {
+ return Ok(existing);
+ }
+
+ let store = result_store.clone();
+ let base_url = format!("https://{}.udemy.com/", portal_name);
+
+ let window = tauri::WebviewWindowBuilder::new(
+ app,
+ "udemy-api",
+ tauri::WebviewUrl::External(base_url.parse().unwrap()),
+ )
+ .visible(false)
+ .inner_size(100.0, 100.0)
+ .initialization_script(
+ r#"window.__omniget_fetch = function(url) {
+ fetch(url, {
+ credentials: 'include',
+ headers: {
+ 'Accept': 'application/json, text/plain, */*',
+ 'X-Requested-With': 'XMLHttpRequest'
+ }
+ })
+ .then(function(r) { return r.text() })
+ .then(function(text) {
+ window.location.href = 'https://omniget-api-result.local/?data=' + encodeURIComponent(text);
+ })
+ .catch(function(err) {
+ window.location.href = 'https://omniget-api-result.local/?error=' + encodeURIComponent(err.message);
+ });
+ };"#,
+ )
+ .on_navigation(move |url| {
+ if url.host_str() == Some("omniget-api-result.local") {
+ for (key, value) in url.query_pairs() {
+ if key == "data" {
+ *store.lock().unwrap() = Some(value.to_string());
+ return false;
+ }
+ if key == "error" {
+ *store.lock().unwrap() =
+ Some(format!("{{\"__fetch_error\":\"{}\"}}", value));
+ return false;
+ }
+ }
+ return false;
+ }
+ true
+ })
+ .build()
+ .map_err(|e| anyhow!("Failed to create API webview: {}", e))?;
+
+ tokio::time::sleep(Duration::from_secs(3)).await;
+
+ Ok(window)
+}
+
+pub async fn webview_get(
+ window: &tauri::WebviewWindow,
+ url: &str,
+ result_store: &Arc<std::sync::Mutex<Option<String>>>,
+) -> anyhow::Result<String> {
+ *result_store.lock().unwrap() = None;
+
+ let js = format!("window.__omniget_fetch('{}')", url);
+ window
+ .eval(&js)
+ .map_err(|e| anyhow!("eval failed: {}", e))?;
+
+ let start = std::time::Instant::now();
+ let timeout = Duration::from_secs(90);
+ let mut poll_interval = 100u64;
+ loop {
+ if let Some(data) = result_store.lock().unwrap().take() {
+ if let Some(err_msg) = data.strip_prefix("{\"__fetch_error\":\"") {
+ let err_msg = err_msg.trim_end_matches("\"}");
+ return Err(anyhow!("Fetch error: {}", err_msg));
+ }
+ return Ok(data);
+ }
+ if start.elapsed() > timeout {
+ return Err(anyhow!(
+ "Timeout waiting for API response ({}s). The page may be blocked by Cloudflare or the server is slow.",
+ timeout.as_secs()
+ ));
+ }
+ tokio::time::sleep(Duration::from_millis(poll_interval)).await;
+ if poll_interval < 500 {
+ poll_interval = (poll_interval * 3 / 2).min(500);
+ }
+ }
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/voompplay/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/voompplay/api.rs
new file mode 100644
index 00000000..8ff9fa8e
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/voompplay/api.rs
@@ -0,0 +1,419 @@
+use std::path::PathBuf;
+use std::time::Duration;
+
+use anyhow::anyhow;
+use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
+
+const USER_AGENT: &str = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0";
+
+#[derive(Clone)]
+pub struct VoompSession {
+ pub token: String,
+ pub client: reqwest::Client,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SavedSession {
+ pub token: String,
+ pub saved_at: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct VoompCourse {
+ pub id: i64,
+ pub name: String,
+ pub lessons_count: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct VoompModule {
+ pub id: i64,
+ pub name: String,
+ pub order: i64,
+ pub lessons: Vec<VoompLesson>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct VoompLesson {
+ pub id: i64,
+ pub name: String,
+ pub order: i64,
+ pub media_type: Option<String>,
+ pub source: Option<String>,
+ pub content: Option<String>,
+ pub duration: Option<f64>,
+ pub attachments: Vec<VoompAttachment>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct VoompAttachment {
+ pub url: String,
+ pub name: String,
+ pub size: Option<u64>,
+}
+
+fn build_client(token: &str) -> anyhow::Result<reqwest::Client> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "Authorization",
+ HeaderValue::from_str(token)?,
+ );
+ headers.insert("Accept", HeaderValue::from_static("application/json"));
+ headers.insert(
+ "Origin",
+ HeaderValue::from_static("https://voompplay.com.br"),
+ );
+ headers.insert(
+ "Referer",
+ HeaderValue::from_static("https://voompplay.com.br/"),
+ );
+
+ let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .default_headers(headers)
+ .redirect(reqwest::redirect::Policy::limited(10))
+ .connect_timeout(Duration::from_secs(30))
+ .timeout(Duration::from_secs(120))
+ .build()?;
+
+ Ok(client)
+}
+
+fn session_file_path() -> anyhow::Result<PathBuf> {
+ let data_dir =
+ dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
+ Ok(data_dir.join("omniget").join("voomp_session.json"))
+}
+
+pub async fn validate_token(session: &VoompSession) -> anyhow::Result<bool> {
+ let resp = session
+ .client
+ .get("https://api.voompplay.com.br/member/me")
+ .send()
+ .await?;
+
+ Ok(resp.status().is_success())
+}
+
+pub async fn list_courses(session: &VoompSession) -> anyhow::Result<Vec<VoompCourse>> {
+ let mut all_courses = Vec::new();
+ let mut page = 1u32;
+
+ loop {
+ let url = format!(
+ "https://api.voompplay.com.br/member/me/all-courses?page={}",
+ page
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "list_courses returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let last_page = body
+ .get("meta")
+ .and_then(|m| m.get("last_page"))
+ .and_then(|v| v.as_u64())
+ .unwrap_or(1) as u32;
+
+ let courses_obj = body
+ .get("courses")
+ .and_then(|v| v.as_object());
+
+ if let Some(sites) = courses_obj {
+ for (_site_name, courses_val) in sites {
+ let courses_arr = match courses_val.as_array() {
+ Some(arr) => arr,
+ None => continue,
+ };
+
+ for item in courses_arr {
+ let has_access = item
+ .get("has_access")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ if !has_access {
+ continue;
+ }
+
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let lessons_count = item
+ .get("lessons_count")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ all_courses.push(VoompCourse {
+ id,
+ name,
+ lessons_count,
+ });
+ }
+ }
+ }
+
+ if page >= last_page {
+ break;
+ }
+
+ page += 1;
+ }
+
+ Ok(all_courses)
+}
+
+pub async fn get_modules(
+ session: &VoompSession,
+ course_id: i64,
+) -> anyhow::Result<Vec<VoompModule>> {
+ let url = format!(
+ "https://api.voompplay.com.br/course/{}/watch?data[]=course&data[]=modules",
+ course_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_modules returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let modules_arr = body
+ .get("modules")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut modules = Vec::new();
+
+ for item in &modules_arr {
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let order = item
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ modules.push(VoompModule {
+ id,
+ name,
+ order,
+ lessons: Vec::new(),
+ });
+ }
+
+ modules.sort_by_key(|m| m.order);
+
+ Ok(modules)
+}
+
+pub async fn get_lessons(
+ session: &VoompSession,
+ course_id: i64,
+ module_id: i64,
+) -> anyhow::Result<Vec<VoompLesson>> {
+ let url = format!(
+ "https://api.voompplay.com.br/course/{}/watch?data[]=currentModuleLessons&current_module_id={}",
+ course_id, module_id
+ );
+
+ let resp = session.client.get(&url).send().await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+
+ if !status.is_success() {
+ return Err(anyhow!(
+ "get_lessons returned status {}: {}",
+ status,
+ &body_text[..body_text.len().min(300)]
+ ));
+ }
+
+ let body: serde_json::Value = serde_json::from_str(&body_text)?;
+
+ let lessons_arr = body
+ .get("currentModuleLessons")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut lessons = Vec::new();
+
+ for item in &lessons_arr {
+ let id = item
+ .get("id")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let name = item
+ .get("title")
+ .or_else(|| item.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+
+ let order = item
+ .get("order")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0);
+
+ let media_type = item
+ .get("mediaType")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let source = item
+ .get("source")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let content = item
+ .get("content")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let duration = item
+ .get("duration")
+ .and_then(|v| v.as_f64());
+
+ let attachments = item
+ .get("attachments")
+ .and_then(|v| v.as_array())
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|a| {
+ let url = a
+ .get("cdn_url")
+ .or_else(|| a.get("path"))
+ .and_then(|v| v.as_str())?
+ .to_string();
+
+ let att_name = a
+ .get("title")
+ .or_else(|| a.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("attachment")
+ .to_string();
+
+ let size = a
+ .get("size")
+ .and_then(|v| v.as_u64());
+
+ Some(VoompAttachment {
+ url,
+ name: att_name,
+ size,
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+
+ lessons.push(VoompLesson {
+ id,
+ name,
+ order,
+ media_type,
+ source,
+ content,
+ duration,
+ attachments,
+ });
+ }
+
+ lessons.sort_by_key(|l| l.order);
+
+ Ok(lessons)
+}
+
+pub fn extract_panda_video_id(source: &str) -> Option<String> {
+ let re = regex::Regex::new(r"[?&]v=([a-f0-9-]+)").ok()?;
+ re.captures(source).map(|c| c[1].to_string())
+}
+
+pub async fn save_session(session: &VoompSession) -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if let Some(parent) = path.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+
+ let saved = SavedSession {
+ token: session.token.clone(),
+ saved_at: std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs(),
+ };
+
+ let json = serde_json::to_string_pretty(&saved)?;
+ tokio::fs::write(&path, json).await?;
+ tracing::info!("[voomp] session saved");
+ Ok(())
+}
+
+pub async fn load_session() -> anyhow::Result<Option<VoompSession>> {
+ let path = session_file_path()?;
+ let json = match tokio::fs::read_to_string(&path).await {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ };
+
+ let saved: SavedSession = serde_json::from_str(&json)?;
+ let client = build_client(&saved.token)?;
+
+ tracing::info!("[voomp] session loaded");
+
+ Ok(Some(VoompSession {
+ token: saved.token,
+ client,
+ }))
+}
+
+pub async fn delete_saved_session() -> anyhow::Result<()> {
+ let path = session_file_path()?;
+ if tokio::fs::try_exists(&path).await.unwrap_or(false) {
+ tokio::fs::remove_file(&path).await?;
+ }
+ Ok(())
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/voompplay/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/voompplay/downloader.rs
new file mode 100644
index 00000000..7612f42c
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/voompplay/downloader.rs
@@ -0,0 +1,342 @@
+use std::path::Path;
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use tauri::Emitter;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use omniget_core::core::filename;
+
+use super::api::{self, VoompCourse, VoompSession};
+
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct VoompCourseDownloadProgress {
+ pub course_id: i64,
+ pub course_name: String,
+ pub percent: f64,
+ pub current_module: String,
+ #[serde(rename = "current_page")]
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ #[serde(rename = "total_pages")]
+ pub total_lessons: u32,
+ #[serde(rename = "completed_pages")]
+ pub completed_lessons: u32,
+ pub total_modules: u32,
+ pub current_module_index: u32,
+}
+
+pub async fn download_full_course(
+ app: &tauri::AppHandle,
+ session: &VoompSession,
+ course: &VoompCourse,
+ output_dir: &str,
+ cancel_token: CancellationToken,
+) -> anyhow::Result<()> {
+ let mut modules = api::get_modules(session, course.id).await?;
+
+ if modules.is_empty() {
+ return Err(anyhow!(
+ "'{}' has no modules available for download",
+ course.name
+ ));
+ }
+
+ for module in &mut modules {
+ let lessons = api::get_lessons(session, course.id, module.id).await?;
+ module.lessons = lessons;
+ }
+
+ let course_dir = format!(
+ "{}/{}",
+ output_dir,
+ filename::sanitize_path_component(&course.name)
+ );
+ tokio::fs::create_dir_all(&course_dir).await?;
+
+ if omniget_core::core::course_utils::is_course_complete(&course_dir) {
+ return Ok(());
+ }
+
+ let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
+ let total_modules = modules.len();
+ let total_bytes = Arc::new(AtomicU64::new(0));
+ let completed = Arc::new(AtomicUsize::new(0));
+
+ let _ = app.emit(
+ "download-progress",
+ &VoompCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: 0.0,
+ current_module: "Starting...".to_string(),
+ current_lesson: String::new(),
+ downloaded_bytes: 0,
+ total_lessons: total_lessons as u32,
+ completed_lessons: 0,
+ total_modules: total_modules as u32,
+ current_module_index: 0,
+ },
+ );
+
+ for (mi, module) in modules.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let mod_name = filename::sanitize_path_component(&module.name);
+ let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
+ tokio::fs::create_dir_all(&mod_dir).await?;
+
+ for (li, lesson) in module.lessons.iter().enumerate() {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let lesson_name = filename::sanitize_path_component(&lesson.name);
+ let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
+ tokio::fs::create_dir_all(&lesson_dir).await?;
+
+ if let Some(ref content) = lesson.content {
+ omniget_core::core::course_utils::save_description(&lesson_dir, content, "html").await.ok();
+ }
+
+ let mut video_url: Option<String> = None;
+
+ if let Some(ref source) = lesson.source {
+ if let Some(ref mt) = lesson.media_type {
+ if mt.contains("panda") {
+ if let Some(_vid) = api::extract_panda_video_id(source) {
+ video_url = Some(source.clone());
+ }
+ }
+ }
+
+ if video_url.is_none()
+ && (source.contains("http://") || source.contains("https://"))
+ {
+ video_url = Some(source.clone());
+ }
+ }
+
+ if let Some(ref url) = video_url {
+ let video_ext = if url.contains(".m3u8") {
+ "mp4"
+ } else {
+ url.rsplit('.')
+ .next()
+ .and_then(|e| {
+ let e = e.split('?').next().unwrap_or(e);
+ if e.len() <= 4 {
+ Some(e)
+ } else {
+ None
+ }
+ })
+ .unwrap_or("mp4")
+ };
+
+ let video_path = format!(
+ "{}/{}. {}.{}",
+ lesson_dir,
+ li + 1,
+ lesson_name,
+ video_ext
+ );
+
+ if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&video_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ tracing::info!("[voomp] Skipping existing: {}", video_path);
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &VoompCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ continue;
+ }
+ }
+
+ if url.contains(".m3u8") {
+ match download_hls_video(url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[voomp] HLS download failed for '{}': {}",
+ lesson.name,
+ e
+ );
+ let _ = tokio::fs::remove_file(&video_path).await;
+ }
+ }
+ } else {
+ match download_with_ytdlp(url, &lesson_dir, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[voomp] yt-dlp download failed for '{}': {}, trying direct download",
+ lesson.name,
+ e
+ );
+ match download_file_direct(&session.client, url, &video_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e2) => {
+ tracing::error!(
+ "[voomp] Direct download also failed for '{}': {}",
+ lesson.name,
+ e2
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ for attachment in &lesson.attachments {
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ let att_name = filename::sanitize_path_component(&attachment.name);
+ let att_path = format!("{}/{}", lesson_dir, att_name);
+
+ if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
+ let meta = tokio::fs::metadata(&att_path).await;
+ if meta.map(|m| m.len() > 0).unwrap_or(false) {
+ continue;
+ }
+ }
+
+ match download_file_direct(&session.client, &attachment.url, &att_path, &cancel_token).await {
+ Ok(size) => {
+ total_bytes.fetch_add(size, Ordering::Relaxed);
+ }
+ Err(e) => {
+ tracing::error!(
+ "[voomp] Attachment download failed for '{}': {}",
+ attachment.name,
+ e
+ );
+ }
+ }
+ }
+
+ let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
+ let _ = app.emit(
+ "download-progress",
+ &VoompCourseDownloadProgress {
+ course_id: course.id,
+ course_name: course.name.clone(),
+ percent: done as f64 / total_lessons as f64 * 100.0,
+ current_module: module.name.clone(),
+ current_lesson: lesson.name.clone(),
+ downloaded_bytes: total_bytes.load(Ordering::Relaxed),
+ total_lessons: total_lessons as u32,
+ completed_lessons: done as u32,
+ total_modules: total_modules as u32,
+ current_module_index: (mi + 1) as u32,
+ },
+ );
+ }
+ }
+
+ if cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled by user"));
+ }
+
+ omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
+
+ Ok(())
+}
+
+async fn download_hls_video(
+ m3u8_url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ use omniget_core::core::media_processor::MediaProcessor;
+
+ let _result = MediaProcessor::download_hls(
+ m3u8_url,
+ output_path,
+ "https://voompplay.com.br/",
+ None,
+ cancel_token.clone(),
+ 20,
+ 3,
+ None,
+ )
+ .await?;
+
+ let meta = tokio::fs::metadata(output_path).await?;
+ Ok(meta.len())
+}
+
+async fn download_with_ytdlp(
+ url: &str,
+ output_dir: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
+ let out_dir = Path::new(output_dir);
+ let (tx, _rx) = mpsc::channel(8);
+
+ let result = omniget_core::core::ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ out_dir,
+ None,
+ tx,
+ None,
+ None,
+ None,
+ Some("https://voompplay.com.br/"),
+ cancel_token.clone(),
+ None,
+ 8,
+ false,
+ &[],
+ )
+ .await?;
+
+ Ok(result.file_size_bytes)
+}
+
+async fn download_file_direct(
+ client: &reqwest::Client,
+ url: &str,
+ output_path: &str,
+ cancel_token: &CancellationToken,
+) -> anyhow::Result<u64> {
+ let out = Path::new(output_path);
+ let (tx, _rx) = mpsc::channel(8);
+
+ omniget_core::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/voompplay/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/voompplay/mod.rs
new file mode 100644
index 00000000..950bcd99
--- /dev/null
+++ b/src-tauri/omniget-plugin-courses/src/platforms/voompplay/mod.rs
@@ -0,0 +1,63 @@
+pub mod api;
+pub mod downloader;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
+use crate::platforms::traits::PlatformDownloader;
+
+pub struct VoompPlayDownloader;
+
+impl VoompPlayDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+impl Default for VoompPlayDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for VoompPlayDownloader {
+ fn name(&self) -> &str {
+ "voompplay"
+ }
+
+ 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 == "voompplay.com.br"
+ || host.ends_with(".voompplay.com.br");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
+ Ok(MediaInfo {
+ title: "Voomp Play".to_string(),
+ author: String::new(),
+ platform: "voompplay".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![],
+ media_type: MediaType::Course,
+ file_size_bytes: None,
+ })
+ }
+
+ async fn download(
+ &self,
+ _info: &MediaInfo,
+ _opts: &DownloadOptions,
+ _progress: mpsc::Sender<f64>,
+ ) -> anyhow::Result<DownloadResult> {
+ Err(anyhow!("Use the courses interface to download from Voomp Play"))
+ }
+}