Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
Remove Udemy and VoompPlay modules and their associated code
Tonhoe085ebe3d79c
diff --git a/src-tauri/src/commands/afya.rs b/src-tauri/src/commands/afya.rsdeleted file mode 100644index e1598d8b..00000000--- a/src-tauri/src/commands/afya.rs+++ /dev/null@@ -1,279 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::afyainternato::api::{self, AfyaCourse, AfyaSession};-use crate::platforms::afyainternato::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct AfyaDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn afya_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,- api_key: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.afya_session.lock().await.take();- *state.afya_session_validated_at.lock().await = None;- *state.afya_courses_cache.lock().await = None;-- match api::authenticate(&email, &password, &api_key).await {- Ok(session) => {- let _ = api::save_session(&session).await;- let mut guard = state.afya_session.lock().await;- *guard = Some(session);- *state.afya_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Err(e) => {- tracing::error!("[afya] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn afya_login_token(- state: tauri::State<'_, AppState>,- token: String,- api_key: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.afya_session.lock().await.take();- *state.afya_session_validated_at.lock().await = None;- *state.afya_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let client = crate::platforms::medcel::api::build_client_with_origin(- &parsed_token,- &api_key,- "https://alunos-internato.afya.com.br",- )- .map_err(|e| format!("Failed to build client: {}", e))?;-- let mut session = AfyaSession {- token: parsed_token.clone(),- api_key: api_key.clone(),- student_id: String::new(),- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- match api::fetch_student_id(&session).await {- Ok(id) => session.student_id = id,- Err(e) => tracing::warn!("[afya] could not fetch student id: {}", e),- }- let _ = api::save_session(&session).await;- let mut guard = state.afya_session.lock().await;- *guard = Some(session);- *state.afya_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn afya_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.afya_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.afya_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.afya_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.afya_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.afya_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.afya_session.lock().await.take();- *state.afya_session_validated_at.lock().await = None;- *state.afya_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn afya_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.afya_session.lock().await.take();- *state.afya_session_validated_at.lock().await = None;- *state.afya_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_afya_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<AfyaCourse>, String> {- let guard = state.afya_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.afya_courses_cache.lock().await;- *cache = Some(crate::AfyaCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn afya_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<AfyaCourse>, String> {- {- let cache = state.afya_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_afya_courses(&state).await-}--#[tauri::command]-pub async fn afya_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<AfyaCourse>, String> {- {- let mut cache = state.afya_courses_cache.lock().await;- *cache = None;- }- fetch_afya_courses(&state).await-}--#[tauri::command]-pub async fn start_afya_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: AfyaCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.afya_session.lock().await;- let afya_session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;- afya_session.clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &AfyaDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[afya] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &AfyaDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/alpaclass.rs b/src-tauri/src/commands/alpaclass.rsdeleted file mode 100644index 8fee9dd7..00000000--- a/src-tauri/src/commands/alpaclass.rs+++ /dev/null@@ -1,238 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::alpaclass::api::{self, AlpaclassCourse};-use crate::platforms::alpaclass::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct AlpaclassDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn alpaclass_login(- state: tauri::State<'_, AppState>,- token: String,- platform_url: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.alpaclass_session.lock().await.take();- *state.alpaclass_session_validated_at.lock().await = None;- *state.alpaclass_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- match api::authenticate(&parsed_token, &platform_url).await {- Ok(session) => {- let subdomain = session.subdomain.clone();- let _ = api::save_session(&session).await;- let mut guard = state.alpaclass_session.lock().await;- *guard = Some(session);- *state.alpaclass_session_validated_at.lock().await = Some(Instant::now());- Ok(subdomain)- }- Err(e) => {- tracing::error!("[alpaclass] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn alpaclass_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.alpaclass_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.alpaclass_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.alpaclass_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let subdomain = session.subdomain.clone();-- {- let validated_at = state.alpaclass_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(subdomain);- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.alpaclass_session_validated_at.lock().await = Some(Instant::now());- Ok(subdomain)- }- Ok(false) => {- state.alpaclass_session.lock().await.take();- *state.alpaclass_session_validated_at.lock().await = None;- *state.alpaclass_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn alpaclass_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.alpaclass_session.lock().await.take();- *state.alpaclass_session_validated_at.lock().await = None;- *state.alpaclass_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_alpaclass_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<AlpaclassCourse>, String> {- let guard = state.alpaclass_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.alpaclass_courses_cache.lock().await;- *cache = Some(crate::AlpaclassCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn alpaclass_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<AlpaclassCourse>, String> {- {- let cache = state.alpaclass_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_alpaclass_courses(&state).await-}--#[tauri::command]-pub async fn alpaclass_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<AlpaclassCourse>, String> {- {- let mut cache = state.alpaclass_courses_cache.lock().await;- *cache = None;- }- fetch_alpaclass_courses(&state).await-}--#[tauri::command]-pub async fn start_alpaclass_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: AlpaclassCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.slug.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id, cancel_token.clone());- }-- let session = {- let guard = state.alpaclass_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &AlpaclassDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[alpaclass] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &AlpaclassDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/areademembros.rs b/src-tauri/src/commands/areademembros.rsdeleted file mode 100644index fc72ba7e..00000000--- a/src-tauri/src/commands/areademembros.rs+++ /dev/null@@ -1,254 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::areademembros::api::{self, AreaDeMembrosApiCourse, AreaDeMembrosSession};-use crate::platforms::areademembros::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct AreaDeMembrosDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn areademembros_login_token(- state: tauri::State<'_, AppState>,- cookies: String,- site_url: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.areademembros_session.lock().await.take();- *state.areademembros_session_validated_at.lock().await = None;- *state.areademembros_courses_cache.lock().await = None;-- let clean_url = site_url.trim_end_matches('/').to_string();- let parsed = crate::core::cookie_parser::parse_cookie_input(&cookies, "session");-- let session = AreaDeMembrosSession {- cookies: parsed.cookie_string.clone(),- site_url: clean_url.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Cookie", parsed.cookie_string.parse().unwrap());- h.insert("Referer", format!("{}/", clean_url).parse().unwrap());- h.insert("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".parse().unwrap());- h- })- .redirect(reqwest::redirect::Policy::limited(10))- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.areademembros_session.lock().await;- *guard = Some(session);- *state.areademembros_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid cookies".to_string()),- Err(e) => Err(format!("Validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn areademembros_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.areademembros_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.areademembros_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.areademembros_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.areademembros_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.areademembros_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.areademembros_session.lock().await.take();- *state.areademembros_session_validated_at.lock().await = None;- *state.areademembros_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn areademembros_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.areademembros_session.lock().await.take();- *state.areademembros_session_validated_at.lock().await = None;- *state.areademembros_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_areademembros_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<AreaDeMembrosApiCourse>, String> {- let guard = state.areademembros_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.areademembros_courses_cache.lock().await;- *cache = Some(crate::AreaDeMembrosCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn areademembros_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<AreaDeMembrosApiCourse>, String> {- {- let cache = state.areademembros_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_areademembros_courses(&state).await-}--#[tauri::command]-pub async fn areademembros_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<AreaDeMembrosApiCourse>, String> {- {- let mut cache = state.areademembros_courses_cache.lock().await;- *cache = None;- }- fetch_areademembros_courses(&state).await-}--#[tauri::command]-pub async fn start_areademembros_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: AreaDeMembrosApiCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.areademembros_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &AreaDeMembrosDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[areademembros] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &AreaDeMembrosDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/astronmembers.rs b/src-tauri/src/commands/astronmembers.rsdeleted file mode 100644index 50d6d484..00000000--- a/src-tauri/src/commands/astronmembers.rs+++ /dev/null@@ -1,283 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::astronmembers::api::{self, AstronCourse, AstronSession};-use crate::platforms::astronmembers::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct AstronDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn astron_login(- state: tauri::State<'_, AppState>,- site_url: String,- login: String,- password: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.astron_session.lock().await.take();- *state.astron_session_validated_at.lock().await = None;- *state.astron_courses_cache.lock().await = None;-- let clean_url = site_url.trim_end_matches('/').to_string();-- match api::authenticate(&clean_url, &login, &password).await {- Ok(session) => {- let _ = api::save_session(&session).await;- let mut guard = state.astron_session.lock().await;- *guard = Some(session);- *state.astron_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Err(e) => {- tracing::error!("[astron] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn astron_login_token(- state: tauri::State<'_, AppState>,- cookies: String,- site_url: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.astron_session.lock().await.take();- *state.astron_session_validated_at.lock().await = None;- *state.astron_courses_cache.lock().await = None;-- let clean_url = site_url.trim_end_matches('/').to_string();- let parsed = crate::core::cookie_parser::parse_cookie_input(&cookies, "session");-- let session = AstronSession {- cookies: parsed.cookie_string.clone(),- site_url: clean_url.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Cookie", parsed.cookie_string.parse().unwrap());- h.insert("Referer", format!("{}/", clean_url).parse().unwrap());- h.insert("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".parse().unwrap());- h- })- .redirect(reqwest::redirect::Policy::limited(10))- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.astron_session.lock().await;- *guard = Some(session);- *state.astron_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid cookies".to_string()),- Err(e) => Err(format!("Validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn astron_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.astron_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.astron_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.astron_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.astron_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.astron_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.astron_session.lock().await.take();- *state.astron_session_validated_at.lock().await = None;- *state.astron_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn astron_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.astron_session.lock().await.take();- *state.astron_session_validated_at.lock().await = None;- *state.astron_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_astron_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<AstronCourse>, String> {- let guard = state.astron_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.astron_courses_cache.lock().await;- *cache = Some(crate::AstronCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn astron_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<AstronCourse>, String> {- {- let cache = state.astron_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_astron_courses(&state).await-}--#[tauri::command]-pub async fn astron_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<AstronCourse>, String> {- {- let mut cache = state.astron_courses_cache.lock().await;- *cache = None;- }- fetch_astron_courses(&state).await-}--#[tauri::command]-pub async fn start_astron_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: AstronCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.astron_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &AstronDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[astron] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &AstronDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/auth.rs b/src-tauri/src/commands/auth.rsdeleted file mode 100644index 257a6d61..00000000--- a/src-tauri/src/commands/auth.rs+++ /dev/null@@ -1,115 +0,0 @@-use std::time::{Duration, Instant};--use crate::platforms::hotmart::auth::{authenticate, delete_saved_session, load_saved_session, save_session};-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);--#[tauri::command]-pub async fn hotmart_login(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- email: String,- password: String,-) -> Result<String, String> {- let _ = delete_saved_session().await;- {- let mut map = state.active_downloads.lock().await;- for token in map.values() {- token.cancel();- }- map.clear();- }- state.hotmart_session.lock().await.take();- *state.session_validated_at.lock().await = None;- *state.courses_cache.lock().await = None;-- match authenticate(&app, &email, &password).await {- Ok(session) => {- let response_email = session.email.clone();- let _ = save_session(&session).await;- let mut guard = state.hotmart_session.lock().await;- *guard = Some(session);- *state.session_validated_at.lock().await = Some(Instant::now());- Ok(response_email)- }- Err(e) => {- tracing::error!("Hotmart login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn hotmart_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.hotmart_session.lock().await.is_some();-- if !has_memory_session {- match load_saved_session().await {- Ok(session) => {- let mut guard = state.hotmart_session.lock().await;- *guard = Some(session);- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.hotmart_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let email = session.email.clone();-- {- let validated_at = state.session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(email);- }- }- }-- let token = session.token.clone();- let client = session.client.clone();- drop(guard);-- let resp = client- .post("https://api-sec-vlc.hotmart.com/security/oauth/check_token")- .form(&[("token", &token)])- .send()- .await- .map_err(|e| format!("Validation error: {}", e))?;-- if resp.status().is_success() {- *state.session_validated_at.lock().await = Some(Instant::now());- Ok(email)- } else {- state.hotmart_session.lock().await.take();- *state.session_validated_at.lock().await = None;- *state.courses_cache.lock().await = None;- let _ = delete_saved_session().await;- Err("session_expired".to_string())- }-}--#[tauri::command]-pub async fn hotmart_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = delete_saved_session().await;- {- let mut map = state.active_downloads.lock().await;- for token in map.values() {- token.cancel();- }- map.clear();- }- state.hotmart_session.lock().await.take();- *state.session_validated_at.lock().await = None;- *state.courses_cache.lock().await = None;- Ok(())-}diff --git a/src-tauri/src/commands/cademi_cmd.rs b/src-tauri/src/commands/cademi_cmd.rsdeleted file mode 100644index 9104d5df..00000000--- a/src-tauri/src/commands/cademi_cmd.rs+++ /dev/null@@ -1,281 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::cademi::api::{self, CademiCourse, CademiSession};-use crate::platforms::cademi::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct CademiDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn cademi_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,- site_url: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.cademi_session.lock().await.take();- *state.cademi_session_validated_at.lock().await = None;- *state.cademi_courses_cache.lock().await = None;-- match api::authenticate(&email, &password, &site_url).await {- Ok(session) => {- let response_url = session.site_url.clone();- let _ = api::save_session(&session).await;- let mut guard = state.cademi_session.lock().await;- *guard = Some(session);- *state.cademi_session_validated_at.lock().await = Some(Instant::now());- Ok(response_url)- }- Err(e) => {- tracing::error!("[cademi] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn cademi_login_cookie(- state: tauri::State<'_, AppState>,- cookie: String,- site_url: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.cademi_session.lock().await.take();- *state.cademi_session_validated_at.lock().await = None;- *state.cademi_courses_cache.lock().await = None;-- let trimmed_url = site_url.trim_end_matches('/').to_string();- let parsed = crate::core::cookie_parser::parse_cookie_input(&cookie, "app_v4_session");-- let session = CademiSession {- cookies: parsed.token.clone(),- site_url: trimmed_url.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Cookie", parsed.cookie_string.parse().unwrap());- h.insert("Referer", format!("{}/", trimmed_url).parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.cademi_session.lock().await;- *guard = Some(session);- *state.cademi_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid cookie".to_string()),- Err(e) => Err(format!("Cookie validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn cademi_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.cademi_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.cademi_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.cademi_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let site_url = session.site_url.clone();-- {- let validated_at = state.cademi_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(site_url);- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.cademi_session_validated_at.lock().await = Some(Instant::now());- Ok(site_url)- }- Ok(false) => {- state.cademi_session.lock().await.take();- *state.cademi_session_validated_at.lock().await = None;- *state.cademi_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn cademi_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.cademi_session.lock().await.take();- *state.cademi_session_validated_at.lock().await = None;- *state.cademi_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_cademi_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<CademiCourse>, String> {- let guard = state.cademi_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.cademi_courses_cache.lock().await;- *cache = Some(crate::CademiCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn cademi_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<CademiCourse>, String> {- {- let cache = state.cademi_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_cademi_courses(&state).await-}--#[tauri::command]-pub async fn cademi_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<CademiCourse>, String> {- {- let mut cache = state.cademi_courses_cache.lock().await;- *cache = None;- }- fetch_cademi_courses(&state).await-}--#[tauri::command]-pub async fn start_cademi_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: CademiCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.cademi_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &CademiDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[cademi] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &CademiDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/cakto.rs b/src-tauri/src/commands/cakto.rsdeleted file mode 100644index 1a617fc4..00000000--- a/src-tauri/src/commands/cakto.rs+++ /dev/null@@ -1,277 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::cakto::api::{self, CaktoCourse, CaktoSession};-use crate::platforms::cakto::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct CaktoDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn cakto_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.cakto_session.lock().await.take();- *state.cakto_session_validated_at.lock().await = None;- *state.cakto_courses_cache.lock().await = None;-- match api::authenticate(&email, &password).await {- Ok(session) => {- let _ = api::save_session(&session).await;- let mut guard = state.cakto_session.lock().await;- *guard = Some(session);- *state.cakto_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Err(e) => {- tracing::error!("[cakto] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn cakto_login_token(- state: tauri::State<'_, AppState>,- cookie: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.cakto_session.lock().await.take();- *state.cakto_session_validated_at.lock().await = None;- *state.cakto_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&cookie, "__Secure-better-auth.session_token");-- let session = CaktoSession {- cookie: parsed.token.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Cookie", parsed.cookie_string.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Origin", "https://aluno.cakto.com.br".parse().unwrap());- h.insert("Referer", "https://aluno.cakto.com.br/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.cakto_session.lock().await;- *guard = Some(session);- *state.cakto_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid cookie".to_string()),- Err(e) => Err(format!("Validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn cakto_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.cakto_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.cakto_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.cakto_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.cakto_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.cakto_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.cakto_session.lock().await.take();- *state.cakto_session_validated_at.lock().await = None;- *state.cakto_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn cakto_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.cakto_session.lock().await.take();- *state.cakto_session_validated_at.lock().await = None;- *state.cakto_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_cakto_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<CaktoCourse>, String> {- let guard = state.cakto_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.cakto_courses_cache.lock().await;- *cache = Some(crate::CaktoCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn cakto_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<CaktoCourse>, String> {- {- let cache = state.cakto_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_cakto_courses(&state).await-}--#[tauri::command]-pub async fn cakto_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<CaktoCourse>, String> {- {- let mut cache = state.cakto_courses_cache.lock().await;- *cache = None;- }- fetch_cakto_courses(&state).await-}--#[tauri::command]-pub async fn start_cakto_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: CaktoCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.cakto_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &CaktoDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[cakto] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &CaktoDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/caktomembers.rs b/src-tauri/src/commands/caktomembers.rsdeleted file mode 100644index 7f1f5f1f..00000000--- a/src-tauri/src/commands/caktomembers.rs+++ /dev/null@@ -1,258 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::caktomembers::api::{self, CaktoMembersCourse, CaktoMembersSession};-use crate::platforms::caktomembers::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct CaktoMembersDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn caktomembers_login_token(- state: tauri::State<'_, AppState>,- cookie: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.caktomembers_session.lock().await.take();- *state.caktomembers_session_validated_at.lock().await = None;- *state.caktomembers_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&cookie, "__Secure-better-auth.session_token");-- let access_token = api::fetch_access_token(&parsed.token)- .await- .map_err(|e| format!("Failed to fetch access token: {}", e))?;-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", access_token).parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Origin", "https://app.cakto.com.br".parse().unwrap());- h.insert("Referer", "https://app.cakto.com.br/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- let session = CaktoMembersSession {- cookie: parsed.token.clone(),- access_token,- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.caktomembers_session.lock().await;- *guard = Some(session);- *state.caktomembers_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid cookie".to_string()),- Err(e) => Err(format!("Validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn caktomembers_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.caktomembers_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.caktomembers_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.caktomembers_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.caktomembers_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.caktomembers_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.caktomembers_session.lock().await.take();- *state.caktomembers_session_validated_at.lock().await = None;- *state.caktomembers_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn caktomembers_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.caktomembers_session.lock().await.take();- *state.caktomembers_session_validated_at.lock().await = None;- *state.caktomembers_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_caktomembers_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<CaktoMembersCourse>, String> {- let guard = state.caktomembers_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.caktomembers_courses_cache.lock().await;- *cache = Some(crate::CaktoMembersCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn caktomembers_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<CaktoMembersCourse>, String> {- {- let cache = state.caktomembers_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_caktomembers_courses(&state).await-}--#[tauri::command]-pub async fn caktomembers_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<CaktoMembersCourse>, String> {- {- let mut cache = state.caktomembers_courses_cache.lock().await;- *cache = None;- }- fetch_caktomembers_courses(&state).await-}--#[tauri::command]-pub async fn start_caktomembers_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: CaktoMembersCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.caktomembers_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &CaktoMembersDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[caktomembers] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &CaktoMembersDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/convert.rs b/src-tauri/src/commands/convert.rsdeleted file mode 100644index e6e5fb9c..00000000--- a/src-tauri/src/commands/convert.rs+++ /dev/null@@ -1,126 +0,0 @@-use serde::Serialize;-use tauri::Emitter;-use tokio::sync::mpsc;-use tokio_util::sync::CancellationToken;--use crate::core::ffmpeg::{self, ConversionOptions, ConversionResult, MediaProbeInfo};-use crate::core::hwaccel::{self, HwAccelInfo};-use crate::AppState;--#[derive(Clone, Serialize)]-struct ConvertProgressEvent {- id: u64,- percent: f64,-}--#[derive(Clone, Serialize)]-struct ConvertCompleteEvent {- id: u64,- success: bool,- result: Option<ConversionResult>,- error: Option<String>,-}--#[tauri::command]-pub async fn probe_file(path: String) -> Result<MediaProbeInfo, String> {- ffmpeg::probe(std::path::Path::new(&path))- .await- .map_err(|e| e.to_string())-}--#[tauri::command]-pub async fn convert_file(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- options: ConversionOptions,-) -> Result<u64, String> {- let conversion_id = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_millis() as u64;-- let cancel_token = CancellationToken::new();-- {- let mut map = state.active_conversions.lock().await;- map.insert(conversion_id, cancel_token.clone());- }-- let active = state.active_conversions.clone();-- tokio::spawn(async move {- let (tx, mut rx) = mpsc::channel::<f64>(32);-- let app_progress = app.clone();- let cid = conversion_id;- let progress_forwarder = tokio::spawn(async move {- while let Some(percent) = rx.recv().await {- let _ = app_progress.emit(- "convert-progress",- ConvertProgressEvent {- id: cid,- percent,- },- );- }- });-- let result = ffmpeg::convert(&options, cancel_token, tx).await;-- let _ = progress_forwarder.await;-- {- let mut map = active.lock().await;- map.remove(&conversion_id);- }-- match result {- Ok(conv_result) => {- let success = conv_result.success;- let error = conv_result.error.clone();- let _ = app.emit(- "convert-complete",- ConvertCompleteEvent {- id: conversion_id,- success,- result: Some(conv_result),- error,- },- );- }- Err(e) => {- let _ = app.emit(- "convert-complete",- ConvertCompleteEvent {- id: conversion_id,- success: false,- result: None,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(conversion_id)-}--#[tauri::command]-pub async fn cancel_conversion(- state: tauri::State<'_, AppState>,- conversion_id: u64,-) -> Result<String, String> {- let mut map = state.active_conversions.lock().await;- match map.remove(&conversion_id) {- Some(token) => {- token.cancel();- Ok("Conversion cancelled".to_string())- }- None => Err("No active conversion for this ID".to_string()),- }-}--#[tauri::command]-pub async fn get_hwaccel_info() -> Result<HwAccelInfo, String> {- Ok(hwaccel::detect_hwaccel().await)-}diff --git a/src-tauri/src/commands/courses.rs b/src-tauri/src/commands/courses.rsdeleted file mode 100644index 72faaf07..00000000--- a/src-tauri/src/commands/courses.rs+++ /dev/null@@ -1,76 +0,0 @@-use std::time::{Duration, Instant};--use crate::platforms::hotmart::api::{self, Course, Module};-use crate::{AppState, CoursesCache};--const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--async fn fetch_courses_from_api(state: &tauri::State<'_, AppState>) -> Result<Vec<Course>, String> {- let guard = state.hotmart_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let subdomains = api::get_subdomains(session).await.unwrap_or_default();-- let mut courses = api::list_courses(session).await.map_err(|e| e.to_string())?;-- api::merge_subdomains(&mut courses, &subdomains);-- for course in &mut courses {- if let Ok(price) = api::get_course_price(session, course.id).await {- course.price = Some(price);- }- }-- let mut cache = state.courses_cache.lock().await;- *cache = Some(CoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn hotmart_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<Course>, String> {- {- let cache = state.courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_courses_from_api(&state).await-}--#[tauri::command]-pub async fn hotmart_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<Course>, String> {- {- let mut cache = state.courses_cache.lock().await;- *cache = None;- }- fetch_courses_from_api(&state).await-}--#[tauri::command]-pub async fn hotmart_get_modules(- state: tauri::State<'_, AppState>,- course_id: u64,- slug: String,-) -> Result<Vec<Module>, String> {- let guard = state.hotmart_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- api::get_modules(session, &slug, course_id)- .await- .map_err(|e| e.to_string())-}diff --git a/src-tauri/src/commands/curseduca.rs b/src-tauri/src/commands/curseduca.rsdeleted file mode 100644index c637e94a..00000000--- a/src-tauri/src/commands/curseduca.rs+++ /dev/null@@ -1,284 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::curseduca::api::{self, CurseducaCourse, CurseducaSession};-use crate::platforms::curseduca::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct CurseducaDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn curseduca_login(- state: tauri::State<'_, AppState>,- site_url: String,- username: String,- password: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.curseduca_session.lock().await.take();- *state.curseduca_session_validated_at.lock().await = None;- *state.curseduca_courses_cache.lock().await = None;-- let clean_url = site_url.trim_end_matches('/').to_string();-- match api::authenticate(&clean_url, &username, &password).await {- Ok(session) => {- let _ = api::save_session(&session).await;- let mut guard = state.curseduca_session.lock().await;- *guard = Some(session);- *state.curseduca_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Err(e) => {- tracing::error!("[curseduca] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn curseduca_login_token(- state: tauri::State<'_, AppState>,- token: String,- api_key: String,- site_url: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.curseduca_session.lock().await.take();- *state.curseduca_session_validated_at.lock().await = None;- *state.curseduca_courses_cache.lock().await = None;-- let clean_url = site_url.trim_end_matches('/').to_string();- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = CurseducaSession {- token: parsed_token.clone(),- api_key: api_key.clone(),- site_url: clean_url,- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("api_key", api_key.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.curseduca_session.lock().await;- *guard = Some(session);- *state.curseduca_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn curseduca_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.curseduca_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.curseduca_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.curseduca_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.curseduca_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.curseduca_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.curseduca_session.lock().await.take();- *state.curseduca_session_validated_at.lock().await = None;- *state.curseduca_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn curseduca_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.curseduca_session.lock().await.take();- *state.curseduca_session_validated_at.lock().await = None;- *state.curseduca_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_curseduca_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<CurseducaCourse>, String> {- let guard = state.curseduca_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.curseduca_courses_cache.lock().await;- *cache = Some(crate::CurseducaCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn curseduca_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<CurseducaCourse>, String> {- {- let cache = state.curseduca_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_curseduca_courses(&state).await-}--#[tauri::command]-pub async fn curseduca_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<CurseducaCourse>, String> {- {- let mut cache = state.curseduca_courses_cache.lock().await;- *cache = None;- }- fetch_curseduca_courses(&state).await-}--#[tauri::command]-pub async fn start_curseduca_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: CurseducaCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.curseduca_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &CurseducaDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[curseduca] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &CurseducaDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/dsa.rs b/src-tauri/src/commands/dsa.rsdeleted file mode 100644index a190c69f..00000000--- a/src-tauri/src/commands/dsa.rs+++ /dev/null@@ -1,251 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::datascienceacademy::api::{self, DsaCourse, DsaSession};-use crate::platforms::datascienceacademy::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct DsaDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn dsa_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.dsa_session.lock().await.take();- *state.dsa_session_validated_at.lock().await = None;- *state.dsa_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = DsaSession {- token: parsed_token.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Token", parsed_token.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Origin", "https://www.datascienceacademy.com.br".parse().unwrap());- h.insert("Referer", "https://www.datascienceacademy.com.br/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.dsa_session.lock().await;- *guard = Some(session);- *state.dsa_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn dsa_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.dsa_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.dsa_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.dsa_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.dsa_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.dsa_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.dsa_session.lock().await.take();- *state.dsa_session_validated_at.lock().await = None;- *state.dsa_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn dsa_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.dsa_session.lock().await.take();- *state.dsa_session_validated_at.lock().await = None;- *state.dsa_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_dsa_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<DsaCourse>, String> {- let guard = state.dsa_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.dsa_courses_cache.lock().await;- *cache = Some(crate::DsaCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn dsa_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<DsaCourse>, String> {- {- let cache = state.dsa_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_dsa_courses(&state).await-}--#[tauri::command]-pub async fn dsa_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<DsaCourse>, String> {- {- let mut cache = state.dsa_courses_cache.lock().await;- *cache = None;- }- fetch_dsa_courses(&state).await-}--#[tauri::command]-pub async fn start_dsa_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: DsaCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.dsa_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &DsaDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[dsa] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &DsaDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/entregadigital.rs b/src-tauri/src/commands/entregadigital.rsdeleted file mode 100644index 07d7466d..00000000--- a/src-tauri/src/commands/entregadigital.rs+++ /dev/null@@ -1,257 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::entregadigital::api::{self, EntregaDigitalCourse, EntregaDigitalSession};-use crate::platforms::entregadigital::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct EntregaDigitalDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn entregadigital_login_token(- state: tauri::State<'_, AppState>,- token: String,- site_url: String,- app_version: String,- device_id: String,- os_value: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.entregadigital_session.lock().await.take();- *state.entregadigital_session_validated_at.lock().await = None;- *state.entregadigital_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let api_base = api::build_api_base(&site_url)- .map_err(|e| format!("Invalid site URL: {}", e))?;-- let session = EntregaDigitalSession {- token: parsed_token.clone(),- api_base,- app_version: app_version.clone(),- device_id: device_id.clone(),- os_value: os_value.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("app-version", app_version.parse().unwrap());- h.insert("device-id", device_id.parse().unwrap());- h.insert("os", os_value.parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.entregadigital_session.lock().await;- *guard = Some(session);- *state.entregadigital_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn entregadigital_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.entregadigital_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.entregadigital_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.entregadigital_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.entregadigital_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.entregadigital_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.entregadigital_session.lock().await.take();- *state.entregadigital_session_validated_at.lock().await = None;- *state.entregadigital_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn entregadigital_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.entregadigital_session.lock().await.take();- *state.entregadigital_session_validated_at.lock().await = None;- *state.entregadigital_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_entregadigital_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<EntregaDigitalCourse>, String> {- let guard = state.entregadigital_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.entregadigital_courses_cache.lock().await;- *cache = Some(crate::EntregaDigitalCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn entregadigital_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<EntregaDigitalCourse>, String> {- {- let cache = state.entregadigital_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_entregadigital_courses(&state).await-}--#[tauri::command]-pub async fn entregadigital_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<EntregaDigitalCourse>, String> {- {- let mut cache = state.entregadigital_courses_cache.lock().await;- *cache = None;- }- fetch_entregadigital_courses(&state).await-}--#[tauri::command]-pub async fn start_entregadigital_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: EntregaDigitalCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id = course.id as u64;- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id, cancel_token.clone());- }-- let session = {- let guard = state.entregadigital_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &EntregaDigitalDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[entregadigital] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &EntregaDigitalDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/estrategia_concursos.rs b/src-tauri/src/commands/estrategia_concursos.rsdeleted file mode 100644index da9e4fbd..00000000--- a/src-tauri/src/commands/estrategia_concursos.rs+++ /dev/null@@ -1,253 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::estrategia_concursos::api::{self, EstrategiaConcursosCourse, EstrategiaConcursosSession};-use crate::platforms::estrategia_concursos::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct EstrategiaConcursosDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn estrategia_concursos_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.estrategia_concursos_session.lock().await.take();- *state.estrategia_concursos_session_validated_at.lock().await = None;- *state.estrategia_concursos_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&token, "__Secure-SID");-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed.token).parse().unwrap());- if parsed.cookies.len() > 1 {- h.insert("Cookie", parsed.cookie_string.parse().unwrap());- } else {- h.insert("Cookie", format!("PHPSESSID={}; __Secure-SID={}", parsed.token, parsed.token).parse().unwrap());- }- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Personificado", "false".parse().unwrap());- h.insert("Origin", "https://www.estrategiaconcursos.com.br".parse().unwrap());- h.insert("Referer", "https://www.estrategiaconcursos.com.br/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- let session = EstrategiaConcursosSession {- token: parsed.token.clone(),- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.estrategia_concursos_session.lock().await;- *guard = Some(session);- *state.estrategia_concursos_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn estrategia_concursos_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.estrategia_concursos_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.estrategia_concursos_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.estrategia_concursos_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.estrategia_concursos_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.estrategia_concursos_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.estrategia_concursos_session.lock().await.take();- *state.estrategia_concursos_session_validated_at.lock().await = None;- *state.estrategia_concursos_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn estrategia_concursos_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.estrategia_concursos_session.lock().await.take();- *state.estrategia_concursos_session_validated_at.lock().await = None;- *state.estrategia_concursos_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_estrategia_concursos_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<EstrategiaConcursosCourse>, String> {- let guard = state.estrategia_concursos_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.estrategia_concursos_courses_cache.lock().await;- *cache = Some(crate::EstrategiaConcursosCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn estrategia_concursos_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<EstrategiaConcursosCourse>, String> {- {- let cache = state.estrategia_concursos_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_estrategia_concursos_courses(&state).await-}--#[tauri::command]-pub async fn estrategia_concursos_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<EstrategiaConcursosCourse>, String> {- {- let mut cache = state.estrategia_concursos_courses_cache.lock().await;- *cache = None;- }- fetch_estrategia_concursos_courses(&state).await-}--#[tauri::command]-pub async fn start_estrategia_concursos_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: EstrategiaConcursosCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id = course.id as u64;- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id, cancel_token.clone());- }-- let session = {- let guard = state.estrategia_concursos_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &EstrategiaConcursosDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[estrategia_concursos] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &EstrategiaConcursosDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/estrategia_ldi.rs b/src-tauri/src/commands/estrategia_ldi.rsdeleted file mode 100644index 95c99ef1..00000000--- a/src-tauri/src/commands/estrategia_ldi.rs+++ /dev/null@@ -1,254 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::estrategia_ldi::api::{self, EstrategiaLdiCourse, EstrategiaLdiSession};-use crate::platforms::estrategia_ldi::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct EstrategiaLdiDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn estrategia_ldi_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.estrategia_ldi_session.lock().await.take();- *state.estrategia_ldi_session_validated_at.lock().await = None;- *state.estrategia_ldi_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&token, "__Secure-SID");-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed.token).parse().unwrap());- h.insert("Cookie", parsed.cookie_string.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Origin", "https://concursos.estrategia.com".parse().unwrap());- h.insert("Referer", "https://concursos.estrategia.com/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- let session = EstrategiaLdiSession {- token: parsed.token.clone(),- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.estrategia_ldi_session.lock().await;- *guard = Some(session);- *state.estrategia_ldi_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn estrategia_ldi_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.estrategia_ldi_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.estrategia_ldi_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.estrategia_ldi_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.estrategia_ldi_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.estrategia_ldi_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.estrategia_ldi_session.lock().await.take();- *state.estrategia_ldi_session_validated_at.lock().await = None;- *state.estrategia_ldi_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn estrategia_ldi_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.estrategia_ldi_session.lock().await.take();- *state.estrategia_ldi_session_validated_at.lock().await = None;- *state.estrategia_ldi_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_estrategia_ldi_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<EstrategiaLdiCourse>, String> {- let guard = state.estrategia_ldi_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.estrategia_ldi_courses_cache.lock().await;- *cache = Some(crate::EstrategiaLdiCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn estrategia_ldi_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<EstrategiaLdiCourse>, String> {- {- let cache = state.estrategia_ldi_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_estrategia_ldi_courses(&state).await-}--#[tauri::command]-pub async fn estrategia_ldi_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<EstrategiaLdiCourse>, String> {- {- let mut cache = state.estrategia_ldi_courses_cache.lock().await;- *cache = None;- }- fetch_estrategia_ldi_courses(&state).await-}--#[tauri::command]-pub async fn start_estrategia_ldi_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: EstrategiaLdiCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.estrategia_ldi_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &EstrategiaLdiDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[estrategia_ldi] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &EstrategiaLdiDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/estrategia_militares.rs b/src-tauri/src/commands/estrategia_militares.rsdeleted file mode 100644index f66107e7..00000000--- a/src-tauri/src/commands/estrategia_militares.rs+++ /dev/null@@ -1,281 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::estrategia_militares::api::{self, EstrategiaMilitaresCourse, EstrategiaMilitaresSession};-use crate::platforms::estrategia_militares::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct EstrategiaMilitaresDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn estrategia_militares_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.estrategia_militares_session.lock().await.take();- *state.estrategia_militares_session_validated_at.lock().await = None;- *state.estrategia_militares_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&token, "__Secure-SID");-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed.token).parse().unwrap());- h.insert("Cookie", parsed.cookie_string.parse().unwrap());- h.insert("Accept", "application/json, text/plain, */*".parse().unwrap());- h.insert("Accept-Language", "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7".parse().unwrap());- h.insert("Origin", "https://militares.estrategia.com".parse().unwrap());- h.insert("Referer", "https://militares.estrategia.com/".parse().unwrap());- h.insert("x-vertical", "militares".parse().unwrap());- h.insert("x-requester-id", "front-student".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- let session = EstrategiaMilitaresSession {- token: parsed.token,- cookie_string: parsed.cookie_string,- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.estrategia_militares_session.lock().await;- *guard = Some(session);- *state.estrategia_militares_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn estrategia_militares_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.estrategia_militares_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.estrategia_militares_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.estrategia_militares_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.estrategia_militares_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.estrategia_militares_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.estrategia_militares_session.lock().await.take();- *state.estrategia_militares_session_validated_at.lock().await = None;- *state.estrategia_militares_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn estrategia_militares_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.estrategia_militares_session.lock().await.take();- *state.estrategia_militares_session_validated_at.lock().await = None;- *state.estrategia_militares_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_estrategia_militares_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<EstrategiaMilitaresCourse>, String> {- let guard = state.estrategia_militares_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.estrategia_militares_courses_cache.lock().await;- *cache = Some(crate::EstrategiaMilitaresCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn estrategia_militares_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<EstrategiaMilitaresCourse>, String> {- {- let cache = state.estrategia_militares_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_estrategia_militares_courses(&state).await-}--#[tauri::command]-pub async fn estrategia_militares_search_courses(- state: tauri::State<'_, AppState>,- query: String,-) -> Result<Vec<EstrategiaMilitaresCourse>, String> {- let guard = state.estrategia_militares_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::search_courses(session, &query)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.estrategia_militares_courses_cache.lock().await;- *cache = Some(crate::EstrategiaMilitaresCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn estrategia_militares_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<EstrategiaMilitaresCourse>, String> {- {- let mut cache = state.estrategia_militares_courses_cache.lock().await;- *cache = None;- }- fetch_estrategia_militares_courses(&state).await-}--#[tauri::command]-pub async fn start_estrategia_militares_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: EstrategiaMilitaresCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.estrategia_militares_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &EstrategiaMilitaresDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[estrategia_militares] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &EstrategiaMilitaresDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/fluencyacademy.rs b/src-tauri/src/commands/fluencyacademy.rsdeleted file mode 100644index d0358e72..00000000--- a/src-tauri/src/commands/fluencyacademy.rs+++ /dev/null@@ -1,280 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::fluencyacademy::api::{self, FluencyCourse, FluencySession};-use crate::platforms::fluencyacademy::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct FluencyDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn fluency_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.fluency_session.lock().await.take();- *state.fluency_session_validated_at.lock().await = None;- *state.fluency_courses_cache.lock().await = None;-- match api::authenticate(&email, &password).await {- Ok(session) => {- let response_email = session.email.clone();- let _ = api::save_session(&session).await;- let mut guard = state.fluency_session.lock().await;- *guard = Some(session);- *state.fluency_session_validated_at.lock().await = Some(Instant::now());- Ok(response_email)- }- Err(e) => {- tracing::error!("[fluency] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn fluency_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.fluency_session.lock().await.take();- *state.fluency_session_validated_at.lock().await = None;- *state.fluency_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = FluencySession {- token: parsed_token.clone(),- email: String::new(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Origin", "https://academy.fluency.io".parse().unwrap());- h.insert("Referer", "https://academy.fluency.io/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.fluency_session.lock().await;- *guard = Some(session);- *state.fluency_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn fluency_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.fluency_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.fluency_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.fluency_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let email = session.email.clone();-- {- let validated_at = state.fluency_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(email);- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.fluency_session_validated_at.lock().await = Some(Instant::now());- Ok(email)- }- Ok(false) => {- state.fluency_session.lock().await.take();- *state.fluency_session_validated_at.lock().await = None;- *state.fluency_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn fluency_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.fluency_session.lock().await.take();- *state.fluency_session_validated_at.lock().await = None;- *state.fluency_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_fluency_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<FluencyCourse>, String> {- let guard = state.fluency_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.fluency_courses_cache.lock().await;- *cache = Some(crate::FluencyCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn fluency_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<FluencyCourse>, String> {- {- let cache = state.fluency_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_fluency_courses(&state).await-}--#[tauri::command]-pub async fn fluency_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<FluencyCourse>, String> {- {- let mut cache = state.fluency_courses_cache.lock().await;- *cache = None;- }- fetch_fluency_courses(&state).await-}--#[tauri::command]-pub async fn start_fluency_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: FluencyCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.fluency_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &FluencyDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[fluency] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &FluencyDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/grancursos.rs b/src-tauri/src/commands/grancursos.rsdeleted file mode 100644index add5e4c4..00000000--- a/src-tauri/src/commands/grancursos.rs+++ /dev/null@@ -1,249 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::grancursos::api::{self, GranCursosCourse, GranCursosSession};-use crate::platforms::grancursos::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct GranCursosDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn grancursos_login_cookies(- state: tauri::State<'_, AppState>,- cookies: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.grancursos_session.lock().await.take();- *state.grancursos_session_validated_at.lock().await = None;- *state.grancursos_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&cookies, "laravel_session");-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Cookie", parsed.cookie_string.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Referer", "https://www.grancursosonline.com.br/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- let mut session = GranCursosSession {- cookies: parsed.cookie_string.clone(),- contract_id: None,- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- let (_, contract_id) = api::search_courses(&session, "").await.unwrap_or_default();- session.contract_id = contract_id;- let _ = api::save_session(&session).await;- let mut guard = state.grancursos_session.lock().await;- *guard = Some(session);- *state.grancursos_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid cookies".to_string()),- Err(e) => Err(format!("Cookie validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn grancursos_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.grancursos_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.grancursos_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.grancursos_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.grancursos_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.grancursos_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.grancursos_session.lock().await.take();- *state.grancursos_session_validated_at.lock().await = None;- *state.grancursos_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn grancursos_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.grancursos_session.lock().await.take();- *state.grancursos_session_validated_at.lock().await = None;- *state.grancursos_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_grancursos_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<GranCursosCourse>, String> {- let guard = state.grancursos_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.grancursos_courses_cache.lock().await;- *cache = Some(crate::GranCursosCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn grancursos_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<GranCursosCourse>, String> {- {- let cache = state.grancursos_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_grancursos_courses(&state).await-}--#[tauri::command]-pub async fn grancursos_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<GranCursosCourse>, String> {- {- let mut cache = state.grancursos_courses_cache.lock().await;- *cache = None;- }- fetch_grancursos_courses(&state).await-}--#[tauri::command]-pub async fn start_grancursos_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: GranCursosCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id = course.id as u64;- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id, cancel_token.clone());- }-- let session = {- let guard = state.grancursos_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &GranCursosDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[grancursos] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &GranCursosDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/greatcourses.rs b/src-tauri/src/commands/greatcourses.rsdeleted file mode 100644index 3507e4f8..00000000--- a/src-tauri/src/commands/greatcourses.rs+++ /dev/null@@ -1,278 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::greatcourses::api::{self, WondriumCourse, WondriumSession};-use crate::platforms::greatcourses::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct WondriumDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn wondrium_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.wondrium_session.lock().await.take();- *state.wondrium_session_validated_at.lock().await = None;- *state.wondrium_courses_cache.lock().await = None;-- match api::authenticate(&email, &password).await {- Ok(session) => {- let response_email = session.email.clone();- let _ = api::save_session(&session).await;- let mut guard = state.wondrium_session.lock().await;- *guard = Some(session);- *state.wondrium_session_validated_at.lock().await = Some(Instant::now());- Ok(response_email)- }- Err(e) => {- tracing::error!("[wondrium] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn wondrium_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.wondrium_session.lock().await.take();- *state.wondrium_session_validated_at.lock().await = None;- *state.wondrium_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = WondriumSession {- token: parsed_token.clone(),- email: String::new(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.wondrium_session.lock().await;- *guard = Some(session);- *state.wondrium_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn wondrium_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.wondrium_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.wondrium_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.wondrium_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let email = session.email.clone();-- {- let validated_at = state.wondrium_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(if email.is_empty() { "authenticated".to_string() } else { email });- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.wondrium_session_validated_at.lock().await = Some(Instant::now());- Ok(if email.is_empty() { "authenticated".to_string() } else { email })- }- Ok(false) => {- state.wondrium_session.lock().await.take();- *state.wondrium_session_validated_at.lock().await = None;- *state.wondrium_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn wondrium_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.wondrium_session.lock().await.take();- *state.wondrium_session_validated_at.lock().await = None;- *state.wondrium_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_wondrium_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<WondriumCourse>, String> {- let guard = state.wondrium_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.wondrium_courses_cache.lock().await;- *cache = Some(crate::WondriumCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn wondrium_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<WondriumCourse>, String> {- {- let cache = state.wondrium_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_wondrium_courses(&state).await-}--#[tauri::command]-pub async fn wondrium_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<WondriumCourse>, String> {- {- let mut cache = state.wondrium_courses_cache.lock().await;- *cache = None;- }- fetch_wondrium_courses(&state).await-}--#[tauri::command]-pub async fn start_wondrium_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: WondriumCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.wondrium_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &WondriumDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[wondrium] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &WondriumDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/greenn.rs b/src-tauri/src/commands/greenn.rsdeleted file mode 100644index cebeef85..00000000--- a/src-tauri/src/commands/greenn.rs+++ /dev/null@@ -1,245 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::greennclub::api::{self, GreennCourse, GreennSession};-use crate::platforms::greennclub::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct GreennDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn greenn_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.greenn_session.lock().await.take();- *state.greenn_session_validated_at.lock().await = None;- *state.greenn_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = GreennSession {- token: parsed_token.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", parsed_token.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Origin", "https://greenn.club".parse().unwrap());- h.insert("Referer", "https://greenn.club/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.greenn_session.lock().await;- *guard = Some(session);- *state.greenn_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn greenn_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.greenn_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.greenn_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.greenn_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.greenn_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.greenn_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.greenn_session.lock().await.take();- *state.greenn_session_validated_at.lock().await = None;- *state.greenn_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn greenn_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.greenn_session.lock().await.take();- *state.greenn_session_validated_at.lock().await = None;- *state.greenn_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_greenn_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<GreennCourse>, String> {- let guard = state.greenn_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.greenn_courses_cache.lock().await;- *cache = Some(crate::GreennCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn greenn_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<GreennCourse>, String> {- {- let cache = state.greenn_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_greenn_courses(&state).await-}--#[tauri::command]-pub async fn greenn_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<GreennCourse>, String> {- {- let mut cache = state.greenn_courses_cache.lock().await;- *cache = None;- }- fetch_greenn_courses(&state).await-}--#[tauri::command]-pub async fn start_greenn_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: GreennCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id = course.id as u64;- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id, cancel_token.clone());- }-- let session = {- let guard = state.greenn_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &GreennDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[greenn] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &GreennDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/gumroad.rs b/src-tauri/src/commands/gumroad.rsdeleted file mode 100644index 771f52fc..00000000--- a/src-tauri/src/commands/gumroad.rs+++ /dev/null@@ -1,280 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::gumroad::api::{self, GumroadProduct, GumroadSession};-use crate::platforms::gumroad::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct GumroadDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn gumroad_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.gumroad_session.lock().await.take();- *state.gumroad_session_validated_at.lock().await = None;- *state.gumroad_courses_cache.lock().await = None;-- match api::authenticate(&email, &password).await {- Ok(session) => {- let response_email = session.email.clone();- let _ = api::save_session(&session).await;- let mut guard = state.gumroad_session.lock().await;- *guard = Some(session);- *state.gumroad_session_validated_at.lock().await = Some(Instant::now());- Ok(response_email)- }- Err(e) => {- tracing::error!("[gumroad] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn gumroad_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.gumroad_session.lock().await.take();- *state.gumroad_session_validated_at.lock().await = None;- *state.gumroad_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = GumroadSession {- token: parsed_token.clone(),- email: String::new(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("okhttp/4.8.1")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.gumroad_session.lock().await;- *guard = Some(session);- *state.gumroad_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn gumroad_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.gumroad_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.gumroad_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.gumroad_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let email = session.email.clone();-- {- let validated_at = state.gumroad_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(email);- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.gumroad_session_validated_at.lock().await = Some(Instant::now());- Ok(email)- }- Ok(false) => {- state.gumroad_session.lock().await.take();- *state.gumroad_session_validated_at.lock().await = None;- *state.gumroad_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn gumroad_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.gumroad_session.lock().await.take();- *state.gumroad_session_validated_at.lock().await = None;- *state.gumroad_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_gumroad_products(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<GumroadProduct>, String> {- let guard = state.gumroad_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let products = api::list_products(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.gumroad_courses_cache.lock().await;- *cache = Some(crate::GumroadCoursesCache {- products: products.clone(),- fetched_at: Instant::now(),- });-- Ok(products)-}--#[tauri::command]-pub async fn gumroad_list_products(- state: tauri::State<'_, AppState>,-) -> Result<Vec<GumroadProduct>, String> {- {- let cache = state.gumroad_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.products.clone());- }- }- }-- fetch_gumroad_products(&state).await-}--#[tauri::command]-pub async fn gumroad_refresh_products(- state: tauri::State<'_, AppState>,-) -> Result<Vec<GumroadProduct>, String> {- {- let mut cache = state.gumroad_courses_cache.lock().await;- *cache = None;- }- fetch_gumroad_products(&state).await-}--#[tauri::command]-pub async fn start_gumroad_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- product_json: String,- output_dir: String,-) -> Result<String, String> {- let product: GumroadProduct =- serde_json::from_str(&product_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let product_raw: serde_json::Value =- serde_json::from_str(&product_json).map_err(|e| format!("Invalid raw JSON: {}", e))?;-- let product_name = product.name.clone();- let product_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- product.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&product_id_hash) {- return Err("Download already in progress for this product".to_string());- }- map.insert(product_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.gumroad_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_product(&app, &session, &product, &product_raw, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&product_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &GumroadDownloadCompleteEvent {- course_name: product.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[gumroad] download error for '{}': {}", product.name, e);- let _ = app.emit(- "download-complete",- &GumroadDownloadCompleteEvent {- course_name: product.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", product_name))-}diff --git a/src-tauri/src/commands/kajabi.rs b/src-tauri/src/commands/kajabi.rsdeleted file mode 100644index be767ab8..00000000--- a/src-tauri/src/commands/kajabi.rs+++ /dev/null@@ -1,371 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::kajabi::api::{self, KajabiCourse, KajabiSession};-use crate::platforms::kajabi::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct KajabiDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn kajabi_request_login_link(- email: String,-) -> Result<String, String> {- api::request_login_link(&email)- .await- .map_err(|e| format!("Login link request failed: {}", e))-}--#[tauri::command]-pub async fn kajabi_verify_login(- state: tauri::State<'_, AppState>,- email: String,- confirmation_code: String,- login_token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.kajabi_session.lock().await.take();- *state.kajabi_session_validated_at.lock().await = None;- *state.kajabi_courses_cache.lock().await = None;-- let bearer_token = api::verify_login(&email, &confirmation_code, &login_token)- .await- .map_err(|e| format!("Verification failed: {}", e))?;-- let sites = api::list_sites(&bearer_token)- .await- .map_err(|e| format!("Failed to list sites: {}", e))?;-- let site_id = sites- .first()- .map(|s| s.id.clone())- .unwrap_or_default();-- let session = KajabiSession {- token: bearer_token,- site_id,- client: reqwest::Client::new(),- };-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("KajabiMobileApp")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", session.token).parse().unwrap());- h.insert("Kjb-App-Id", "Kajabi".parse().unwrap());- h.insert("KJB-DP", "ANDROID".parse().unwrap());- h.insert("KJB-SITE-ID", session.site_id.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- let session = KajabiSession {- token: session.token,- site_id: session.site_id,- client,- };-- let _ = api::save_session(&session).await;- let mut guard = state.kajabi_session.lock().await;- *guard = Some(session);- *state.kajabi_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())-}--#[tauri::command]-pub async fn kajabi_login_token(- state: tauri::State<'_, AppState>,- token: String,- site_id: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.kajabi_session.lock().await.take();- *state.kajabi_session_validated_at.lock().await = None;- *state.kajabi_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("KajabiMobileApp")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("Kjb-App-Id", "Kajabi".parse().unwrap());- h.insert("KJB-DP", "ANDROID".parse().unwrap());- h.insert("KJB-SITE-ID", site_id.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- let session = KajabiSession {- token: parsed_token,- site_id,- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.kajabi_session.lock().await;- *guard = Some(session);- *state.kajabi_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn kajabi_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.kajabi_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.kajabi_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.kajabi_session.lock().await;- let _session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.kajabi_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = guard.as_ref().unwrap().clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.kajabi_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.kajabi_session.lock().await.take();- *state.kajabi_session_validated_at.lock().await = None;- *state.kajabi_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn kajabi_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.kajabi_session.lock().await.take();- *state.kajabi_session_validated_at.lock().await = None;- *state.kajabi_courses_cache.lock().await = None;- Ok(())-}--#[tauri::command]-pub async fn kajabi_list_sites(- state: tauri::State<'_, AppState>,-) -> Result<Vec<api::KajabiSite>, String> {- let guard = state.kajabi_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- api::list_sites(&session.token)- .await- .map_err(|e| e.to_string())-}--#[tauri::command]-pub async fn kajabi_set_site(- state: tauri::State<'_, AppState>,- site_id: String,-) -> Result<(), String> {- let mut guard = state.kajabi_session.lock().await;- let session = guard- .as_mut()- .ok_or_else(|| "Not authenticated".to_string())?;-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("KajabiMobileApp")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", session.token).parse().unwrap());- h.insert("Kjb-App-Id", "Kajabi".parse().unwrap());- h.insert("KJB-DP", "ANDROID".parse().unwrap());- h.insert("KJB-SITE-ID", site_id.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- session.site_id = site_id;- session.client = client;- let _ = api::save_session(session).await;- Ok(())-}--async fn fetch_kajabi_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<KajabiCourse>, String> {- let guard = state.kajabi_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.kajabi_courses_cache.lock().await;- *cache = Some(crate::KajabiCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn kajabi_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<KajabiCourse>, String> {- {- let cache = state.kajabi_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_kajabi_courses(&state).await-}--#[tauri::command]-pub async fn kajabi_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<KajabiCourse>, String> {- {- let mut cache = state.kajabi_courses_cache.lock().await;- *cache = None;- }- fetch_kajabi_courses(&state).await-}--#[tauri::command]-pub async fn start_kajabi_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: KajabiCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.kajabi_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &KajabiDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[kajabi] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &KajabiDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/kirvano.rs b/src-tauri/src/commands/kirvano.rsdeleted file mode 100644index 5ba1c2d4..00000000--- a/src-tauri/src/commands/kirvano.rs+++ /dev/null@@ -1,280 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::kirvano::api::{self, KirvanoCourse, KirvanoSession};-use crate::platforms::kirvano::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct KirvanoDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn kirvano_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.kirvano_session.lock().await.take();- *state.kirvano_session_validated_at.lock().await = None;- *state.kirvano_courses_cache.lock().await = None;-- match api::authenticate(&email, &password).await {- Ok(session) => {- let response_email = session.email.clone();- let _ = api::save_session(&session).await;- let mut guard = state.kirvano_session.lock().await;- *guard = Some(session);- *state.kirvano_session_validated_at.lock().await = Some(Instant::now());- Ok(response_email)- }- Err(e) => {- tracing::error!("[kirvano] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn kirvano_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.kirvano_session.lock().await.take();- *state.kirvano_session_validated_at.lock().await = None;- *state.kirvano_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = KirvanoSession {- token: parsed_token.clone(),- email: String::new(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Origin", "https://app.kirvano.com".parse().unwrap());- h.insert("Referer", "https://app.kirvano.com/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.kirvano_session.lock().await;- *guard = Some(session);- *state.kirvano_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn kirvano_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.kirvano_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.kirvano_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.kirvano_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let email = session.email.clone();-- {- let validated_at = state.kirvano_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(email);- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.kirvano_session_validated_at.lock().await = Some(Instant::now());- Ok(email)- }- Ok(false) => {- state.kirvano_session.lock().await.take();- *state.kirvano_session_validated_at.lock().await = None;- *state.kirvano_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn kirvano_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.kirvano_session.lock().await.take();- *state.kirvano_session_validated_at.lock().await = None;- *state.kirvano_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_kirvano_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<KirvanoCourse>, String> {- let guard = state.kirvano_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.kirvano_courses_cache.lock().await;- *cache = Some(crate::KirvanoCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn kirvano_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<KirvanoCourse>, String> {- {- let cache = state.kirvano_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_kirvano_courses(&state).await-}--#[tauri::command]-pub async fn kirvano_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<KirvanoCourse>, String> {- {- let mut cache = state.kirvano_courses_cache.lock().await;- *cache = None;- }- fetch_kirvano_courses(&state).await-}--#[tauri::command]-pub async fn start_kirvano_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: KirvanoCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.kirvano_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &KirvanoDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[kirvano] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &KirvanoDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/kiwify.rs b/src-tauri/src/commands/kiwify.rsdeleted file mode 100644index a36c80ac..00000000--- a/src-tauri/src/commands/kiwify.rs+++ /dev/null@@ -1,281 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::kiwify::api::{self, KiwifyCourse, KiwifySession};-use crate::platforms::kiwify::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct KiwifyDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn kiwify_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.kiwify_session.lock().await.take();- *state.kiwify_session_validated_at.lock().await = None;- *state.kiwify_courses_cache.lock().await = None;-- match api::authenticate(&email, &password).await {- Ok(session) => {- let response_email = session.email.clone();- let _ = api::save_session(&session).await;- let mut guard = state.kiwify_session.lock().await;- *guard = Some(session);- *state.kiwify_session_validated_at.lock().await = Some(Instant::now());- Ok(response_email)- }- Err(e) => {- tracing::error!("[kiwify] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn kiwify_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.kiwify_session.lock().await.take();- *state.kiwify_session_validated_at.lock().await = None;- *state.kiwify_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = KiwifySession {- token: parsed_token.clone(),- email: String::new(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Origin", "https://admin.kiwify.com.br".parse().unwrap());- h.insert("Referer", "https://admin.kiwify.com.br/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.kiwify_session.lock().await;- *guard = Some(session);- *state.kiwify_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn kiwify_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.kiwify_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.kiwify_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.kiwify_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let email = session.email.clone();-- {- let validated_at = state.kiwify_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(email);- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.kiwify_session_validated_at.lock().await = Some(Instant::now());- Ok(email)- }- Ok(false) => {- state.kiwify_session.lock().await.take();- *state.kiwify_session_validated_at.lock().await = None;- *state.kiwify_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn kiwify_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.kiwify_session.lock().await.take();- *state.kiwify_session_validated_at.lock().await = None;- *state.kiwify_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_kiwify_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<KiwifyCourse>, String> {- let session = {- let guard = state.kiwify_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- let courses = tokio::time::timeout(- std::time::Duration::from_secs(60),- api::list_courses(&session),- )- .await- .map_err(|_| "Timeout loading courses (60s)".to_string())?- .map_err(|e| e.to_string())?;-- let mut cache = state.kiwify_courses_cache.lock().await;- *cache = Some(crate::KiwifyCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn kiwify_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<KiwifyCourse>, String> {- {- let cache = state.kiwify_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_kiwify_courses(&state).await-}--#[tauri::command]-pub async fn kiwify_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<KiwifyCourse>, String> {- {- let mut cache = state.kiwify_courses_cache.lock().await;- *cache = None;- }- fetch_kiwify_courses(&state).await-}--#[tauri::command]-pub async fn start_kiwify_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: KiwifyCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id = course.id as u64;- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id, cancel_token.clone());- }-- let session = {- let guard = state.kiwify_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &KiwifyDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[kiwify] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &KiwifyDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/masterclass.rs b/src-tauri/src/commands/masterclass.rsdeleted file mode 100644index 91f4a873..00000000--- a/src-tauri/src/commands/masterclass.rs+++ /dev/null@@ -1,237 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::masterclass::api::{self, MasterClassCourse};-use crate::platforms::masterclass::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct MasterClassDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn masterclass_login_cookies(- state: tauri::State<'_, AppState>,- cookies: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.masterclass_session.lock().await.take();- *state.masterclass_session_validated_at.lock().await = None;- *state.masterclass_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&cookies, "access_token");-- let session = api::authenticate_cookies(&parsed.cookie_string)- .await- .map_err(|e| format!("Authentication failed: {}", e))?;-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.masterclass_session.lock().await;- *guard = Some(session);- *state.masterclass_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid cookies".to_string()),- Err(e) => Err(format!("Cookie validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn masterclass_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.masterclass_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.masterclass_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.masterclass_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.masterclass_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.masterclass_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.masterclass_session.lock().await.take();- *state.masterclass_session_validated_at.lock().await = None;- *state.masterclass_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn masterclass_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.masterclass_session.lock().await.take();- *state.masterclass_session_validated_at.lock().await = None;- *state.masterclass_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_masterclass_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<MasterClassCourse>, String> {- let guard = state.masterclass_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.masterclass_courses_cache.lock().await;- *cache = Some(crate::MasterClassCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn masterclass_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<MasterClassCourse>, String> {- {- let cache = state.masterclass_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_masterclass_courses(&state).await-}--#[tauri::command]-pub async fn masterclass_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<MasterClassCourse>, String> {- {- let mut cache = state.masterclass_courses_cache.lock().await;- *cache = None;- }- fetch_masterclass_courses(&state).await-}--#[tauri::command]-pub async fn start_masterclass_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: MasterClassCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.masterclass_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &MasterClassDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[masterclass] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &MasterClassDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/medcel.rs b/src-tauri/src/commands/medcel.rsdeleted file mode 100644index f7d34ac4..00000000--- a/src-tauri/src/commands/medcel.rs+++ /dev/null@@ -1,275 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::medcel::api::{self, MedcelCourse, MedcelSession};-use crate::platforms::medcel::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct MedcelDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn medcel_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,- api_key: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.medcel_session.lock().await.take();- *state.medcel_session_validated_at.lock().await = None;- *state.medcel_courses_cache.lock().await = None;-- match api::authenticate(&email, &password, &api_key).await {- Ok(session) => {- let _ = api::save_session(&session).await;- let mut guard = state.medcel_session.lock().await;- *guard = Some(session);- *state.medcel_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Err(e) => {- tracing::error!("[medcel] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn medcel_login_token(- state: tauri::State<'_, AppState>,- token: String,- api_key: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.medcel_session.lock().await.take();- *state.medcel_session_validated_at.lock().await = None;- *state.medcel_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let client = api::build_client_with_origin(&parsed_token, &api_key, "https://areaaluno.medcel.com.br")- .map_err(|e| format!("Failed to build client: {}", e))?;-- let mut session = MedcelSession {- token: parsed_token.clone(),- api_key: api_key.clone(),- student_id: String::new(),- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- match api::fetch_student_id(&session).await {- Ok(id) => session.student_id = id,- Err(e) => tracing::warn!("[medcel] could not fetch student id: {}", e),- }- let _ = api::save_session(&session).await;- let mut guard = state.medcel_session.lock().await;- *guard = Some(session);- *state.medcel_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn medcel_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.medcel_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.medcel_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.medcel_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.medcel_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.medcel_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.medcel_session.lock().await.take();- *state.medcel_session_validated_at.lock().await = None;- *state.medcel_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn medcel_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.medcel_session.lock().await.take();- *state.medcel_session_validated_at.lock().await = None;- *state.medcel_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_medcel_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<MedcelCourse>, String> {- let guard = state.medcel_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.medcel_courses_cache.lock().await;- *cache = Some(crate::MedcelCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn medcel_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<MedcelCourse>, String> {- {- let cache = state.medcel_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_medcel_courses(&state).await-}--#[tauri::command]-pub async fn medcel_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<MedcelCourse>, String> {- {- let mut cache = state.medcel_courses_cache.lock().await;- *cache = None;- }- fetch_medcel_courses(&state).await-}--#[tauri::command]-pub async fn start_medcel_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: MedcelCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.medcel_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &MedcelDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[medcel] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &MedcelDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/medcof.rs b/src-tauri/src/commands/medcof.rsdeleted file mode 100644index 95eccccc..00000000--- a/src-tauri/src/commands/medcof.rs+++ /dev/null@@ -1,249 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::medcof::api::{self, MedcofCourse, MedcofSession};-use crate::platforms::medcof::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct MedcofDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn medcof_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.medcof_session.lock().await.take();- *state.medcof_session_validated_at.lock().await = None;- *state.medcof_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = MedcofSession {- token: parsed_token.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.medcof_session.lock().await;- *guard = Some(session);- *state.medcof_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn medcof_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.medcof_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.medcof_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.medcof_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.medcof_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.medcof_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.medcof_session.lock().await.take();- *state.medcof_session_validated_at.lock().await = None;- *state.medcof_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn medcof_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.medcof_session.lock().await.take();- *state.medcof_session_validated_at.lock().await = None;- *state.medcof_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_medcof_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<MedcofCourse>, String> {- let guard = state.medcof_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.medcof_courses_cache.lock().await;- *cache = Some(crate::MedcofCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn medcof_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<MedcofCourse>, String> {- {- let cache = state.medcof_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_medcof_courses(&state).await-}--#[tauri::command]-pub async fn medcof_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<MedcofCourse>, String> {- {- let mut cache = state.medcof_courses_cache.lock().await;- *cache = None;- }- fetch_medcof_courses(&state).await-}--#[tauri::command]-pub async fn start_medcof_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: MedcofCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.medcof_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &MedcofDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[medcof] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &MedcofDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/medway.rs b/src-tauri/src/commands/medway.rsdeleted file mode 100644index 7b02d7fc..00000000--- a/src-tauri/src/commands/medway.rs+++ /dev/null@@ -1,245 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::medway::api::{self, MedwayCourse, MedwaySession};-use crate::platforms::medway::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct MedwayDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn medway_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.medway_session.lock().await.take();- *state.medway_session_validated_at.lock().await = None;- *state.medway_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- let session = MedwaySession {- token: parsed_token.clone(),- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.medway_session.lock().await;- *guard = Some(session);- *state.medway_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn medway_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.medway_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.medway_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.medway_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.medway_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.medway_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.medway_session.lock().await.take();- *state.medway_session_validated_at.lock().await = None;- *state.medway_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn medway_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.medway_session.lock().await.take();- *state.medway_session_validated_at.lock().await = None;- *state.medway_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_medway_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<MedwayCourse>, String> {- let guard = state.medway_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.medway_courses_cache.lock().await;- *cache = Some(crate::MedwayCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn medway_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<MedwayCourse>, String> {- {- let cache = state.medway_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_medway_courses(&state).await-}--#[tauri::command]-pub async fn medway_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<MedwayCourse>, String> {- {- let mut cache = state.medway_courses_cache.lock().await;- *cache = None;- }- fetch_medway_courses(&state).await-}--#[tauri::command]-pub async fn start_medway_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: MedwayCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id = course.id as u64;- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id, cancel_token.clone());- }-- let session = {- let guard = state.medway_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &MedwayDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[medway] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &MedwayDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/memberkit_cmd.rs b/src-tauri/src/commands/memberkit_cmd.rsdeleted file mode 100644index 9c11f2eb..00000000--- a/src-tauri/src/commands/memberkit_cmd.rs+++ /dev/null@@ -1,281 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::memberkit::api::{self, MemberkitCourse, MemberkitSession};-use crate::platforms::memberkit::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct MemberkitDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn memberkit_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,- site_url: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.memberkit_session.lock().await.take();- *state.memberkit_session_validated_at.lock().await = None;- *state.memberkit_courses_cache.lock().await = None;-- match api::authenticate(&email, &password, &site_url).await {- Ok(session) => {- let response_url = session.site_url.clone();- let _ = api::save_session(&session).await;- let mut guard = state.memberkit_session.lock().await;- *guard = Some(session);- *state.memberkit_session_validated_at.lock().await = Some(Instant::now());- Ok(response_url)- }- Err(e) => {- tracing::error!("[memberkit] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn memberkit_login_cookie(- state: tauri::State<'_, AppState>,- cookie: String,- site_url: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.memberkit_session.lock().await.take();- *state.memberkit_session_validated_at.lock().await = None;- *state.memberkit_courses_cache.lock().await = None;-- let trimmed_url = site_url.trim_end_matches('/').to_string();- let parsed = crate::core::cookie_parser::parse_cookie_input(&cookie, "_memberkit_session");-- let session = MemberkitSession {- cookies: parsed.token.clone(),- site_url: trimmed_url.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Cookie", parsed.cookie_string.parse().unwrap());- h.insert("Referer", format!("{}/", trimmed_url).parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.memberkit_session.lock().await;- *guard = Some(session);- *state.memberkit_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid cookie".to_string()),- Err(e) => Err(format!("Cookie validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn memberkit_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.memberkit_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.memberkit_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.memberkit_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let site_url = session.site_url.clone();-- {- let validated_at = state.memberkit_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(site_url);- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.memberkit_session_validated_at.lock().await = Some(Instant::now());- Ok(site_url)- }- Ok(false) => {- state.memberkit_session.lock().await.take();- *state.memberkit_session_validated_at.lock().await = None;- *state.memberkit_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn memberkit_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.memberkit_session.lock().await.take();- *state.memberkit_session_validated_at.lock().await = None;- *state.memberkit_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_memberkit_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<MemberkitCourse>, String> {- let guard = state.memberkit_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.memberkit_courses_cache.lock().await;- *cache = Some(crate::MemberkitCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn memberkit_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<MemberkitCourse>, String> {- {- let cache = state.memberkit_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_memberkit_courses(&state).await-}--#[tauri::command]-pub async fn memberkit_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<MemberkitCourse>, String> {- {- let mut cache = state.memberkit_courses_cache.lock().await;- *cache = None;- }- fetch_memberkit_courses(&state).await-}--#[tauri::command]-pub async fn start_memberkit_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: MemberkitCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.memberkit_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &MemberkitDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[memberkit] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &MemberkitDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/nutror.rs b/src-tauri/src/commands/nutror.rsdeleted file mode 100644index 933cef47..00000000--- a/src-tauri/src/commands/nutror.rs+++ /dev/null@@ -1,272 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::eduzznutror::api::{self, NutrorCourse, NutrorSession};-use crate::platforms::eduzznutror::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct NutrorDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn nutror_login_token(- state: tauri::State<'_, AppState>,- token: String,- refresh_token: Option<String>,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.nutror_session.lock().await.take();- *state.nutror_session_validated_at.lock().await = None;- *state.nutror_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = NutrorSession {- token: parsed_token.clone(),- refresh_token: refresh_token.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("FrontVersion", "1458".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.nutror_session.lock().await;- *guard = Some(session);- *state.nutror_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn nutror_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.nutror_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.nutror_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.nutror_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.nutror_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.nutror_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- let session_clone2 = {- let guard = state.nutror_session.lock().await;- guard.as_ref().cloned()- };-- if let Some(old_session) = session_clone2 {- if old_session.refresh_token.is_some() {- match api::refresh_token(&old_session).await {- Ok(new_session) => {- let _ = api::save_session(&new_session).await;- let mut guard = state.nutror_session.lock().await;- *guard = Some(new_session);- *state.nutror_session_validated_at.lock().await = Some(Instant::now());- return Ok("authenticated".to_string());- }- Err(_) => {}- }- }- }-- state.nutror_session.lock().await.take();- *state.nutror_session_validated_at.lock().await = None;- *state.nutror_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn nutror_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.nutror_session.lock().await.take();- *state.nutror_session_validated_at.lock().await = None;- *state.nutror_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_nutror_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<NutrorCourse>, String> {- let guard = state.nutror_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.nutror_courses_cache.lock().await;- *cache = Some(crate::NutrorCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn nutror_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<NutrorCourse>, String> {- {- let cache = state.nutror_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_nutror_courses(&state).await-}--#[tauri::command]-pub async fn nutror_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<NutrorCourse>, String> {- {- let mut cache = state.nutror_courses_cache.lock().await;- *cache = None;- }- fetch_nutror_courses(&state).await-}--#[tauri::command]-pub async fn start_nutror_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: NutrorCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.nutror_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &NutrorDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[nutror] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &NutrorDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/pluralsight.rs b/src-tauri/src/commands/pluralsight.rsdeleted file mode 100644index d26de6a4..00000000--- a/src-tauri/src/commands/pluralsight.rs+++ /dev/null@@ -1,236 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::pluralsight::api::{self, PluralsightCourse};-use crate::platforms::pluralsight::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct PluralsightDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn pluralsight_login_cookies(- state: tauri::State<'_, AppState>,- cookies: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.pluralsight_session.lock().await.take();- *state.pluralsight_session_validated_at.lock().await = None;- *state.pluralsight_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&cookies, "PsJwt-production");-- let session = api::authenticate_cookies(&parsed.cookie_string)- .map_err(|e| format!("Authentication failed: {}", e))?;-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.pluralsight_session.lock().await;- *guard = Some(session);- *state.pluralsight_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid cookies".to_string()),- Err(e) => Err(format!("Cookie validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn pluralsight_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.pluralsight_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.pluralsight_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.pluralsight_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.pluralsight_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.pluralsight_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.pluralsight_session.lock().await.take();- *state.pluralsight_session_validated_at.lock().await = None;- *state.pluralsight_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn pluralsight_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.pluralsight_session.lock().await.take();- *state.pluralsight_session_validated_at.lock().await = None;- *state.pluralsight_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_pluralsight_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<PluralsightCourse>, String> {- let guard = state.pluralsight_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.pluralsight_courses_cache.lock().await;- *cache = Some(crate::PluralsightCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn pluralsight_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<PluralsightCourse>, String> {- {- let cache = state.pluralsight_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_pluralsight_courses(&state).await-}--#[tauri::command]-pub async fn pluralsight_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<PluralsightCourse>, String> {- {- let mut cache = state.pluralsight_courses_cache.lock().await;- *cache = None;- }- fetch_pluralsight_courses(&state).await-}--#[tauri::command]-pub async fn start_pluralsight_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: PluralsightCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.pluralsight_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &PluralsightDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[pluralsight] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &PluralsightDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/rocketseat.rs b/src-tauri/src/commands/rocketseat.rsdeleted file mode 100644index 8c3c4df6..00000000--- a/src-tauri/src/commands/rocketseat.rs+++ /dev/null@@ -1,280 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::rocketseat::api::{self, RocketseatCourse};-use crate::platforms::rocketseat::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct RocketseatDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn rocketseat_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.rocketseat_session.lock().await.take();- *state.rocketseat_session_validated_at.lock().await = None;- *state.rocketseat_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&token, "skylab_next_access_token_v4");-- tracing::info!(- "[rocketseat] parsed: token_len={}, cookie_count={}, cookie_string_len={}",- parsed.token.len(),- parsed.cookies.len(),- parsed.cookie_string.len()- );-- let parsed_token = if parsed.token.is_empty() {- let bearer = crate::core::cookie_parser::parse_bearer_input(&token);- tracing::info!("[rocketseat] fallback to parse_bearer_input: len={}", bearer.len());- bearer- } else {- parsed.token- };-- if parsed_token.is_empty() || parsed_token.len() < 10 {- return Err("Could not extract token. Paste the value of cookie 'skylab_next_access_token_v4' or the full cookie JSON.".to_string());- }-- tracing::info!("[rocketseat] using token: {}...", &parsed_token[..parsed_token.len().min(30)]);-- let session = api::create_session(&parsed_token)- .map_err(|e| format!("Failed to create session: {}", e))?;-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.rocketseat_session.lock().await;- *guard = Some(session);- *state.rocketseat_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn rocketseat_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.rocketseat_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.rocketseat_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.rocketseat_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.rocketseat_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.rocketseat_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.rocketseat_session.lock().await.take();- *state.rocketseat_session_validated_at.lock().await = None;- *state.rocketseat_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn rocketseat_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.rocketseat_session.lock().await.take();- *state.rocketseat_session_validated_at.lock().await = None;- *state.rocketseat_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_rocketseat_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<RocketseatCourse>, String> {- let guard = state.rocketseat_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.rocketseat_courses_cache.lock().await;- *cache = Some(crate::RocketseatCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn rocketseat_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<RocketseatCourse>, String> {- {- let cache = state.rocketseat_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_rocketseat_courses(&state).await-}--#[tauri::command]-pub async fn rocketseat_search_courses(- state: tauri::State<'_, AppState>,- query: String,-) -> Result<Vec<RocketseatCourse>, String> {- let guard = state.rocketseat_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::search_courses(session, &query)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.rocketseat_courses_cache.lock().await;- *cache = Some(crate::RocketseatCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn rocketseat_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<RocketseatCourse>, String> {- {- let mut cache = state.rocketseat_courses_cache.lock().await;- *cache = None;- }- fetch_rocketseat_courses(&state).await-}--#[tauri::command]-pub async fn start_rocketseat_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: RocketseatCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.rocketseat_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &RocketseatDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[rocketseat] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &RocketseatDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/skool.rs b/src-tauri/src/commands/skool.rsdeleted file mode 100644index 0f2111c7..00000000--- a/src-tauri/src/commands/skool.rs+++ /dev/null@@ -1,281 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::skool::api::{self, SkoolGroup, SkoolSession};-use crate::platforms::skool::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct SkoolDownloadCompleteEvent {- group_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn skool_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.skool_session.lock().await.take();- *state.skool_session_validated_at.lock().await = None;- *state.skool_courses_cache.lock().await = None;-- match api::authenticate(&email, &password).await {- Ok(session) => {- let _ = api::save_session(&session).await;- let mut guard = state.skool_session.lock().await;- *guard = Some(session);- *state.skool_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Err(e) => {- tracing::error!("[skool] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn skool_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.skool_session.lock().await.take();- *state.skool_session_validated_at.lock().await = None;- *state.skool_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&token, "skooltok");-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Cookie", parsed.cookie_string.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Referer", "https://www.skool.com/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- let build_id = String::new();-- let session = SkoolSession {- cookie_token: parsed.token,- build_id,- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.skool_session.lock().await;- *guard = Some(session);- *state.skool_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn skool_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.skool_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.skool_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.skool_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.skool_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.skool_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.skool_session.lock().await.take();- *state.skool_session_validated_at.lock().await = None;- *state.skool_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn skool_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.skool_session.lock().await.take();- *state.skool_session_validated_at.lock().await = None;- *state.skool_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_skool_groups(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<SkoolGroup>, String> {- let guard = state.skool_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let groups = api::list_groups(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.skool_courses_cache.lock().await;- *cache = Some(crate::SkoolCoursesCache {- groups: groups.clone(),- fetched_at: Instant::now(),- });-- Ok(groups)-}--#[tauri::command]-pub async fn skool_list_groups(- state: tauri::State<'_, AppState>,-) -> Result<Vec<SkoolGroup>, String> {- {- let cache = state.skool_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.groups.clone());- }- }- }-- fetch_skool_groups(&state).await-}--#[tauri::command]-pub async fn skool_refresh_groups(- state: tauri::State<'_, AppState>,-) -> Result<Vec<SkoolGroup>, String> {- {- let mut cache = state.skool_courses_cache.lock().await;- *cache = None;- }- fetch_skool_groups(&state).await-}--#[tauri::command]-pub async fn start_skool_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let group: SkoolGroup =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let group_name = group.name.clone();- let group_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- group.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&group_id_hash) {- return Err("Download already in progress for this group".to_string());- }- map.insert(group_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.skool_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &group, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&group_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &SkoolDownloadCompleteEvent {- group_name: group.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[skool] download error for '{}': {}", group.name, e);- let _ = app.emit(- "download-complete",- &SkoolDownloadCompleteEvent {- group_name: group.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", group_name))-}diff --git a/src-tauri/src/commands/teachable.rs b/src-tauri/src/commands/teachable.rsdeleted file mode 100644index 2060d89c..00000000--- a/src-tauri/src/commands/teachable.rs+++ /dev/null@@ -1,323 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::teachable::api::{self, TeachableCourse, TeachableSession};-use crate::platforms::teachable::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct TeachableDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn teachable_request_otp(- email: String,-) -> Result<(), String> {- api::request_otp(&email)- .await- .map_err(|e| format!("OTP request failed: {}", e))-}--#[tauri::command]-pub async fn teachable_verify_otp(- state: tauri::State<'_, AppState>,- email: String,- otp_code: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.teachable_session.lock().await.take();- *state.teachable_session_validated_at.lock().await = None;- *state.teachable_courses_cache.lock().await = None;-- match api::verify_otp(&email, &otp_code).await {- Ok(session) => {- let _ = api::save_session(&session).await;- let mut guard = state.teachable_session.lock().await;- *guard = Some(session);- *state.teachable_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Err(e) => {- tracing::error!("[teachable] OTP verify failed: {}", e);- Err(format!("OTP verification failed: {}", e))- }- }-}--#[tauri::command]-pub async fn teachable_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.teachable_session.lock().await.take();- *state.teachable_session_validated_at.lock().await = None;- *state.teachable_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("ktor-client")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", format!("Bearer {}", parsed_token).parse().unwrap());- h.insert("CLIENT-TOKEN", "9e44e885ac601aae4ee7109baec9ee0a503bfbb4fd11cbcb7d1de9d5e84f395b37d1521b08add19c2604dbe3c1d6c986bbd62a2513884e04e5b40704e77944e4".parse().unwrap());- h.insert("X-APP-VERSION", "2.3.0".parse().unwrap());- h.insert("X-DEVICE-OS", "Android 35".parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?;-- let session = TeachableSession {- token: parsed_token,- school_id: None,- client,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.teachable_session.lock().await;- *guard = Some(session);- *state.teachable_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn teachable_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.teachable_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.teachable_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.teachable_session.lock().await;- let _session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.teachable_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = guard.as_ref().unwrap().clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.teachable_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.teachable_session.lock().await.take();- *state.teachable_session_validated_at.lock().await = None;- *state.teachable_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn teachable_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.teachable_session.lock().await.take();- *state.teachable_session_validated_at.lock().await = None;- *state.teachable_courses_cache.lock().await = None;- Ok(())-}--#[tauri::command]-pub async fn teachable_set_school(- state: tauri::State<'_, AppState>,- school_id: String,-) -> Result<(), String> {- let mut guard = state.teachable_session.lock().await;- let session = guard- .as_mut()- .ok_or_else(|| "Not authenticated".to_string())?;- session.school_id = Some(school_id);- let _ = api::save_session(session).await;- Ok(())-}--#[tauri::command]-pub async fn teachable_list_schools(- state: tauri::State<'_, AppState>,-) -> Result<Vec<api::TeachableSchool>, String> {- let guard = state.teachable_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- api::list_schools(session)- .await- .map_err(|e| e.to_string())-}--async fn fetch_teachable_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<TeachableCourse>, String> {- let guard = state.teachable_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let school_id = session- .school_id- .as_ref()- .ok_or_else(|| "No school selected. Please select a school first.".to_string())?;-- let courses = api::list_courses(session, school_id)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.teachable_courses_cache.lock().await;- *cache = Some(crate::TeachableCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn teachable_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<TeachableCourse>, String> {- {- let cache = state.teachable_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_teachable_courses(&state).await-}--#[tauri::command]-pub async fn teachable_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<TeachableCourse>, String> {- {- let mut cache = state.teachable_courses_cache.lock().await;- *cache = None;- }- fetch_teachable_courses(&state).await-}--#[tauri::command]-pub async fn start_teachable_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: TeachableCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.teachable_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &TeachableDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[teachable] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &TeachableDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/telegram.rs b/src-tauri/src/commands/telegram.rsdeleted file mode 100644index c223da1a..00000000--- a/src-tauri/src/commands/telegram.rs+++ /dev/null@@ -1,597 +0,0 @@-use std::sync::Arc;--use serde::{Deserialize, Serialize};-use tauri::Emitter;-use tokio::sync::{mpsc, Semaphore};-use tokio_util::sync::CancellationToken;--use base64::Engine;--use crate::platforms::telegram::api::{self, TelegramChat, TelegramMediaItem};-use crate::platforms::telegram::auth::{self, QrPollStatus, VerifyError};-use crate::platforms::telegram::thumbnail_cache;-use crate::storage::config;-use crate::AppState;--#[derive(Clone, Serialize)]-struct GenericDownloadProgress {- id: u64,- title: String,- platform: String,- percent: f64,-}--#[derive(Clone, Serialize)]-struct GenericDownloadComplete {- id: u64,- title: String,- platform: String,- success: bool,- error: Option<String>,- file_path: Option<String>,- file_size_bytes: Option<u64>,- file_count: Option<u32>,-}--#[derive(Clone, Serialize)]-pub struct TelegramDownloadStarted {- pub id: u64,- pub file_name: String,-}--#[tauri::command]-pub async fn telegram_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- auth::check_session(&state.telegram_session)- .await- .map_err(|e| e.to_string())-}--#[derive(Clone, Serialize)]-pub struct QrStartResponse {- pub svg: String,- pub expires: i32,-}--#[tauri::command]-pub async fn telegram_qr_start(- state: tauri::State<'_, AppState>,-) -> Result<QrStartResponse, String> {- let result = auth::qr_login_start(&state.telegram_session)- .await- .map_err(|e| e.to_string())?;- Ok(QrStartResponse {- svg: result.qr_svg,- expires: result.expires,- })-}--#[tauri::command]-pub async fn telegram_qr_poll(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- match auth::qr_login_poll(&state.telegram_session).await {- Ok(QrPollStatus::Waiting) => Ok("waiting".to_string()),- Ok(QrPollStatus::Success { phone }) => Ok(format!("success:{}", phone)),- Ok(QrPollStatus::PasswordRequired { hint }) => {- if hint.is_empty() {- Ok("password_required".to_string())- } else {- Ok(format!("password_required:{}", hint))- }- }- Err(e) => Err(e.to_string()),- }-}--#[tauri::command]-pub async fn telegram_send_code(- state: tauri::State<'_, AppState>,- phone: String,-) -> Result<(), String> {- auth::send_code(&state.telegram_session, &phone)- .await- .map_err(|e| e.to_string())-}--#[tauri::command]-pub async fn telegram_verify_code(- state: tauri::State<'_, AppState>,- code: String,-) -> Result<String, String> {- match auth::verify_code(&state.telegram_session, &code).await {- Ok(phone) => Ok(phone),- Err(VerifyError::InvalidCode) => Err("invalid_code".to_string()),- Err(VerifyError::PasswordRequired { hint }) => {- Err(format!("password_required:{}", hint))- }- Err(VerifyError::NoSession) => Err("no_session".to_string()),- Err(VerifyError::Other(msg)) => Err(msg),- }-}--#[tauri::command]-pub async fn telegram_verify_2fa(- state: tauri::State<'_, AppState>,- password: String,-) -> Result<String, String> {- auth::verify_password(&state.telegram_session, &password)- .await- .map_err(|e| e.to_string())-}--#[tauri::command]-pub async fn telegram_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- thumbnail_cache::clear_cache().await;- auth::logout(&state.telegram_session)- .await- .map_err(|e| e.to_string())-}--#[tauri::command]-pub async fn telegram_list_chats(- state: tauri::State<'_, AppState>,-) -> Result<Vec<TelegramChat>, String> {- api::list_chats(&state.telegram_session)- .await- .map_err(|e| e.to_string())-}--#[tauri::command]-pub async fn telegram_list_media(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- chat_id: i64,- chat_type: String,- media_type: Option<String>,- offset: i32,- limit: u32,-) -> Result<Vec<TelegramMediaItem>, String> {- let fix_extensions = config::load_settings(&app).telegram.fix_file_extensions;- api::list_media(- &state.telegram_session,- chat_id,- &chat_type,- media_type.as_deref(),- offset,- limit,- fix_extensions,- )- .await- .map_err(|e| e.to_string())-}--#[tauri::command]-pub async fn telegram_download_media(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- chat_id: i64,- chat_type: String,- message_id: i32,- file_name: String,- output_dir: String,-) -> Result<TelegramDownloadStarted, String> {- tracing::info!(- "[tg-cmd] telegram_download_media: chat_id={}, chat_type={}, message_id={}, file_name={}",- chat_id, chat_type, message_id, file_name- );-- let download_id = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_millis() as u64;-- let cancel_token = CancellationToken::new();-- {- let mut active = state.active_generic_downloads.lock().await;- let key = format!("tg:{}:{}", chat_id, message_id);- if active.values().any(|(u, _)| u == &key) {- return Err("Download already in progress for this media".to_string());- }- active.insert(download_id, (key, cancel_token.clone()));- }-- let session = state.telegram_session.clone();- let active_downloads = state.active_generic_downloads.clone();- let file_name_clone = file_name.clone();-- tokio::spawn(async move {- let output_path = std::path::PathBuf::from(&output_dir).join(&file_name_clone);-- let _ = app.emit("generic-download-progress", &GenericDownloadProgress {- id: download_id,- title: file_name_clone.clone(),- platform: "telegram".to_string(),- percent: 0.0,- });-- let (tx, mut rx) = mpsc::channel::<f64>(32);-- let app_progress = app.clone();- let file_name_progress = file_name_clone.clone();- let progress_forwarder = tokio::spawn(async move {- while let Some(percent) = rx.recv().await {- let _ = app_progress.emit("generic-download-progress", &GenericDownloadProgress {- id: download_id,- title: file_name_progress.clone(),- platform: "telegram".to_string(),- percent,- });- }- });-- let result = api::download_media_with_retry(- &session,- chat_id,- &chat_type,- message_id,- &output_path,- tx,- &cancel_token,- ).await;-- let _ = progress_forwarder.await;-- {- active_downloads.lock().await.remove(&download_id);- }-- match result {- Ok(size) => {- let _ = app.emit("generic-download-complete", &GenericDownloadComplete {- id: download_id,- title: file_name_clone,- platform: "telegram".to_string(),- success: true,- error: None,- file_path: Some(output_path.to_string_lossy().to_string()),- file_size_bytes: Some(size),- file_count: Some(1),- });- }- Err(e) => {- let _ = app.emit("generic-download-complete", &GenericDownloadComplete {- id: download_id,- title: file_name_clone,- platform: "telegram".to_string(),- success: false,- error: Some(e.to_string()),- file_path: None,- file_size_bytes: None,- file_count: None,- });- }- }- });-- Ok(TelegramDownloadStarted { id: download_id, file_name })-}--#[derive(Clone, Deserialize)]-pub struct BatchItem {- pub message_id: i32,- pub file_name: String,- pub file_size: u64,-}--#[derive(Clone, Serialize)]-struct BatchFileStatus {- batch_id: u64,- message_id: i32,- status: String, // "waiting" | "downloading" | "done" | "error" | "skipped"- percent: f64,- error: Option<String>,-}--#[tauri::command]-pub async fn telegram_download_batch(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- chat_id: i64,- chat_type: String,- chat_title: String,- items: Vec<BatchItem>,- output_dir: String,-) -> Result<u64, String> {- tracing::info!(- "[tg-cmd] telegram_download_batch: chat_id={}, chat_type={}, items={}, output_dir={}",- chat_id, chat_type, items.len(), output_dir- );-- let batch_id = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_millis() as u64;-- let cancel_token = CancellationToken::new();-- {- let mut active = state.active_generic_downloads.lock().await;- let key = format!("tg-batch:{}", batch_id);- active.insert(batch_id, (key, cancel_token.clone()));- }-- let session = state.telegram_session.clone();- let active_downloads = state.active_generic_downloads.clone();- let total_files = items.len() as u32;-- // Read Telegram settings- let tg_settings = config::load_settings(&app).telegram;- let concurrent = tg_settings.concurrent_downloads.clamp(1, 10) as usize;-- // Emit initial 0% batch progress- let _ = app.emit("generic-download-progress", &GenericDownloadProgress {- id: batch_id,- title: chat_title.clone(),- platform: "telegram".to_string(),- percent: 0.0,- });-- tokio::spawn(async move {- let semaphore = Arc::new(Semaphore::new(concurrent));- let completed = Arc::new(std::sync::atomic::AtomicU32::new(0));- let failed = Arc::new(std::sync::atomic::AtomicU32::new(0));- let skipped = Arc::new(std::sync::atomic::AtomicU32::new(0));-- let mut handles = Vec::new();-- for item in items {- let sem = semaphore.clone();- let session = session.clone();- let app = app.clone();- let chat_type = chat_type.clone();- let chat_title = chat_title.clone();- let output_dir = output_dir.clone();- let cancel = cancel_token.clone();- let completed = completed.clone();- let failed = failed.clone();- let skipped = skipped.clone();-- let handle = tokio::spawn(async move {- // Check cancellation before acquiring permit- if cancel.is_cancelled() {- return;- }-- let output_path = std::path::PathBuf::from(&output_dir).join(&item.file_name);-- // Skip existing files- if let Ok(true) = tokio::fs::try_exists(&output_path).await {- if let Ok(meta) = tokio::fs::metadata(&output_path).await {- if meta.len() > 0 {- skipped.fetch_add(1, std::sync::atomic::Ordering::Relaxed);- let done = completed.load(std::sync::atomic::Ordering::Relaxed)- + failed.load(std::sync::atomic::Ordering::Relaxed)- + skipped.load(std::sync::atomic::Ordering::Relaxed);- let percent = (done as f64 / total_files as f64) * 100.0;-- let _ = app.emit("telegram-batch-file-status", &BatchFileStatus {- batch_id,- message_id: item.message_id,- status: "skipped".to_string(),- percent: 100.0,- error: None,- });- let _ = app.emit("generic-download-progress", &GenericDownloadProgress {- id: batch_id,- title: chat_title,- platform: "telegram".to_string(),- percent,- });- return;- }- }- }-- // Acquire semaphore permit- let _permit = tokio::select! {- p = sem.acquire() => match p {- Ok(p) => p,- Err(_) => return,- },- _ = cancel.cancelled() => return,- };-- if cancel.is_cancelled() {- return;- }-- // Emit downloading status- let _ = app.emit("telegram-batch-file-status", &BatchFileStatus {- batch_id,- message_id: item.message_id,- status: "downloading".to_string(),- percent: 0.0,- error: None,- });-- let (tx, mut rx) = mpsc::channel::<f64>(32);-- let app_progress = app.clone();- let progress_forwarder = tokio::spawn(async move {- while let Some(percent) = rx.recv().await {- let _ = app_progress.emit("telegram-batch-file-status", &BatchFileStatus {- batch_id,- message_id: item.message_id,- status: "downloading".to_string(),- percent,- error: None,- });- }- });-- let result = api::download_media_with_retry(- &session,- chat_id,- &chat_type,- item.message_id,- &output_path,- tx,- &cancel,- ).await;-- let _ = progress_forwarder.await;-- match result {- Ok(_) => {- completed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);- let _ = app.emit("telegram-batch-file-status", &BatchFileStatus {- batch_id,- message_id: item.message_id,- status: "done".to_string(),- percent: 100.0,- error: None,- });- }- Err(e) => {- let err_str = e.to_string();- if err_str.contains("cancelled") {- return;- }- failed.fetch_add(1, std::sync::atomic::Ordering::Relaxed);- let _ = app.emit("telegram-batch-file-status", &BatchFileStatus {- batch_id,- message_id: item.message_id,- status: "error".to_string(),- percent: 0.0,- error: Some(err_str),- });- }- }-- let done = completed.load(std::sync::atomic::Ordering::Relaxed)- + failed.load(std::sync::atomic::Ordering::Relaxed)- + skipped.load(std::sync::atomic::Ordering::Relaxed);- let percent = (done as f64 / total_files as f64) * 100.0;-- let _ = app.emit("generic-download-progress", &GenericDownloadProgress {- id: batch_id,- title: chat_title,- platform: "telegram".to_string(),- percent,- });- });-- handles.push(handle);- }-- // Wait for all file downloads to complete- for h in handles {- let _ = h.await;- }-- // Clean up active download entry- {- active_downloads.lock().await.remove(&batch_id);- }-- let done_count = completed.load(std::sync::atomic::Ordering::Relaxed);- let fail_count = failed.load(std::sync::atomic::Ordering::Relaxed);- let skip_count = skipped.load(std::sync::atomic::Ordering::Relaxed);- let success = fail_count == 0 && !cancel_token.is_cancelled();-- let _ = app.emit("generic-download-complete", &GenericDownloadComplete {- id: batch_id,- title: chat_title,- platform: "telegram".to_string(),- success,- error: if cancel_token.is_cancelled() {- Some("Batch cancelled".to_string())- } else if fail_count > 0 {- Some(format!("{} files failed", fail_count))- } else {- None- },- file_path: Some(output_dir),- file_size_bytes: None,- file_count: Some(done_count + skip_count),- });- });-- Ok(batch_id)-}--#[tauri::command]-pub async fn telegram_cancel_batch(- state: tauri::State<'_, AppState>,- batch_id: u64,-) -> Result<(), String> {- let active = state.active_generic_downloads.lock().await;- if let Some((key, token)) = active.get(&batch_id) {- if key.starts_with("tg-batch:") {- token.cancel();- return Ok(());- }- }- Err("Batch not found".to_string())-}--#[tauri::command]-pub async fn telegram_get_thumbnail(- state: tauri::State<'_, AppState>,- chat_id: i64,- chat_type: String,- message_id: i32,-) -> Result<String, String> {- let data = thumbnail_cache::get_thumbnail(- &state.telegram_session,- chat_id,- &chat_type,- message_id,- )- .await- .map_err(|e| e.to_string())?;-- Ok(base64::engine::general_purpose::STANDARD.encode(&data))-}--#[tauri::command]-pub async fn telegram_search_media(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- chat_id: i64,- chat_type: String,- query: String,- media_type: Option<String>,- limit: u32,-) -> Result<Vec<TelegramMediaItem>, String> {- let fix_extensions = config::load_settings(&app).telegram.fix_file_extensions;- api::search_media(- &state.telegram_session,- chat_id,- &chat_type,- &query,- media_type.as_deref(),- limit,- fix_extensions,- )- .await- .map_err(|e| e.to_string())-}--#[tauri::command]-pub async fn telegram_get_chat_photo(- state: tauri::State<'_, AppState>,- chat_id: i64,- chat_type: String,-) -> Result<String, String> {- let data = thumbnail_cache::get_chat_photo(- &state.telegram_session,- chat_id,- &chat_type,- )- .await- .map_err(|e| e.to_string())?;-- Ok(base64::engine::general_purpose::STANDARD.encode(&data))-}--#[tauri::command]-pub async fn telegram_clear_thumbnail_cache() -> Result<(), String> {- thumbnail_cache::clear_cache().await;- Ok(())-}diff --git a/src-tauri/src/commands/themembers.rs b/src-tauri/src/commands/themembers.rsdeleted file mode 100644index d6a1c95b..00000000--- a/src-tauri/src/commands/themembers.rs+++ /dev/null@@ -1,260 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::themembers::api::{self, TheMembersCourse};-use crate::platforms::themembers::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct TheMembersDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn themembers_login(- state: tauri::State<'_, AppState>,- email: String,- password: String,- domain: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.themembers_session.lock().await.take();- *state.themembers_session_validated_at.lock().await = None;- *state.themembers_courses_cache.lock().await = None;-- match api::authenticate(&email, &password, &domain).await {- Ok(session) => {- let response_domain = session.domain.clone();- let _ = api::save_session(&session).await;- let mut guard = state.themembers_session.lock().await;- *guard = Some(session);- *state.themembers_session_validated_at.lock().await = Some(Instant::now());- Ok(response_domain)- }- Err(e) => {- tracing::error!("[themembers] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn themembers_login_token(- state: tauri::State<'_, AppState>,- token: String,- domain: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.themembers_session.lock().await.take();- *state.themembers_session_validated_at.lock().await = None;- *state.themembers_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- match api::authenticate_token(&parsed_token, &domain).await {- Ok(session) => {- let response_domain = session.domain.clone();- let _ = api::save_session(&session).await;- let mut guard = state.themembers_session.lock().await;- *guard = Some(session);- *state.themembers_session_validated_at.lock().await = Some(Instant::now());- Ok(response_domain)- }- Err(e) => {- tracing::error!("[themembers] token login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn themembers_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.themembers_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.themembers_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.themembers_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let domain = session.domain.clone();-- {- let validated_at = state.themembers_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(domain);- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.themembers_session_validated_at.lock().await = Some(Instant::now());- Ok(domain)- }- Ok(false) => {- state.themembers_session.lock().await.take();- *state.themembers_session_validated_at.lock().await = None;- *state.themembers_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn themembers_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.themembers_session.lock().await.take();- *state.themembers_session_validated_at.lock().await = None;- *state.themembers_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_themembers_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<TheMembersCourse>, String> {- let guard = state.themembers_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.themembers_courses_cache.lock().await;- *cache = Some(crate::TheMembersCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn themembers_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<TheMembersCourse>, String> {- {- let cache = state.themembers_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_themembers_courses(&state).await-}--#[tauri::command]-pub async fn themembers_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<TheMembersCourse>, String> {- {- let mut cache = state.themembers_courses_cache.lock().await;- *cache = None;- }- fetch_themembers_courses(&state).await-}--#[tauri::command]-pub async fn start_themembers_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: TheMembersCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id = course.id as u64;- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id, cancel_token.clone());- }-- let session = {- let guard = state.themembers_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &TheMembersDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[themembers] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &TheMembersDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/thinkific.rs b/src-tauri/src/commands/thinkific.rsdeleted file mode 100644index 90d2a6bb..00000000--- a/src-tauri/src/commands/thinkific.rs+++ /dev/null@@ -1,239 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::thinkific::api::{self, ThinkificCourse};-use crate::platforms::thinkific::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct ThinkificDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn thinkific_login(- state: tauri::State<'_, AppState>,- cookies: String,- site_url: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.thinkific_session.lock().await.take();- *state.thinkific_session_validated_at.lock().await = None;- *state.thinkific_courses_cache.lock().await = None;-- let parsed = crate::core::cookie_parser::parse_cookie_input(&cookies, "thinkific_session");-- let session = api::create_session(&parsed.cookie_string, &site_url)- .map_err(|e| format!("Failed to create session: {}", e))?;-- match api::validate_session(&session).await {- Ok(true) => {- let site = session.site_url.clone();- let _ = api::save_session(&session).await;- let mut guard = state.thinkific_session.lock().await;- *guard = Some(session);- *state.thinkific_session_validated_at.lock().await = Some(Instant::now());- Ok(site)- }- Ok(false) => Err("Invalid cookies or site URL".to_string()),- Err(e) => Err(format!("Session validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn thinkific_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.thinkific_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.thinkific_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.thinkific_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let site_url = session.site_url.clone();-- {- let validated_at = state.thinkific_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(site_url);- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_session(&session_clone).await {- Ok(true) => {- *state.thinkific_session_validated_at.lock().await = Some(Instant::now());- Ok(site_url)- }- Ok(false) => {- state.thinkific_session.lock().await.take();- *state.thinkific_session_validated_at.lock().await = None;- *state.thinkific_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn thinkific_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.thinkific_session.lock().await.take();- *state.thinkific_session_validated_at.lock().await = None;- *state.thinkific_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_thinkific_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<ThinkificCourse>, String> {- let guard = state.thinkific_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.thinkific_courses_cache.lock().await;- *cache = Some(crate::ThinkificCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn thinkific_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<ThinkificCourse>, String> {- {- let cache = state.thinkific_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_thinkific_courses(&state).await-}--#[tauri::command]-pub async fn thinkific_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<ThinkificCourse>, String> {- {- let mut cache = state.thinkific_courses_cache.lock().await;- *cache = None;- }- fetch_thinkific_courses(&state).await-}--#[tauri::command]-pub async fn start_thinkific_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: ThinkificCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id_hash = {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};- let mut hasher = DefaultHasher::new();- course.id.hash(&mut hasher);- hasher.finish()- };- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id_hash) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id_hash, cancel_token.clone());- }-- let session = {- let guard = state.thinkific_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id_hash);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &ThinkificDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[thinkific] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &ThinkificDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/commands/udemy_auth.rs b/src-tauri/src/commands/udemy_auth.rsdeleted file mode 100644index 92f180d4..00000000--- a/src-tauri/src/commands/udemy_auth.rs+++ /dev/null@@ -1,161 +0,0 @@-use std::time::{Duration, Instant};--use crate::platforms::udemy::auth::{- authenticate, authenticate_with_cookie_json, delete_saved_session, load_saved_session,- save_session,-};-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);--#[tauri::command]-pub async fn udemy_login(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- email: String,-) -> Result<String, String> {- let _ = delete_saved_session().await;- state.udemy_session.lock().await.take();- *state.udemy_session_validated_at.lock().await = None;- *state.udemy_courses_cache.lock().await = None;-- match authenticate(&app, &email).await {- Ok(session) => {- let response_email = session.email.clone();- let _ = save_session(&session).await;- let mut guard = state.udemy_session.lock().await;- *guard = Some(session);- *state.udemy_session_validated_at.lock().await = Some(Instant::now());- Ok(response_email)- }- Err(e) => {- tracing::error!("[udemy] login failed: {}", e);- Err(format!("Login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn udemy_login_cookies(- state: tauri::State<'_, AppState>,- cookie_json: String,-) -> Result<String, String> {- let _ = delete_saved_session().await;- state.udemy_session.lock().await.take();- *state.udemy_session_validated_at.lock().await = None;- *state.udemy_courses_cache.lock().await = None;-- match authenticate_with_cookie_json(&cookie_json).await {- Ok(session) => {- let response_email = session.email.clone();- let _ = save_session(&session).await;- let mut guard = state.udemy_session.lock().await;- *guard = Some(session);- *state.udemy_session_validated_at.lock().await = Some(Instant::now());- Ok(response_email)- }- Err(e) => {- tracing::error!("[udemy] cookie login failed: {}", e);- Err(format!("Cookie login failed: {}", e))- }- }-}--#[tauri::command]-pub async fn udemy_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.udemy_session.lock().await.is_some();-- if !has_memory_session {- match load_saved_session().await {- Ok(session) => {- let mut guard = state.udemy_session.lock().await;- *guard = Some(session);- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.udemy_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;- let email = session.email.clone();-- {- let validated_at = state.udemy_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok(email);- }- }- }-- let client = session.client.clone();- let portal = session.portal_name.clone();- drop(guard);-- let validation_url = format!("https://{}.udemy.com/api-2.0/users/me/", portal);- let resp = client- .get(&validation_url)- .send()- .await- .map_err(|e| format!("Validation error: {}", e))?;-- let status = resp.status();- if status.is_success() {- *state.udemy_session_validated_at.lock().await = Some(Instant::now());- Ok(email)- } else if status == reqwest::StatusCode::UNAUTHORIZED {- state.udemy_session.lock().await.take();- *state.udemy_session_validated_at.lock().await = None;- *state.udemy_courses_cache.lock().await = None;- let _ = delete_saved_session().await;- Err("session_expired".to_string())- } else if status == reqwest::StatusCode::FORBIDDEN {- let body = resp.text().await.unwrap_or_default();- let body_lower = body.to_lowercase();- if body_lower.contains("just a moment") || body_lower.contains("cf_chl") || body_lower.contains("<!doctype") {- tracing::warn!("[udemy] check_session got Cloudflare challenge, keeping session alive");- *state.udemy_session_validated_at.lock().await = Some(Instant::now());- Ok(email)- } else {- tracing::error!("[udemy] check_session got real 403: {}", &body[..body.len().min(300)]);- state.udemy_session.lock().await.take();- *state.udemy_session_validated_at.lock().await = None;- *state.udemy_courses_cache.lock().await = None;- let _ = delete_saved_session().await;- Err("session_expired".to_string())- }- } else {- Err(format!("session_check_failed: {}", status))- }-}--#[tauri::command]-pub async fn udemy_get_portal(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let guard = state.udemy_session.lock().await;- Ok(guard- .as_ref()- .map(|s| s.portal_name.clone())- .unwrap_or_else(|| "www".into()))-}--#[tauri::command]-pub async fn udemy_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = delete_saved_session().await;- state.udemy_session.lock().await.take();- *state.udemy_session_validated_at.lock().await = None;- *state.udemy_courses_cache.lock().await = None;- if let Some(w) = state.udemy_api_webview.lock().await.take() {- let _ = w.close();- }- Ok(())-}diff --git a/src-tauri/src/commands/udemy_courses.rs b/src-tauri/src/commands/udemy_courses.rsdeleted file mode 100644index 35e9ccca..00000000--- a/src-tauri/src/commands/udemy_courses.rs+++ /dev/null@@ -1,246 +0,0 @@-use std::time::Instant;--use crate::platforms::udemy::api::UdemyCourse;-use crate::platforms::udemy::webview_api;-use crate::{AppState, UdemyCoursesCache};--const COURSES_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(10 * 60);--async fn get_portal(state: &tauri::State<'_, AppState>) -> String {- let guard = state.udemy_session.lock().await;- guard- .as_ref()- .map(|s| s.portal_name.clone())- .unwrap_or_else(|| "www".into())-}--fn parse_courses_from_results(results: &[serde_json::Value]) -> Vec<UdemyCourse> {- results- .iter()- .filter_map(|item| {- 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,- })- })- .collect()-}--async fn fetch_courses_via_api(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<UdemyCourse>, String> {- let (client, portal) = {- let guard = state.udemy_session.lock().await;- let session = guard.as_ref().ok_or("not_authenticated")?;- (session.client.clone(), session.portal_name.clone())- };-- 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- );-- tracing::info!("[udemy-api] fetching courses via direct API for portal={}", portal);-- let resp = client- .get(&url)- .send()- .await- .map_err(|e| format!("API request failed: {}", e))?;-- if !resp.status().is_success() {- return Err(format!("API returned status {}", resp.status()));- }-- let body = resp.text().await.map_err(|e| format!("Read body failed: {}", e))?;- let data: serde_json::Value =- serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {}", e))?;-- let results = data- .get("results")- .and_then(|r| r.as_array())- .cloned()- .unwrap_or_default();-- let mut courses = parse_courses_from_results(&results);-- let sub_url = format!(- "https://{}.udemy.com/api-2.0/users/me/subscription-course-enrollments?fields[course]=id,title,published_title,image_240x135,num_published_lectures&page=1&page_size=50",- portal- );-- if let Ok(sub_resp) = client.get(&sub_url).send().await {- if sub_resp.status().is_success() {- if let Ok(sub_body) = sub_resp.text().await {- if let Ok(sub_data) = serde_json::from_str::<serde_json::Value>(&sub_body) {- if let Some(sub_results) = sub_data.get("results").and_then(|r| r.as_array()) {- let existing_ids: std::collections::HashSet<u64> =- courses.iter().map(|c| c.id).collect();- for c in parse_courses_from_results(sub_results) {- if !existing_ids.contains(&c.id) {- courses.push(c);- }- }- }- }- }- }- }-- tracing::info!("[udemy-api] found {} total courses via direct API", courses.len());-- let mut cache = state.udemy_courses_cache.lock().await;- *cache = Some(UdemyCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--async fn fetch_courses_via_webview(- app: &tauri::AppHandle,- state: &tauri::State<'_, AppState>,-) -> Result<Vec<UdemyCourse>, String> {- let portal = get_portal(state).await;-- let result_store = state.udemy_api_result.clone();-- let window = {- let mut wv_guard = state.udemy_api_webview.lock().await;- match &*wv_guard {- Some(w) => w.clone(),- None => {- let w = webview_api::ensure_api_webview(app, &result_store, &portal)- .await- .map_err(|e| e.to_string())?;- *wv_guard = Some(w.clone());- w- }- }- };-- 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- );-- tracing::info!("[udemy-api] fetching courses via webview");-- let body = webview_api::webview_get(&window, &url, &result_store)- .await- .map_err(|e| e.to_string())?;-- let data: serde_json::Value =- serde_json::from_str(&body).map_err(|e| format!("JSON parse error: {}", e))?;-- let results = data- .get("results")- .and_then(|r| r.as_array())- .cloned()- .unwrap_or_default();-- let mut courses = parse_courses_from_results(&results);-- let sub_url = format!(- "https://{}.udemy.com/api-2.0/users/me/subscription-course-enrollments?fields[course]=id,title,published_title,image_240x135,num_published_lectures&page=1&page_size=50",- portal- );-- if let Ok(sub_body) = webview_api::webview_get(&window, &sub_url, &result_store).await {- if let Ok(sub_data) = serde_json::from_str::<serde_json::Value>(&sub_body) {- if let Some(sub_results) = sub_data.get("results").and_then(|r| r.as_array()) {- let existing_ids: std::collections::HashSet<u64> =- courses.iter().map(|c| c.id).collect();- for c in parse_courses_from_results(sub_results) {- if !existing_ids.contains(&c.id) {- courses.push(c);- }- }- }- }- }-- tracing::info!("[udemy-api] found {} total courses via webview", courses.len());-- let mut cache = state.udemy_courses_cache.lock().await;- *cache = Some(UdemyCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--async fn fetch_courses(- app: &tauri::AppHandle,- state: &tauri::State<'_, AppState>,-) -> Result<Vec<UdemyCourse>, String> {- let portal = get_portal(state).await;-- if portal != "www" {- match fetch_courses_via_api(state).await {- Ok(courses) => return Ok(courses),- Err(e) => {- tracing::warn!("[udemy-api] direct API failed for portal={}, falling back to webview: {}", portal, e);- }- }- }-- fetch_courses_via_webview(app, state).await-}--#[tauri::command]-pub async fn udemy_list_courses(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,-) -> Result<Vec<UdemyCourse>, String> {- {- let cache = state.udemy_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_courses(&app, &state).await-}--#[tauri::command]-pub async fn udemy_refresh_courses(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,-) -> Result<Vec<UdemyCourse>, String> {- {- let mut cache = state.udemy_courses_cache.lock().await;- *cache = None;- }- fetch_courses(&app, &state).await-}diff --git a/src-tauri/src/commands/udemy_downloads.rs b/src-tauri/src/commands/udemy_downloads.rsdeleted file mode 100644index f6ed0c0f..00000000--- a/src-tauri/src/commands/udemy_downloads.rs+++ /dev/null@@ -1,306 +0,0 @@-use std::sync::Arc;--use serde::Serialize;-use tauri::Emitter;-use tokio::sync::mpsc;-use tokio_util::sync::CancellationToken;--use crate::platforms::udemy::api::{self, UdemyCourse, UdemyCurriculum};-use crate::platforms::udemy::downloader::UdemyDownloader;-use crate::platforms::udemy::webview_api;-use crate::storage::config;-use crate::AppState;--#[derive(Clone, Serialize)]-struct UdemyDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,- drm_skipped: u32,-}--async fn fetch_curriculum_via_webview(- app: &tauri::AppHandle,- api_webview: &Arc<tokio::sync::Mutex<Option<tauri::WebviewWindow>>>,- result_store: &Arc<std::sync::Mutex<Option<String>>>,- course_id: u64,- portal_name: &str,-) -> Result<UdemyCurriculum, String> {- let window = {- let mut wv_guard = api_webview.lock().await;- match &*wv_guard {- Some(w) => w.clone(),- None => {- let w = webview_api::ensure_api_webview(app, result_store, portal_name)- .await- .map_err(|e| e.to_string())?;- *wv_guard = Some(w.clone());- w- }- }- };-- let url = format!(- "https://{}.udemy.com/api-2.0/courses/{}/subscriber-curriculum-items/?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",- portal_name, course_id- );-- tracing::info!("[udemy-api] fetching curriculum via webview for course {}", course_id);-- let body = webview_api::webview_get(&window, &url, result_store)- .await- .map_err(|e| e.to_string())?;-- let mut data: serde_json::Value = serde_json::from_str(&body)- .map_err(|e| format!("JSON parse error: {}", e))?;-- let mut all_results = data.get("results")- .and_then(|r| r.as_array())- .cloned()- .unwrap_or_default();-- loop {- let next_url = data.get("next").and_then(|n| n.as_str()).map(|s| s.to_string());- match next_url {- Some(next) if !next.is_empty() => {- tracing::info!("[udemy-api] fetching next curriculum page via webview");- tokio::time::sleep(std::time::Duration::from_millis(200)).await;-- let page_body = webview_api::webview_get(&window, &next, result_store)- .await- .map_err(|e| e.to_string())?;-- let page_data: serde_json::Value = serde_json::from_str(&page_body)- .map_err(|e| format!("JSON parse error on page: {}", e))?;-- if let Some(new_results) = page_data.get("results").and_then(|r| r.as_array()) {- all_results.extend(new_results.iter().cloned());- }-- data = page_data;- }- _ => break,- }- }-- tracing::info!("[udemy-api] curriculum fetched: {} items total", all_results.len());-- api::parse_curriculum(course_id, &all_results).map_err(|e| e.to_string())-}--async fn fetch_curriculum_via_api(- state: &tauri::State<'_, AppState>,- course_id: u64,- portal_name: &str,-) -> Result<UdemyCurriculum, String> {- let client = {- let guard = state.udemy_session.lock().await;- let session = guard.as_ref().ok_or("not_authenticated")?;- session.client.clone()- };-- let url = format!(- "https://{}.udemy.com/api-2.0/courses/{}/subscriber-curriculum-items/?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",- portal_name, course_id- );-- tracing::info!("[udemy-api] fetching curriculum via direct API for course {}", course_id);-- let resp = client- .get(&url)- .send()- .await- .map_err(|e| format!("API request failed: {}", e))?;-- if !resp.status().is_success() {- return Err(format!("API returned status {}", resp.status()));- }-- let body = resp.text().await.map_err(|e| format!("Read body failed: {}", e))?;-- let mut data: serde_json::Value = serde_json::from_str(&body)- .map_err(|e| format!("JSON parse error: {}", e))?;-- let mut all_results = data.get("results")- .and_then(|r| r.as_array())- .cloned()- .unwrap_or_default();-- loop {- let next_url = data.get("next").and_then(|n| n.as_str()).map(|s| s.to_string());- match next_url {- Some(next) if !next.is_empty() => {- tracing::info!("[udemy-api] fetching next curriculum page via direct API");- tokio::time::sleep(std::time::Duration::from_millis(200)).await;-- let page_resp = client- .get(&next)- .send()- .await- .map_err(|e| format!("API page request failed: {}", e))?;-- if !page_resp.status().is_success() {- break;- }-- let page_body = page_resp.text().await- .map_err(|e| format!("Read page body failed: {}", e))?;-- let page_data: serde_json::Value = serde_json::from_str(&page_body)- .map_err(|e| format!("JSON parse error on page: {}", e))?;-- if let Some(new_results) = page_data.get("results").and_then(|r| r.as_array()) {- all_results.extend(new_results.iter().cloned());- }-- data = page_data;- }- _ => break,- }- }-- tracing::info!("[udemy-api] curriculum fetched via direct API: {} items total", all_results.len());-- api::parse_curriculum(course_id, &all_results).map_err(|e| e.to_string())-}--#[tauri::command]-pub async fn start_udemy_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: UdemyCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.title.clone();- let course_id = course.id;- let session = state.udemy_session.clone();- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id, cancel_token.clone());- }-- let portal = {- let guard = state.udemy_session.lock().await;- guard- .as_ref()- .map(|s| s.portal_name.clone())- .unwrap_or_else(|| "www".into())- };-- let curriculum = if portal != "www" {- match fetch_curriculum_via_api(&state, course_id, &portal).await {- Ok(c) => c,- Err(e) => {- tracing::warn!("[udemy-api] direct API curriculum failed for portal={}, falling back to webview: {}", portal, e);- let api_webview = state.udemy_api_webview.clone();- let result_store = state.udemy_api_result.clone();- match fetch_curriculum_via_webview(&app, &api_webview, &result_store, course_id, &portal).await {- Ok(c) => c,- Err(e2) => {- active.lock().await.remove(&course_id);- return Err(format!("Failed to fetch curriculum: {}", e2));- }- }- }- }- } else {- let api_webview = state.udemy_api_webview.clone();- let result_store = state.udemy_api_result.clone();- match fetch_curriculum_via_webview(&app, &api_webview, &result_store, course_id, &portal).await {- Ok(c) => c,- Err(e) => {- active.lock().await.remove(&course_id);- return Err(format!("Failed to fetch curriculum: {}", e));- }- }- };-- if curriculum.drm_video_lectures > 0- && curriculum.drm_video_lectures == curriculum.total_video_lectures- && curriculum.total_video_lectures > 0- {- active.lock().await.remove(&course_id);- return Err("drm_protected".to_string());- }-- let settings = config::load_settings(&app);-- tokio::spawn(async move {- let downloader = UdemyDownloader::new(- session,- settings.advanced.max_concurrent_segments,- settings.advanced.max_retries,- );- let (tx, mut rx) = mpsc::channel(32);-- let app_clone = app.clone();- let progress_forwarder = tokio::spawn(async move {- while let Some(progress) = rx.recv().await {- let _ = app_clone.emit("udemy-download-progress", &progress);- }- });-- let result = downloader- .download_full_course(&course, &output_dir, curriculum, tx, cancel_token)- .await;-- let _ = progress_forwarder.await;-- {- let mut map = active.lock().await;- map.remove(&course_id);- }-- match result {- Ok(drm_skipped) => {- let _ = app.emit(- "udemy-download-complete",- &UdemyDownloadCompleteEvent {- course_name: course.title,- success: true,- error: None,- drm_skipped,- },- );- }- Err(e) => {- tracing::error!("[udemy] download error for '{}': {}", course.title, e);- let _ = app.emit(- "udemy-download-complete",- &UdemyDownloadCompleteEvent {- course_name: course.title,- success: false,- error: Some(e.to_string()),- drm_skipped: 0,- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}--#[tauri::command]-pub async fn cancel_udemy_course_download(- state: tauri::State<'_, AppState>,- course_id: u64,-) -> Result<(), String> {- let map = state.active_downloads.lock().await;- if let Some(token) = map.get(&course_id) {- token.cancel();- Ok(())- } else {- Err("No active download for this course".to_string())- }-}diff --git a/src-tauri/src/commands/voomp.rs b/src-tauri/src/commands/voomp.rsdeleted file mode 100644index 96ebd849..00000000--- a/src-tauri/src/commands/voomp.rs+++ /dev/null@@ -1,245 +0,0 @@-use std::time::{Duration, Instant};--use serde::Serialize;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::platforms::voompplay::api::{self, VoompCourse, VoompSession};-use crate::platforms::voompplay::downloader;-use crate::AppState;--const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);--#[derive(Clone, Serialize)]-struct VoompDownloadCompleteEvent {- course_name: String,- success: bool,- error: Option<String>,-}--#[tauri::command]-pub async fn voomp_login_token(- state: tauri::State<'_, AppState>,- token: String,-) -> Result<String, String> {- let _ = api::delete_saved_session().await;- state.voomp_session.lock().await.take();- *state.voomp_session_validated_at.lock().await = None;- *state.voomp_courses_cache.lock().await = None;-- let parsed_token = crate::core::cookie_parser::parse_bearer_input(&token);-- let session = VoompSession {- token: parsed_token.clone(),- client: crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .default_headers({- let mut h = reqwest::header::HeaderMap::new();- h.insert("Authorization", parsed_token.parse().unwrap());- h.insert("Accept", "application/json".parse().unwrap());- h.insert("Origin", "https://voompplay.com.br".parse().unwrap());- h.insert("Referer", "https://voompplay.com.br/".parse().unwrap());- h- })- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(120))- .build()- .map_err(|e| format!("Failed to build client: {}", e))?,- };-- match api::validate_token(&session).await {- Ok(true) => {- let _ = api::save_session(&session).await;- let mut guard = state.voomp_session.lock().await;- *guard = Some(session);- *state.voomp_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => Err("Invalid token".to_string()),- Err(e) => Err(format!("Token validation failed: {}", e)),- }-}--#[tauri::command]-pub async fn voomp_check_session(- state: tauri::State<'_, AppState>,-) -> Result<String, String> {- let has_memory_session = state.voomp_session.lock().await.is_some();-- if !has_memory_session {- match api::load_session().await {- Ok(Some(session)) => {- let mut guard = state.voomp_session.lock().await;- *guard = Some(session);- }- Ok(None) => {- return Err("not_authenticated".to_string());- }- Err(_) => {- return Err("not_authenticated".to_string());- }- }- }-- let guard = state.voomp_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "not_authenticated".to_string())?;-- {- let validated_at = state.voomp_session_validated_at.lock().await;- if let Some(at) = *validated_at {- if at.elapsed() < SESSION_COOLDOWN {- return Ok("authenticated".to_string());- }- }- }-- let session_clone = session.clone();- drop(guard);-- match api::validate_token(&session_clone).await {- Ok(true) => {- *state.voomp_session_validated_at.lock().await = Some(Instant::now());- Ok("authenticated".to_string())- }- Ok(false) => {- state.voomp_session.lock().await.take();- *state.voomp_session_validated_at.lock().await = None;- *state.voomp_courses_cache.lock().await = None;- let _ = api::delete_saved_session().await;- Err("session_expired".to_string())- }- Err(e) => Err(format!("session_check_failed: {}", e)),- }-}--#[tauri::command]-pub async fn voomp_logout(- state: tauri::State<'_, AppState>,-) -> Result<(), String> {- let _ = api::delete_saved_session().await;- state.voomp_session.lock().await.take();- *state.voomp_session_validated_at.lock().await = None;- *state.voomp_courses_cache.lock().await = None;- Ok(())-}--async fn fetch_voomp_courses(- state: &tauri::State<'_, AppState>,-) -> Result<Vec<VoompCourse>, String> {- let guard = state.voomp_session.lock().await;- let session = guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?;-- let courses = api::list_courses(session)- .await- .map_err(|e| e.to_string())?;-- let mut cache = state.voomp_courses_cache.lock().await;- *cache = Some(crate::VoompCoursesCache {- courses: courses.clone(),- fetched_at: Instant::now(),- });-- Ok(courses)-}--#[tauri::command]-pub async fn voomp_list_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<VoompCourse>, String> {- {- let cache = state.voomp_courses_cache.lock().await;- if let Some(ref cached) = *cache {- if cached.fetched_at.elapsed() < COURSES_CACHE_TTL {- return Ok(cached.courses.clone());- }- }- }-- fetch_voomp_courses(&state).await-}--#[tauri::command]-pub async fn voomp_refresh_courses(- state: tauri::State<'_, AppState>,-) -> Result<Vec<VoompCourse>, String> {- {- let mut cache = state.voomp_courses_cache.lock().await;- *cache = None;- }- fetch_voomp_courses(&state).await-}--#[tauri::command]-pub async fn start_voomp_course_download(- app: tauri::AppHandle,- state: tauri::State<'_, AppState>,- course_json: String,- output_dir: String,-) -> Result<String, String> {- let course: VoompCourse =- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;-- let course_name = course.name.clone();- let course_id = course.id as u64;- let active = state.active_downloads.clone();-- let cancel_token = CancellationToken::new();-- {- let mut map = active.lock().await;- if map.contains_key(&course_id) {- return Err("Download already in progress for this course".to_string());- }- map.insert(course_id, cancel_token.clone());- }-- let session = {- let guard = state.voomp_session.lock().await;- guard- .as_ref()- .ok_or_else(|| "Not authenticated. Please log in first.".to_string())?- .clone()- };-- tokio::spawn(async move {- let result =- downloader::download_full_course(&app, &session, &course, &output_dir, cancel_token)- .await;-- {- let mut map = active.lock().await;- map.remove(&course_id);- }-- match result {- Ok(()) => {- let _ = app.emit(- "download-complete",- &VoompDownloadCompleteEvent {- course_name: course.name,- success: true,- error: None,- },- );- }- Err(e) => {- tracing::error!("[voomp] download error for '{}': {}", course.name, e);- let _ = app.emit(- "download-complete",- &VoompDownloadCompleteEvent {- course_name: course.name,- success: false,- error: Some(e.to_string()),- },- );- }- }- });-- Ok(format!("Download started: {}", course_name))-}diff --git a/src-tauri/src/core/clipboard.rs b/src-tauri/src/core/clipboard.rsdeleted file mode 100644index 8a9b0ed0..00000000--- a/src-tauri/src/core/clipboard.rs+++ /dev/null@@ -1,151 +0,0 @@-use std::path::Path;--#[cfg(target_os = "windows")]-const CREATE_NO_WINDOW: u32 = 0x08000000;--const MAX_CLIPBOARD_FILE_SIZE: u64 = 1_073_741_824; // 1 GB--pub async fn copy_file_to_clipboard(path: &Path) -> anyhow::Result<()> {- let metadata = tokio::fs::metadata(path).await?;- if metadata.len() > MAX_CLIPBOARD_FILE_SIZE {- tracing::info!(- "[clipboard] skipping copy: file too large ({} bytes)",- metadata.len()- );- return Ok(());- }-- let path_str = path.to_string_lossy().to_string();-- #[cfg(target_os = "macos")]- {- copy_file_macos(&path_str).await- }-- #[cfg(target_os = "linux")]- {- copy_file_linux(&path_str).await- }-- #[cfg(target_os = "windows")]- {- copy_file_windows(&path_str).await- }-}--#[cfg(target_os = "macos")]-async fn copy_file_macos(path: &str) -> anyhow::Result<()> {- let output = tokio::process::Command::new("osascript")- .args([- "-e",- &format!("set the clipboard to POSIX file \"{}\"", path),- ])- .output()- .await?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- return Err(anyhow::anyhow!("osascript failed: {}", stderr));- }-- tracing::info!("[clipboard] copied file to clipboard (macOS): {}", path);- Ok(())-}--#[cfg(target_os = "linux")]-async fn copy_file_linux(path: &str) -> anyhow::Result<()> {- let uri = format!("file://{}", path);-- let xclip = tokio::process::Command::new("xclip")- .args(["-selection", "clipboard", "-target", "text/uri-list"])- .stdin(std::process::Stdio::piped())- .spawn();-- match xclip {- Ok(mut child) => {- if let Some(ref mut stdin) = child.stdin {- use tokio::io::AsyncWriteExt;- stdin.write_all(uri.as_bytes()).await?;- }- let output = child.wait_with_output().await?;- if output.status.success() {- tracing::info!("[clipboard] copied file to clipboard (xclip): {}", path);- return Ok(());- }- }- Err(_) => {- tracing::debug!("[clipboard] xclip not found, trying xsel");- }- }-- let xsel = tokio::process::Command::new("xsel")- .args(["--clipboard", "--input"])- .stdin(std::process::Stdio::piped())- .spawn();-- match xsel {- Ok(mut child) => {- if let Some(ref mut stdin) = child.stdin {- use tokio::io::AsyncWriteExt;- stdin.write_all(uri.as_bytes()).await?;- }- let output = child.wait_with_output().await?;- if output.status.success() {- tracing::info!("[clipboard] copied file URI to clipboard (xsel): {}", path);- return Ok(());- }- }- Err(_) => {- tracing::debug!("[clipboard] xsel not found, trying wl-copy");- }- }-- let wl_copy = tokio::process::Command::new("wl-copy")- .args(["--type", "text/uri-list"])- .stdin(std::process::Stdio::piped())- .spawn();-- match wl_copy {- Ok(mut child) => {- if let Some(ref mut stdin) = child.stdin {- use tokio::io::AsyncWriteExt;- stdin.write_all(uri.as_bytes()).await?;- }- let output = child.wait_with_output().await?;- if output.status.success() {- tracing::info!(- "[clipboard] copied file to clipboard (wl-copy): {}",- path- );- return Ok(());- }- }- Err(_) => {}- }-- Err(anyhow::anyhow!(- "No clipboard tool found (tried xclip, xsel, wl-copy)"- ))-}--#[cfg(target_os = "windows")]-async fn copy_file_windows(path: &str) -> anyhow::Result<()> {- let ps_script = format!(- "Set-Clipboard -LiteralPath '{}'",- path.replace('\'', "''")- );-- let output = tokio::process::Command::new("powershell")- .args(["-NoProfile", "-NonInteractive", "-Command", &ps_script])- .creation_flags(CREATE_NO_WINDOW)- .output()- .await?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- return Err(anyhow::anyhow!("PowerShell Set-Clipboard failed: {}", stderr));- }-- tracing::info!("[clipboard] copied file to clipboard (Windows): {}", path);- Ok(())-}diff --git a/src-tauri/src/core/cookie_parser.rs b/src-tauri/src/core/cookie_parser.rsdeleted file mode 100644index f22229ed..00000000--- a/src-tauri/src/core/cookie_parser.rs+++ /dev/null@@ -1,160 +0,0 @@-use std::collections::HashMap;--pub struct ParsedInput {- pub token: String,- pub cookie_string: String,- pub cookies: HashMap<String, String>,- pub extra_fields: HashMap<String, String>,-}--pub fn parse_cookie_input(input: &str, target_cookie: &str) -> ParsedInput {- let trimmed = input.trim();-- if trimmed.starts_with('{') || trimmed.starts_with('[') {- if let Ok(val) = serde_json::from_str::<serde_json::Value>(trimmed) {- let cookie_array = if let Some(arr) = val.get("cookies").and_then(|c| c.as_array()) {- arr.clone()- } else if let Some(arr) = val.as_array() {- arr.clone()- } else if val.get("name").is_some() && val.get("value").is_some() {- vec![val.clone()]- } else {- Vec::new()- };-- if !cookie_array.is_empty() {- let mut cookies = HashMap::new();- let mut parts = Vec::new();-- for cookie_obj in &cookie_array {- if let (Some(name), Some(value)) = (- cookie_obj.get("name").and_then(|n| n.as_str()),- cookie_obj.get("value").and_then(|v| v.as_str()),- ) {- cookies.insert(name.to_string(), value.to_string());- parts.push(format!("{}={}", name, value));- }- }-- let cookie_string = parts.join("; ");-- let token = if !target_cookie.is_empty() {- if let Some(t) = cookies.get(target_cookie) {- t.clone()- } else {- cookies- .values()- .find(|v| v.starts_with("eyJ"))- .cloned()- .unwrap_or_default()- }- } else {- cookies- .values()- .find(|v| v.starts_with("eyJ"))- .cloned()- .unwrap_or_default()- };-- return ParsedInput {- token,- cookie_string,- cookies,- extra_fields: HashMap::new(),- };- }- }- }-- if trimmed.contains("; ") || (trimmed.contains('=') && !trimmed.starts_with("eyJ")) {- let mut cookies = HashMap::new();- for pair in trimmed.split("; ") {- if let Some(idx) = pair.find('=') {- let name = pair[..idx].trim().to_string();- let value = pair[idx + 1..].trim().to_string();- cookies.insert(name, value);- }- }-- let token = if !target_cookie.is_empty() {- cookies.get(target_cookie).cloned().unwrap_or_default()- } else {- cookies- .values()- .find(|v| v.starts_with("eyJ"))- .cloned()- .unwrap_or_default()- };-- return ParsedInput {- token,- cookie_string: trimmed.to_string(),- cookies,- extra_fields: HashMap::new(),- };- }-- let token = trimmed.to_string();- let cookie_string = if !target_cookie.is_empty() {- format!("{}={}", target_cookie, token)- } else {- String::new()- };- let mut cookies = HashMap::new();- if !target_cookie.is_empty() {- cookies.insert(target_cookie.to_string(), token.clone());- }-- ParsedInput {- token,- cookie_string,- cookies,- extra_fields: HashMap::new(),- }-}--pub fn parse_bearer_input(input: &str) -> String {- let trimmed = input.trim();-- if trimmed.starts_with('{') || trimmed.starts_with('[') {- if let Ok(val) = serde_json::from_str::<serde_json::Value>(trimmed) {- for key in &["access_token", "token", "idToken", "bearerToken", "bearer_token"] {- if let Some(t) = val.get(*key).and_then(|v| v.as_str()) {- return t.to_string();- }- }-- let cookie_array = if let Some(arr) = val.get("cookies").and_then(|c| c.as_array()) {- arr.clone()- } else if let Some(arr) = val.as_array() {- arr.clone()- } else {- Vec::new()- };-- for cookie_obj in &cookie_array {- if let Some(value) = cookie_obj.get("value").and_then(|v| v.as_str()) {- if value.starts_with("eyJ") && value.len() > 50 {- return value.to_string();- }- }- }-- for cookie_obj in &cookie_array {- if let (Some(name), Some(value)) = (- cookie_obj.get("name").and_then(|n| n.as_str()),- cookie_obj.get("value").and_then(|v| v.as_str()),- ) {- let lower = name.to_lowercase();- if lower.contains("token") || lower.contains("auth") || lower.contains("session") || lower.contains("sid") {- if value.len() > 20 {- return value.to_string();- }- }- }- }- }- }-- trimmed.to_string()-}diff --git a/src-tauri/src/core/course_utils.rs b/src-tauri/src/core/course_utils.rsdeleted file mode 100644index ee1f2814..00000000--- a/src-tauri/src/core/course_utils.rs+++ /dev/null@@ -1,116 +0,0 @@-use std::path::Path;--use anyhow::anyhow;-use tokio_util::sync::CancellationToken;--pub async fn save_description(dir: &str, content: &str, format: &str) -> anyhow::Result<()> {- if content.trim().is_empty() {- return Ok(());- }-- let ext = match format {- "markdown" | "md" => "md",- "text" | "txt" => "txt",- _ => "html",- };-- let path = format!("{}/description.{}", dir, ext);-- if tokio::fs::try_exists(&path).await.unwrap_or(false) {- return Ok(());- }-- let wrapped = if ext == "html" && !content.trim_start().starts_with("<!") && !content.trim_start().starts_with("<html") {- format!(- "<!DOCTYPE html>\n<html>\n<head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><style>body{{max-width:800px;margin:40px auto;padding:0 20px;font-family:system-ui,sans-serif;line-height:1.6;color:#333}}img{{max-width:100%;height:auto}}a{{color:#0066cc}}</style></head>\n<body>\n{}\n</body>\n</html>",- content- )- } else {- content.to_string()- };-- tokio::fs::write(&path, wrapped.as_bytes()).await?;- tracing::debug!("[course] saved description: {}", path);- Ok(())-}--pub async fn download_attachment(- client: &reqwest::Client,- url: &str,- dir: &str,- name: &str,- cancel_token: &CancellationToken,-) -> anyhow::Result<u64> {- if url.is_empty() || name.is_empty() {- return Ok(0);- }-- let sanitized = sanitize_filename::sanitize(name);- let filename = if sanitized.is_empty() {- let ext = url- .rsplit('.')- .next()- .and_then(|e| e.split('?').next())- .filter(|e| e.len() <= 5)- .unwrap_or("bin");- format!("attachment.{}", ext)- } else {- sanitized- };-- let path = format!("{}/{}", dir, filename);-- if tokio::fs::try_exists(&path).await.unwrap_or(false) {- let meta = tokio::fs::metadata(&path).await;- if meta.map(|m| m.len() > 0).unwrap_or(false) {- return Ok(0);- }- }-- if cancel_token.is_cancelled() {- return Err(anyhow!("Download cancelled"));- }-- let resp = client- .get(url)- .send()- .await- .map_err(|e| anyhow!("Failed to download attachment: {}", e))?;-- if !resp.status().is_success() {- return Err(anyhow!(- "Attachment download failed: HTTP {}",- resp.status()- ));- }-- let bytes = resp.bytes().await?;- let size = bytes.len() as u64;-- if size == 0 {- return Ok(0);- }-- let part_path = format!("{}.part", path);- tokio::fs::write(&part_path, &bytes).await?;- tokio::fs::rename(&part_path, &path).await?;-- tracing::debug!("[course] attachment saved: {} ({} bytes)", path, size);- Ok(size)-}--pub async fn mark_course_complete(course_dir: &str) -> anyhow::Result<()> {- let marker = format!("{}/.complete", course_dir);- tokio::fs::write(&marker, "done").await?;- tracing::info!("[course] marked complete: {}", course_dir);- Ok(())-}--pub fn is_course_complete(course_dir: &str) -> bool {- Path::new(&format!("{}/.complete", course_dir)).exists()-}--pub async fn ensure_dir(path: &str) -> anyhow::Result<()> {- tokio::fs::create_dir_all(path).await?;- Ok(())-}diff --git a/src-tauri/src/core/dependencies.rs b/src-tauri/src/core/dependencies.rsdeleted file mode 100644index adfc2cc7..00000000--- a/src-tauri/src/core/dependencies.rs+++ /dev/null@@ -1,557 +0,0 @@-use std::path::PathBuf;-use std::process::Stdio;--use anyhow::anyhow;-use futures::StreamExt;--pub fn is_flatpak() -> bool {- std::path::Path::new("/.flatpak-info").exists()- || std::env::var("FLATPAK_ID").is_ok()-}--fn managed_bin_dir() -> Option<PathBuf> {- Some(crate::core::paths::app_data_dir()?.join("bin"))-}--pub fn bin_name(tool: &str) -> String {- if cfg!(target_os = "windows") {- format!("{}.exe", tool)- } else {- tool.to_string()- }-}--pub async fn find_tool(tool: &str) -> Option<PathBuf> {- let _timer_start = std::time::Instant::now();- let name = bin_name(tool);- let version_flag = version_flag_for(tool);-- #[cfg(target_os = "linux")]- {- let flatpak_path = PathBuf::from("/app/bin").join(&name);- if flatpak_path.exists() {- tracing::debug!("[perf] find_tool({}) took {:?}", tool, _timer_start.elapsed());- return Some(flatpak_path);- }- }-- if let Ok(status) = crate::core::process::command(&name)- .arg(version_flag)- .stdout(Stdio::null())- .stderr(Stdio::null())- .status()- .await- {- if status.success() {- tracing::debug!("[perf] find_tool({}) took {:?}", tool, _timer_start.elapsed());- return Some(PathBuf::from(&name));- }- }-- let managed = managed_bin_dir()?.join(&name);- if managed.exists() {- if let Ok(status) = crate::core::process::command(&managed)- .arg(version_flag)- .stdout(Stdio::null())- .stderr(Stdio::null())- .status()- .await- {- if status.success() {- tracing::debug!("[perf] find_tool({}) took {:?}", tool, _timer_start.elapsed());- return Some(managed);- }- }- tracing::warn!("find_tool({}): binary exists at {} but failed to execute", tool, managed.display());- }-- tracing::debug!("[perf] find_tool({}) took {:?}", tool, _timer_start.elapsed());- None-}--fn version_flag_for(tool: &str) -> &'static str {- match tool {- "ffmpeg" | "ffprobe" => "-version",- _ => "--version",- }-}--pub async fn check_version(tool: &str) -> Option<String> {- let _timer_start = std::time::Instant::now();- let path = find_tool(tool).await?;- let version_flag = version_flag_for(tool);- let output = crate::core::process::command(&path)- .arg(version_flag)- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .await- .ok()?;-- if !output.status.success() {- tracing::debug!("[perf] check_version({}) took {:?}", tool, _timer_start.elapsed());- return None;- }-- let stdout = String::from_utf8_lossy(&output.stdout);- let first_line = stdout.lines().next().unwrap_or("");-- let result = if tool == "ffmpeg" || tool == "ffprobe" {- first_line- .split_whitespace()- .nth(2)- .map(|s| s.to_string())- } else if tool == "yt-dlp" {- Some(first_line.trim().to_string())- } else if tool == "aria2c" {- first_line- .split_whitespace()- .nth(2)- .map(|s| s.to_string())- } else {- Some(first_line.trim().to_string())- };-- tracing::debug!("[perf] check_version({}) took {:?}", tool, _timer_start.elapsed());- result-}--pub async fn ensure_ffmpeg() -> anyhow::Result<PathBuf> {- if let Some(path) = find_tool("ffmpeg").await {- return Ok(path);- }- if is_flatpak() {- return Err(anyhow!("FFmpeg not found in Flatpak sandbox"));- }- let path = download_ffmpeg().await?;- crate::core::ytdlp::reset_ffmpeg_location_cache();- Ok(path)-}--async fn download_ffmpeg() -> anyhow::Result<PathBuf> {- let bin_dir = managed_bin_dir()- .ok_or_else(|| anyhow!("Could not determine data directory"))?;- tokio::fs::create_dir_all(&bin_dir).await?;-- let ffmpeg_name = bin_name("ffmpeg");- let ffprobe_name = bin_name("ffprobe");- let ffmpeg_target = bin_dir.join(&ffmpeg_name);-- let downloads = ffmpeg_download_urls();-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .timeout(std::time::Duration::from_secs(300))- .build()?;-- for (url, archive_type) in downloads {- tracing::info!("Downloading FFmpeg component from {}", url);- let response = client.get(url).send().await?;- if !response.status().is_success() {- return Err(anyhow!("Failed to download FFmpeg from {}: HTTP {}", url, response.status()));- }-- let temp_path = bin_dir.join(".ffmpeg_download.tmp");- {- let mut file = tokio::fs::File::create(&temp_path).await?;- let mut stream = response.bytes_stream();- 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?;- }- tokio::io::AsyncWriteExt::flush(&mut file).await?;- }-- match archive_type {- ArchiveType::Zip => extract_zip_ffmpeg(&temp_path, &bin_dir, &ffmpeg_name, &ffprobe_name).await?,- ArchiveType::TarXz => extract_tar_xz_ffmpeg(&temp_path, &bin_dir, &ffmpeg_name, &ffprobe_name).await?,- }-- let _ = tokio::fs::remove_file(&temp_path).await;- }-- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let perms = std::fs::Permissions::from_mode(0o755);- let _ = tokio::fs::set_permissions(&ffmpeg_target, perms.clone()).await;- let ffprobe_path = bin_dir.join(&ffprobe_name);- if ffprobe_path.exists() {- let _ = tokio::fs::set_permissions(&ffprobe_path, perms).await;- }- }-- #[cfg(target_os = "macos")]- {- if let Err(e) = tokio::process::Command::new("xattr")- .args(["-d", "com.apple.quarantine"])- .arg(&ffmpeg_target)- .output()- .await- {- tracing::warn!("Failed to remove quarantine from ffmpeg: {}", e);- }- let ffprobe_path = bin_dir.join(&ffprobe_name);- if ffprobe_path.exists() {- if let Err(e) = tokio::process::Command::new("xattr")- .args(["-d", "com.apple.quarantine"])- .arg(&ffprobe_path)- .output()- .await- {- tracing::warn!("Failed to remove quarantine from ffprobe: {}", e);- }- }- }-- if !ffmpeg_target.exists() {- return Err(anyhow!("FFmpeg binary not found after extraction"));- }-- let verify = crate::core::process::command(&ffmpeg_target)- .arg("-version")- .stdout(Stdio::null())- .stderr(Stdio::null())- .status()- .await;- match verify {- Ok(s) if s.success() => {}- Ok(s) => return Err(anyhow!("FFmpeg installed but failed to execute (exit code {})", s)),- Err(e) => return Err(anyhow!("FFmpeg installed but failed to execute: {}", e)),- }-- tracing::info!("FFmpeg installed to {}", ffmpeg_target.display());- Ok(ffmpeg_target)-}--enum ArchiveType {- Zip,- TarXz,-}--fn ffmpeg_download_urls() -> Vec<(&'static str, ArchiveType)> {- if cfg!(target_os = "windows") {- vec![(- "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip",- ArchiveType::Zip,- )]- } else if cfg!(target_os = "macos") {- if cfg!(target_arch = "aarch64") {- vec![- ("https://www.osxexperts.net/ffmpeg80arm.zip", ArchiveType::Zip),- ("https://www.osxexperts.net/ffprobe80arm.zip", ArchiveType::Zip),- ]- } else {- vec![- ("https://www.osxexperts.net/ffmpeg80intel.zip", ArchiveType::Zip),- ("https://www.osxexperts.net/ffprobe80intel.zip", ArchiveType::Zip),- ]- }- } else if cfg!(target_arch = "aarch64") {- vec![(- "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linuxarm64-gpl.tar.xz",- ArchiveType::TarXz,- )]- } else {- vec![(- "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-linux64-gpl.tar.xz",- ArchiveType::TarXz,- )]- }-}--async fn extract_zip_ffmpeg(- archive_path: &std::path::Path,- bin_dir: &std::path::Path,- ffmpeg_name: &str,- ffprobe_name: &str,-) -> anyhow::Result<()> {- let archive_path = archive_path.to_path_buf();- let bin_dir = bin_dir.to_path_buf();- let ffmpeg_name = ffmpeg_name.to_string();- let ffprobe_name = ffprobe_name.to_string();-- tokio::task::spawn_blocking(move || {- let file = std::fs::File::open(&archive_path)- .map_err(|e| anyhow!("Failed to open archive: {}", e))?;- let mut archive = zip::ZipArchive::new(file)- .map_err(|e| anyhow!("Failed to open zip: {}", e))?;-- let targets = [ffmpeg_name.as_str(), ffprobe_name.as_str()];-- for i in 0..archive.len() {- let mut entry = archive- .by_index(i)- .map_err(|e| anyhow!("Failed to read zip entry: {}", e))?;-- let name = entry.name().to_string();- for target in &targets {- if name.ends_with(target) {- let dest = bin_dir.join(target);- let mut out = std::fs::File::create(&dest)?;- std::io::copy(&mut entry, &mut out)?;- break;- }- }- }-- Ok::<(), anyhow::Error>(())- })- .await- .map_err(|e| anyhow!("Spawn blocking failed: {}", e))??;-- Ok(())-}--async fn extract_tar_xz_ffmpeg(- archive_path: &std::path::Path,- bin_dir: &std::path::Path,- ffmpeg_name: &str,- ffprobe_name: &str,-) -> anyhow::Result<()> {- let archive_path = archive_path.to_path_buf();- let bin_dir = bin_dir.to_path_buf();- let ffmpeg_name = ffmpeg_name.to_string();- let ffprobe_name = ffprobe_name.to_string();-- tokio::task::spawn_blocking(move || {- let file = std::fs::File::open(&archive_path)- .map_err(|e| anyhow!("Failed to open archive: {}", e))?;- let decompressor = xz2::read::XzDecoder::new(file);- let mut archive = tar::Archive::new(decompressor);- let targets = [ffmpeg_name.as_str(), ffprobe_name.as_str()];-- for entry_result in archive.entries()- .map_err(|e| anyhow!("Failed to read tar entries: {}", e))?- {- let mut entry = entry_result- .map_err(|e| anyhow!("Failed to read tar entry: {}", e))?;- let path = entry.path()- .map_err(|e| anyhow!("Failed to read entry path: {}", e))?;- let file_name = path.file_name()- .and_then(|n| n.to_str())- .unwrap_or("");- for target in &targets {- if file_name == *target {- let dest = bin_dir.join(target);- let mut out = std::fs::File::create(&dest)?;- std::io::copy(&mut entry, &mut out)?;- break;- }- }- }- Ok::<(), anyhow::Error>(())- })- .await- .map_err(|e| anyhow!("Spawn blocking failed: {}", e))??;- Ok(())-}--// --- aria2c -----// --- deno (JS runtime for yt-dlp nsig challenge) -----/// Ensures a JavaScript runtime is available for yt-dlp's YouTube nsig-/// challenge solver. Checks for any existing runtime first (Node.js, Deno,-/// Bun), then auto-downloads Deno if none is found.-pub async fn ensure_js_runtime() -> Option<PathBuf> {- // Check system-installed runtimes first.- for tool in &["deno", "node", "bun"] {- if let Some(path) = find_tool(tool).await {- return Some(path);- }- }-- // Check well-known install locations on Windows.- #[cfg(target_os = "windows")]- {- let candidates = [- r"C:\Program Files\nodejs\node.exe",- r"C:\Program Files (x86)\nodejs\node.exe",- ];- for path in &candidates {- let p = PathBuf::from(path);- if p.exists() {- return Some(p);- }- }- }-- // No runtime found — download Deno (recommended by yt-dlp, fast, single binary).- match download_deno().await {- Ok(path) => {- crate::core::ytdlp::reset_js_runtime_cache();- Some(path)- }- Err(e) => {- tracing::warn!("Failed to download Deno JS runtime: {}", e);- None- }- }-}--async fn download_deno() -> anyhow::Result<PathBuf> {- let bin_dir = managed_bin_dir()- .ok_or_else(|| anyhow!("Could not determine data directory"))?;- tokio::fs::create_dir_all(&bin_dir).await?;-- let deno_name = bin_name("deno");- let deno_target = bin_dir.join(&deno_name);-- if deno_target.exists() {- return Ok(deno_target);- }-- let url = if cfg!(target_os = "windows") {- "https://github.com/denoland/deno/releases/latest/download/deno-x86_64-pc-windows-msvc.zip"- } else if cfg!(target_os = "macos") {- if cfg!(target_arch = "aarch64") {- "https://github.com/denoland/deno/releases/latest/download/deno-aarch64-apple-darwin.zip"- } else {- "https://github.com/denoland/deno/releases/latest/download/deno-x86_64-apple-darwin.zip"- }- } else if cfg!(target_arch = "aarch64") {- "https://github.com/denoland/deno/releases/latest/download/deno-aarch64-unknown-linux-gnu.zip"- } else {- "https://github.com/denoland/deno/releases/latest/download/deno-x86_64-unknown-linux-gnu.zip"- };-- tracing::info!("Downloading Deno JS runtime from {}", url);-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .timeout(std::time::Duration::from_secs(300))- .build()?;-- let response = client.get(url).send().await?;- if !response.status().is_success() {- return Err(anyhow!("Failed to download Deno: HTTP {}", response.status()));- }-- let bytes = response.bytes().await?;- let data = bytes.to_vec();- let bin_dir_clone = bin_dir.clone();- let deno_name_clone = deno_name.clone();-- tokio::task::spawn_blocking(move || {- let cursor = std::io::Cursor::new(&data);- let mut archive = zip::ZipArchive::new(cursor)- .map_err(|e| anyhow!("Failed to open Deno zip: {}", e))?;-- for i in 0..archive.len() {- let mut file = archive- .by_index(i)- .map_err(|e| anyhow!("Failed to read zip entry: {}", e))?;-- let name = file.name().to_string();- if name.ends_with(&deno_name_clone) || name == "deno" || name == "deno.exe" {- let dest = bin_dir_clone.join(&deno_name_clone);- let mut buf = Vec::new();- std::io::Read::read_to_end(&mut file, &mut buf)?;- std::fs::write(&dest, &buf)?;- break;- }- }-- Ok::<(), anyhow::Error>(())- })- .await- .map_err(|e| anyhow!("Spawn blocking failed: {}", e))??;-- if !deno_target.exists() {- return Err(anyhow!("Deno binary not found after extraction"));- }-- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let _ = tokio::fs::set_permissions(&deno_target, std::fs::Permissions::from_mode(0o755)).await;- }-- #[cfg(target_os = "macos")]- {- let _ = tokio::process::Command::new("xattr")- .args(["-d", "com.apple.quarantine"])- .arg(&deno_target)- .output()- .await;- }-- tracing::info!("Deno installed to {}", deno_target.display());- Ok(deno_target)-}--pub async fn ensure_aria2c() -> Option<PathBuf> {- if let Some(path) = find_tool("aria2c").await {- return Some(path);- }-- // Auto-download only on Windows- #[cfg(target_os = "windows")]- {- match download_aria2c().await {- Ok(path) => return Some(path),- Err(e) => {- tracing::warn!("Failed to download aria2c: {}", e);- }- }- }-- None-}--#[cfg(target_os = "windows")]-async fn download_aria2c() -> anyhow::Result<PathBuf> {- let bin_dir = managed_bin_dir()- .ok_or_else(|| anyhow!("Could not determine data directory"))?;- tokio::fs::create_dir_all(&bin_dir).await?;-- let aria2c_name = bin_name("aria2c");- let aria2c_target = bin_dir.join(&aria2c_name);-- let url = "https://github.com/aria2/aria2/releases/download/release-1.37.0/aria2-1.37.0-win-64bit-build1.zip";-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .timeout(std::time::Duration::from_secs(120))- .build()?;-- let response = client.get(url).send().await?;- if !response.status().is_success() {- return Err(anyhow!("Failed to download aria2c: HTTP {}", response.status()));- }-- let bytes = response.bytes().await?;-- let data = bytes.to_vec();- let bin_dir_clone = bin_dir.clone();- let aria2c_name_clone = aria2c_name.clone();-- tokio::task::spawn_blocking(move || {- let cursor = std::io::Cursor::new(&data);- let mut archive = zip::ZipArchive::new(cursor)- .map_err(|e| anyhow!("Failed to open aria2c zip: {}", e))?;-- for i in 0..archive.len() {- let mut file = archive- .by_index(i)- .map_err(|e| anyhow!("Failed to read zip entry: {}", e))?;-- let name = file.name().to_string();- if name.ends_with(&aria2c_name_clone) {- let dest = bin_dir_clone.join(&aria2c_name_clone);- let mut buf = Vec::new();- std::io::Read::read_to_end(&mut file, &mut buf)?;- std::fs::write(&dest, &buf)?;- break;- }- }-- Ok::<(), anyhow::Error>(())- })- .await- .map_err(|e| anyhow!("Spawn blocking failed: {}", e))??;-- if !aria2c_target.exists() {- return Err(anyhow!("aria2c binary not found after extraction"));- }-- Ok(aria2c_target)-}diff --git a/src-tauri/src/core/direct_downloader.rs b/src-tauri/src/core/direct_downloader.rsdeleted file mode 100644index bc58b5e1..00000000--- a/src-tauri/src/core/direct_downloader.rs+++ /dev/null@@ -1,569 +0,0 @@-use std::collections::HashMap;-use std::path::{Path, PathBuf};-use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::{Arc, OnceLock};--use std::time::Duration;--use anyhow::anyhow;-use futures::StreamExt;-use tokio::io::{AsyncSeekExt, AsyncWriteExt};-use tokio::sync::{mpsc, Semaphore};-use tokio_util::sync::CancellationToken;--const CHUNK_TIMEOUT: Duration = Duration::from_secs(45);-const MAX_RETRIES: u32 = 3;-const CHUNK_SIZE: u64 = 10 * 1024 * 1024;-const CHUNK_THRESHOLD: u64 = 10 * 1024 * 1024;-const MAX_PARALLEL: usize = 12;-const MAX_PER_HOST: usize = 16;--fn host_semaphores() -> &'static tokio::sync::Mutex<HashMap<String, Arc<Semaphore>>> {- static MAP: OnceLock<tokio::sync::Mutex<HashMap<String, Arc<Semaphore>>>> = OnceLock::new();- MAP.get_or_init(|| tokio::sync::Mutex::new(HashMap::new()))-}--pub async fn get_host_semaphore(url: &str) -> Arc<Semaphore> {- let host = url::Url::parse(url)- .ok()- .and_then(|u| u.host_str().map(|h| h.to_string()))- .unwrap_or_default();- let mut map = host_semaphores().lock().await;- map.entry(host)- .or_insert_with(|| Arc::new(Semaphore::new(MAX_PER_HOST)))- .clone()-}--struct ProbeResult {- content_length: Option<u64>,- accept_ranges: bool,-}--pub async fn download_direct(- client: &reqwest::Client,- url: &str,- output: &Path,- progress_tx: mpsc::Sender<f64>,- cancel: Option<&CancellationToken>,-) -> anyhow::Result<u64> {- download_direct_with_headers(client, url, output, progress_tx, None, cancel).await-}--pub async fn download_direct_with_headers(- client: &reqwest::Client,- url: &str,- output: &Path,- progress_tx: mpsc::Sender<f64>,- headers: Option<reqwest::header::HeaderMap>,- cancel: Option<&CancellationToken>,-) -> anyhow::Result<u64> {- let mut last_err = None;-- for attempt in 0..MAX_RETRIES {- if let Some(token) = cancel {- if token.is_cancelled() {- return Err(anyhow!("Download cancelled"));- }- }-- if attempt > 0 {- let base = 1000 * (attempt as u64);- let jitter = rand::random::<u64>() % (base / 2 + 1);- tokio::time::sleep(Duration::from_millis(base + jitter)).await;- }-- match download_attempt(client, url, output, &progress_tx, headers.clone(), cancel).await {- Ok(bytes) => return Ok(bytes),- Err(e) => {- if is_fatal_error(&e) {- let _ = tokio::fs::remove_file(&part_path_for(output)).await;- return Err(e);- }- tracing::warn!(- "[direct] attempt {}/{} failed: {}",- attempt + 1,- MAX_RETRIES,- e- );- last_err = Some(e);- }- }- }-- let _ = tokio::fs::remove_file(&part_path_for(output)).await;- Err(last_err.unwrap_or_else(|| anyhow!("Download failed after {} attempts", MAX_RETRIES)))-}--fn part_path_for(output: &Path) -> PathBuf {- let mut part = output.as_os_str().to_owned();- part.push(".part");- PathBuf::from(part)-}--fn is_fatal_error(err: &anyhow::Error) -> bool {- let msg = err.to_string();- for code in &[- "HTTP 400", "HTTP 401", "HTTP 403", "HTTP 404", "HTTP 405",- "HTTP 410", "HTTP 451",- ] {- if msg.contains(code) {- return true;- }- }- if msg.contains("HTML instead of media") {- return true;- }- if msg.contains("cancelled") {- return true;- }- false-}--async fn probe_url(- client: &reqwest::Client,- url: &str,- headers: Option<&reqwest::header::HeaderMap>,-) -> ProbeResult {- let mut request = client.head(url);- if let Some(h) = headers {- request = request.headers(h.clone());- }- match tokio::time::timeout(Duration::from_secs(15), request.send()).await {- Ok(Ok(resp)) if resp.status().is_success() => {- let content_length = resp.content_length();- let accept_ranges = resp- .headers()- .get("accept-ranges")- .and_then(|v| v.to_str().ok())- .map(|v| v.contains("bytes"))- .unwrap_or(false);- ProbeResult {- content_length,- accept_ranges,- }- }- _ => ProbeResult {- content_length: None,- accept_ranges: false,- },- }-}--async fn download_attempt(- client: &reqwest::Client,- url: &str,- output: &Path,- progress_tx: &mpsc::Sender<f64>,- headers: Option<reqwest::header::HeaderMap>,- cancel: Option<&CancellationToken>,-) -> anyhow::Result<u64> {- let part_path = part_path_for(output);- if let Some(parent) = output.parent() {- tokio::fs::create_dir_all(parent).await?;- }-- let probe = probe_url(client, url, headers.as_ref()).await;-- let use_chunked = probe.accept_ranges- && probe.content_length.is_some_and(|s| s > CHUNK_THRESHOLD);-- if use_chunked {- let total = probe.content_length.unwrap();- let _ = tokio::fs::remove_file(&part_path).await;- if let Err(chunked_err) = download_chunked(- client, url, &part_path, total, progress_tx, headers.clone(), cancel,- )- .await- {- if is_fatal_error(&chunked_err) {- return Err(chunked_err);- }- let _ = tokio::fs::remove_file(&part_path).await;- tracing::warn!("[direct] chunked failed, falling back: {}", chunked_err);- download_single_stream(- client, url, &part_path, 0, probe.content_length, progress_tx, headers, cancel,- )- .await?;- }- } else {- let existing = match tokio::fs::metadata(&part_path).await {- Ok(m) if m.len() > 0 && probe.accept_ranges => m.len(),- _ => 0,- };- download_single_stream(- client, url, &part_path, existing, probe.content_length, progress_tx, headers, cancel,- )- .await?;- }-- if let Some(expected) = probe.content_length {- let actual = tokio::fs::metadata(&part_path).await?.len();- if expected > 0 && actual != expected {- let _ = tokio::fs::remove_file(&part_path).await;- return Err(anyhow!(- "Size mismatch: expected {} bytes, got {}",- expected,- actual- ));- }- }-- tokio::fs::rename(&part_path, output).await?;- let _ = progress_tx.send(100.0).await;-- let size = tokio::fs::metadata(output).await?.len();- Ok(size)-}--async fn download_chunked(- client: &reqwest::Client,- url: &str,- part_path: &Path,- total_size: u64,- progress_tx: &mpsc::Sender<f64>,- headers: Option<reqwest::header::HeaderMap>,- cancel: Option<&CancellationToken>,-) -> anyhow::Result<()> {- let file = tokio::fs::File::create(part_path).await?;- file.set_len(total_size).await?;- drop(file);-- let num_chunks = total_size.div_ceil(CHUNK_SIZE);- let downloaded = Arc::new(AtomicU64::new(0));- let semaphore = Arc::new(Semaphore::new(MAX_PARALLEL));- let cancel_token = match cancel {- Some(ct) => ct.clone(),- None => CancellationToken::new(),- };-- let mut join_set = tokio::task::JoinSet::new();- for i in 0..num_chunks {- let start = i * CHUNK_SIZE;- let end = ((i + 1) * CHUNK_SIZE).min(total_size) - 1;- let client = client.clone();- let url = url.to_string();- let path = part_path.to_owned();- let sem = semaphore.clone();- let dl = downloaded.clone();- let ptx = progress_tx.clone();- let ct = cancel_token.clone();- let hdrs = headers.clone();-- join_set.spawn(async move {- let _permit = sem.acquire().await.unwrap();- if ct.is_cancelled() {- return Err(anyhow!("Download cancelled"));- }- download_chunk(&client, &url, &path, start, end, &dl, total_size, &ptx, hdrs, &ct)- .await- });- }-- while let Some(result) = join_set.join_next().await {- if cancel_token.is_cancelled() {- join_set.abort_all();- return Err(anyhow!("Download cancelled"));- }- match result {- Ok(Ok(())) => {}- Ok(Err(e)) => {- join_set.abort_all();- return Err(e);- }- Err(e) => {- join_set.abort_all();- return Err(anyhow!("Chunk task failed: {:?}", e));- }- }- }-- Ok(())-}--#[allow(clippy::too_many_arguments)]-async fn download_chunk(- client: &reqwest::Client,- url: &str,- part_path: &Path,- start: u64,- end: u64,- downloaded: &AtomicU64,- total_size: u64,- progress_tx: &mpsc::Sender<f64>,- headers: Option<reqwest::header::HeaderMap>,- cancel: &CancellationToken,-) -> anyhow::Result<()> {- let mut request = client.get(url);- if let Some(h) = headers {- request = request.headers(h);- }- request = request.header("Range", format!("bytes={}-{}", start, end));-- let response = tokio::time::timeout(Duration::from_secs(30), request.send())- .await- .map_err(|_| anyhow!("Timeout connecting to chunk"))??;-- let status = response.status();- if status != reqwest::StatusCode::PARTIAL_CONTENT {- if status.is_success() {- return Err(anyhow!("Server did not support Range request (HTTP 200)"));- }- return Err(anyhow!("HTTP {} downloading chunk", status));- }-- let mut file = tokio::fs::OpenOptions::new()- .write(true)- .open(part_path)- .await?;- file.seek(std::io::SeekFrom::Start(start)).await?;-- let expected_size = end - start + 1;- let mut chunk_written: u64 = 0;- let mut stream = response.bytes_stream();-- loop {- if cancel.is_cancelled() {- return Err(anyhow!("Download cancelled"));- }-- let chunk_result = tokio::time::timeout(CHUNK_TIMEOUT, stream.next()).await;- match chunk_result {- Ok(Some(Ok(data))) => {- file.write_all(&data).await.map_err(|e| {- anyhow!("Write error (disk full?): {}", e)- })?;- chunk_written += data.len() as u64;- let total_dl =- downloaded.fetch_add(data.len() as u64, Ordering::Relaxed) + data.len() as u64;- let percent = (total_dl as f64 / total_size as f64) * 100.0;- let _ = progress_tx.send(percent.min(99.9)).await;- }- Ok(Some(Err(e))) => return Err(anyhow!("Chunk stream error: {}", e)),- Ok(None) => break,- Err(_) => {- return Err(anyhow!(- "Chunk timeout — no data received for 30 seconds"- ))- }- }- }-- if chunk_written != expected_size {- return Err(anyhow!(- "Incomplete chunk: expected {} bytes, got {}",- expected_size,- chunk_written- ));- }-- file.flush().await?;- Ok(())-}--#[allow(clippy::too_many_arguments)]-async fn download_single_stream(- client: &reqwest::Client,- url: &str,- part_path: &Path,- existing_bytes: u64,- total_size: Option<u64>,- progress_tx: &mpsc::Sender<f64>,- headers: Option<reqwest::header::HeaderMap>,- cancel: Option<&CancellationToken>,-) -> anyhow::Result<()> {- let mut request = client.get(url);- if let Some(h) = headers {- request = request.headers(h);- }-- if existing_bytes > 0 {- if let Some(total) = total_size {- if existing_bytes >= total {- return Ok(());- }- }- request = request.header("Range", format!("bytes={}-", existing_bytes));- }-- let response = request.send().await?;-- let mut offset = 0u64;- if existing_bytes > 0 {- if response.status() == reqwest::StatusCode::PARTIAL_CONTENT {- offset = existing_bytes;- } else if response.status() == reqwest::StatusCode::RANGE_NOT_SATISFIABLE {- let _ = tokio::fs::remove_file(part_path).await;- return Err(anyhow!("Range not satisfiable, restarting"));- } else if !response.status().is_success() {- return Err(anyhow!("HTTP {} downloading {}", response.status(), url));- }- } else if !response.status().is_success() {- return Err(anyhow!("HTTP {} downloading {}", response.status(), url));- }-- if let Some(ct) = response.headers().get("content-type") {- if let Ok(ct_str) = ct.to_str() {- if ct_str.contains("text/html") {- return Err(anyhow!(- "Server returned HTML instead of media — URL may have expired"- ));- }- }- }-- let file = if offset > 0 {- tokio::fs::OpenOptions::new()- .append(true)- .open(part_path)- .await?- } else {- tokio::fs::File::create(part_path).await?- };-- let mut file = tokio::io::BufWriter::with_capacity(256 * 1024, file);- let mut downloaded = offset;- let mut stream = response.bytes_stream();-- loop {- if let Some(token) = cancel {- if token.is_cancelled() {- file.flush().await?;- return Err(anyhow!("Download cancelled"));- }- }-- let chunk_result = tokio::time::timeout(CHUNK_TIMEOUT, stream.next()).await;- match chunk_result {- Ok(Some(Ok(chunk))) => {- file.write_all(&chunk).await.map_err(|e| {- anyhow!("Write error (disk full?): {}", e)- })?;- downloaded += chunk.len() as u64;-- if let Some(total) = total_size {- if total > 0 {- let percent = (downloaded as f64 / total as f64) * 100.0;- let _ = progress_tx.send(percent).await;- }- } else {- let percent =- (downloaded as f64 / (downloaded as f64 + 500_000.0)) * 100.0;- let _ = progress_tx.send(percent.min(95.0)).await;- }- }- Ok(Some(Err(e))) => {- file.flush().await?;- return Err(anyhow!("Download stream error: {}", e));- }- Ok(None) => break,- Err(_) => {- file.flush().await?;- return Err(anyhow!(- "Download timeout — no data received for 30 seconds"- ));- }- }- }-- file.flush().await?;- Ok(())-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn part_path_appends_suffix() {- let output = Path::new("video.mp4");- let part = part_path_for(output);- assert_eq!(part, PathBuf::from("video.mp4.part"));- }-- #[test]- fn part_path_no_extension() {- let output = Path::new("video");- let part = part_path_for(output);- assert_eq!(part, PathBuf::from("video.part"));- }-- #[test]- fn part_path_nested() {- let output = Path::new("downloads/curso/aula.mp4");- let part = part_path_for(output);- assert_eq!(part, PathBuf::from("downloads/curso/aula.mp4.part"));- }-- #[test]- fn is_fatal_http_400() {- assert!(is_fatal_error(&anyhow!("HTTP 400 downloading url")));- }-- #[test]- fn is_fatal_http_401() {- assert!(is_fatal_error(&anyhow!("HTTP 401 downloading url")));- }-- #[test]- fn is_fatal_http_403() {- assert!(is_fatal_error(&anyhow!("HTTP 403 downloading url")));- }-- #[test]- fn is_fatal_http_404() {- assert!(is_fatal_error(&anyhow!("HTTP 404 downloading url")));- }-- #[test]- fn is_fatal_html_response() {- assert!(is_fatal_error(&anyhow!(- "Server returned HTML instead of media — URL may have expired"- )));- }-- #[test]- fn is_fatal_cancelled() {- assert!(is_fatal_error(&anyhow!("Download cancelled")));- }-- #[test]- fn is_not_fatal_500() {- assert!(!is_fatal_error(&anyhow!("HTTP 500 Internal Server Error")));- }-- #[test]- fn is_not_fatal_502() {- assert!(!is_fatal_error(&anyhow!("HTTP 502 Bad Gateway")));- }-- #[test]- fn is_not_fatal_timeout() {- assert!(!is_fatal_error(&anyhow!("connection timed out")));- }-- #[test]- fn is_not_fatal_network() {- assert!(!is_fatal_error(&anyhow!("network error")));- }-- #[test]- fn chunk_count_for_12mb() {- let total: u64 = 12 * 1024 * 1024;- assert_eq!(total.div_ceil(CHUNK_SIZE), 2);- }-- #[test]- fn chunk_count_exact_boundary() {- assert_eq!(CHUNK_SIZE.div_ceil(CHUNK_SIZE), 1);- }-- #[test]- fn chunk_count_single_byte_over() {- assert_eq!((CHUNK_SIZE + 1).div_ceil(CHUNK_SIZE), 2);- }-- #[test]- fn threshold_gte_chunk_size() {- assert!(CHUNK_THRESHOLD >= CHUNK_SIZE);- }-}diff --git a/src-tauri/src/core/ffmpeg.rs b/src-tauri/src/core/ffmpeg.rsdeleted file mode 100644index 6b153c5d..00000000--- a/src-tauri/src/core/ffmpeg.rs+++ /dev/null@@ -1,634 +0,0 @@-use std::path::Path;--use anyhow::anyhow;-use serde::{Deserialize, Serialize};-use tokio::io::{AsyncBufReadExt, BufReader};-use tokio::sync::mpsc;-use tokio_util::sync::CancellationToken;--static FFMPEG_AVAILABLE_CACHE: std::sync::RwLock<Option<bool>> = std::sync::RwLock::new(None);--pub async fn is_ffmpeg_available() -> bool {- if let Ok(cache) = FFMPEG_AVAILABLE_CACHE.read() {- if let Some(val) = *cache {- return val;- }- }- let available = crate::core::dependencies::find_tool("ffmpeg")- .await- .is_some();- if let Ok(mut cache) = FFMPEG_AVAILABLE_CACHE.write() {- *cache = Some(available);- }- available-}--pub fn reset_ffmpeg_available_cache() {- if let Ok(mut cache) = FFMPEG_AVAILABLE_CACHE.write() {- *cache = None;- }-}--pub async fn mux_video_audio(video: &Path, audio: &Path, output: &Path) -> anyhow::Result<()> {- if let Some(parent) = output.parent() {- tokio::fs::create_dir_all(parent).await?;- }-- let status = crate::core::process::command("ffmpeg")- .args([- "-y",- "-i",- &video.to_string_lossy(),- "-i",- &audio.to_string_lossy(),- "-c",- "copy",- &output.to_string_lossy(),- ])- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .status()- .await- .map_err(|e| anyhow!("Failed to run ffmpeg: {}", e))?;-- if !status.success() {- return Err(anyhow!("ffmpeg returned code {}", status));- }-- Ok(())-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ConversionOptions {- pub input_path: String,- pub output_path: String,- pub video_codec: Option<String>,- pub audio_codec: Option<String>,- pub resolution: Option<String>,- pub video_bitrate: Option<String>,- pub audio_bitrate: Option<String>,- pub sample_rate: Option<u32>,- pub fps: Option<f64>,- pub trim_start: Option<String>,- pub trim_end: Option<String>,- pub additional_input_args: Option<Vec<String>>,- pub additional_output_args: Option<Vec<String>>,- pub preset: Option<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct MediaProbeInfo {- pub duration_seconds: f64,- pub format_name: String,- pub format_long_name: String,- pub file_size_bytes: u64,- pub bit_rate: u64,- pub streams: Vec<StreamInfo>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct StreamInfo {- pub index: u32,- pub codec_type: String,- pub codec_name: String,- pub codec_long_name: String,- pub width: Option<u32>,- pub height: Option<u32>,- pub fps: Option<f64>,- pub bit_rate: Option<u64>,- pub sample_rate: Option<u32>,- pub channels: Option<u32>,- pub duration_seconds: Option<f64>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct ConversionResult {- pub success: bool,- pub output_path: String,- pub file_size_bytes: u64,- pub duration_seconds: f64,- pub error: Option<String>,-}--pub async fn probe(path: &Path) -> anyhow::Result<MediaProbeInfo> {- let output = crate::core::process::command("ffprobe")- .args([- "-v",- "quiet",- "-print_format",- "json",- "-show_format",- "-show_streams",- &path.to_string_lossy(),- ])- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped())- .output()- .await- .map_err(|e| anyhow!("Failed to run ffprobe: {}", e))?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- return Err(anyhow!("ffprobe failed: {}", stderr));- }-- let json: serde_json::Value = serde_json::from_slice(&output.stdout)- .map_err(|e| anyhow!("Failed to parse ffprobe JSON: {}", e))?;-- let format = json.get("format").ok_or_else(|| anyhow!("Missing 'format' field"))?;-- let duration_seconds = format- .get("duration")- .and_then(|v| v.as_str())- .and_then(|s| s.parse::<f64>().ok())- .unwrap_or(0.0);-- let format_name = format- .get("format_name")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let format_long_name = format- .get("format_long_name")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let file_size_bytes = format- .get("size")- .and_then(|v| v.as_str())- .and_then(|s| s.parse::<u64>().ok())- .unwrap_or(0);-- let bit_rate = format- .get("bit_rate")- .and_then(|v| v.as_str())- .and_then(|s| s.parse::<u64>().ok())- .unwrap_or(0);-- let streams = json- .get("streams")- .and_then(|v| v.as_array())- .map(|arr| arr.iter().map(parse_stream_info).collect())- .unwrap_or_default();-- Ok(MediaProbeInfo {- duration_seconds,- format_name,- format_long_name,- file_size_bytes,- bit_rate,- streams,- })-}--fn parse_stream_info(s: &serde_json::Value) -> StreamInfo {- let index = s.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as u32;-- let codec_type = s- .get("codec_type")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let codec_name = s- .get("codec_name")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let codec_long_name = s- .get("codec_long_name")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let width = s.get("width").and_then(|v| v.as_u64()).map(|v| v as u32);- let height = s.get("height").and_then(|v| v.as_u64()).map(|v| v as u32);-- let fps = s- .get("r_frame_rate")- .and_then(|v| v.as_str())- .and_then(parse_frame_rate);-- let bit_rate = s- .get("bit_rate")- .and_then(|v| v.as_str())- .and_then(|s| s.parse::<u64>().ok());-- let sample_rate = s- .get("sample_rate")- .and_then(|v| v.as_str())- .and_then(|s| s.parse::<u32>().ok());-- let channels = s.get("channels").and_then(|v| v.as_u64()).map(|v| v as u32);-- let duration_seconds = s- .get("duration")- .and_then(|v| v.as_str())- .and_then(|s| s.parse::<f64>().ok());-- StreamInfo {- index,- codec_type,- codec_name,- codec_long_name,- width,- height,- fps,- bit_rate,- sample_rate,- channels,- duration_seconds,- }-}--fn parse_frame_rate(s: &str) -> Option<f64> {- let parts: Vec<&str> = s.split('/').collect();- if parts.len() == 2 {- let num = parts[0].parse::<f64>().ok()?;- let den = parts[1].parse::<f64>().ok()?;- if den > 0.0 {- return Some(num / den);- }- }- s.parse::<f64>().ok()-}--pub async fn get_duration_us(path: &Path) -> anyhow::Result<u64> {- let info = probe(path).await?;- Ok((info.duration_seconds * 1_000_000.0) as u64)-}--pub async fn convert(- opts: &ConversionOptions,- cancel_token: CancellationToken,- progress_tx: mpsc::Sender<f64>,-) -> anyhow::Result<ConversionResult> {- let input_path = Path::new(&opts.input_path);- let output_path = Path::new(&opts.output_path);-- if let Some(parent) = output_path.parent() {- tokio::fs::create_dir_all(parent).await?;- }-- let total_duration_us = get_duration_us(input_path).await.unwrap_or(0);-- let mut args: Vec<String> = vec!["-y".to_string()];-- if let Some(ref start) = opts.trim_start {- args.extend(["-ss".to_string(), start.clone()]);- }-- if let Some(ref extra) = opts.additional_input_args {- args.extend(extra.clone());- }-- args.extend(["-i".to_string(), opts.input_path.clone()]);-- if let Some(ref end) = opts.trim_end {- args.extend(["-to".to_string(), end.clone()]);- }-- if let Some(ref codec) = opts.video_codec {- args.extend(["-c:v".to_string(), codec.clone()]);- }-- if let Some(ref codec) = opts.audio_codec {- args.extend(["-c:a".to_string(), codec.clone()]);- }-- if let Some(ref res) = opts.resolution {- args.extend(["-s".to_string(), res.clone()]);- }-- if let Some(ref br) = opts.video_bitrate {- args.extend(["-b:v".to_string(), br.clone()]);- }-- if let Some(ref br) = opts.audio_bitrate {- args.extend(["-b:a".to_string(), br.clone()]);- }-- if let Some(sr) = opts.sample_rate {- args.extend(["-ar".to_string(), sr.to_string()]);- }-- if let Some(fps) = opts.fps {- args.extend(["-r".to_string(), fps.to_string()]);- }-- if let Some(ref preset) = opts.preset {- args.extend(["-preset".to_string(), preset.clone()]);- }-- if let Some(ref extra) = opts.additional_output_args {- args.extend(extra.clone());- }-- args.extend([- "-progress".to_string(),- "pipe:1".to_string(),- "-nostats".to_string(),- opts.output_path.clone(),- ]);-- let mut child = crate::core::process::command("ffmpeg")- .args(&args)- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped())- .spawn()- .map_err(|e| anyhow!("Failed to start ffmpeg: {}", e))?;-- let stdout = child- .stdout- .take()- .ok_or_else(|| anyhow!("No stdout from ffmpeg"))?;- let reader = BufReader::new(stdout);- let mut lines = reader.lines();-- let cancel = cancel_token.clone();- let progress = progress_tx.clone();- let line_reader = tokio::spawn(async move {- while let Ok(Some(line)) = lines.next_line().await {- if cancel.is_cancelled() {- break;- }- if let Some(us) = parse_out_time_us(&line) {- if total_duration_us > 0 {- let pct = (us as f64 / total_duration_us as f64 * 100.0).min(100.0);- let _ = progress.send(pct).await;- }- }- }- });-- let result = tokio::select! {- status = child.wait() => {- let _ = line_reader.await;- status.map_err(|e| anyhow!("ffmpeg process failed: {}", e))- }- _ = cancel_token.cancelled() => {- let _ = child.kill().await;- let _ = line_reader.await;- return Ok(ConversionResult {- success: false,- output_path: opts.output_path.clone(),- file_size_bytes: 0,- duration_seconds: 0.0,- error: Some("Conversion cancelled".to_string()),- });- }- };-- match result {- Ok(status) if status.success() => {- let _ = progress_tx.send(100.0).await;- let meta = tokio::fs::metadata(output_path).await;- let file_size = meta.map(|m| m.len()).unwrap_or(0);-- let duration = probe(output_path)- .await- .map(|i| i.duration_seconds)- .unwrap_or(0.0);-- Ok(ConversionResult {- success: true,- output_path: opts.output_path.clone(),- file_size_bytes: file_size,- duration_seconds: duration,- error: None,- })- }- Ok(status) => Ok(ConversionResult {- success: false,- output_path: opts.output_path.clone(),- file_size_bytes: 0,- duration_seconds: 0.0,- error: Some(format!("ffmpeg exited with code {}", status)),- }),- Err(e) => Ok(ConversionResult {- success: false,- output_path: opts.output_path.clone(),- file_size_bytes: 0,- duration_seconds: 0.0,- error: Some(e.to_string()),- }),- }-}--#[derive(Debug, Clone, Serialize, Deserialize, Default)]-pub struct MetadataEmbed {- pub title: Option<String>,- pub artist: Option<String>,- pub album: Option<String>,- pub track_number: Option<String>,- pub genre: Option<String>,- pub year: Option<String>,- pub comment: Option<String>,- pub thumbnail_url: Option<String>,-}--pub async fn embed_metadata(- file: &Path,- metadata: &MetadataEmbed,- embed_thumbnail: bool,- http_client: &reqwest::Client,-) -> anyhow::Result<()> {- if !is_ffmpeg_available().await {- return Err(anyhow!("ffmpeg not available"));- }-- let temp_dir = file.parent().unwrap_or(Path::new("."));- let ext = file- .extension()- .and_then(|e| e.to_str())- .unwrap_or("mp4");- let temp_output = temp_dir.join(format!(- ".omniget_meta_{}.{}",- uuid::Uuid::new_v4(),- ext- ));-- let is_audio_only = matches!(- ext.to_lowercase().as_str(),- "mp3" | "m4a" | "aac" | "ogg" | "opus" | "flac" | "wav" | "wma"- );-- let thumbnail_path = if embed_thumbnail && is_audio_only {- if let Some(ref url) = metadata.thumbnail_url {- match download_thumbnail(http_client, url, temp_dir).await {- Ok(p) => Some(p),- Err(e) => {- tracing::warn!("Failed to download thumbnail: {}", e);- None- }- }- } else {- None- }- } else {- None- };-- let mut args: Vec<String> = vec!["-y".to_string(), "-i".to_string(), file.to_string_lossy().to_string()];-- if let Some(ref thumb) = thumbnail_path {- args.extend(["-i".to_string(), thumb.to_string_lossy().to_string()]);- }-- if let Some(ref thumb) = thumbnail_path {- let _ = thumb;- args.extend([- "-map".to_string(), "0:a".to_string(),- "-map".to_string(), "1:v".to_string(),- "-c".to_string(), "copy".to_string(),- "-disposition:v:0".to_string(), "attached_pic".to_string(),- ]);- } else {- args.extend(["-c".to_string(), "copy".to_string()]);- }-- if let Some(ref v) = metadata.title {- args.extend(["-metadata".to_string(), format!("title={}", v)]);- }- if let Some(ref v) = metadata.artist {- args.extend(["-metadata".to_string(), format!("artist={}", v)]);- }- if let Some(ref v) = metadata.album {- args.extend(["-metadata".to_string(), format!("album={}", v)]);- }- if let Some(ref v) = metadata.track_number {- args.extend(["-metadata".to_string(), format!("track={}", v)]);- }- if let Some(ref v) = metadata.genre {- args.extend(["-metadata".to_string(), format!("genre={}", v)]);- }- if let Some(ref v) = metadata.year {- args.extend(["-metadata".to_string(), format!("date={}", v)]);- }- if let Some(ref v) = metadata.comment {- args.extend(["-metadata".to_string(), format!("comment={}", v)]);- }-- args.push(temp_output.to_string_lossy().to_string());-- let output = crate::core::process::command("ffmpeg")- .args(&args)- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped())- .output()- .await- .map_err(|e| anyhow!("Failed to run ffmpeg: {}", e))?;-- if let Some(ref thumb) = thumbnail_path {- let _ = tokio::fs::remove_file(thumb).await;- }-- if !output.status.success() {- let _ = tokio::fs::remove_file(&temp_output).await;- let stderr = String::from_utf8_lossy(&output.stderr);- return Err(anyhow!("ffmpeg metadata failed: {}", stderr));- }-- let mut rename_ok = false;- for attempt in 0..3 {- match tokio::fs::rename(&temp_output, file).await {- Ok(()) => {- rename_ok = true;- break;- }- Err(e) if attempt < 2 => {- tracing::warn!(- "Failed to replace file (attempt {}): {}, retrying...",- attempt + 1,- e- );- tokio::time::sleep(std::time::Duration::from_millis(500 * (attempt as u64 + 1)))- .await;- }- Err(e) => {- let _ = tokio::fs::remove_file(&temp_output).await;- return Err(anyhow!("Failed to replace file after 3 attempts: {}", e));- }- }- }- if !rename_ok {- let _ = tokio::fs::remove_file(&temp_output).await;- return Err(anyhow!("Failed to replace file"));- }-- Ok(())-}--async fn download_thumbnail(- client: &reqwest::Client,- url: &str,- dest_dir: &Path,-) -> anyhow::Result<std::path::PathBuf> {- let response = client- .get(url)- .send()- .await- .map_err(|e| anyhow!("Failed to download thumbnail: {}", e))?;-- let content_type = response- .headers()- .get("content-type")- .and_then(|v| v.to_str().ok())- .unwrap_or("image/jpeg")- .to_string();-- let bytes = response- .bytes()- .await- .map_err(|e| anyhow!("Failed to read thumbnail: {}", e))?;-- let ext = if content_type.contains("png") {- "png"- } else {- "jpg"- };-- let thumb_path = dest_dir.join(format!(".omniget_thumb_{}.{}", uuid::Uuid::new_v4(), ext));- tokio::fs::write(&thumb_path, &bytes).await?;-- if ext == "png" {- let jpg_path = dest_dir.join(format!(".omniget_thumb_{}.jpg", uuid::Uuid::new_v4()));- let convert_result = crate::core::process::command("ffmpeg")- .args([- "-y",- "-i",- &thumb_path.to_string_lossy(),- &jpg_path.to_string_lossy(),- ])- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .status()- .await;-- let _ = tokio::fs::remove_file(&thumb_path).await;-- if let Ok(status) = convert_result {- if status.success() {- return Ok(jpg_path);- }- }- let _ = tokio::fs::remove_file(&jpg_path).await;- return Err(anyhow!("Failed to convert thumbnail to JPEG"));- }-- Ok(thumb_path)-}--fn parse_out_time_us(line: &str) -> Option<u64> {- let line = line.trim();- if let Some(val) = line.strip_prefix("out_time_us=") {- return val.trim().parse::<u64>().ok();- }- if let Some(val) = line.strip_prefix("out_time_ms=") {- return val.trim().parse::<u64>().ok().map(|ms| ms * 1000);- }- None-}diff --git a/src-tauri/src/core/filename.rs b/src-tauri/src/core/filename.rsdeleted file mode 100644index 081b92d0..00000000--- a/src-tauri/src/core/filename.rs+++ /dev/null@@ -1,109 +0,0 @@-use regex::Regex;-use std::sync::LazyLock;-use unicode_normalization::UnicodeNormalization;--static WS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+").unwrap());--pub fn sanitize_path_component(name: &str) -> String {- let name: String = name.nfc().collect();- let name = name.trim().replace(['\t', '\n'], "");- let name = WS_RE.replace_all(&name, " ");- let name = name.replace(" | ", "|");-- let name = name.trim_end_matches([' ', '-', '.', ';']);-- let forbidden: &[(char, char)] = &[- ('<', '<'),- ('>', '>'),- (':', '꞉'),- ('"', '"'),- ('/', '⧸'),- ('\\', '\'),- ('|', '|'),- ('?', '?'),- ('*', ' '),- ];-- let mut result = name.to_string();- for (from, to) in forbidden {- result = result.replace(*from, &to.to_string());- }-- result.trim().to_string()-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn sanitize_basic_forbidden_chars() {- assert_eq!(sanitize_path_component("a:b?c"), "a꞉b?c");- }-- #[test]- fn sanitize_collapses_whitespace() {- assert_eq!(sanitize_path_component("hello world"), "hello world");- }-- #[test]- fn sanitize_trims_trailing_punctuation() {- assert_eq!(sanitize_path_component("file name - "), "file name");- }-- #[test]- fn sanitize_unicode_nfc_normalization() {- let decomposed = "e\u{0301}";- let result = sanitize_path_component(decomposed);- assert_eq!(result, "\u{00e9}");- }-- #[test]- fn sanitize_pipe_separator() {- assert_eq!(sanitize_path_component("a | b"), "a|b");- }-- #[test]- fn sanitize_long_path_with_special_chars() {- let input = "Video: \"Best of 2024\" <HD> | 1080p";- let result = sanitize_path_component(input);- assert!(!result.contains(':'));- assert!(!result.contains('"'));- assert!(!result.contains('<'));- assert!(!result.contains('>'));- }-- #[test]- fn sanitize_windows_forbidden_paths() {- let chars = ['<', '>', ':', '"', '/', '\\', '|', '?', '*'];- for c in chars {- let input = format!("test{}file", c);- let result = sanitize_path_component(&input);- assert!(!result.contains(c), "char '{}' should be replaced", c);- }- }-- #[test]- fn omniget_prefix_basic() {- let name = "omniget-My Video Title [abc123]";- let result = sanitize_path_component(name);- assert!(result.starts_with("omniget-"));- assert!(!result.contains(':'));- }-- #[test]- fn omniget_prefix_with_special_chars() {- let name = "omniget-Video: \"Best\" <2024> [id]";- let result = sanitize_path_component(name);- assert!(result.starts_with("omniget-"));- }-- #[test]- fn omniget_prefix_long_name() {- let long_title = "a".repeat(250);- let name = format!("omniget-{} [id]", long_title);- let result = sanitize_path_component(&name);- assert!(result.starts_with("omniget-"));- assert!(result.ends_with("[id]"));- }-}diff --git a/src-tauri/src/core/hls_downloader.rs b/src-tauri/src/core/hls_downloader.rsdeleted file mode 100644index 40945a87..00000000--- a/src-tauri/src/core/hls_downloader.rs+++ /dev/null@@ -1,787 +0,0 @@-use std::collections::{BTreeMap, HashMap};-use std::path::PathBuf;-use std::sync::atomic::{AtomicUsize, Ordering};-use std::sync::Arc;-use std::time::Duration;--use futures::stream::{self, StreamExt};-use m3u8_rs::{parse_master_playlist, parse_media_playlist, MasterPlaylist, VariantStream};-use reqwest::Client;-use tokio::io::AsyncWriteExt;-use tokio::sync::mpsc::{self, UnboundedSender};-use tokio::sync::Semaphore;-use tokio_util::sync::CancellationToken;--const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";--pub struct HlsDownloadResult {- pub path: PathBuf,- pub file_size: u64,- pub segments: usize,-}--pub struct HlsDownloader {- client: Client,-}--impl Default for HlsDownloader {- fn default() -> Self {- Self::new()- }-}--impl HlsDownloader {- pub fn new() -> Self {- Self::with_client(- Client::builder()- .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(),- )- }-- pub fn with_client(client: Client) -> Self {- Self { client }- }-- #[allow(clippy::too_many_arguments)]- pub async fn download(- &self,- m3u8_url: &str,- output_path: &str,- referer: &str,- bytes_tx: Option<UnboundedSender<u64>>,- cancel_token: CancellationToken,- max_concurrent: u32,- max_retries: u32,- ) -> anyhow::Result<HlsDownloadResult> {- self.download_with_quality(m3u8_url, output_path, referer, bytes_tx, cancel_token, max_concurrent, max_retries, None).await- }-- #[allow(clippy::too_many_arguments)]- pub async fn download_with_quality(- &self,- m3u8_url: &str,- output_path: &str,- referer: &str,- bytes_tx: Option<UnboundedSender<u64>>,- cancel_token: CancellationToken,- max_concurrent: u32,- max_retries: u32,- max_height: Option<u32>,- ) -> anyhow::Result<HlsDownloadResult> {- if cancel_token.is_cancelled() {- anyhow::bail!("Download cancelled by user");- }-- let m3u8_text = self.fetch_m3u8_with_retry(m3u8_url, referer, 3).await?;-- let m3u8_bytes = m3u8_text.as_bytes();-- if let Ok((_, master)) = parse_master_playlist(m3u8_bytes) {- if let Some(variant) = select_best_variant(&master, max_height.unwrap_or(720)) {- let variant_url = resolve_url(m3u8_url, &variant.uri);- return self- .download_media_playlist(&variant_url, output_path, referer, bytes_tx, cancel_token, max_concurrent, max_retries)- .await;- }- }-- if parse_media_playlist(m3u8_bytes).is_ok() {- return self- .download_media_playlist(m3u8_url, output_path, referer, bytes_tx, cancel_token, max_concurrent, max_retries)- .await;- }-- anyhow::bail!("Failed to parse m3u8: neither master nor media playlist")- }-- async fn fetch_m3u8_with_retry(- &self,- url: &str,- referer: &str,- max_retries: u32,- ) -> anyhow::Result<String> {- let mut last_err = None;- for attempt in 0..max_retries {- match self- .client- .get(url)- .header("Referer", referer)- .header("User-Agent", USER_AGENT)- .send()- .await- {- Ok(resp) => match resp.text().await {- Ok(text) => return Ok(text),- Err(e) => last_err = Some(anyhow::anyhow!(e)),- },- Err(e) => last_err = Some(anyhow::anyhow!(e)),- }- if attempt < max_retries - 1 {- let base = 500 * (attempt as u64 + 1);- let jitter = rand::random::<u64>() % (base / 2 + 1);- tokio::time::sleep(Duration::from_millis(base + jitter)).await;- }- }- Err(last_err.unwrap_or_else(|| {- anyhow::anyhow!("Failed to fetch m3u8 after {} attempts", max_retries)- }))- }-- #[allow(clippy::too_many_arguments)]- async fn download_media_playlist(- &self,- m3u8_url: &str,- output_path: &str,- referer: &str,- bytes_tx: Option<UnboundedSender<u64>>,- cancel_token: CancellationToken,- max_concurrent: u32,- max_retries: u32,- ) -> anyhow::Result<HlsDownloadResult> {- let resp = self- .client- .get(m3u8_url)- .header("Referer", referer)- .header("User-Agent", USER_AGENT)- .send()- .await?;-- let text = resp.text().await?;-- let (_, playlist) = parse_media_playlist(text.as_bytes())- .map_err(|e| anyhow::anyhow!("Parse media playlist: {:?}", e))?;-- let total_segments = playlist.segments.len();-- let encryption = self- .fetch_encryption_info(&playlist, m3u8_url, referer)- .await?;-- let output = PathBuf::from(output_path);- let part_path = {- let mut p = output.as_os_str().to_owned();- p.push(".part");- PathBuf::from(p)- };- if let Some(parent) = output.parent() {- tokio::fs::create_dir_all(parent).await?;- }-- let (seg_tx, seg_rx) = mpsc::channel::<(usize, Vec<u8>)>(max_concurrent as usize);-- let writer_output = part_path.clone();- let media_sequence = playlist.media_sequence;- let writer = tokio::spawn(async move {- write_segments_ordered(seg_rx, &writer_output, &encryption, media_sequence, total_segments).await- });-- let semaphore = Arc::new(Semaphore::new(max_concurrent as usize));- let completed = Arc::new(AtomicUsize::new(0));- let fail_token = cancel_token.child_token();- let errors: Arc<tokio::sync::Mutex<HashMap<String, u32>>> = Arc::new(tokio::sync::Mutex::new(HashMap::new()));-- let segment_urls: Vec<(usize, String)> = playlist- .segments- .iter()- .enumerate()- .map(|(i, seg)| (i, resolve_url(m3u8_url, &seg.uri)))- .collect();-- let client = &self.client;- let errors_ref = &errors;- let completed_ref = &completed;- let fail_ref = &fail_token;- let sem_ref = &semaphore;-- stream::iter(segment_urls)- .map(|(i, url)| {- let bytes_tx = bytes_tx.clone();- let seg_tx = seg_tx.clone();- let referer = referer.to_string();- async move {- let _permit = sem_ref.acquire().await.unwrap();- if fail_ref.is_cancelled() {- return;- }- match download_segment_with_retry(client, &url, &referer, max_retries, fail_ref).await {- Ok(data) => {- if let Some(ref btx) = bytes_tx {- let _ = btx.send(data.len() as u64);- }- completed_ref.fetch_add(1, Ordering::Relaxed);- let _ = seg_tx.send((i, data)).await;- }- Err(e) => {- let key = e.to_string();- let mut errs = errors_ref.lock().await;- *errs.entry(key).or_insert(0) += 1;- drop(errs);- fail_ref.cancel();- }- }- }- })- .buffer_unordered(max_concurrent as usize)- .collect::<()>()- .await;-- drop(seg_tx);-- let writer_result = writer.await- .map_err(|e| anyhow::anyhow!("Writer task panicked: {:?}", e))?;-- if cancel_token.is_cancelled() {- let _ = tokio::fs::remove_file(&part_path).await;- anyhow::bail!("Download cancelled by user");- }-- let errs = errors.lock().await;- if !errs.is_empty() {- let _ = tokio::fs::remove_file(&part_path).await;- let summary: Vec<String> = errs- .iter()- .map(|(msg, count)| {- if *count > 1 {- format!("{} (x{})", msg, count)- } else {- msg.clone()- }- })- .collect();- anyhow::bail!("Segment download failed: {}", summary.join("; "));- }- drop(errs);-- writer_result?;-- tokio::fs::rename(&part_path, &output).await?;-- let file_size = tokio::fs::metadata(&output).await?.len();-- Ok(HlsDownloadResult {- path: output,- file_size,- segments: total_segments,- })- }-- async fn fetch_encryption_info(- &self,- playlist: &m3u8_rs::MediaPlaylist,- m3u8_url: &str,- referer: &str,- ) -> anyhow::Result<Option<EncryptionInfo>> {- for segment in &playlist.segments {- if let Some(key) = &segment.key {- match key.method {- m3u8_rs::KeyMethod::AES128 => {- if let Some(uri) = &key.uri {- let key_url = resolve_url(m3u8_url, uri);- let key_bytes = self.fetch_key_with_retry(&key_url, referer, 3).await?;- let iv = key.iv.as_ref().map(|iv_str| parse_hex_iv(iv_str));- return Ok(Some(EncryptionInfo { key_bytes, iv }));- }- }- m3u8_rs::KeyMethod::SampleAES => {- anyhow::bail!("HLS stream uses SAMPLE-AES (FairPlay DRM), cannot decrypt");- }- _ => {}- }- }- }- Ok(None)- }-- async fn fetch_key_with_retry(- &self,- url: &str,- referer: &str,- max_retries: u32,- ) -> anyhow::Result<Vec<u8>> {- let mut last_err = None;- for attempt in 0..max_retries {- match self- .client- .get(url)- .header("Referer", referer)- .header("User-Agent", USER_AGENT)- .send()- .await- {- Ok(resp) => {- if !resp.status().is_success() {- last_err = Some(anyhow::anyhow!("HTTP {} fetching AES key", resp.status()));- } else {- match resp.bytes().await {- Ok(bytes) => return Ok(bytes.to_vec()),- Err(e) => last_err = Some(anyhow::anyhow!(e)),- }- }- }- Err(e) => last_err = Some(anyhow::anyhow!(e)),- }- if attempt < max_retries - 1 {- let base = 500 * (attempt as u64 + 1);- let jitter = rand::random::<u64>() % (base / 2 + 1);- tokio::time::sleep(Duration::from_millis(base + jitter)).await;- }- }- Err(last_err.unwrap_or_else(|| {- anyhow::anyhow!("Failed to fetch AES key after {} attempts", max_retries)- }))- }-}--struct EncryptionInfo {- key_bytes: Vec<u8>,- iv: Option<[u8; 16]>,-}--fn select_best_variant(master: &MasterPlaylist, max_height: u32) -> Option<&VariantStream> {- let real: Vec<&VariantStream> = master- .variants- .iter()- .filter(|v| !v.is_i_frame)- .collect();-- if real.is_empty() {- return None;- }-- let mut sorted = real;- sorted.sort_by_key(|v| v.resolution.as_ref().map(|r| r.height).unwrap_or(0));-- let max_h = max_height as u64;- let mut best: Option<&VariantStream> = None;- for v in &sorted {- if v.resolution- .as_ref()- .map(|r| r.height <= max_h)- .unwrap_or(true)- {- best = Some(*v);- }- }-- best.or_else(|| sorted.first().copied())-}--fn resolve_url(base: &str, relative: &str) -> String {- if relative.starts_with("http://") || relative.starts_with("https://") {- return relative.to_string();- }-- let (base_path, query) = match base.find('?') {- Some(pos) => (&base[..pos], Some(&base[pos..])),- None => (base, None),- };-- let resolved = if let Some(pos) = base_path.rfind('/') {- format!("{}/{}", &base_path[..pos], relative)- } else {- relative.to_string()- };-- match query {- Some(q) if !relative.contains('?') => format!("{}{}", resolved, q),- _ => resolved,- }-}--async fn write_segments_ordered(- mut rx: mpsc::Receiver<(usize, Vec<u8>)>,- output_path: &PathBuf,- encryption: &Option<EncryptionInfo>,- media_sequence: u64,- total_segments: usize,-) -> anyhow::Result<()> {- let mut file = tokio::io::BufWriter::with_capacity(- 256 * 1024,- tokio::fs::File::create(output_path).await?,- );- let mut next_expected: usize = 0;- let mut pending: BTreeMap<usize, Vec<u8>> = BTreeMap::new();-- while let Some((idx, data)) = rx.recv().await {- pending.insert(idx, data);-- while let Some(segment_data) = pending.remove(&next_expected) {- if let Some(enc) = encryption {- use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, KeyIvInit};- type Aes128CbcDec = cbc::Decryptor<aes::Aes128>;-- let iv = compute_iv(enc, next_expected, media_sequence);- let mut buf = segment_data;- let decryptor = Aes128CbcDec::new_from_slices(&enc.key_bytes, &iv)- .map_err(|e| anyhow::anyhow!("AES init: {:?}", e))?;- let decrypted = decryptor- .decrypt_padded_mut::<Pkcs7>(&mut buf)- .map_err(|e| anyhow::anyhow!("AES decrypt: {:?}", e))?;- file.write_all(decrypted).await?;- } else {- file.write_all(&segment_data).await?;- }- next_expected += 1;- }- }-- file.flush().await?;-- if next_expected < total_segments {- anyhow::bail!(- "Only {} of {} segments were written",- next_expected,- total_segments- );- }-- Ok(())-}--const SEGMENT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);--async fn download_segment_with_retry(- client: &Client,- url: &str,- referer: &str,- max_retries: u32,- cancel: &CancellationToken,-) -> anyhow::Result<Vec<u8>> {- let mut last_err = None;- for attempt in 0..max_retries {- if cancel.is_cancelled() {- anyhow::bail!("Download cancelled");- }-- let result = tokio::time::timeout(SEGMENT_TIMEOUT, async {- let resp = client- .get(url)- .header("Referer", referer)- .header("User-Agent", USER_AGENT)- .send()- .await?;-- let status = resp.status();- if !status.is_success() {- let code = status.as_u16();- if (400..500).contains(&code) && code != 429 && code != 408 {- return Err(anyhow::anyhow!("HTTP {} (fatal) downloading segment", code));- }- return Err(anyhow::anyhow!("HTTP {} downloading segment", code));- }-- resp.bytes().await.map(|b| b.to_vec()).map_err(|e| anyhow::anyhow!(e))- })- .await;-- match result {- Ok(Ok(data)) => return Ok(data),- Ok(Err(e)) => {- if e.to_string().contains("(fatal)") {- return Err(e);- }- last_err = Some(e);- }- Err(_) => last_err = Some(anyhow::anyhow!("Timeout downloading segment")),- }- if attempt < max_retries - 1 {- let base = 500 * (attempt as u64 + 1);- let jitter = rand::random::<u64>() % (base / 2 + 1);- tokio::time::sleep(std::time::Duration::from_millis(base + jitter))- .await;- }- }- Err(last_err- .unwrap_or_else(|| anyhow::anyhow!("Segment download failed after {} attempts", max_retries)))-}--fn compute_iv(encryption: &EncryptionInfo, segment_index: usize, media_sequence: u64) -> [u8; 16] {- if let Some(iv) = &encryption.iv {- return *iv;- }- let seq = media_sequence + segment_index as u64;- let mut iv = [0u8; 16];- iv[8..16].copy_from_slice(&seq.to_be_bytes());- iv-}--fn parse_hex_iv(iv_str: &str) -> [u8; 16] {- let hex = iv_str- .trim_start_matches("0x")- .trim_start_matches("0X");- let mut result = [0u8; 16];- let padded = format!("{:0>32}", hex);- for i in 0..16 {- result[i] = u8::from_str_radix(&padded[i * 2..i * 2 + 2], 16).unwrap_or(0);- }- result-}--#[cfg(test)]-mod tests {- use super::*;- use m3u8_rs::{MasterPlaylist, Resolution, VariantStream};-- #[test]- fn resolve_url_absolute_passthrough() {- assert_eq!(- resolve_url(- "https://cdn.example.com/path/master.m3u8",- "https://other.com/video.ts"- ),- "https://other.com/video.ts"- );- }-- #[test]- fn resolve_url_relative() {- assert_eq!(- resolve_url("https://cdn.example.com/path/master.m3u8", "segment0.ts"),- "https://cdn.example.com/path/segment0.ts"- );- }-- #[test]- fn resolve_url_propagates_query() {- assert_eq!(- resolve_url(- "https://cdn.example.com/path/master.m3u8?token=abc",- "segment0.ts"- ),- "https://cdn.example.com/path/segment0.ts?token=abc"- );- }-- #[test]- fn resolve_url_relative_with_own_query_skips_base_query() {- assert_eq!(- resolve_url(- "https://cdn.example.com/path/master.m3u8?token=abc",- "segment0.ts?key=123"- ),- "https://cdn.example.com/path/segment0.ts?key=123"- );- }-- #[test]- fn resolve_url_no_slash_in_base() {- assert_eq!(resolve_url("master.m3u8", "segment0.ts"), "segment0.ts");- }-- #[test]- fn select_best_variant_picks_720() {- let master = MasterPlaylist {- variants: vec![- VariantStream {- uri: "360.m3u8".into(),- bandwidth: 800_000,- resolution: Some(Resolution {- width: 640,- height: 360,- }),- ..Default::default()- },- VariantStream {- uri: "720.m3u8".into(),- bandwidth: 2_500_000,- resolution: Some(Resolution {- width: 1280,- height: 720,- }),- ..Default::default()- },- VariantStream {- uri: "1080.m3u8".into(),- bandwidth: 5_000_000,- resolution: Some(Resolution {- width: 1920,- height: 1080,- }),- ..Default::default()- },- ],- ..Default::default()- };- let best = select_best_variant(&master, 720).unwrap();- assert_eq!(best.uri, "720.m3u8");- }-- #[test]- fn select_best_variant_picks_1080() {- let master = MasterPlaylist {- variants: vec![- VariantStream {- uri: "720.m3u8".into(),- bandwidth: 2_500_000,- resolution: Some(Resolution {- width: 1280,- height: 720,- }),- ..Default::default()- },- VariantStream {- uri: "1080.m3u8".into(),- bandwidth: 5_000_000,- resolution: Some(Resolution {- width: 1920,- height: 1080,- }),- ..Default::default()- },- ],- ..Default::default()- };- let best = select_best_variant(&master, 1080).unwrap();- assert_eq!(best.uri, "1080.m3u8");- }-- #[test]- fn select_best_variant_empty_returns_none() {- let master = MasterPlaylist {- variants: vec![],- ..Default::default()- };- assert!(select_best_variant(&master, 720).is_none());- }-- #[test]- fn select_best_variant_skips_iframe() {- let master = MasterPlaylist {- variants: vec![- VariantStream {- uri: "iframe.m3u8".into(),- bandwidth: 100_000,- is_i_frame: true,- resolution: Some(Resolution {- width: 320,- height: 180,- }),- ..Default::default()- },- VariantStream {- uri: "720.m3u8".into(),- bandwidth: 2_500_000,- resolution: Some(Resolution {- width: 1280,- height: 720,- }),- ..Default::default()- },- ],- ..Default::default()- };- let best = select_best_variant(&master, 720).unwrap();- assert_eq!(best.uri, "720.m3u8");- }-- #[test]- fn select_best_variant_fallback_to_lowest_when_all_exceed() {- let master = MasterPlaylist {- variants: vec![- VariantStream {- uri: "1080.m3u8".into(),- bandwidth: 5_000_000,- resolution: Some(Resolution {- width: 1920,- height: 1080,- }),- ..Default::default()- },- VariantStream {- uri: "4k.m3u8".into(),- bandwidth: 15_000_000,- resolution: Some(Resolution {- width: 3840,- height: 2160,- }),- ..Default::default()- },- ],- ..Default::default()- };- let best = select_best_variant(&master, 360).unwrap();- assert_eq!(best.uri, "1080.m3u8");- }-- #[test]- fn select_best_variant_no_resolution_treated_as_eligible() {- let master = MasterPlaylist {- variants: vec![VariantStream {- uri: "audio.m3u8".into(),- bandwidth: 128_000,- resolution: None,- ..Default::default()- }],- ..Default::default()- };- let best = select_best_variant(&master, 720).unwrap();- assert_eq!(best.uri, "audio.m3u8");- }-- #[test]- fn parse_hex_iv_full_32_chars() {- let iv = parse_hex_iv("0x00000000000000000000000000000001");- let mut expected = [0u8; 16];- expected[15] = 1;- assert_eq!(iv, expected);- }-- #[test]- fn parse_hex_iv_short_padded() {- let iv = parse_hex_iv("0xFF");- let mut expected = [0u8; 16];- expected[15] = 0xFF;- assert_eq!(iv, expected);- }-- #[test]- fn parse_hex_iv_uppercase_prefix() {- let iv = parse_hex_iv("0X0A0B0C0D0E0F10111213141516171819");- assert_eq!(iv[0], 0x0A);- assert_eq!(iv[7], 0x11);- assert_eq!(iv[15], 0x19);- }-- #[test]- fn parse_hex_iv_no_prefix() {- let iv = parse_hex_iv("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");- assert_eq!(iv, [0xFF; 16]);- }-- #[test]- fn compute_iv_returns_explicit_when_present() {- let explicit_iv = [0xAB; 16];- let enc = EncryptionInfo {- key_bytes: vec![0u8; 16],- iv: Some(explicit_iv),- };- assert_eq!(compute_iv(&enc, 5, 100), explicit_iv);- }-- #[test]- fn compute_iv_derives_from_sequence() {- let enc = EncryptionInfo {- key_bytes: vec![0u8; 16],- iv: None,- };- let result = compute_iv(&enc, 3, 100);- let mut expected = [0u8; 16];- expected[8..16].copy_from_slice(&103u64.to_be_bytes());- assert_eq!(result, expected);- }-- #[test]- fn compute_iv_sequence_zero() {- let enc = EncryptionInfo {- key_bytes: vec![0u8; 16],- iv: None,- };- let result = compute_iv(&enc, 0, 0);- assert_eq!(result, [0u8; 16]);- }-}diff --git a/src-tauri/src/core/http_client.rs b/src-tauri/src/core/http_client.rsdeleted file mode 100644index e548af94..00000000--- a/src-tauri/src/core/http_client.rs+++ /dev/null@@ -1,74 +0,0 @@-use std::sync::LazyLock;-use std::sync::RwLock;--use omniget_core::models::settings::ProxySettings;--static GLOBAL_PROXY: LazyLock<RwLock<ProxySettings>> =- LazyLock::new(|| RwLock::new(ProxySettings::default()));--pub fn init_proxy(proxy: ProxySettings) {- if let Ok(mut guard) = GLOBAL_PROXY.write() {- *guard = proxy;- }-}--pub fn get_proxy_snapshot() -> ProxySettings {- GLOBAL_PROXY- .read()- .map(|g| g.clone())- .unwrap_or_default()-}--pub fn proxy_url() -> Option<String> {- let proxy = get_proxy_snapshot();- if !proxy.enabled || proxy.host.is_empty() {- return None;- }- let scheme = match proxy.proxy_type.as_str() {- "socks5" => "socks5",- "https" => "https",- _ => "http",- };- if !proxy.username.is_empty() {- Some(format!(- "{}://{}:{}@{}:{}",- scheme, proxy.username, proxy.password, proxy.host, proxy.port- ))- } else {- Some(format!("{}://{}:{}", scheme, proxy.host, proxy.port))- }-}--pub fn apply_proxy(- builder: reqwest::ClientBuilder,- proxy: &ProxySettings,-) -> reqwest::ClientBuilder {- if !proxy.enabled || proxy.host.is_empty() {- return builder;- }- let scheme = match proxy.proxy_type.as_str() {- "socks5" => "socks5",- "https" => "https",- _ => "http",- };- let proxy_url = if !proxy.username.is_empty() {- format!(- "{}://{}:{}@{}:{}",- scheme, proxy.username, proxy.password, proxy.host, proxy.port- )- } else {- format!("{}://{}:{}", scheme, proxy.host, proxy.port)- };- match reqwest::Proxy::all(&proxy_url) {- Ok(p) => builder.proxy(p),- Err(e) => {- tracing::warn!("Invalid proxy URL: {}", e);- builder- }- }-}--pub fn apply_global_proxy(builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder {- let proxy = get_proxy_snapshot();- apply_proxy(builder, &proxy)-}diff --git a/src-tauri/src/core/hwaccel.rs b/src-tauri/src/core/hwaccel.rsdeleted file mode 100644index ea1b53c3..00000000--- a/src-tauri/src/core/hwaccel.rs+++ /dev/null@@ -1,89 +0,0 @@-use serde::{Deserialize, Serialize};-use tokio::sync::OnceCell;--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct HwAccelInfo {- pub encoders: Vec<String>,- pub decoders: Vec<String>,- pub recommended_video_encoder: Option<String>,- pub recommended_decoder: Option<String>,-}--static HW_ACCEL_CACHE: OnceCell<HwAccelInfo> = OnceCell::const_new();--const GPU_ENCODER_PRIORITY: &[&str] = &[- "h264_nvenc",- "h264_qsv",- "h264_amf",- "h264_videotoolbox",- "h264_vaapi",-];--const GPU_DECODER_PRIORITY: &[&str] = &[- "h264_cuvid",- "h264_qsv",- "h264_videotoolbox",- "h264_vaapi",-];--pub async fn detect_hwaccel() -> HwAccelInfo {- HW_ACCEL_CACHE- .get_or_init(|| async { detect_hwaccel_inner().await })- .await- .clone()-}--async fn detect_hwaccel_inner() -> HwAccelInfo {- let encoders = query_codecs("encoders").await;- let decoders = query_codecs("decoders").await;-- let recommended_video_encoder = GPU_ENCODER_PRIORITY- .iter()- .find(|c| encoders.iter().any(|e| e == *c))- .map(|s| s.to_string());-- let recommended_decoder = GPU_DECODER_PRIORITY- .iter()- .find(|c| decoders.iter().any(|d| d == *c))- .map(|s| s.to_string());-- HwAccelInfo {- encoders,- decoders,- recommended_video_encoder,- recommended_decoder,- }-}--async fn query_codecs(flag: &str) -> Vec<String> {- let output = crate::core::process::command("ffmpeg")- .args([&format!("-{}", flag), "-hide_banner"])- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::piped())- .output()- .await;-- let output = match output {- Ok(o) => o,- Err(_) => return Vec::new(),- };-- let text = String::from_utf8_lossy(&output.stdout);- let gpu_keywords = [- "nvenc", "qsv", "amf", "videotoolbox", "vaapi", "cuvid", "cuda",- ];-- text.lines()- .filter_map(|line| {- let trimmed = line.trim();- let parts: Vec<&str> = trimmed.split_whitespace().collect();- if parts.len() >= 2 {- let codec_name = parts[1];- if gpu_keywords.iter().any(|kw| codec_name.contains(kw)) {- return Some(codec_name.to_string());- }- }- None- })- .collect()-}diff --git a/src-tauri/src/core/media_processor.rs b/src-tauri/src/core/media_processor.rsdeleted file mode 100644index 9e41f902..00000000--- a/src-tauri/src/core/media_processor.rs+++ /dev/null@@ -1,148 +0,0 @@-use crate::core::hls_downloader::HlsDownloadResult;-use tokio_util::sync::CancellationToken;--pub struct MediaProcessor;--impl MediaProcessor {- #[allow(clippy::too_many_arguments)]- pub async fn download_hls(- m3u8_url: &str,- output: &str,- referer: &str,- bytes_tx: Option<tokio::sync::mpsc::UnboundedSender<u64>>,- cancel_token: CancellationToken,- max_concurrent: u32,- max_retries: u32,- client: Option<reqwest::Client>,- ) -> anyhow::Result<HlsDownloadResult> {- let downloader = match client {- Some(c) => crate::core::hls_downloader::HlsDownloader::with_client(c),- None => crate::core::hls_downloader::HlsDownloader::new(),- };- downloader.download(m3u8_url, output, referer, bytes_tx, cancel_token, max_concurrent, max_retries).await- }-- #[allow(clippy::too_many_arguments)]- pub async fn download_hls_with_quality(- m3u8_url: &str,- output: &str,- referer: &str,- bytes_tx: Option<tokio::sync::mpsc::UnboundedSender<u64>>,- cancel_token: CancellationToken,- max_concurrent: u32,- max_retries: u32,- client: Option<reqwest::Client>,- max_height: Option<u32>,- ) -> anyhow::Result<HlsDownloadResult> {- let downloader = match client {- Some(c) => crate::core::hls_downloader::HlsDownloader::with_client(c),- None => crate::core::hls_downloader::HlsDownloader::new(),- };- downloader.download_with_quality(m3u8_url, output, referer, bytes_tx, cancel_token, max_concurrent, max_retries, max_height).await- }-- pub async fn remux(input: &str, output: &str) -> anyhow::Result<()> {- let status = crate::core::process::command("ffmpeg")- .args(["-y", "-i", input, "-c", "copy", output])- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::piped())- .status()- .await?;-- if !status.success() {- anyhow::bail!("FFmpeg remux falhou com status {}", status);- }-- Ok(())- }-- pub async fn merge_audio_video(- video: &str,- audio: &str,- output: &str,- ) -> anyhow::Result<()> {- let status = crate::core::process::command("ffmpeg")- .args([- "-y", "-i", video, "-i", audio, "-map", "0:v", "-map", "1:a", "-c", "copy",- output,- ])- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::piped())- .status()- .await?;-- if !status.success() {- anyhow::bail!("FFmpeg merge falhou com status {}", status);- }-- Ok(())- }-- pub async fn download_direct(- url: &str,- output: &str,- headers: &[(&str, &str)],- ) -> anyhow::Result<()> {- let mut args = vec!["-y".to_string()];-- if !headers.is_empty() {- let header_str: String = headers- .iter()- .map(|(k, v)| format!("{}: {}\r\n", k, v))- .collect();- args.extend(["-headers".to_string(), header_str]);- }-- args.extend([- "-i".to_string(),- url.to_string(),- "-c".to_string(),- "copy".to_string(),- output.to_string(),- ]);-- let status = crate::core::process::command("ffmpeg")- .args(&args)- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::piped())- .status()- .await?;-- if !status.success() {- anyhow::bail!("FFmpeg download_direct falhou com status {}", status);- }-- Ok(())- }-}--pub fn check_ffmpeg() -> bool {- crate::core::process::std_command("ffmpeg")- .arg("-version")- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .status()- .map(|s| s.success())- .unwrap_or(false)-}--pub fn check_ytdlp() -> bool {- crate::core::process::std_command("yt-dlp")- .arg("--version")- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .status()- .map(|s| s.success())- .unwrap_or(false)-}--pub fn check_dependencies() -> Vec<String> {- let mut missing = Vec::new();- if !check_ytdlp() {- missing.push("yt-dlp".into());- }- if !check_ffmpeg() {- missing.push("ffmpeg".into());- }- missing-}diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rsindex 2d80b24f..1e93e65f 100644--- a/src-tauri/src/core/mod.rs+++ b/src-tauri/src/core/mod.rs@@ -1,28 +1,21 @@+pub use omniget_core::core::registry;+pub use omniget_core::core::clipboard;+pub use omniget_core::core::cookie_parser;+pub use omniget_core::core::course_utils;+pub use omniget_core::core::direct_downloader;+pub use omniget_core::core::filename;+pub use omniget_core::core::hls_downloader;+pub use omniget_core::core::http_client;+pub use omniget_core::core::hwaccel;+pub use omniget_core::core::media_processor;+pub use omniget_core::core::paths;+pub use omniget_core::core::process;+pub use omniget_core::core::redirect;+pub use omniget_core::core::dependencies;+pub use omniget_core::core::ffmpeg;+pub use omniget_core::core::ytdlp;+pub mod auth;-pub mod cookie_parser;pub mod events;-pub mod http_client;-pub mod paths;-pub use omniget_core::core::registry;-pub mod hls_downloader;-pub mod direct_downloader;-pub mod redirect;-pub mod filename;pub mod url_parser;pub mod queue;-#[cfg(not(target_os = "android"))]-pub mod clipboard;--#[cfg(not(target_os = "android"))]-pub mod process;-#[cfg(not(target_os = "android"))]-pub mod ffmpeg;-#[cfg(not(target_os = "android"))]-pub mod hwaccel;-#[cfg(not(target_os = "android"))]-pub mod media_processor;-#[cfg(not(target_os = "android"))]-pub mod ytdlp;-#[cfg(not(target_os = "android"))]-pub mod dependencies;-pub mod course_utils;diff --git a/src-tauri/src/core/paths.rs b/src-tauri/src/core/paths.rsdeleted file mode 100644index 65ad9791..00000000--- a/src-tauri/src/core/paths.rs+++ /dev/null@@ -1,6 +0,0 @@-pub fn app_data_dir() -> Option<std::path::PathBuf> {- if let Ok(dir) = std::env::var("OMNIGET_DATA_DIR") {- return Some(std::path::PathBuf::from(dir));- }- dirs::data_dir().map(|d| d.join("omniget"))-}diff --git a/src-tauri/src/core/process.rs b/src-tauri/src/core/process.rsdeleted file mode 100644index 699adb59..00000000--- a/src-tauri/src/core/process.rs+++ /dev/null@@ -1,61 +0,0 @@-fn enhanced_path() -> Option<String> {- use std::sync::OnceLock;- static CACHED: OnceLock<Option<String>> = OnceLock::new();- CACHED- .get_or_init(|| {- let bin_dir = crate::core::paths::app_data_dir()?.join("bin");- let sep = if cfg!(windows) { ";" } else { ":" };- let current = std::env::var("PATH").unwrap_or_default();-- #[allow(unused_mut)]- let mut extra_dirs: Vec<String> = vec![bin_dir.display().to_string()];-- #[cfg(target_os = "macos")]- {- extra_dirs.push("/opt/homebrew/bin".into());- extra_dirs.push("/usr/local/bin".into());- }-- #[cfg(target_os = "linux")]- {- if let Some(home) = dirs::home_dir() {- extra_dirs.push(home.join(".local").join("bin").display().to_string());- }- extra_dirs.push("/usr/local/bin".into());- }-- Some(format!("{}{}{}", extra_dirs.join(sep), sep, current))- })- .clone()-}--pub fn command<S: AsRef<std::ffi::OsStr>>(program: S) -> tokio::process::Command {- let mut cmd = tokio::process::Command::new(program);- #[cfg(target_os = "windows")]- cmd.creation_flags(0x08000000);- if let Some(path) = enhanced_path() {- cmd.env("PATH", path);- }- cmd.env_remove("PYTHONHOME");- cmd.env_remove("PYTHONPATH");- cmd.env("PYTHONIOENCODING", "utf-8");- cmd.env("PYTHONUTF8", "1");- cmd-}--pub fn std_command<S: AsRef<std::ffi::OsStr>>(program: S) -> std::process::Command {- let mut cmd = std::process::Command::new(program);- #[cfg(target_os = "windows")]- {- use std::os::windows::process::CommandExt;- cmd.creation_flags(0x08000000);- }- if let Some(path) = enhanced_path() {- cmd.env("PATH", path);- }- cmd.env_remove("PYTHONHOME");- cmd.env_remove("PYTHONPATH");- cmd.env("PYTHONIOENCODING", "utf-8");- cmd.env("PYTHONUTF8", "1");- cmd-}diff --git a/src-tauri/src/core/redirect.rs b/src-tauri/src/core/redirect.rsdeleted file mode 100644index 9d1bd07b..00000000--- a/src-tauri/src/core/redirect.rs+++ /dev/null@@ -1,16 +0,0 @@-use anyhow::anyhow;--pub async fn resolve_redirect(client: &reqwest::Client, url: &str) -> anyhow::Result<String> {- let response = client- .get(url)- .send()- .await?;-- let final_url = response.url().to_string();-- if final_url == url {- return Err(anyhow!("Nenhum redirect encontrado para {}", url));- }-- Ok(final_url)-}diff --git a/src-tauri/src/core/ytdlp.rs b/src-tauri/src/core/ytdlp.rsdeleted file mode 100644index 55e4caa7..00000000--- a/src-tauri/src/core/ytdlp.rs+++ /dev/null@@ -1,2139 +0,0 @@-use std::path::{Path, PathBuf};-use std::process::Stdio;-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};-use std::sync::{Arc, Mutex, OnceLock};--use anyhow::anyhow;-use futures::StreamExt;-use tokio::io::{AsyncBufReadExt, BufReader};-use tokio::sync::mpsc;-use tokio_util::sync::CancellationToken;--use crate::models::media::{DownloadResult, FormatInfo};--static YTDLP_UPDATING: AtomicBool = AtomicBool::new(false);-static YTDLP_PATH_CACHE: std::sync::RwLock<Option<Option<PathBuf>>> =- std::sync::RwLock::new(None);-static FFMPEG_LOCATION_CACHE: std::sync::RwLock<Option<Option<String>>> =- std::sync::RwLock::new(None);-static COOKIES_BROWSER_CACHE: std::sync::RwLock<Option<Option<String>>> =- std::sync::RwLock::new(None);-static JS_RUNTIME_CACHE: std::sync::RwLock<Option<Option<String>>> =- std::sync::RwLock::new(None);-static RATE_LIMIT_429_COUNT: AtomicU64 = AtomicU64::new(0);-static RATE_LIMIT_429_LAST_TS: AtomicU64 = AtomicU64::new(0);-static COOKIE_ERROR_FLAG: AtomicBool = AtomicBool::new(false);--pub fn has_cookie_error() -> bool {- COOKIE_ERROR_FLAG.load(std::sync::atomic::Ordering::Relaxed)-}--pub fn clear_cookie_error() {- COOKIE_ERROR_FLAG.store(false, std::sync::atomic::Ordering::Relaxed);-}--fn rate_limit_429_count() -> u64 {- let last = RATE_LIMIT_429_LAST_TS.load(Ordering::Relaxed);- if last == 0 {- return 0;- }- let now = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_secs();- if now.saturating_sub(last) > 1800 {- RATE_LIMIT_429_COUNT.store(0, Ordering::Relaxed);- RATE_LIMIT_429_LAST_TS.store(0, Ordering::Relaxed);- return 0;- }- RATE_LIMIT_429_COUNT.load(Ordering::Relaxed)-}--fn rate_limit_429_increment() {- RATE_LIMIT_429_COUNT.fetch_add(1, Ordering::Relaxed);- let now = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_secs();- RATE_LIMIT_429_LAST_TS.store(now, Ordering::Relaxed);-}--pub fn reset_ytdlp_cache() {- if let Ok(mut cache) = YTDLP_PATH_CACHE.write() {- *cache = None;- }-}--pub fn reset_ffmpeg_location_cache() {- if let Ok(mut cache) = FFMPEG_LOCATION_CACHE.write() {- *cache = None;- }-}--pub fn reset_js_runtime_cache() {- if let Ok(mut cache) = JS_RUNTIME_CACHE.write() {- *cache = None;- }-}--pub fn reset_cookies_browser_cache() {- if let Ok(mut cache) = COOKIES_BROWSER_CACHE.write() {- *cache = None;- }-}--fn proxy_args() -> Vec<String> {- match crate::core::http_client::proxy_url() {- Some(url) => vec!["--proxy".to_string(), url],- None => Vec::new(),- }-}--struct YtRateLimiter {- semaphore: tokio::sync::Semaphore,- last_request_ns: AtomicU64,-}--impl YtRateLimiter {- async fn acquire(&self) {- let _permit = self- .semaphore- .acquire()- .await- .unwrap_or_else(|_| panic!("semaphore closed"));- let min_interval_ns = 500_000_000u64;- let now_ns = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_nanos() as u64;- let last = self.last_request_ns.load(Ordering::Relaxed);- let elapsed = now_ns.saturating_sub(last);- if elapsed < min_interval_ns {- let wait_ns = min_interval_ns - elapsed;- let wait_duration = std::time::Duration::from_nanos(wait_ns);- tokio::time::sleep(wait_duration).await;- }- self.last_request_ns.store(now_ns, Ordering::Relaxed);- }-}--static YT_RATE_LIMITER: OnceLock<YtRateLimiter> = OnceLock::new();--fn yt_rate_limiter() -> &'static YtRateLimiter {- YT_RATE_LIMITER.get_or_init(|| YtRateLimiter {- semaphore: tokio::sync::Semaphore::new(3),- last_request_ns: AtomicU64::new(0),- })-}--const CHROME_UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";--pub async fn find_ytdlp() -> Option<PathBuf> {- let _timer_start = std::time::Instant::now();- let bin_name = if cfg!(target_os = "windows") {- "yt-dlp.exe"- } else {- "yt-dlp"- };-- #[cfg(target_os = "linux")]- {- let flatpak_path = PathBuf::from("/app/bin").join(bin_name);- if flatpak_path.exists() {- tracing::debug!("[perf] find_ytdlp took {:?}", _timer_start.elapsed());- return Some(flatpak_path);- }- }-- if let Ok(output) = crate::core::process::command(bin_name)- .arg("--version")- .stdout(Stdio::null())- .stderr(Stdio::null())- .status()- .await- {- if output.success() {- tracing::debug!("[perf] find_ytdlp took {:?}", _timer_start.elapsed());- return Some(PathBuf::from(bin_name));- }- }-- let managed = managed_ytdlp_path()?;- if managed.exists() {- tracing::debug!("[perf] find_ytdlp took {:?}", _timer_start.elapsed());- return Some(managed);- }-- tracing::debug!("[perf] find_ytdlp took {:?}", _timer_start.elapsed());- None-}--pub async fn find_ytdlp_cached() -> Option<PathBuf> {- let _timer_start = std::time::Instant::now();- if let Ok(cache) = YTDLP_PATH_CACHE.read() {- if let Some(ref cached) = *cache {- if let Some(ref path) = cached {- if path.exists() {- tracing::debug!("[perf] find_ytdlp_cached (hit): {:?}", _timer_start.elapsed());- return cached.clone();- }- tracing::warn!("[ytdlp] cached path no longer exists: {}", path.display());- } else {- return None;- }- }- }- let result = find_ytdlp().await;- if let Ok(mut cache) = YTDLP_PATH_CACHE.write() {- *cache = Some(result.clone());- }- tracing::debug!("[perf] find_ytdlp_cached (miss): {:?}", _timer_start.elapsed());- result-}--fn managed_ytdlp_path() -> Option<PathBuf> {- let data = crate::core::paths::app_data_dir()?;- let bin_name = if cfg!(target_os = "windows") {- "yt-dlp.exe"- } else {- "yt-dlp"- };- Some(data.join("bin").join(bin_name))-}--pub async fn ensure_ytdlp() -> anyhow::Result<PathBuf> {- let _timer_start = std::time::Instant::now();- if let Some(path) = find_ytdlp_cached().await {- let path_clone = path.clone();- tokio::spawn(async move {- check_ytdlp_freshness(&path_clone).await;- });- // Ensure a JS runtime is available in the background (for YouTube nsig).- tokio::spawn(async { crate::core::dependencies::ensure_js_runtime().await; });- tracing::debug!("[perf] ensure_ytdlp took {:?}", _timer_start.elapsed());- return Ok(path);- }-- if crate::core::dependencies::is_flatpak() {- tracing::debug!("[perf] ensure_ytdlp took {:?}", _timer_start.elapsed());- return Err(anyhow!("yt-dlp not found in Flatpak sandbox"));- }-- let path = download_ytdlp_binary().await?;- reset_ytdlp_cache();- // Ensure a JS runtime is available in the background (for YouTube nsig).- tokio::spawn(async { crate::core::dependencies::ensure_js_runtime().await; });- tracing::debug!("[perf] ensure_ytdlp took {:?}", _timer_start.elapsed());- Ok(path)-}--async fn download_ytdlp_binary() -> anyhow::Result<PathBuf> {- let target =- managed_ytdlp_path().ok_or_else(|| anyhow!("Could not determine data directory"))?;-- if let Some(parent) = target.parent() {- tokio::fs::create_dir_all(parent).await?;- }-- let download_url = if cfg!(target_os = "windows") {- "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe"- } else if cfg!(target_os = "macos") {- "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos"- } else if cfg!(target_arch = "aarch64") {- "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_aarch64"- } else {- "https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp"- };-- let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .timeout(std::time::Duration::from_secs(120))- .build()?;-- let response = client.get(download_url).send().await?;-- if !response.status().is_success() {- return Err(anyhow!(- "Failed to download yt-dlp: HTTP {}",- response.status()- ));- }-- {- let mut file = tokio::fs::File::create(&target).await?;- let mut stream = response.bytes_stream();- 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?;- }- tokio::io::AsyncWriteExt::flush(&mut file).await?;- }-- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt;- let perms = std::fs::Permissions::from_mode(0o755);- tokio::fs::set_permissions(&target, perms).await?;- }-- #[cfg(target_os = "macos")]- {- let _ = tokio::process::Command::new("xattr")- .args(["-d", "com.apple.quarantine"])- .arg(&target)- .output()- .await;- }-- Ok(target)-}--async fn check_ytdlp_freshness(path: &Path) {- if let Some(managed) = managed_ytdlp_path() {- if path != managed.as_path() {- return;- }- } else {- return;- }-- if let Ok(meta) = tokio::fs::metadata(path).await {- if let Ok(modified) = meta.modified() {- if let Ok(age) = modified.elapsed() {- if age > std::time::Duration::from_secs(2 * 24 * 60 * 60) {- if YTDLP_UPDATING- .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)- .is_err()- {- return;- }- tracing::info!("yt-dlp is older than 2 days, updating in background");- tokio::spawn(async {- match download_ytdlp_binary().await {- Ok(_) => tracing::info!("yt-dlp updated successfully"),- Err(e) => tracing::warn!("Failed to update yt-dlp: {}", e),- }- YTDLP_UPDATING.store(false, Ordering::SeqCst);- });- }- }- }- }-}--async fn find_ffmpeg_location() -> Option<String> {- let _timer_start = std::time::Instant::now();- let result = if let Some(path) = crate::core::dependencies::find_tool("ffmpeg").await {- path.parent()- .and_then(|dir| dir.to_str())- .filter(|s| !s.is_empty())- .map(|s| s.to_string())- } else {- None- };- tracing::debug!(- "[perf] find_ffmpeg_location took {:?}",- _timer_start.elapsed()- );- result-}--async fn find_ffmpeg_location_cached() -> Option<String> {- if let Ok(cache) = FFMPEG_LOCATION_CACHE.read() {- if let Some(ref cached) = *cache {- if let Some(ref dir) = cached {- let check_path = std::path::Path::new(dir).join(crate::core::dependencies::bin_name("ffmpeg"));- if check_path.exists() {- return cached.clone();- }- tracing::warn!("[ffmpeg] cached location no longer valid: {}", dir);- } else {- return None;- }- }- }- let result = find_ffmpeg_location().await;- if let Ok(mut cache) = FFMPEG_LOCATION_CACHE.write() {- *cache = Some(result.clone());- }- result-}--/// Returns a disposable copy of the extension cookie file for yt-dlp.-///-/// yt-dlp rewrites `--cookies` files after every run, which corrupts the-/// original cookies written by the Chrome extension. We copy the source-/// file to a sibling temp file so yt-dlp mutates the copy, not the original.-fn extension_cookie_file() -> Option<std::path::PathBuf> {- let source = crate::native_host::extension_cookie_file_path();- if !source.exists() {- return None;- }- let metadata = std::fs::metadata(&source).ok()?;- let modified = metadata.modified().ok()?;- if modified.elapsed().unwrap_or_default() >= std::time::Duration::from_secs(86400) {- return None;- }- let copy = source.with_file_name("chrome-extension-cookies-session.txt");- std::fs::copy(&source, ©).ok()?;- Some(copy)-}--fn detect_cookies_browser() -> Option<String> {- let _timer_start = std::time::Instant::now();- let result = (|| -> Option<String> {- #[cfg(target_os = "windows")]- {- if let Some(roaming) = dirs::data_dir() {- if roaming- .join("Mozilla")- .join("Firefox")- .join("Profiles")- .is_dir()- {- return Some("firefox".to_string());- }- }- if let Some(local) = dirs::data_local_dir() {- if local- .join("BraveSoftware")- .join("Brave-Browser")- .join("User Data")- .is_dir()- {- return Some("brave".to_string());- }- if local- .join("Microsoft")- .join("Edge")- .join("User Data")- .is_dir()- {- return Some("edge".to_string());- }- if local- .join("Google")- .join("Chrome")- .join("User Data")- .is_dir()- {- return Some("chrome".to_string());- }- }- }- #[cfg(target_os = "macos")]- {- if let Some(home) = dirs::home_dir() {- let support = home.join("Library").join("Application Support");- if support.join("Firefox").join("Profiles").is_dir() {- return Some("firefox".to_string());- }- if support.join("Google").join("Chrome").is_dir() {- return Some("chrome".to_string());- }- }- }- #[cfg(target_os = "linux")]- {- if let Some(config) = dirs::config_dir() {- if config.join("google-chrome").is_dir() {- return Some("chrome".to_string());- }- if config.join("chromium").is_dir() {- return Some("chromium".to_string());- }- if config.join("BraveSoftware").join("Brave-Browser").is_dir() {- return Some("brave".to_string());- }- if config.join("microsoft-edge").is_dir() {- return Some("edge".to_string());- }- if config.join("vivaldi").is_dir() {- return Some("vivaldi".to_string());- }- }- if let Some(home) = dirs::home_dir() {- let fp = home.join(".var").join("app");-- if fp- .join("com.google.Chrome")- .join("config")- .join("google-chrome")- .is_dir()- {- return Some("chrome".to_string());- }- if fp- .join("org.chromium.Chromium")- .join("config")- .join("chromium")- .is_dir()- {- return Some("chromium".to_string());- }- if fp- .join("com.brave.Browser")- .join("config")- .join("BraveSoftware")- .join("Brave-Browser")- .is_dir()- {- return Some("brave".to_string());- }-- if home- .join("snap")- .join("chromium")- .join("common")- .join("chromium")- .is_dir()- {- return Some("chromium".to_string());- }-- if home.join(".mozilla").join("firefox").is_dir() {- return Some("firefox".to_string());- }- if fp- .join("org.mozilla.firefox")- .join(".mozilla")- .join("firefox")- .is_dir()- {- return Some("firefox".to_string());- }- if home- .join("snap")- .join("firefox")- .join("common")- .join(".mozilla")- .join("firefox")- .is_dir()- {- return Some("firefox".to_string());- }- }- }- None- })();- tracing::debug!(- "[perf] detect_cookies_browser took {:?}",- _timer_start.elapsed()- );- result-}--async fn detect_cookies_browser_cached() -> Option<String> {- if let Ok(cache) = COOKIES_BROWSER_CACHE.read() {- if let Some(ref cached) = *cache {- return cached.clone();- }- }- let result = tokio::task::spawn_blocking(detect_cookies_browser)- .await- .unwrap_or(None);- if let Ok(mut cache) = COOKIES_BROWSER_CACHE.write() {- *cache = Some(result.clone());- }- result-}--/// Detect a JavaScript runtime for yt-dlp's nsig challenge solver.-/// yt-dlp standalone binaries cannot discover runtimes from PATH on their-/// own, so we locate the binary and pass it via `--js-runtimes runtime:path`.-fn detect_js_runtime() -> Option<String> {- let runtimes: &[(&str, &str)] = if cfg!(target_os = "windows") {- &[("node", "node.exe"), ("deno", "deno.exe"), ("bun", "bun.exe")]- } else {- &[("node", "node"), ("deno", "deno"), ("bun", "bun")]- };-- // Try system PATH via `where` (Windows) or `which` (Unix).- for &(runtime, bin) in runtimes {- let finder = if cfg!(target_os = "windows") { "where" } else { "which" };- if let Ok(output) = std::process::Command::new(finder)- .arg(bin)- .stdout(std::process::Stdio::piped())- .stderr(std::process::Stdio::null())- .output()- {- if output.status.success() {- if let Some(line) = String::from_utf8_lossy(&output.stdout).lines().next() {- let path = line.trim();- if !path.is_empty() && std::path::Path::new(path).exists() {- return Some(format!("{}:{}", runtime, path));- }- }- }- }- }-- // Check managed bin dir (Deno auto-downloaded alongside yt-dlp).- if let Some(bin_dir) = crate::core::paths::app_data_dir().map(|d| d.join("bin")) {- for &(runtime, bin) in runtimes {- let managed = bin_dir.join(bin);- if managed.exists() {- return Some(format!("{}:{}", runtime, managed.display()));- }- }- }-- // Fallback: well-known install locations on Windows.- #[cfg(target_os = "windows")]- {- let candidates = [- ("node", r"C:\Program Files\nodejs\node.exe"),- ("node", r"C:\Program Files (x86)\nodejs\node.exe"),- ];- for (runtime, path) in &candidates {- if std::path::Path::new(path).exists() {- return Some(format!("{}:{}", runtime, path));- }- }- }-- None-}--fn js_runtime_args() -> Vec<String> {- let cached = {- if let Ok(cache) = JS_RUNTIME_CACHE.read() {- cache.clone()- } else {- None- }- };-- let runtime = match cached {- Some(val) => val,- None => {- let val = detect_js_runtime();- if let Ok(mut cache) = JS_RUNTIME_CACHE.write() {- *cache = Some(val.clone());- }- val- }- };-- match runtime {- Some(rt) => vec!["--js-runtimes".to_string(), rt],- None => vec![],- }-}--fn is_youtube_url(url: &str) -> bool {- let lower = url.to_lowercase();- lower.contains("youtube.com") || lower.contains("youtu.be")-}--/// Extracts the most meaningful error line from yt-dlp stderr output.-/// Prefers lines starting with "ERROR:", falls back to "WARNING:", then raw trimmed output.-fn extract_error_message(stderr: &str) -> String {- let error_line = stderr- .lines()- .find(|l| l.to_uppercase().contains("ERROR:"))- .map(|l| l.trim().to_string());-- if let Some(msg) = error_line {- return msg;- }-- let warning_line = stderr- .lines()- .find(|l| l.to_uppercase().contains("WARNING:"))- .map(|l| l.trim().to_string());-- if let Some(msg) = warning_line {- return msg;- }-- stderr.trim().to_string()-}--pub async fn get_video_info(- ytdlp: &Path,- url: &str,- extra_flags: &[String],-) -> anyhow::Result<serde_json::Value> {- let _timer_start = std::time::Instant::now();-- if is_youtube_url(url) {- yt_rate_limiter().acquire().await;- }-- let is_yt = is_youtube_url(url);- let clients: &[Option<&str>] = if is_yt {- &[None, Some("youtube:player_client=default,mweb")]- } else {- &[None]- };-- let mut last_error = String::new();-- for (attempt, client) in clients.iter().enumerate() {- tracing::info!(- "[yt-dlp] info fetch attempt {}/{} for URL",- attempt + 1,- clients.len()- );-- let mut args = vec![- "--dump-single-json".to_string(),- "--no-warnings".to_string(),- "--no-playlist".to_string(),- "--no-check-certificates".to_string(),- "--socket-timeout".to_string(),- "15".to_string(),- "--retries".to_string(),- "1".to_string(),- "--extractor-retries".to_string(),- "2".to_string(),- "--retry-sleep".to_string(),- "exp=1:30".to_string(),- "--user-agent".to_string(),- CHROME_UA.to_string(),- "--skip-download".to_string(),- ];- args.extend(js_runtime_args());-- if let Some(extractor_args) = client {- args.push("--extractor-args".to_string());- args.push(extractor_args.to_string());- }-- let extension_cookies = extension_cookie_file();- if let Some(ref cf) = extension_cookies {- args.push("--cookies".to_string());- args.push(cf.to_string_lossy().to_string());- } else {- let browser_cookies = detect_cookies_browser_cached().await;- if let Some(ref browser) = browser_cookies {- args.push("--cookies-from-browser".to_string());- args.push(browser.clone());- }- }-- args.extend(proxy_args());- args.extend(extra_flags.iter().cloned());- args.push(url.to_string());-- let child = crate::core::process::command(ytdlp)- .args(&args)- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()- .map_err(|e| anyhow!("Failed to run yt-dlp: {}", e))?;- tracing::debug!(- "[perf] get_video_info: yt-dlp process spawned at {:?} (attempt {})",- _timer_start.elapsed(),- attempt + 1- );-- let result =- tokio::time::timeout(std::time::Duration::from_secs(60), child.wait_with_output())- .await- .map_err(|_| {- tracing::debug!("[perf] get_video_info took {:?}", _timer_start.elapsed());- anyhow!("Timeout fetching video info (60s)")- })?- .map_err(|e| {- tracing::debug!("[perf] get_video_info took {:?}", _timer_start.elapsed());- anyhow!("Failed to run yt-dlp: {}", e)- })?;-- tracing::debug!(- "[perf] get_video_info: yt-dlp process exited at {:?} (attempt {})",- _timer_start.elapsed(),- attempt + 1- );-- if result.status.success() {- let json: serde_json::Value = serde_json::from_slice(&result.stdout)- .map_err(|e| anyhow!("yt-dlp returned invalid JSON: {}", e))?;- tracing::debug!("[perf] get_video_info took {:?}", _timer_start.elapsed());- return Ok(json);- }-- let stderr = String::from_utf8_lossy(&result.stderr).to_string();- tracing::debug!("[yt-dlp info] stderr ({} bytes): {}", stderr.len(), stderr.trim());- let stderr_lower = stderr.to_lowercase();- if stderr_lower.contains("http error 429") {- rate_limit_429_increment();- let sanitized_url = sanitize_log_line(url);- tracing::warn!(- "[yt-429] rate limit in get_video_info: url={} attempt={}/{}",- sanitized_url,- attempt + 1,- clients.len()- );- }-- let is_retryable = is_yt- && attempt < clients.len() - 1- && (stderr_lower.contains("requested format")- || stderr_lower.contains("not available")- || stderr_lower.contains("http error 403")- || stderr_lower.contains("nsig")- || stderr_lower.contains("http error 429"));-- if is_retryable {- tracing::warn!(- "[yt-dlp] info fetch attempt {} failed, retrying with fallback player_client: {}",- attempt + 1,- stderr.trim().lines().last().unwrap_or("")- );- if stderr_lower.contains("http error 429") {- tokio::time::sleep(std::time::Duration::from_secs(5)).await;- }- last_error = stderr;- continue;- }-- tracing::debug!("[perf] get_video_info took {:?}", _timer_start.elapsed());- return Err(translate_ytdlp_error(&stderr));- }-- tracing::debug!("[perf] get_video_info took {:?}", _timer_start.elapsed());- Err(translate_ytdlp_error(&last_error))-}--pub async fn get_playlist_info(- ytdlp: &Path,- url: &str,- extra_flags: &[String],-) -> anyhow::Result<(String, Vec<PlaylistEntry>)> {- if is_youtube_url(url) {- yt_rate_limiter().acquire().await;- }-- let mut args = vec![- "--flat-playlist".to_string(),- "--dump-json".to_string(),- "--no-warnings".to_string(),- "--socket-timeout".to_string(),- "30".to_string(),- "--retries".to_string(),- "3".to_string(),- "--extractor-retries".to_string(),- "3".to_string(),- "--retry-sleep".to_string(),- "exp=1:60".to_string(),- "--user-agent".to_string(),- CHROME_UA.to_string(),- ];- args.extend(js_runtime_args());-- if is_youtube_url(url) {- args.push("--extractor-args".to_string());- args.push("youtube:player_client=default".to_string());- }-- args.extend(proxy_args());- args.extend(extra_flags.iter().cloned());- args.push(url.to_string());-- let output = tokio::time::timeout(- std::time::Duration::from_secs(120),- crate::core::process::command(ytdlp)- .args(&args)- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output(),- )- .await- .map_err(|_| anyhow!("Timeout fetching playlist (120s)"))?- .map_err(|e| anyhow!("Failed to run yt-dlp: {}", e))?;-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- let stderr_lower = stderr.to_lowercase();- if stderr_lower.contains("http error 429") {- rate_limit_429_increment();- let sanitized_url = sanitize_log_line(url);- let player_client = if is_youtube_url(url) {- "default"- } else {- "n/a"- };- tracing::warn!(- "[yt-429] rate limit in get_playlist_info: url={} player_client={} retries=3",- sanitized_url,- player_client- );- }- return Err(anyhow!("yt-dlp playlist failed: {}", extract_error_message(&stderr)));- }-- let stdout = String::from_utf8_lossy(&output.stdout);- let mut entries = Vec::new();- let mut playlist_title = String::new();-- for line in stdout.lines() {- if line.trim().is_empty() {- continue;- }- if let Ok(json) = serde_json::from_str::<serde_json::Value>(line) {- if playlist_title.is_empty() {- playlist_title = json- .get("playlist_title")- .or_else(|| json.get("playlist"))- .and_then(|v| v.as_str())- .unwrap_or("playlist")- .to_string();- }-- let id = json- .get("id")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();- let title = json- .get("title")- .and_then(|v| v.as_str())- .unwrap_or("unknown")- .to_string();- let url = json- .get("url")- .and_then(|v| v.as_str())- .map(|s| s.to_string())- .unwrap_or_else(|| format!("https://www.youtube.com/watch?v={}", id));- let duration = json.get("duration").and_then(|v| v.as_f64());-- if !id.is_empty() {- entries.push(PlaylistEntry {- id,- title,- url,- duration,- });- }- }- }-- Ok((playlist_title, entries))-}--pub struct PlaylistEntry {- pub id: String,- pub title: String,- pub url: String,- pub duration: Option<f64>,-}--fn parse_destination_line(line: &str) -> Option<String> {- let line = line.trim();-- if let Some(rest) = line.strip_prefix("[download] Destination:") {- let path = rest.trim();- if !path.is_empty() {- return Some(path.to_string());- }- }-- if let Some(rest) = line.strip_prefix("[Merger] Merging formats into \"") {- let path = rest.trim_end_matches('"');- if !path.is_empty() {- return Some(path.to_string());- }- }-- None-}--pub async fn write_netscape_cookie_file(- cookies: &[(String, String)],- domain: &str,- path: &Path,-) -> anyhow::Result<()> {- let mut content = String::from("# Netscape HTTP Cookie File\n");- for (name, value) in cookies {- content.push_str(&format!(- "{}\tTRUE\t/\tTRUE\t0\t{}\t{}\n",- domain, name, value- ));- }- tokio::fs::write(path, content).await?;- Ok(())-}--#[allow(clippy::too_many_arguments)]-pub async fn download_video(- ytdlp: &Path,- url: &str,- output_dir: &Path,- quality_height: Option<u32>,- progress: mpsc::Sender<f64>,- download_mode: Option<&str>,- format_id: Option<&str>,- filename_template: Option<&str>,- referer: Option<&str>,- cancel_token: CancellationToken,- cookie_file: Option<&Path>,- concurrent_fragments: u32,- download_subtitles: bool,- extra_flags: &[String],-) -> anyhow::Result<DownloadResult> {- let _timer_start = std::time::Instant::now();-- if is_youtube_url(url) {- yt_rate_limiter().acquire().await;- }-- let _ = progress.send(-1.0).await;-- let mode = download_mode.unwrap_or("auto");- let is_audio_only = mode == "audio";- let (ffmpeg_available, ffmpeg_location, aria2c_path) = tokio::join!(- crate::core::ffmpeg::is_ffmpeg_available(),- find_ffmpeg_location_cached(),- crate::core::dependencies::ensure_aria2c(),- );-- let format_selector = if let Some(fid) = format_id {- fid.to_string()- } else {- match mode {- "audio" => "ba/b".to_string(),- "mute" => match quality_height {- Some(h) if h > 0 => format!("bv*[height<={}]/bv*/b", h),- _ => "bv*/b".to_string(),- },- _ => {- if ffmpeg_available {- match quality_height {- Some(h) if h > 0 => format!(- "bv*[height<={}]+ba[ext=m4a]/bv*[height<={}]+ba/b[height<={}]/b",- h, h, h- ),- _ => "bv*+ba[ext=m4a]/bv*+ba/b".to_string(),- }- } else {- tracing::warn!("[yt-dlp] ffmpeg not available, using fallback format selector");- match quality_height {- Some(h) if h > 0 => format!(- "b[height<={}]/bv*[height<={}]/b",- h, h- ),- _ => "b/bv*".to_string(),- }- }- }- }- };-- let dir_len = output_dir.to_string_lossy().len();- let max_name = if cfg!(target_os = "windows") {- 250_usize.saturating_sub(dir_len).min(200)- } else {- 200- };- let template = filename_template- .map(|t| t.to_string())- .unwrap_or_else(|| format!("%(title).{}s [%(id)s].%(ext)s", max_name));- let output_template = output_dir.join(&template).to_string_lossy().to_string();-- tokio::fs::create_dir_all(output_dir).await?;-- let global_cookie_file = {- let settings = crate::storage::config::load_settings_standalone();- let cf = settings.download.cookie_file.clone();- if !cf.is_empty() && std::path::Path::new(&cf).exists() {- Some(cf)- } else {- None- }- };-- let ext_cookies = if cookie_file.is_none() && global_cookie_file.is_none() {- extension_cookie_file()- } else {- None- };-- let browser_cookies = if cookie_file.is_none() && global_cookie_file.is_none() && ext_cookies.is_none() {- detect_cookies_browser_cached().await- } else {- None- };-- let effective_cookie_file = cookie_file- .map(|p| p.to_path_buf())- .or_else(|| global_cookie_file.map(std::path::PathBuf::from))- .or(ext_cookies);- let mut base_args = vec!["-f".to_string(), format_selector];- base_args.extend(js_runtime_args());-- if format_id.is_none() {- base_args.push("-S".to_string());- if mode == "audio" {- base_args.push("+codec:aac:m4a".to_string());- } else {- base_args.push("+codec:avc:m4a".to_string());- }- }-- if format_id.is_none() && mode != "audio" && ffmpeg_available {- base_args.push("--merge-output-format".to_string());- base_args.push("mp4".to_string());- }-- if let Some(ref_url) = referer {- base_args.push("--referer".to_string());- base_args.push(ref_url.to_string());- base_args.push("--add-headers".to_string());- base_args.push(format!("Referer:{}", ref_url));- }-- if let Some(ref cf) = effective_cookie_file {- base_args.push("--cookies".to_string());- base_args.push(cf.to_string_lossy().to_string());- }-- if let Some(ref loc) = ffmpeg_location {- base_args.push("--ffmpeg-location".to_string());- base_args.push(loc.clone());- }-- let effective_fragments = if is_youtube_url(url) {- let rate_limit_count = rate_limit_429_count();- let max_frags = if rate_limit_count >= 2 {- 2- } else if rate_limit_count > 0 {- 4- } else {- 8- };- concurrent_fragments.min(max_frags)- } else {- concurrent_fragments- };- base_args.push("-N".to_string());- base_args.push(effective_fragments.to_string());-- if is_youtube_url(url) {- base_args.push("--extractor-args".to_string());- base_args.push("youtube:player_client=default".to_string());-- base_args.push("--throttled-rate".to_string());- base_args.push("100K".to_string());-- base_args.push("--sleep-subtitles".to_string());- base_args.push("5".to_string());- }-- base_args.extend(["--buffer-size".to_string(), "16M".to_string()]);- if !is_youtube_url(url) {- base_args.extend(["--http-chunk-size".to_string(), "10M".to_string()]);- }-- let mut use_aria2c = aria2c_path.is_some()- && mode != "audio"- && effective_cookie_file.is_none()- && browser_cookies.is_none();-- base_args.extend([- "--no-check-certificate".to_string(),- "--no-warnings".to_string(),- "--no-mtime".to_string(),- "--user-agent".to_string(),- CHROME_UA.to_string(),- "--socket-timeout".to_string(),- "30".to_string(),- "--retries".to_string(),- "5".to_string(),- "--fragment-retries".to_string(),- "5".to_string(),- "--extractor-retries".to_string(),- "3".to_string(),- "--file-access-retries".to_string(),- "3".to_string(),- "--retry-sleep".to_string(),- "exp=1:30".to_string(),- "--trim-filenames".to_string(),- max_name.to_string(),- "--no-playlist".to_string(),- "--newline".to_string(),- "--progress-template".to_string(),- "download:%(progress._percent_str)s".to_string(),- "-o".to_string(),- output_template,- "--skip-unavailable-fragments".to_string(),- ]);-- base_args.extend(proxy_args());- base_args.extend(extra_flags.iter().cloned());-- if cfg!(target_os = "windows") {- base_args.push("--windows-filenames".to_string());- }-- let should_download_subs =- download_subtitles && rate_limit_429_count() < 2;- let subtitle_args = if should_download_subs {- vec![- "--write-sub".to_string(),- "--write-auto-sub".to_string(),- "--sub-lang".to_string(),- "en,pt,es".to_string(),- "--sub-format".to_string(),- "best".to_string(),- "--convert-subs".to_string(),- "srt".to_string(),- ]- } else {- Vec::new()- };-- let max_attempts: usize = 3;- let mut extra_args: Vec<String> = Vec::new();- let mut last_error = String::new();- let mut use_subtitles = should_download_subs;- let mut use_browser_cookies = false;- let mut format_already_simplified = false;- let mut last_was_429 = false;-- for attempt in 0..max_attempts {- tracing::info!("[yt-dlp] download attempt {}/{}", attempt + 1, max_attempts);- if cancel_token.is_cancelled() {- tracing::debug!("[perf] download_video took {:?}", _timer_start.elapsed());- anyhow::bail!("Download cancelled");- }-- if attempt > 0 {- let wait: u64 = if last_was_429 {- match attempt {- 1 => 3,- 2 => 8,- _ => 15,- }- } else {- 1- };- tracing::info!(- "[yt-dlp] retry {}/{} after {}s (429={})",- attempt,- max_attempts - 1,- wait,- last_was_429- );- tokio::time::sleep(std::time::Duration::from_secs(wait)).await;- cleanup_part_files(output_dir).await;- }-- let mut args = base_args.clone();-- if use_subtitles {- args.extend(subtitle_args.iter().cloned());- }-- if use_browser_cookies {- if let Some(ref browser) = browser_cookies {- args.push("--cookies-from-browser".to_string());- args.push(browser.clone());- }- }-- if use_aria2c && !use_browser_cookies {- if let Some(ref a2_path) = aria2c_path {- let conns = if is_youtube_url(url) {- effective_fragments.max(1)- } else {- effective_fragments.clamp(8, 16)- };- args.push("--downloader".to_string());- args.push(a2_path.to_string_lossy().to_string());- args.push("--downloader-args".to_string());- let aria2c_proxy = match crate::core::http_client::proxy_url() {- Some(url) => format!(" --all-proxy={}", url),- None => String::new(),- };- args.push(format!("aria2c:-x {} -k 1M -j {} --min-split-size=1M --file-allocation=none --optimize-concurrent-downloads=true --auto-file-renaming=false --summary-interval=0{}", conns, conns, aria2c_proxy));- }- }-- args.extend(extra_args.iter().cloned());- args.push(url.to_string());-- let mut child = crate::core::process::command(ytdlp)- .args(&args)- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()- .map_err(|e| anyhow!("Failed to start yt-dlp: {}", e))?;- tracing::debug!(- "[perf] download_video: yt-dlp process spawned at {:?} (attempt {})",- _timer_start.elapsed(),- attempt + 1- );-- let _ = progress.send(-2.0).await;-- let stdout = child.stdout.take().ok_or_else(|| anyhow!("No stdout"))?;- let stderr_pipe = child.stderr.take().ok_or_else(|| anyhow!("No stderr"))?;-- let reader = BufReader::new(stdout);- let mut lines = reader.lines();-- let progress_tx = progress.clone();- let captured_path: Arc<Mutex<Option<PathBuf>>> = Arc::new(Mutex::new(None));- let captured_path_writer = captured_path.clone();-- let line_reader = tokio::spawn(async move {- let mut phase = 0u32;- let mut max_reported = 0.0f64;- let mut first_line_logged = false;- let mut first_progress_logged = false;- let mut last_send = std::time::Instant::now();- let throttle = std::time::Duration::from_millis(250);- while let Ok(Some(line)) = lines.next_line().await {- if !first_line_logged {- first_line_logged = true;- tracing::debug!(- "[perf] download_video first_byte_time: {:?}",- _timer_start.elapsed()- );- }- if let Some(dest) = parse_destination_line(&line) {- let dest_path = PathBuf::from(&dest);- let ext = dest_path- .extension()- .and_then(|e| e.to_str())- .unwrap_or("")- .to_lowercase();- let is_subtitle = matches!(- ext.as_str(),- "vtt" | "srt" | "ass" | "ssa" | "sub" | "lrc"- );- if !is_subtitle {- phase += 1;- let mut guard = captured_path_writer.lock().unwrap();- *guard = Some(dest_path);- }- }- if line.contains("[Merger]") {- if 99.0 > max_reported {- max_reported = 99.0;- let _ = progress_tx.send(99.0).await;- last_send = std::time::Instant::now();- }- continue;- }- if let Some(pct) = parse_progress_line(&line) {- if !first_progress_logged && pct > 0.0 {- first_progress_logged = true;- tracing::debug!(- "[perf] download_video: first_progress > 0% at {:?}",- _timer_start.elapsed()- );- }- if is_audio_only {- if pct >= 99.0 || last_send.elapsed() >= throttle {- let _ = progress_tx.send(pct).await;- last_send = std::time::Instant::now();- }- } else {- let adjusted = if phase <= 1 {- pct * 0.5- } else {- 50.0 + pct * 0.5- };- if adjusted > max_reported- && (adjusted >= 99.0 || last_send.elapsed() >= throttle)- {- max_reported = adjusted;- let _ = progress_tx.send(adjusted).await;- last_send = std::time::Instant::now();- }- }- }- }- });-- let stderr_reader = tokio::spawn(async move {- let mut buf = String::new();- let stderr_buf = BufReader::new(stderr_pipe);- let mut stderr_lines = stderr_buf.lines();- while let Ok(Some(line)) = stderr_lines.next_line().await {- buf.push_str(&line);- buf.push('\n');- }- buf- });-- let status = tokio::select! {- s = child.wait() => s.map_err(|e| anyhow!("yt-dlp process failed: {}", e))?,- _ = cancel_token.cancelled() => {- let _ = child.kill().await;- let _ = line_reader.await;- let _ = stderr_reader.await;- cleanup_part_files(output_dir).await;- tracing::debug!("[perf] download_video took {:?}", _timer_start.elapsed());- anyhow::bail!("Download cancelled");- }- };-- let _ = line_reader.await;- let stderr_content = stderr_reader.await.unwrap_or_default();-- if status.success() {- let _ = progress.send(100.0).await;-- let file_path = {- let guard = captured_path.lock().unwrap();- guard.clone()- };-- let file_path = match file_path {- Some(p) if p.exists() => {- let ext = p.extension().and_then(|e| e.to_str()).unwrap_or("");- let is_audio_ext = matches!(- ext.to_lowercase().as_str(),- "m4a" | "mp3" | "ogg" | "opus" | "flac" | "aac" | "wav"- );- if is_audio_ext && !is_audio_only {- let stem = p.file_stem().and_then(|s| s.to_str()).unwrap_or("");- let mp4_candidate = p.with_file_name(format!("{}.mp4", stem));- if mp4_candidate.exists() {- mp4_candidate- } else {- find_downloaded_file(output_dir, url).await.unwrap_or(p)- }- } else {- p- }- }- _ => find_downloaded_file(output_dir, url).await?,- };-- let meta = tokio::fs::metadata(&file_path).await?;- tracing::debug!("[perf] download_video took {:?}", _timer_start.elapsed());- return Ok(DownloadResult {- file_path,- file_size_bytes: meta.len(),- duration_seconds: 0.0,- torrent_id: None,- });- }-- last_error = stderr_content;- let stderr_lower = last_error.to_lowercase();-- if attempt < max_attempts - 1 {- if use_aria2c- && (stderr_lower.contains("aria2") || stderr_lower.contains("external downloader"))- {- use_aria2c = false;- tracing::warn!("[yt-dlp] aria2c failed, retrying with native downloader");- }-- last_was_429 = stderr_lower.contains("http error 429");-- if last_was_429 {- let is_subtitle_only_429 = last_error.lines().all(|line| {- let ll = line.to_lowercase();- !ll.contains("429") || ll.contains("subtitle")- });-- if use_subtitles {- use_subtitles = false;- tracing::warn!(- "[yt-dlp] 429 detected, disabling subtitle download for remaining retries"- );- }-- if is_subtitle_only_429 {- tracing::warn!("[yt-dlp] subtitle-only 429, retrying without subtitles (keeping current player_client)");- tokio::time::sleep(std::time::Duration::from_secs(3)).await;- } else {- rate_limit_429_increment();- let sanitized_url = sanitize_log_line(url);- let player_client = if is_youtube_url(url) {- "default"- } else {- "n/a"- };- let cookies_enabled = use_browser_cookies || effective_cookie_file.is_some();- tracing::warn!(- "[yt-429] rate limit in download_video: url={} attempt={}/{} player_client={} cookies={} aria2c={}",- sanitized_url,- attempt + 1,- max_attempts,- player_client,- cookies_enabled,- use_aria2c- );- let base_secs = 10u64 * 2u64.pow(attempt as u32);- let jitter_secs = (attempt as u64 * 7 + url.len() as u64) % 5;- let wait_secs = base_secs + jitter_secs;- tracing::warn!(- "[yt-dlp] rate limited (429), waiting {}s (base={}s + jitter={}s)",- wait_secs,- base_secs,- jitter_secs- );- tokio::time::sleep(std::time::Duration::from_secs(wait_secs)).await;-- if is_youtube_url(url) {- base_args- .retain(|a| a != "--extractor-args" && !a.contains("player_client"));- extra_args- .retain(|a| a != "--extractor-args" && !a.contains("player_client"));- let client = match attempt {- 0 => "youtube:player_client=mweb",- 1 => "youtube:player_client=ios",- _ => "youtube:player_client=ios",- };- extra_args.push("--extractor-args".to_string());- extra_args.push(client.to_string());- tracing::warn!(- "[yt-dlp] 429 detected, rotating player_client to {}",- client- );- }- }- }-- if stderr_lower.contains("nsig") {- base_args.retain(|a| a != "--extractor-args" && !a.contains("player_client"));- extra_args.retain(|a| a != "--extractor-args" && !a.contains("player_client"));- let client = if attempt == 0 {- "youtube:player_client=ios"- } else {- "youtube:player_client=mweb"- };- extra_args.push("--extractor-args".to_string());- extra_args.push(client.to_string());- tracing::warn!("[yt-dlp] nsig error, switching to {}", client);- }-- if (stderr_lower.contains("http error 403") || stderr_lower.contains("forbidden"))- && !extra_args.contains(&"--force-ipv4".to_string())- {- extra_args.push("--force-ipv4".to_string());- tracing::warn!("[yt-dlp] 403 forbidden, adding --force-ipv4");- }-- if stderr_lower.contains("subtitle") && use_subtitles && !last_was_429 {- tracing::warn!("[yt-dlp] subtitle error detected, disabling subtitles for retry");- use_subtitles = false;- }-- if stderr_lower.contains("timed out") || stderr_lower.contains("timeout") {- tracing::warn!("[yt-dlp] socket timeout on attempt {}", attempt + 1);- }-- if stderr_lower.contains("certificate") || stderr_lower.contains("ssl") {- tracing::warn!("[yt-dlp] SSL/certificate error on attempt {}", attempt + 1);- }-- if (stderr_lower.contains("invalid argument") || stderr_lower.contains("errno 22"))- && !extra_args.contains(&"--restrict-filenames".to_string())- {- extra_args.push("--restrict-filenames".to_string());- tracing::warn!("[yt-dlp] Errno 22, adding --restrict-filenames");- }-- if ((stderr_lower.contains("could not") && stderr_lower.contains("cookie"))- || stderr_lower.contains("cookies-from-browser")- || stderr_lower.contains("failed to decrypt")- || stderr_lower.contains("keyring")- || stderr_lower.contains("permission denied"))- && use_browser_cookies- {- use_browser_cookies = false;- tracing::warn!("[yt-dlp] cookies-from-browser failed (Chrome/Edge cookie encryption). Use Firefox or set a cookie file in Settings.");- COOKIE_ERROR_FLAG.store(true, std::sync::atomic::Ordering::Relaxed);- }-- if (stderr_lower.contains("sign in") || stderr_lower.contains("login required"))- && !use_browser_cookies- && browser_cookies.is_some()- {- use_browser_cookies = true;- tracing::warn!("[yt-dlp] login required, enabling cookies-from-browser");- }-- if stderr_lower.contains("requested format") && stderr_lower.contains("not available")- || stderr_lower.contains("ffmpeg") && stderr_lower.contains("not found")- || stderr_lower.contains("postprocessing")- {- if format_already_simplified {- tracing::warn!("[yt-dlp] format/postprocessing error after simplification, giving up");- break;- }-- base_args.retain(|a| a != "--extractor-args" && !a.contains("player_client"));- extra_args.retain(|a| a != "--extractor-args" && !a.contains("player_client"));- base_args.retain(|a| a != "--merge-output-format" && a != "mp4");-- if let Some(pos) = base_args.iter().position(|a| a == "-f") {- base_args.remove(pos + 1);- base_args.remove(pos);- }- tracing::warn!("[yt-dlp] format/postprocessing error on attempt {}, removed -f and player_client to use yt-dlp defaults", attempt + 1);- format_already_simplified = true;- }-- let last_line = last_error.lines().last().unwrap_or("unknown error").trim();- let sanitized = sanitize_log_line(last_line);- tracing::warn!(- "[yt-dlp] attempt {}/{} failed: {}",- attempt + 1,- max_attempts,- sanitized- );- continue;- }- }-- tracing::debug!("[perf] download_video took {:?}", _timer_start.elapsed());- Err(translate_ytdlp_error(&last_error))-}--async fn cleanup_part_files(dir: &Path) {- if let Ok(mut entries) = tokio::fs::read_dir(dir).await {- while let Ok(Some(entry)) = entries.next_entry().await {- let name = entry.file_name();- let name = name.to_string_lossy();- if name.ends_with(".part") || name.ends_with(".ytdl") {- let _ = tokio::fs::remove_file(entry.path()).await;- }- }- }-}--fn sanitize_log_line(line: &str) -> String {- let mut result = String::with_capacity(line.len());- let mut remaining = line;- loop {- let found = remaining- .find("https://")- .or_else(|| remaining.find("http://"));- match found {- Some(start) => {- result.push_str(&remaining[..start]);- let url_part = &remaining[start..];- let url_end = url_part- .find(|c: char| c.is_whitespace() || c == '"' || c == '\'' || c == '>')- .unwrap_or(url_part.len());- let url = &url_part[..url_end];- if let Some(q) = url.find('?') {- result.push_str(&url[..q]);- } else {- result.push_str(url);- }- remaining = &url_part[url_end..];- }- None => {- result.push_str(remaining);- break;- }- }- }- result-}--fn translate_ytdlp_error(stderr: &str) -> anyhow::Error {- let lower = stderr.to_lowercase();-- if lower.contains("http error 429") {- return anyhow!("Server returned error 429 (too many requests). Try again later.");- }- if lower.contains("http error 403") || lower.contains("forbidden") {- return anyhow!("Access denied (403). The video may be private or region-restricted.");- }- if lower.contains("sign in to confirm") || lower.contains("login required") {- return anyhow!("Video requires login. Use browser cookies or try another URL.");- }- if lower.contains("nsig extraction failed") || lower.contains("nsig") {- return anyhow!("Video extraction failed. Update yt-dlp or try again.");- }- if lower.contains("requested format") && lower.contains("not available") {- return anyhow!(- "Requested format is not available. The download will retry with a compatible format."- );- }- if lower.contains("video unavailable") || lower.contains("not available") {- return anyhow!("Video unavailable or removed.");- }- if lower.contains("private video") {- return anyhow!("This video is private.");- }- if lower.contains("copyright") {- return anyhow!("Video blocked due to copyright.");- }- if lower.contains("geo") && lower.contains("block") {- return anyhow!("Video restricted in your region.");- }- if lower.contains("timed out") || lower.contains("timeout") {- return anyhow!("Connection timed out. Check your internet and try again.");- }- if lower.contains("ffmpeg") && (lower.contains("not found") || lower.contains("no such file")) {- return anyhow!("FFmpeg not found. Install FFmpeg to download this format.");- }- if lower.contains("unsupported url") || lower.contains("no suitable infojson") {- return anyhow!("Unsupported URL. Check that the link is correct.");- }- if lower.contains("unable to download") && lower.contains("webpage") {- return anyhow!("Failed to access the page. Check the link and your connection.");- }- if lower.contains("is not a valid url") || lower.contains("no video formats") {- return anyhow!("No video formats found for this link.");- }-- let last_error_line = stderr- .lines()- .rev()- .find(|l| {- let t = l.trim().to_lowercase();- t.starts_with("error:") || t.starts_with("error ")- })- .unwrap_or("")- .trim();-- let msg = if !last_error_line.is_empty() {- last_error_line- .strip_prefix("ERROR: ")- .or_else(|| last_error_line.strip_prefix("ERROR:"))- .or_else(|| last_error_line.strip_prefix("error: "))- .unwrap_or(last_error_line)- } else {- let trimmed = stderr.trim();- if trimmed.len() > 300 {- &trimmed[..300]- } else {- trimmed- }- };-- anyhow!("yt-dlp: {}", msg)-}--pub fn get_rate_limit_stats() -> serde_json::Value {- serde_json::json!({- "rate_limit_429_count": RATE_LIMIT_429_COUNT.load(Ordering::Relaxed)- })-}--fn parse_progress_line(line: &str) -> Option<f64> {- let line = line.trim();- let pct_str = if let Some(rest) = line.strip_prefix("download:") {- rest.trim().trim_end_matches('%')- } else if line.ends_with('%') {- line.trim_end_matches('%').split_whitespace().last()?- } else {- return None;- };-- pct_str.trim().parse::<f64>().ok()-}--async fn find_downloaded_file(output_dir: &Path, url: &str) -> anyhow::Result<PathBuf> {- let video_id = extract_id_from_url(url).unwrap_or_default();- let media_extensions: &[&str] = &[- "mp4", "mkv", "webm", "m4a", "mp3", "ogg", "opus", "flac", "avi", "mov", "ts", "m4v",- "3gp", "aac", "wav",- ];- let now = std::time::SystemTime::now();- let recency_limit = std::time::Duration::from_secs(600);-- let mut entries = tokio::fs::read_dir(output_dir).await?;- let mut candidates: Vec<(PathBuf, std::time::SystemTime, bool)> = Vec::new();-- while let Some(entry) = entries.next_entry().await? {- let path = entry.path();- if !path.is_file() {- continue;- }-- let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");- if name.ends_with(".part") || name.ends_with(".ytdl") || name.starts_with('.') {- continue;- }-- let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");- let is_media = media_extensions- .iter()- .any(|&e| ext.eq_ignore_ascii_case(e));- if !is_media {- continue;- }-- if let Ok(meta) = entry.metadata().await {- if meta.len() == 0 {- continue;- }- if let Ok(modified) = meta.modified() {- let is_recent = now.duration_since(modified).unwrap_or_default() < recency_limit;- let matches_id = !video_id.is_empty() && name.contains(&video_id);-- if matches_id || is_recent {- candidates.push((path, modified, matches_id));- }- }- }- }-- candidates.sort_by(|a, b| b.2.cmp(&a.2).then_with(|| b.1.cmp(&a.1)));-- candidates- .into_iter()- .next()- .map(|(p, _, _)| p)- .ok_or_else(|| anyhow!("Downloaded file not found in {:?}", output_dir))-}--pub fn parse_formats(json: &serde_json::Value) -> Vec<FormatInfo> {- let formats = match json.get("formats").and_then(|v| v.as_array()) {- Some(f) => f,- None => return Vec::new(),- };-- let mut result = Vec::new();- for f in formats {- let format_id = match f.get("format_id").and_then(|v| v.as_str()) {- Some(id) => id.to_string(),- None => continue,- };-- let ext = f- .get("ext")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();- let width = f.get("width").and_then(|v| v.as_u64()).map(|v| v as u32);- let height = f.get("height").and_then(|v| v.as_u64()).map(|v| v as u32);- let fps = f.get("fps").and_then(|v| v.as_f64());- let vcodec = f- .get("vcodec")- .and_then(|v| v.as_str())- .map(|s| s.to_string());- let acodec = f- .get("acodec")- .and_then(|v| v.as_str())- .map(|s| s.to_string());- let filesize = f- .get("filesize")- .or_else(|| f.get("filesize_approx"))- .and_then(|v| v.as_u64());- let tbr = f.get("tbr").and_then(|v| v.as_f64());- let format_note = f- .get("format_note")- .and_then(|v| v.as_str())- .map(|s| s.to_string());-- let has_video = vcodec.as_deref().map(|v| v != "none").unwrap_or(false);- let has_audio = acodec.as_deref().map(|v| v != "none").unwrap_or(false);-- if !has_video && !has_audio {- continue;- }-- let resolution = match (width, height) {- (Some(w), Some(h)) if w > 0 && h > 0 => Some(format!("{}x{}", w, h)),- _ => f- .get("resolution")- .and_then(|v| v.as_str())- .map(|s| s.to_string()),- };-- result.push(FormatInfo {- format_id,- ext,- resolution,- width,- height,- fps,- vcodec,- acodec,- filesize,- tbr,- has_video,- has_audio,- format_note,- });- }-- result-}--fn extract_id_from_url(url: &str) -> Option<String> {- let parsed = url::Url::parse(url).ok()?;- let host = parsed.host_str()?.to_lowercase();-- if host.contains("youtu.be") {- let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();- return segments.first().map(|s| s.to_string());- }-- if host.contains("youtube.com") && parsed.path().starts_with("/embed/") {- let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();- return segments.last().map(|s| s.to_string());- }-- if host.contains("youtube.com") {- let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();- if segments.first() == Some(&"shorts") {- return segments.get(1).map(|s| s.to_string());- }- return parsed- .query_pairs()- .find(|(k, _)| k == "v")- .map(|(_, v)| v.to_string());- }-- None-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn parse_progress_download_prefix() {- assert_eq!(parse_progress_line("download: 45.2%"), Some(45.2));- }-- #[test]- fn parse_progress_100_percent() {- assert_eq!(parse_progress_line("download:100.0%"), Some(100.0));- }-- #[test]- fn parse_progress_bare_percent() {- assert_eq!(parse_progress_line(" 92.5%"), Some(92.5));- }-- #[test]- fn parse_progress_integer() {- assert_eq!(parse_progress_line("download:100%"), Some(100.0));- }-- #[test]- fn parse_progress_garbage_returns_none() {- assert_eq!(parse_progress_line("[info] Writing video subtitles"), None);- }-- #[test]- fn parse_progress_empty_returns_none() {- assert_eq!(parse_progress_line(""), None);- }-- #[test]- fn parse_destination_standard() {- assert_eq!(- parse_destination_line("[download] Destination: /tmp/video.mp4"),- Some("/tmp/video.mp4".to_string())- );- }-- #[test]- fn parse_destination_merger() {- assert_eq!(- parse_destination_line("[Merger] Merging formats into \"/tmp/video.mp4\""),- Some("/tmp/video.mp4".to_string())- );- }-- #[test]- fn parse_destination_no_match() {- assert_eq!(parse_destination_line("[download] 100% of 50.0MiB"), None);- }-- #[test]- fn parse_destination_empty_path_returns_none() {- assert_eq!(parse_destination_line("[download] Destination:"), None);- }-- #[test]- fn is_youtube_url_standard() {- assert!(is_youtube_url(- "https://www.youtube.com/watch?v=dQw4w9WgXcQ"- ));- }-- #[test]- fn is_youtube_url_short() {- assert!(is_youtube_url("https://youtu.be/dQw4w9WgXcQ"));- }-- #[test]- fn is_youtube_url_case_insensitive() {- assert!(is_youtube_url("https://www.YouTube.com/watch?v=test"));- }-- #[test]- fn is_youtube_url_other_site() {- assert!(!is_youtube_url("https://vimeo.com/123456"));- }-- #[test]- fn sanitize_strips_query_params() {- let input = "Error downloading https://example.com/video?token=secret&key=123 failed";- let result = sanitize_log_line(input);- assert_eq!(result, "Error downloading https://example.com/video failed");- }-- #[test]- fn sanitize_preserves_url_without_query() {- let input = "Error downloading https://example.com/video failed";- let result = sanitize_log_line(input);- assert_eq!(result, input);- }-- #[test]- fn sanitize_multiple_urls() {- let input = "from https://a.com/x?s=1 to https://b.com/y?t=2 done";- let result = sanitize_log_line(input);- assert_eq!(result, "from https://a.com/x to https://b.com/y done");- }-- #[test]- fn sanitize_no_urls() {- let input = "plain error message";- let result = sanitize_log_line(input);- assert_eq!(result, input);- }-- #[test]- fn extract_id_youtube_standard() {- assert_eq!(- extract_id_from_url("https://www.youtube.com/watch?v=dQw4w9WgXcQ"),- Some("dQw4w9WgXcQ".to_string())- );- }-- #[test]- fn extract_id_youtu_be() {- assert_eq!(- extract_id_from_url("https://youtu.be/dQw4w9WgXcQ"),- Some("dQw4w9WgXcQ".to_string())- );- }-- #[test]- fn extract_id_youtube_embed() {- assert_eq!(- extract_id_from_url("https://www.youtube.com/embed/dQw4w9WgXcQ"),- Some("dQw4w9WgXcQ".to_string())- );- }-- #[test]- fn extract_id_shorts() {- assert_eq!(- extract_id_from_url("https://www.youtube.com/shorts/abc123"),- Some("abc123".to_string())- );- }-- #[test]- fn extract_id_non_youtube() {- assert_eq!(extract_id_from_url("https://vimeo.com/123456"), None);- }-- #[test]- fn translate_error_429() {- let err = translate_ytdlp_error("HTTP Error 429: Too Many Requests");- assert!(err.to_string().contains("429"));- }-- #[test]- fn translate_error_403() {- let err = translate_ytdlp_error("HTTP Error 403: Forbidden");- assert!(err.to_string().contains("403"));- }-- #[test]- fn translate_error_nsig() {- let err = translate_ytdlp_error("nsig extraction failed");- assert!(err.to_string().contains("extraction"));- }-- #[test]- fn translate_error_unavailable() {- let err = translate_ytdlp_error("Video unavailable");- assert!(err.to_string().contains("unavailable"));- }-- #[test]- fn translate_error_requested_format() {- let err = translate_ytdlp_error("ERROR: Requested format is not available. Use --list-formats for a list of available formats");- assert!(err.to_string().contains("Requested format"), "Got: {}", err);- assert!(- !err.to_string().contains("Video unavailable"),- "Should not contain 'Video unavailable', got: {}",- err- );- }-- #[test]- fn translate_error_private() {- let err = translate_ytdlp_error("This is a private video");- assert!(err.to_string().contains("private"));- }-- #[test]- fn translate_error_timeout() {- let err = translate_ytdlp_error("Connection timed out");- assert!(err.to_string().contains("timed out"));- }-- #[test]- fn translate_error_unknown_falls_through() {- let err = translate_ytdlp_error("ERROR: some unknown thing happened");- assert!(err.to_string().contains("yt-dlp"));- }-- #[test]- fn parse_formats_empty_json() {- let json = serde_json::json!({});- assert!(parse_formats(&json).is_empty());- }-- #[test]- fn parse_formats_extracts_fields() {- let json = serde_json::json!({- "formats": [- {- "format_id": "22",- "ext": "mp4",- "width": 1280,- "height": 720,- "fps": 30.0,- "vcodec": "avc1.64001F",- "acodec": "mp4a.40.2",- "filesize": 50_000_000u64,- "tbr": 2500.0,- "format_note": "720p"- }- ]- });- let formats = parse_formats(&json);- assert_eq!(formats.len(), 1);- assert_eq!(formats[0].format_id, "22");- assert_eq!(formats[0].height, Some(720));- assert!(formats[0].has_video);- assert!(formats[0].has_audio);- assert_eq!(formats[0].resolution, Some("1280x720".to_string()));- }-- #[test]- fn parse_formats_video_only() {- let json = serde_json::json!({- "formats": [- {- "format_id": "137",- "ext": "mp4",- "width": 1920,- "height": 1080,- "vcodec": "avc1.640028",- "acodec": "none"- }- ]- });- let formats = parse_formats(&json);- assert_eq!(formats.len(), 1);- assert!(formats[0].has_video);- assert!(!formats[0].has_audio);- }-}diff --git a/src-tauri/src/platforms/afyainternato/api.rs b/src-tauri/src/platforms/afyainternato/api.rsdeleted file mode 100644index 8750b954..00000000--- a/src-tauri/src/platforms/afyainternato/api.rs+++ /dev/null@@ -1,189 +0,0 @@-use std::path::PathBuf;-use std::time::Duration;--use anyhow::anyhow;-use serde::{Deserialize, Serialize};--use crate::platforms::medcel::api as medcel_api;--const ORIGIN_URL: &str = "https://alunos-internato.afya.com.br";-const API_BASE: &str = "https://service.medcel.com.br";--#[derive(Clone)]-pub struct AfyaSession {- 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,-}--pub type AfyaCourse = medcel_api::MedcelCourse;-pub type AfyaModule = medcel_api::MedcelModule;-pub type AfyaLesson = medcel_api::MedcelLesson;-pub type AfyaMaterial = medcel_api::MedcelMaterial;--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("afya_session.json"))-}--pub async fn authenticate(email: &str, password: &str, api_key: &str) -> anyhow::Result<AfyaSession> {- let temp_client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0")- .connect_timeout(Duration::from_secs(30))- .timeout(Duration::from_secs(60))- .build()?;-- let mut headers = reqwest::header::HeaderMap::new();- headers.insert(- "X-Api-Key",- reqwest::header::HeaderValue::from_str(api_key)?,- );- headers.insert(- "Referer",- reqwest::header::HeaderValue::from_str(&format!("{}/", ORIGIN_URL))?,- );- headers.insert(- "Origin",- reqwest::header::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 = medcel_api::build_client_with_origin(&session_token, api_key, ORIGIN_URL)?;-- Ok(AfyaSession {- token: session_token,- api_key: api_key.to_string(),- student_id,- client,- })-}--pub fn to_medcel_session(session: &AfyaSession) -> medcel_api::MedcelSession {- medcel_api::MedcelSession {- token: session.token.clone(),- api_key: session.api_key.clone(),- student_id: session.student_id.clone(),- client: session.client.clone(),- }-}--pub async fn validate_token(session: &AfyaSession) -> anyhow::Result<bool> {- let ms = to_medcel_session(session);- medcel_api::validate_token(&ms).await-}--pub async fn fetch_student_id(session: &AfyaSession) -> anyhow::Result<String> {- let ms = to_medcel_session(session);- medcel_api::fetch_student_id(&ms).await-}--pub async fn list_courses(session: &AfyaSession) -> anyhow::Result<Vec<AfyaCourse>> {- let ms = to_medcel_session(session);- medcel_api::list_courses(&ms).await-}--pub async fn get_modules(session: &AfyaSession, product_id: &str) -> anyhow::Result<Vec<AfyaModule>> {- let ms = to_medcel_session(session);- medcel_api::get_modules(&ms, product_id).await-}--pub async fn get_video_url(session: &AfyaSession, class_id: &str, product_id: &str) -> anyhow::Result<String> {- let ms = to_medcel_session(session);- medcel_api::get_video_url(&ms, class_id, product_id).await-}--pub async fn save_session(session: &AfyaSession) -> 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!("[afya] session saved");- Ok(())-}--pub async fn load_session() -> anyhow::Result<Option<AfyaSession>> {- 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 = medcel_api::build_client_with_origin(&saved.token, &saved.api_key, ORIGIN_URL)?;-- tracing::info!("[afya] session loaded");-- Ok(Some(AfyaSession {- 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/src/platforms/afyainternato/downloader.rs b/src-tauri/src/platforms/afyainternato/downloader.rsdeleted file mode 100644index 1a2a06c1..00000000--- a/src-tauri/src/platforms/afyainternato/downloader.rs+++ /dev/null@@ -1,316 +0,0 @@-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 crate::core::filename;--use super::api::{self, AfyaCourse, AfyaSession};--#[derive(Debug, Clone, serde::Serialize)]-pub struct AfyaCourseDownloadProgress {- 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: &AfyaSession,- course: &AfyaCourse,- 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 crate::core::course_utils::is_course_complete(&course_dir) {- tracing::info!("[afya] 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",- &AfyaCourseDownloadProgress {- 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 {- crate::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!("[afya] Skipping existing: {}", video_path);- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AfyaCourseDownloadProgress {- 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!(- "[afya] 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!(- "[afya] 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!(- "[afya] Direct download also failed for '{}': {}",- lesson.name,- e2- );- }- }- }- }- }- }- Err(e) => {- tracing::error!(- "[afya] 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!(- "[afya] Material download failed for '{}': {}",- material.title,- e- );- }- }- }-- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AfyaCourseDownloadProgress {- 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"));- }-- crate::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 crate::core::media_processor::MediaProcessor;-- let _result = MediaProcessor::download_hls(- m3u8_url,- output_path,- "https://alunos-internato.afya.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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::core::ytdlp::download_video(- &ytdlp_path,- url,- out_dir,- None,- tx,- None,- None,- None,- Some("https://alunos-internato.afya.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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/afyainternato/mod.rs b/src-tauri/src/platforms/afyainternato/mod.rsdeleted file mode 100644index 28248efb..00000000--- a/src-tauri/src/platforms/afyainternato/mod.rs+++ /dev/null@@ -1,71 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};-use crate::platforms::traits::PlatformDownloader;--pub struct AfyaInternatoDownloader;--impl AfyaInternatoDownloader {- pub fn new() -> Self {- Self- }-}--impl Default for AfyaInternatoDownloader {- fn default() -> Self {- Self::new()- }-}--#[async_trait]-impl PlatformDownloader for AfyaInternatoDownloader {- fn name(&self) -> &str {- "afyainternato"- }-- 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 == "afya.com.br"- || host.ends_with(".afya.com.br");- }- }- false- }-- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {- Ok(MediaInfo {- title: "Afya Internato Course".to_string(),- author: String::new(),- platform: "afyainternato".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 Afya Internato courses"- ))- }-}diff --git a/src-tauri/src/platforms/alpaclass/api.rs b/src-tauri/src/platforms/alpaclass/api.rsdeleted file mode 100644index c03fee33..00000000--- a/src-tauri/src/platforms/alpaclass/api.rs+++ /dev/null@@ -1,483 +0,0 @@-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://learner-api.alpaclass.com";--#[derive(Clone)]-pub struct AlpaclassSession {- pub token: String,- pub subdomain: String,- pub origin_url: String,- pub client: reqwest::Client,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct SavedSession {- pub token: String,- pub subdomain: String,- pub origin_url: String,- pub saved_at: u64,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AlpaclassCourse {- pub slug: String,- pub name: String,- pub author: String,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AlpaclassCategory {- pub id: i64,- pub name: String,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AlpaclassModule {- pub slug: String,- pub name: String,- pub order: i64,- pub lessons: Vec<AlpaclassLesson>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AlpaclassLesson {- pub slug: String,- pub name: String,- pub lesson_type: String,- pub order: i64,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AlpaclassLessonDetail {- pub slug: String,- pub name: String,- pub html_content: Option<String>,- pub video_url: Option<String>,- pub files: Vec<AlpaclassFile>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AlpaclassFile {- pub name: String,- pub url: String,-}--fn extract_subdomain(platform_url: &str) -> anyhow::Result<String> {- let parsed = url::Url::parse(platform_url)- .map_err(|e| anyhow!("Invalid platform URL: {}", e))?;- let host = parsed- .host_str()- .ok_or_else(|| anyhow!("No host in platform URL"))?;- let parts: Vec<&str> = host.split('.').collect();- if parts.len() >= 3 {- Ok(parts[0].to_string())- } else {- Ok(host.to_string())- }-}--fn build_client(token: &str, subdomain: &str, origin_url: &str) -> anyhow::Result<reqwest::Client> {- let mut headers = HeaderMap::new();- headers.insert(- "Authorization",- HeaderValue::from_str(&format!("Bearer {}", token))?,- );- headers.insert("subdomain", HeaderValue::from_str(subdomain)?);- headers.insert("Accept", HeaderValue::from_static("application/json"));- headers.insert("Origin", HeaderValue::from_str(origin_url)?);- headers.insert(- "Referer",- HeaderValue::from_str(&format!("{}/", origin_url))?,- );-- let client = crate::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("alpaclass_session.json"))-}--pub async fn authenticate(token: &str, platform_url: &str) -> anyhow::Result<AlpaclassSession> {- let origin = platform_url.trim_end_matches('/').to_string();- let subdomain = extract_subdomain(&origin)?;- let client = build_client(token, &subdomain, &origin)?;-- let session = AlpaclassSession {- token: token.to_string(),- subdomain,- origin_url: origin,- client,- };-- let valid = validate_token(&session).await?;- if !valid {- return Err(anyhow!("Invalid token or platform URL"));- }-- Ok(session)-}--pub async fn validate_token(session: &AlpaclassSession) -> anyhow::Result<bool> {- let resp = session- .client- .get(format!("{}/learner/categories", API_BASE))- .send()- .await?;-- Ok(resp.status().is_success())-}--pub async fn list_categories(session: &AlpaclassSession) -> anyhow::Result<Vec<AlpaclassCategory>> {- let resp = session- .client- .get(format!("{}/learner/categories", API_BASE))- .send()- .await?;-- let status = resp.status();- let body_text = resp.text().await?;-- if !status.is_success() {- return Err(anyhow!(- "list_categories returned status {}: {}",- status,- &body_text[..body_text.len().min(300)]- ));- }-- let body: serde_json::Value = serde_json::from_str(&body_text)?;-- let cats_arr = body- .get("categories")- .and_then(|v| v.as_array())- .cloned()- .unwrap_or_default();-- let mut categories = Vec::new();- for item in &cats_arr {- 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("")- .to_string();- categories.push(AlpaclassCategory { id, name });- }-- Ok(categories)-}--pub async fn list_courses(session: &AlpaclassSession) -> anyhow::Result<Vec<AlpaclassCourse>> {- let categories = list_categories(session).await?;- let mut all_courses = Vec::new();-- for cat in &categories {- let url = format!(- "{}/learner/categories/{}/courses?showUnavailableCourses=true",- API_BASE, cat.id- );-- let resp = session.client.get(&url).send().await?;- let status = resp.status();- let body_text = resp.text().await?;-- if !status.is_success() {- tracing::error!(- "[alpaclass] list_courses for category {} returned status {}: {}",- cat.name,- status,- &body_text[..body_text.len().min(300)]- );- continue;- }-- let body: serde_json::Value = serde_json::from_str(&body_text)?;-- let courses_arr = match &body {- serde_json::Value::Array(arr) => arr.clone(),- _ => body- .get("courses")- .and_then(|v| v.as_array())- .cloned()- .unwrap_or_default(),- };-- for item in &courses_arr {- let slug = item- .get("slug")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let name = item- .get("name")- .or_else(|| item.get("title"))- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let author = item- .get("author")- .and_then(|a| a.get("name").and_then(|n| n.as_str()))- .unwrap_or("")- .to_string();-- if !slug.is_empty() {- all_courses.push(AlpaclassCourse { slug, name, author });- }- }- }-- Ok(all_courses)-}--pub async fn get_course_content(- session: &AlpaclassSession,- course_slug: &str,-) -> anyhow::Result<Vec<AlpaclassModule>> {- let url = format!("{}/learner/courses/{}", API_BASE, 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 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 slug = module_val- .get("slug")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let name = module_val- .get("name")- .or_else(|| module_val.get("title"))- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let mut lessons = Vec::new();-- let lessons_arr = module_val- .get("lessons")- .and_then(|v| v.as_array())- .cloned()- .unwrap_or_default();-- for (li, lesson_val) in lessons_arr.iter().enumerate() {- let lesson_slug = lesson_val- .get("slug")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let lesson_title = lesson_val- .get("title")- .or_else(|| lesson_val.get("name"))- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let lesson_type = lesson_val- .get("type")- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- lessons.push(AlpaclassLesson {- slug: lesson_slug,- name: lesson_title,- lesson_type,- order: li as i64,- });- }-- modules.push(AlpaclassModule {- slug,- name,- order: mi as i64,- lessons,- });- }-- Ok(modules)-}--pub async fn get_lesson_detail(- session: &AlpaclassSession,- lesson_slug: &str,-) -> anyhow::Result<AlpaclassLessonDetail> {- let url = format!("{}/learner/lessons/{}", API_BASE, lesson_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_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("title")- .or_else(|| body.get("name"))- .and_then(|v| v.as_str())- .unwrap_or(lesson_slug)- .to_string();-- let html_content = body- .get("htmlContent")- .and_then(|v| v.as_str())- .map(String::from);-- let video_url = body- .get("content")- .and_then(|c| {- let content_type = c.get("type").and_then(|v| v.as_str()).unwrap_or("");- match content_type {- "pandavideo" | "safevideo_video" => {- c.get("data").and_then(|v| v.as_str()).map(String::from)- }- _ => None,- }- });-- let files_url = format!("{}/learner/lessons/{}/files", API_BASE, lesson_slug);- let files = match session.client.get(&files_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("files")- .and_then(|v| v.as_array())- .cloned()- .unwrap_or_default(),- };-- files_arr- .iter()- .filter_map(|f| {- let file_name = f- .get("name")- .and_then(|v| v.as_str())- .unwrap_or("file")- .to_string();-- let file_url = f.get("url").and_then(|v| v.as_str()).map(|u| {- if u.starts_with("http") {- u.to_string()- } else {- format!("{}{}", API_BASE, u)- }- });-- file_url.map(|url| AlpaclassFile {- name: file_name,- url,- })- })- .collect()- }- _ => vec![],- };-- Ok(AlpaclassLessonDetail {- slug: lesson_slug.to_string(),- name,- html_content,- video_url,- files,- })-}--pub async fn save_session(session: &AlpaclassSession) -> 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(),- subdomain: session.subdomain.clone(),- origin_url: session.origin_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!("[alpaclass] session saved for {}", session.subdomain);- Ok(())-}--pub async fn load_session() -> anyhow::Result<Option<AlpaclassSession>> {- 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.subdomain, &saved.origin_url)?;-- tracing::info!("[alpaclass] session loaded for {}", saved.subdomain);-- Ok(Some(AlpaclassSession {- token: saved.token,- subdomain: saved.subdomain,- origin_url: saved.origin_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/src/platforms/alpaclass/downloader.rs b/src-tauri/src/platforms/alpaclass/downloader.rsdeleted file mode 100644index 04e97f1d..00000000--- a/src-tauri/src/platforms/alpaclass/downloader.rs+++ /dev/null@@ -1,350 +0,0 @@-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 crate::core::filename;--use super::api::{self, AlpaclassCourse, AlpaclassSession};--#[derive(Debug, Clone, serde::Serialize)]-pub struct AlpaclassCourseDownloadProgress {- pub course_slug: 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: &AlpaclassSession,- course: &AlpaclassCourse,- 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 crate::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",- &AlpaclassCourseDownloadProgress {- course_slug: course.slug.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.slug).await {- Ok(d) => d,- Err(e) => {- tracing::error!(- "[alpaclass] Failed to get lesson detail '{}': {}. Continuing...",- lesson.name,- e- );- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AlpaclassCourseDownloadProgress {- course_slug: course.slug.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 html) = detail.html_content {- crate::core::course_utils::save_description(&lesson_dir, html, "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!("[alpaclass] Skipping existing: {}", video_path);- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AlpaclassCourseDownloadProgress {- course_slug: course.slug.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, &session.origin_url, &cancel_token).await {- Ok(size) => {- total_bytes.fetch_add(size, Ordering::Relaxed);- }- Err(e) => {- tracing::error!(- "[alpaclass] HLS download failed for '{}': {}",- lesson.name,- e- );- let _ = tokio::fs::remove_file(&video_path).await;- }- }- } else {- match download_with_ytdlp(video_url, &lesson_dir, &session.origin_url, &cancel_token).await {- Ok(size) => {- total_bytes.fetch_add(size, Ordering::Relaxed);- }- Err(e) => {- tracing::error!(- "[alpaclass] 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!(- "[alpaclass] 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!(- "[alpaclass] File download failed for '{}': {}",- file.name,- e- );- }- }- }-- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AlpaclassCourseDownloadProgress {- course_slug: course.slug.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"));- }-- crate::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 crate::core::media_processor::MediaProcessor;-- let _result = MediaProcessor::download_hls(- m3u8_url,- output_path,- &format!("{}/", 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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::core::ytdlp::download_video(- &ytdlp_path,- url,- out_dir,- None,- tx,- None,- None,- None,- Some(&format!("{}/", 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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/alpaclass/mod.rs b/src-tauri/src/platforms/alpaclass/mod.rsdeleted file mode 100644index 10ba6079..00000000--- a/src-tauri/src/platforms/alpaclass/mod.rs+++ /dev/null@@ -1,63 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};-use crate::platforms::traits::PlatformDownloader;--pub struct AlpaclassDownloader;--impl AlpaclassDownloader {- pub fn new() -> Self {- Self- }-}--impl Default for AlpaclassDownloader {- fn default() -> Self {- Self::new()- }-}--#[async_trait]-impl PlatformDownloader for AlpaclassDownloader {- fn name(&self) -> &str {- "alpaclass"- }-- 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 == "alpaclass.com"- || host.ends_with(".alpaclass.com");- }- }- false- }-- async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {- Ok(MediaInfo {- title: "Alpaclass".to_string(),- author: String::new(),- platform: "alpaclass".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 Alpaclass"))- }-}diff --git a/src-tauri/src/platforms/areademembros/api.rs b/src-tauri/src/platforms/areademembros/api.rsdeleted file mode 100644index 3543a5ce..00000000--- a/src-tauri/src/platforms/areademembros/api.rs+++ /dev/null@@ -1,351 +0,0 @@-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 AreaDeMembrosSession {- 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 AreaDeMembrosApiCourse {- pub id: String,- pub name: String,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AreaDeMembrosModule {- pub id: String,- pub name: String,- pub order: i64,- pub lessons: Vec<AreaDeMembrosLesson>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AreaDeMembrosLesson {- pub id: String,- pub name: String,- pub order: i64,- 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(cookies)?,- );- headers.insert(- "Referer",- HeaderValue::from_str(&format!("{}/", site_url))?,- );- headers.insert("Accept", HeaderValue::from_static("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));-- let client = crate::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("areademembros_session.json"))-}--pub async fn validate_token(session: &AreaDeMembrosSession) -> anyhow::Result<bool> {- let url = format!("{}/area/vitrine", session.site_url);- let resp = session.client.get(&url).send().await?;- Ok(resp.status().is_success())-}--pub async fn list_courses(session: &AreaDeMembrosSession) -> anyhow::Result<Vec<AreaDeMembrosApiCourse>> {- let url = format!("{}/area/vitrine", session.site_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 mut courses = Vec::new();-- for line in body_text.lines() {- if let Some(pos) = line.find("id=\"grupo-vitrine-") {- let rest = &line[pos + 18..];- if let Some(end) = rest.find('"') {- let id = rest[..end].to_string();- let name = extract_text_after(rest, ">")- .unwrap_or_else(|| id.clone());- courses.push(AreaDeMembrosApiCourse {- id: id.clone(),- name: if name.trim().is_empty() { id } else { name.trim().to_string() },- });- }- }- }-- if courses.is_empty() {- for line in body_text.lines() {- let trimmed = line.trim();- if trimmed.contains("grupo-vitrine") || trimmed.contains("vitrine-produto") {- if let Some(href) = extract_attr(trimmed, "href") {- let id = href.rsplit('/').next().unwrap_or(&href).to_string();- let name = extract_text_content(trimmed).unwrap_or_else(|| id.clone());- if !courses.iter().any(|c: &AreaDeMembrosApiCourse| c.id == id) {- courses.push(AreaDeMembrosApiCourse { id, name });- }- }- }- }- }-- Ok(courses)-}--pub async fn get_course_content(- session: &AreaDeMembrosSession,- course_id: &str,-) -> anyhow::Result<Vec<AreaDeMembrosModule>> {- let url = format!("{}/area/produto/{}", session.site_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_course_content returned status {}: {}",- status,- &body_text[..body_text.len().min(300)]- ));- }-- let mut modules = Vec::new();- let mut current_module: Option<(String, String, Vec<AreaDeMembrosLesson>)> = None;- let mut module_order = 0i64;- let mut lesson_order = 0i64;-- for line in body_text.lines() {- let trimmed = line.trim();-- if trimmed.contains("section-group-titulo") && trimmed.contains("data-target") {- if let Some((id, name, lessons)) = current_module.take() {- modules.push(AreaDeMembrosModule {- id,- name,- order: module_order,- lessons,- });- }- module_order += 1;- lesson_order = 0;- let mod_id = extract_attr(trimmed, "data-target")- .unwrap_or_else(|| format!("mod-{}", module_order));- let mod_name = extract_text_content(trimmed)- .unwrap_or_else(|| format!("Module {}", module_order));- current_module = Some((mod_id, mod_name, Vec::new()));- }-- if trimmed.contains("layer-link") && trimmed.contains("/area/produto/item/") {- if let Some(href) = extract_attr(trimmed, "href") {- lesson_order += 1;- let lesson_id = href.rsplit('/').next().unwrap_or(&href).to_string();- let lesson_name = extract_text_content(trimmed)- .unwrap_or_else(|| format!("Lesson {}", lesson_order));- let full_url = if href.starts_with("http") {- href- } else {- format!("{}{}", session.site_url, href)- };- if let Some(ref mut m) = current_module {- m.2.push(AreaDeMembrosLesson {- id: lesson_id,- name: lesson_name,- order: lesson_order,- url: full_url,- });- }- }- }- }-- if let Some((id, name, lessons)) = current_module.take() {- modules.push(AreaDeMembrosModule {- id,- name,- order: module_order,- lessons,- });- }-- Ok(modules)-}--pub async fn get_lesson_video_url(- session: &AreaDeMembrosSession,- lesson_url: &str,-) -> anyhow::Result<(Option<String>, Option<String>)> {- let resp = session.client.get(lesson_url).send().await?;- let body = resp.text().await?;-- let mut video_url = None;-- for line in body.lines() {- let trimmed = line.trim();- if trimmed.contains("video-container") || trimmed.contains("<iframe") {- if let Some(src) = extract_attr(trimmed, "src") {- if src.contains("youtube") || src.contains("vimeo") || src.contains("player") || src.contains("embed") {- video_url = Some(src);- break;- }- }- }- }-- if video_url.is_none() {- if let Some(pos) = body.find("<iframe") {- let rest = &body[pos..];- if let Some(src) = extract_attr(rest, "src") {- video_url = Some(src);- }- }- }-- let description = extract_lesson_description(&body);-- Ok((video_url, description))-}--fn extract_lesson_description(html: &str) -> Option<String> {- if let Some(start) = html.find("class=\"conteudo-aula\"").or_else(|| html.find("class=\"lesson-content\"")).or_else(|| html.find("class=\"aula-conteudo\"")) {- let rest = &html[start..];- if let Some(tag_end) = rest.find('>') {- let content = &rest[tag_end + 1..];- if let Some(end) = content.find("</div>") {- let text = content[..end].trim();- if !text.is_empty() {- return Some(text.to_string());- }- }- }- }- None-}--fn extract_attr(html: &str, attr: &str) -> Option<String> {- let pattern = format!("{}=\"", attr);- if let Some(pos) = html.find(&pattern) {- let rest = &html[pos + pattern.len()..];- if let Some(end) = rest.find('"') {- return Some(rest[..end].to_string());- }- }- let pattern2 = format!("{}='", attr);- if let Some(pos) = html.find(&pattern2) {- let rest = &html[pos + pattern2.len()..];- if let Some(end) = rest.find('\'') {- return Some(rest[..end].to_string());- }- }- None-}--fn extract_text_content(html: &str) -> Option<String> {- if let Some(pos) = html.rfind('>') {- let rest = &html[pos + 1..];- if let Some(end) = rest.find('<') {- let text = rest[..end].trim().to_string();- if !text.is_empty() {- return Some(text);- }- }- }- None-}--fn extract_text_after(html: &str, pattern: &str) -> Option<String> {- if let Some(pos) = html.find(pattern) {- let rest = &html[pos + pattern.len()..];- if let Some(end) = rest.find('<') {- let text = rest[..end].trim().to_string();- if !text.is_empty() {- return Some(text);- }- }- }- None-}--pub async fn save_session(session: &AreaDeMembrosSession) -> 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!("[areademembros] session saved");- Ok(())-}--pub async fn load_session() -> anyhow::Result<Option<AreaDeMembrosSession>> {- 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!("[areademembros] session loaded");-- Ok(Some(AreaDeMembrosSession {- 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/src/platforms/areademembros/downloader.rs b/src-tauri/src/platforms/areademembros/downloader.rsdeleted file mode 100644index 6b3915dc..00000000--- a/src-tauri/src/platforms/areademembros/downloader.rs+++ /dev/null@@ -1,250 +0,0 @@-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 crate::core::filename;--use super::api::{self, AreaDeMembrosApiCourse, AreaDeMembrosSession};--#[derive(Debug, Clone, serde::Serialize)]-pub struct AreaDeMembrosDownloadProgress {- 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: &AreaDeMembrosSession,- course: &AreaDeMembrosApiCourse,- 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 crate::core::course_utils::is_course_complete(&course_dir) {- tracing::info!("[areademembros] 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",- &AreaDeMembrosDownloadProgress {- 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_url_opt, description) = match api::get_lesson_video_url(session, &lesson.url).await {- Ok(result) => result,- Err(e) => {- tracing::error!("[areademembros] Failed to get video URL for '{}': {}", lesson.name, e);- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AreaDeMembrosDownloadProgress {- 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) = description {- let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);- tokio::fs::create_dir_all(&lesson_desc_dir).await?;- crate::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();- }-- let video_url = match video_url_opt {- Some(url) => url,- None => {- tracing::warn!("[areademembros] No video found for lesson '{}'", lesson.name);- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AreaDeMembrosDownloadProgress {- 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!("[areademembros] Skipping existing: {}", video_path);- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AreaDeMembrosDownloadProgress {- 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!(- "[areademembros] yt-dlp download failed for '{}': {}",- lesson.name,- e- );- }- }-- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AreaDeMembrosDownloadProgress {- 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"));- }-- crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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/src/platforms/areademembros/mod.rs b/src-tauri/src/platforms/areademembros/mod.rsdeleted file mode 100644index ff4ceb33..00000000--- a/src-tauri/src/platforms/areademembros/mod.rs+++ /dev/null@@ -1,63 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};-use crate::platforms::traits::PlatformDownloader;--pub struct AreaDeMembrosDownloader;--impl AreaDeMembrosDownloader {- pub fn new() -> Self {- Self- }-}--impl Default for AreaDeMembrosDownloader {- fn default() -> Self {- Self::new()- }-}--#[async_trait]-impl PlatformDownloader for AreaDeMembrosDownloader {- fn name(&self) -> &str {- "areademembros"- }-- 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 == "areademembros.com"- || host.ends_with(".areademembros.com");- }- }- false- }-- async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {- Ok(MediaInfo {- title: "Area de Membros".to_string(),- author: String::new(),- platform: "areademembros".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 Area de Membros"))- }-}diff --git a/src-tauri/src/platforms/astronmembers/api.rs b/src-tauri/src/platforms/astronmembers/api.rsdeleted file mode 100644index a90e82a2..00000000--- a/src-tauri/src/platforms/astronmembers/api.rs+++ /dev/null@@ -1,424 +0,0 @@-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 AstronSession {- 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 AstronCourse {- pub id: String,- pub name: String,- pub slug: String,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AstronModule {- pub id: String,- pub name: String,- pub order: i64,- pub lessons: Vec<AstronLesson>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct AstronLesson {- pub id: String,- pub name: String,- pub order: i64,- 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(cookies)?,- );- headers.insert(- "Referer",- HeaderValue::from_str(&format!("{}/", site_url))?,- );- headers.insert("Accept", HeaderValue::from_static("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));-- let client = crate::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("astron_session.json"))-}--pub async fn authenticate(site_url: &str, login: &str, password: &str) -> anyhow::Result<AstronSession> {- let temp_client = crate::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_url = format!("{}/entrar", site_url);- let resp = temp_client- .post(&login_url)- .form(&[("login", login), ("senha", password)])- .send()- .await?;-- if !resp.status().is_success() && !resp.status().is_redirection() {- return Err(anyhow!("Authentication failed (status {})", resp.status()));- }-- let mut cookie_strings = Vec::new();- for cookie in resp.cookies() {- cookie_strings.push(format!("{}={}", cookie.name(), cookie.value()));- }- let cookies = cookie_strings.join("; ");-- if cookies.is_empty() {- return Err(anyhow!("No cookies received from login"));- }-- let client = build_client(&cookies, site_url)?;-- Ok(AstronSession {- cookies,- site_url: site_url.to_string(),- client,- })-}--pub async fn validate_token(session: &AstronSession) -> anyhow::Result<bool> {- let resp = session.client.get(&session.site_url).send().await?;- let body = resp.text().await?;- Ok(!body.contains("/entrar") || body.contains("box-slider-cursos"))-}--pub async fn list_courses(session: &AstronSession) -> anyhow::Result<Vec<AstronCourse>> {- 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();-- for line in body_text.lines() {- let trimmed = line.trim();- if trimmed.contains("href=") && trimmed.contains("curso/") {- if let Some(href) = extract_attr(trimmed, "href") {- if href.contains("curso/") {- let slug = href.rsplit("curso/").next().unwrap_or("").trim_matches('/').to_string();- if !slug.is_empty() && !courses.iter().any(|c: &AstronCourse| c.slug == slug) {- let name = extract_text_content(trimmed)- .unwrap_or_else(|| slug.replace('-', " "));- courses.push(AstronCourse {- id: slug.clone(),- name,- slug,- });- }- }- }- }- }-- Ok(courses)-}--pub async fn get_course_content(- session: &AstronSession,- course_slug: &str,-) -> anyhow::Result<Vec<AstronModule>> {- let url = format!("{}/curso/{}", 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_course_content returned status {}: {}",- status,- &body_text[..body_text.len().min(300)]- ));- }-- let mut modules = Vec::new();- let mut current_module: Option<(String, Vec<AstronLesson>)> = None;- let mut module_order = 0i64;- let mut lesson_order = 0i64;-- for line in body_text.lines() {- let trimmed = line.trim();-- if trimmed.contains("<dt") {- if let Some((name, lessons)) = current_module.take() {- modules.push(AstronModule {- id: format!("mod-{}", module_order),- name,- order: module_order,- lessons,- });- }- module_order += 1;- lesson_order = 0;- let mod_name = extract_text_content(trimmed)- .unwrap_or_else(|| format!("Module {}", module_order));- current_module = Some((mod_name, Vec::new()));- }-- if trimmed.contains("aulabox") && trimmed.contains("href=") {- if let Some(href) = extract_attr(trimmed, "href") {- lesson_order += 1;- let lesson_id = href.rsplit('/').next().unwrap_or(&href).to_string();- let lesson_name = extract_text_content(trimmed)- .unwrap_or_else(|| format!("Lesson {}", lesson_order));- let full_url = if href.starts_with("http") {- href- } else {- format!("{}{}", session.site_url, href)- };- if let Some(ref mut m) = current_module {- m.1.push(AstronLesson {- id: lesson_id,- name: lesson_name,- order: lesson_order,- url: full_url,- });- }- }- }- }-- if let Some((name, lessons)) = current_module.take() {- modules.push(AstronModule {- id: format!("mod-{}", module_order),- name,- order: module_order,- lessons,- });- }-- Ok(modules)-}--pub async fn get_lesson_video_url(- session: &AstronSession,- lesson_url: &str,-) -> anyhow::Result<(Option<String>, Option<String>)> {- let resp = session.client.get(lesson_url).send().await?;- let body = resp.text().await?;-- let mut video_url = None;-- if let Some(pos) = body.find("streaming-video-url") {- let rest = &body[pos..];- if let Some(src) = extract_attr(rest, "src") {- if src.contains("panda") {- video_url = Some(convert_panda_url(&src));- } else {- video_url = Some(src);- }- }- }-- if video_url.is_none() {- for line in body.lines() {- let trimmed = line.trim();- if trimmed.contains("<iframe") {- if let Some(src) = extract_attr(trimmed, "src") {- if src.contains("youtube") || src.contains("vimeo") || src.contains("player") || src.contains("panda") || src.contains("embed") {- if src.contains("panda") {- video_url = Some(convert_panda_url(&src));- } else {- video_url = Some(src);- }- break;- }- }- }- }- }-- if video_url.is_none() {- if let Some(pos) = body.find("__NEXT_DATA__") {- let rest = &body[pos..];- if let Some(start) = rest.find('{') {- let json_str = &rest[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(url) = extract_video_from_next_data(&data) {- video_url = Some(url);- }- }- }- }- }- }-- let description = extract_lesson_description(&body);-- Ok((video_url, description))-}--fn extract_lesson_description(html: &str) -> Option<String> {- if let Some(start) = html.find("class=\"conteudo-aula\"").or_else(|| html.find("class=\"lesson-content\"")).or_else(|| html.find("class=\"aula-conteudo\"")) {- let rest = &html[start..];- if let Some(tag_end) = rest.find('>') {- let content = &rest[tag_end + 1..];- if let Some(end) = content.find("</div>") {- let text = content[..end].trim();- if !text.is_empty() {- return Some(text.to_string());- }- }- }- }- None-}--fn convert_panda_url(url: &str) -> String {- url.to_string()-}--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_video_from_next_data(data: &serde_json::Value) -> Option<String> {- if let Some(url) = data.get("videoUrl").and_then(|v| v.as_str()) {- return Some(url.to_string());- }- if let Some(props) = data.get("props") {- if let Some(page_props) = props.get("pageProps") {- if let Some(url) = page_props.get("videoUrl").and_then(|v| v.as_str()) {- return Some(url.to_string());- }- }- }- None-}--fn extract_attr(html: &str, attr: &str) -> Option<String> {- let pattern = format!("{}=\"", attr);- if let Some(pos) = html.find(&pattern) {- let rest = &html[pos + pattern.len()..];- if let Some(end) = rest.find('"') {- return Some(rest[..end].to_string());- }- }- let pattern2 = format!("{}='", attr);- if let Some(pos) = html.find(&pattern2) {- let rest = &html[pos + pattern2.len()..];- if let Some(end) = rest.find('\'') {- return Some(rest[..end].to_string());- }- }- None-}--fn extract_text_content(html: &str) -> Option<String> {- if let Some(pos) = html.rfind('>') {- let rest = &html[pos + 1..];- if let Some(end) = rest.find('<') {- let text = rest[..end].trim().to_string();- if !text.is_empty() {- return Some(text);- }- }- }- None-}--pub async fn save_session(session: &AstronSession) -> 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!("[astron] session saved");- Ok(())-}--pub async fn load_session() -> anyhow::Result<Option<AstronSession>> {- 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!("[astron] session loaded");-- Ok(Some(AstronSession {- 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/src/platforms/astronmembers/downloader.rs b/src-tauri/src/platforms/astronmembers/downloader.rsdeleted file mode 100644index 8763d926..00000000--- a/src-tauri/src/platforms/astronmembers/downloader.rs+++ /dev/null@@ -1,281 +0,0 @@-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 crate::core::filename;--use super::api::{self, AstronCourse, AstronSession};--#[derive(Debug, Clone, serde::Serialize)]-pub struct AstronDownloadProgress {- 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: &AstronSession,- course: &AstronCourse,- 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 crate::core::course_utils::is_course_complete(&course_dir) {- tracing::info!("[astron] 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",- &AstronDownloadProgress {- 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_url_opt, description) = match api::get_lesson_video_url(session, &lesson.url).await {- Ok(result) => result,- Err(e) => {- tracing::error!("[astron] Failed to get video URL for '{}': {}", lesson.name, e);- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AstronDownloadProgress {- 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) = description {- let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);- tokio::fs::create_dir_all(&lesson_desc_dir).await?;- crate::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();- }-- let video_url = match video_url_opt {- Some(url) => url,- None => {- tracing::warn!("[astron] No video found for lesson '{}'", lesson.name);- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AstronDownloadProgress {- 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!("[astron] Skipping existing: {}", video_path);- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AstronDownloadProgress {- 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!("[astron] 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!("[astron] yt-dlp download failed for '{}': {}", lesson.name, e);- }- }- }-- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &AstronDownloadProgress {- 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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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/src/platforms/astronmembers/mod.rs b/src-tauri/src/platforms/astronmembers/mod.rsdeleted file mode 100644index 78f428c5..00000000--- a/src-tauri/src/platforms/astronmembers/mod.rs+++ /dev/null@@ -1,63 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};-use crate::platforms::traits::PlatformDownloader;--pub struct AstronMembersDownloader;--impl AstronMembersDownloader {- pub fn new() -> Self {- Self- }-}--impl Default for AstronMembersDownloader {- fn default() -> Self {- Self::new()- }-}--#[async_trait]-impl PlatformDownloader for AstronMembersDownloader {- fn name(&self) -> &str {- "astronmembers"- }-- 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 == "astronmembers.com"- || host.ends_with(".astronmembers.com");- }- }- false- }-- async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {- Ok(MediaInfo {- title: "Astron Members".to_string(),- author: String::new(),- platform: "astronmembers".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 Astron Members"))- }-}diff --git a/src-tauri/src/platforms/cademi/api.rs b/src-tauri/src/platforms/cademi/api.rsdeleted file mode 100644index ebf91d62..00000000--- a/src-tauri/src/platforms/cademi/api.rs+++ /dev/null@@ -1,459 +0,0 @@-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 CademiSession {- 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 CademiCourse {- pub id: String,- pub name: String,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct CademiModule {- pub id: String,- pub name: String,- pub order: i64,- pub lessons: Vec<CademiLesson>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct CademiLesson {- pub id: String,- pub name: String,- pub order: i64,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct CademiLessonDetail {- pub id: String,- pub name: String,- pub video_url: Option<String>,- pub description: Option<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!("app_v4_session={}", cookies))?,- );- headers.insert(- "Referer",- HeaderValue::from_str(&format!("{}/", site_url))?,- );-- let client = crate::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("cademi_session.json"))-}--pub async fn authenticate(- email: &str,- password: &str,- site_url: &str,-) -> anyhow::Result<CademiSession> {- let temp_client = crate::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!("{}/login", 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_input_value(&login_html, "_token")- .ok_or_else(|| anyhow!("Could not find CSRF token on login page"))?;-- let form_url = format!("{}/acesso", site_url.trim_end_matches('/'));- let resp = temp_client- .post(&form_url)- .form(&[- ("_token", csrf_token.as_str()),- ("Acesso[email]", email),- ("Acesso[senha]", password),- ])- .send()- .await?;-- let status = resp.status();- let resp_url = resp.url().to_string();- let _body = resp.text().await?;-- if resp_url.contains("/login") || resp_url.contains("/acesso") {- if !status.is_success() && !status.is_redirection() {- return Err(anyhow!("Authentication failed (status {})", status));- }- return Err(anyhow!("Authentication failed - invalid credentials"));- }-- let area_resp = temp_client- .get(&format!("{}/area/vitrine", site_url.trim_end_matches('/')))- .send()- .await?;-- if !area_resp.status().is_success() {- return Err(anyhow!("Authentication failed - cannot access member area"));- }-- let cookies_header = area_resp- .headers()- .get_all("set-cookie")- .iter()- .filter_map(|v| v.to_str().ok())- .filter_map(|s| {- if s.contains("app_v4_session=") {- let start = s.find("app_v4_session=")? + 15;- 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(CademiSession {- cookies: session_cookie,- site_url: site_url.trim_end_matches('/').to_string(),- client,- })-}--pub async fn validate_token(session: &CademiSession) -> anyhow::Result<bool> {- let url = format!("{}/area/vitrine", session.site_url);- let resp = session.client.get(&url).send().await?;-- Ok(resp.status().is_success())-}--pub async fn list_courses(session: &CademiSession) -> anyhow::Result<Vec<CademiCourse>> {- let url = format!("{}/area/vitrine", session.site_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 mut courses = Vec::new();- let re = regex::Regex::new(r#"/area/produto/(\d+)"#)?;-- for cap in re.captures_iter(&body_text) {- let id = cap[1].to_string();-- if courses.iter().any(|c: &CademiCourse| c.id == id) {- continue;- }-- let name_re = regex::Regex::new(&format!(- r#"/area/produto/{}[^>]*>([^<]+)"#,- regex::escape(&id)- ))?;-- let name = name_re- .captures(&body_text)- .and_then(|c| Some(c[1].trim().to_string()))- .unwrap_or_else(|| format!("Course {}", id));-- courses.push(CademiCourse { id, name });- }-- Ok(courses)-}--pub async fn get_modules(- session: &CademiSession,- course_id: &str,-) -> anyhow::Result<Vec<CademiModule>> {- let url = format!("{}/area/produto/{}", session.site_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_modules returned status {}: {}",- status,- &body_text[..body_text.len().min(300)]- ));- }-- let mut modules = Vec::new();-- let section_re = regex::Regex::new(- r#"(?s)data-secao-id="(\d+)"[^>]*>.*?<[^>]*class="[^"]*section-title[^"]*"[^>]*>([^<]+)"#- )?;-- let lesson_re = regex::Regex::new(- r#"/area/produto/item/(\d+)[^>]*>([^<]+)"#- )?;-- 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_name = cap[2].trim().to_string();-- if lessons.iter().any(|l: &CademiLesson| l.id == lesson_id) {- continue;- }-- lessons.push(CademiLesson {- id: lesson_id,- name: lesson_name,- order: i as i64,- });- }-- if !lessons.is_empty() {- modules.push(CademiModule {- id: "0".to_string(),- name: "Content".to_string(),- order: 0,- lessons,- });- }- } else {- for (section_id, section_name, idx) in §ions {- let section_start = body_text- .find(&format!("data-secao-id=\"{}\"", section_id))- .unwrap_or(0);-- let section_end = if idx + 1 < sections.len() {- body_text- .find(&format!("data-secao-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_name = cap[2].trim().to_string();-- if lessons.iter().any(|l: &CademiLesson| l.id == lesson_id) {- continue;- }-- lessons.push(CademiLesson {- id: lesson_id,- name: lesson_name,- order: i as i64,- });- }-- modules.push(CademiModule {- id: section_id.clone(),- name: section_name.clone(),- order: *idx as i64,- lessons,- });- }- }-- Ok(modules)-}--pub async fn get_lesson_detail(- session: &CademiSession,- lesson_id: &str,-) -> anyhow::Result<CademiLessonDetail> {- let url = format!("{}/area/produto/item/{}", session.site_url, 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 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 mut video_url: Option<String> = None;-- let panda_re = regex::Regex::new(r#"(?s)pandavideo[^>]*src="([^"]+)""#)?;- 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("pandavideo")- || src.contains("youtube")- || src.contains("vimeo")- || 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());- }- }-- if video_url.is_none() {- let source_re = regex::Regex::new(r#"<source[^>]+src="([^"]+\.(?:mp4|m3u8)[^"]*)""#)?;- if let Some(cap) = source_re.captures(&body_text) {- video_url = Some(cap[1].to_string());- }- }-- let mut description: Option<String> = None;- let article_re = regex::Regex::new(r#"(?s)<article[^>]*>(.*?)</article>"#)?;- if let Some(cap) = article_re.captures(&body_text) {- let text = cap[1].trim();- if !text.is_empty() {- description = Some(text.to_string());- }- }- if description.is_none() {- let content_re = regex::Regex::new(r#"(?s)class="conteudo-aula"[^>]*>(.*?)</div>"#)?;- if let Some(cap) = content_re.captures(&body_text) {- let text = cap[1].trim();- if !text.is_empty() {- description = Some(text.to_string());- }- }- }-- Ok(CademiLessonDetail {- id: lesson_id.to_string(),- name,- video_url,- description,- })-}--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: &CademiSession) -> 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!("[cademi] session saved for {}", session.site_url);- Ok(())-}--pub async fn load_session() -> anyhow::Result<Option<CademiSession>> {- 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!("[cademi] session loaded for {}", saved.site_url);-- Ok(Some(CademiSession {- 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/src/platforms/cademi/downloader.rs b/src-tauri/src/platforms/cademi/downloader.rsdeleted file mode 100644index 9bb248c1..00000000--- a/src-tauri/src/platforms/cademi/downloader.rs+++ /dev/null@@ -1,263 +0,0 @@-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 crate::core::filename;--use super::api::{self, CademiCourse, CademiSession};--#[derive(Debug, Clone, serde::Serialize)]-pub struct CademiCourseDownloadProgress {- 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: &CademiSession,- course: &CademiCourse,- 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 crate::core::course_utils::is_course_complete(&course_dir) {- tracing::info!("[cademi] 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",- &CademiCourseDownloadProgress {- 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!(- "[cademi] Failed to get lesson detail '{}': {}. Continuing...",- lesson.name,- e- );- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &CademiCourseDownloadProgress {- 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?;- crate::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();- }-- if let Some(ref video_url) = detail.video_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!("[cademi] Skipping existing: {}", video_path);- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &CademiCourseDownloadProgress {- 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!(- "[cademi] 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!(- "[cademi] Direct download also failed for '{}': {}",- lesson.name,- e2- );- }- }- }- }- }-- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &CademiCourseDownloadProgress {- 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"));- }-- crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/cademi/mod.rs b/src-tauri/src/platforms/cademi/mod.rsdeleted file mode 100644index 24fca0b8..00000000--- a/src-tauri/src/platforms/cademi/mod.rs+++ /dev/null@@ -1,68 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};-use crate::platforms::traits::PlatformDownloader;--pub struct CademiDownloader;--impl Default for CademiDownloader {- fn default() -> Self {- Self::new()- }-}--impl CademiDownloader {- pub fn new() -> Self {- Self- }-}--#[async_trait]-impl PlatformDownloader for CademiDownloader {- fn name(&self) -> &str {- "cademi"- }-- 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 == "cademi.com.br" || host.ends_with(".cademi.com.br");- }- }- false- }-- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {- Ok(MediaInfo {- title: "Cademi".to_string(),- author: String::new(),- platform: "cademi".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 Cademi"))- }-}diff --git a/src-tauri/src/platforms/cakto/api.rs b/src-tauri/src/platforms/cakto/api.rsdeleted file mode 100644index 9c16d0ea..00000000--- a/src-tauri/src/platforms/cakto/api.rs+++ /dev/null@@ -1,417 +0,0 @@-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://aluno.cakto.com.br";--#[derive(Clone)]-pub struct CaktoSession {- pub cookie: String,- pub client: reqwest::Client,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct SavedSession {- pub cookie: String,- pub saved_at: u64,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct CaktoCourse {- pub id: String,- pub name: String,- pub image_url: Option<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct CaktoModule {- pub id: String,- pub name: String,- pub order: i64,- pub lessons: Vec<CaktoLesson>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct CaktoLesson {- pub id: String,- pub name: String,- pub order: i64,- pub video_url: Option<String>,- pub files: Vec<CaktoFile>,- pub description: Option<String>,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct CaktoFile {- pub id: String,- pub name: String,- pub url: Option<String>,-}--fn build_client(cookie: &str) -> anyhow::Result<reqwest::Client> {- let mut headers = HeaderMap::new();- headers.insert(- "Cookie",- HeaderValue::from_str(&format!("__Secure-better-auth.session_token={}", cookie))?,- );- 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 = crate::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("cakto_session.json"))-}--pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<CaktoSession> {- let temp_client = crate::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,- "callbackURL": "/app",- });-- let resp = temp_client- .post(format!("{}/api/auth/sign-in/email", API_BASE))- .json(&payload)- .send()- .await?;-- let status = resp.status();-- let mut cookie_value = String::new();- for cookie in resp.cookies() {- if cookie.name().contains("better-auth.session_token") {- cookie_value = cookie.value().to_string();- break;- }- }-- if cookie_value.is_empty() {- let body_text = resp.text().await.unwrap_or_default();- if !status.is_success() {- return Err(anyhow!(- "Authentication failed (status {}): {}",- status,- &body_text[..body_text.len().min(300)]- ));- }-- if let Ok(body) = serde_json::from_str::<serde_json::Value>(&body_text) {- if let Some(token) = body.get("token").and_then(|v| v.as_str()) {- cookie_value = token.to_string();- } else if let Some(session) = body.get("session") {- if let Some(token) = session.get("token").and_then(|v| v.as_str()) {- cookie_value = token.to_string();- }- }- }-- if cookie_value.is_empty() {- return Err(anyhow!("No session token received from login"));- }- }-- let client = build_client(&cookie_value)?;-- Ok(CaktoSession {- cookie: cookie_value,- client,- })-}--pub async fn validate_token(session: &CaktoSession) -> anyhow::Result<bool> {- let url = format!("{}/api/user/courses?page=1&limit=1", API_BASE);- let resp = session.client.get(&url).send().await?;- Ok(resp.status().is_success())-}--pub async fn list_courses(session: &CaktoSession) -> anyhow::Result<Vec<CaktoCourse>> {- let mut all_courses = Vec::new();- let mut page = 1u32;-- loop {- let url = format!("{}/api/user/courses?page={}&limit=50", API_BASE, 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("courses")- .or_else(|| body.get("data"))- .and_then(|v| v.as_array())- .cloned()- .unwrap_or_default();-- if courses_arr.is_empty() {- break;- }-- for item in &courses_arr {- let id = item- .get("courseId")- .or_else(|| item.get("id"))- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let name = item- .get("title")- .or_else(|| item.get("name"))- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- let image_url = item- .get("image")- .or_else(|| item.get("thumbnail"))- .and_then(|v| v.as_str())- .map(String::from);-- if !id.is_empty() {- all_courses.push(CaktoCourse {- id,- name,- image_url,- });- }- }-- page += 1;- if courses_arr.len() < 50 {- break;- }- }-- Ok(all_courses)-}--pub async fn get_course_content(- session: &CaktoSession,- course_id: &str,-) -> anyhow::Result<Vec<CaktoModule>> {- let url = format!("{}/api/courses/{}", 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 course_data = body.get("course").unwrap_or(&body);-- let modules_arr = course_data- .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_str())- .unwrap_or("")- .to_string();-- let mod_name = module_val- .get("title")- .or_else(|| module_val.get("name"))- .and_then(|v| v.as_str())- .unwrap_or("")- .to_string();-- 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_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 video_url = lesson_val- .get("videoUrl")- .or_else(|| lesson_val.get("video_url"))- .and_then(|v| v.as_str())- .map(String::from);-- let files = lesson_val- .get("files")- .and_then(|v| v.as_array())- .map(|arr| {- arr.iter()- .map(|f| {- let fid = f.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();- let fname = f.get("name").and_then(|v| v.as_str()).unwrap_or("file").to_string();- let furl = f.get("url").and_then(|v| v.as_str()).map(String::from);- CaktoFile { id: fid, name: fname, url: furl }- })- .collect()- })- .unwrap_or_default();-- 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(CaktoLesson {- id: if lesson_id.is_empty() { format!("{}", li) } else { lesson_id },- name: lesson_name,- order: li as i64,- video_url,- files,- description,- });- }-- modules.push(CaktoModule {- id: if mod_id.is_empty() { format!("{}", mi) } else { mod_id },- name: mod_name,- order: mi as i64,- lessons,- });- }-- Ok(modules)-}--pub async fn get_file_download_url(- session: &CaktoSession,- lesson_id: &str,- file_id: &str,-) -> anyhow::Result<String> {- let url = format!("{}/api/lessons/{}/files/{}/download", API_BASE, lesson_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: &CaktoSession) -> 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(),- 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!("[cakto] session saved");- Ok(())-}--pub async fn load_session() -> anyhow::Result<Option<CaktoSession>> {- 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)?;-- tracing::info!("[cakto] session loaded");-- Ok(Some(CaktoSession {- cookie: saved.cookie,- 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/src/platforms/cakto/downloader.rs b/src-tauri/src/platforms/cakto/downloader.rsdeleted file mode 100644index fc49ff86..00000000--- a/src-tauri/src/platforms/cakto/downloader.rs+++ /dev/null@@ -1,270 +0,0 @@-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 crate::core::filename;--use super::api::{self, CaktoCourse, CaktoSession};--#[derive(Debug, Clone, serde::Serialize)]-pub struct CaktoDownloadProgress {- 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: &CaktoSession,- course: &CaktoCourse,- 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 crate::core::course_utils::is_course_complete(&course_dir) {- tracing::info!("[cakto] 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",- &CaktoDownloadProgress {- 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 {- crate::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();- }-- if let Some(ref video_url) = lesson.video_url {- if !video_url.is_empty() {- 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!("[cakto] Skipping existing: {}", video_path);- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &CaktoDownloadProgress {- 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!(- "[cakto] yt-dlp download 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!("[cakto] Direct download also failed for '{}': {}", lesson.name, e2);- }- }- }- }- }- }-- for file in &lesson.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, &lesson.id, &file.id).await {- Ok(url) => url,- Err(e) => {- tracing::error!("[cakto] 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!("[cakto] File download failed for '{}': {}", file.name, e);- }- }- }-- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;- let _ = app.emit(- "download-progress",- &CaktoDownloadProgress {- 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"));- }-- crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::core::ytdlp::download_video(- &ytdlp_path,- url,- out_dir,- None,- tx,- None,- None,- None,- Some("https://aluno.cakto.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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/cakto/mod.rs b/src-tauri/src/platforms/cakto/mod.rsdeleted file mode 100644index 847ac0cd..00000000--- a/src-tauri/src/platforms/cakto/mod.rs+++ /dev/null@@ -1,70 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/caktomembers/api.rs b/src-tauri/src/platforms/caktomembers/api.rsdeleted file mode 100644index 7884013b..00000000--- a/src-tauri/src/platforms/caktomembers/api.rs+++ /dev/null@@ -1,408 +0,0 @@-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 = crate::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 = crate::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/src/platforms/caktomembers/downloader.rs b/src-tauri/src/platforms/caktomembers/downloader.rsdeleted file mode 100644index 11daf5c9..00000000--- a/src-tauri/src/platforms/caktomembers/downloader.rs+++ /dev/null@@ -1,275 +0,0 @@-use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};-use std::sync::Arc;--use anyhow::anyhow;-use tauri::Emitter;-use tokio_util::sync::CancellationToken;--use crate::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 crate::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?;- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = std::path::Path::new(output_dir);- let (tx, _rx) = tokio::sync::mpsc::channel(8);-- let result = crate::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/src/platforms/caktomembers/mod.rs b/src-tauri/src/platforms/caktomembers/mod.rsdeleted file mode 100644index 23f00b5f..00000000--- a/src-tauri/src/platforms/caktomembers/mod.rs+++ /dev/null@@ -1,68 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/curseduca/api.rs b/src-tauri/src/platforms/curseduca/api.rsdeleted file mode 100644index 7957d97a..00000000--- a/src-tauri/src/platforms/curseduca/api.rs+++ /dev/null@@ -1,514 +0,0 @@-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 = crate::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 = crate::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 = crate::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/src/platforms/curseduca/downloader.rs b/src-tauri/src/platforms/curseduca/downloader.rsdeleted file mode 100644index df3f9505..00000000--- a/src-tauri/src/platforms/curseduca/downloader.rs+++ /dev/null@@ -1,279 +0,0 @@-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 crate::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 crate::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?;- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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/src/platforms/curseduca/mod.rs b/src-tauri/src/platforms/curseduca/mod.rsdeleted file mode 100644index 2ddbf8c2..00000000--- a/src-tauri/src/platforms/curseduca/mod.rs+++ /dev/null@@ -1,70 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/datascienceacademy/api.rs b/src-tauri/src/platforms/datascienceacademy/api.rsdeleted file mode 100644index ea9be4b7..00000000--- a/src-tauri/src/platforms/datascienceacademy/api.rs+++ /dev/null@@ -1,402 +0,0 @@-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 = crate::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/src/platforms/datascienceacademy/downloader.rs b/src-tauri/src/platforms/datascienceacademy/downloader.rsdeleted file mode 100644index c98c10ef..00000000--- a/src-tauri/src/platforms/datascienceacademy/downloader.rs+++ /dev/null@@ -1,228 +0,0 @@-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 crate::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 crate::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?;- crate::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"));- }-- crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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/src/platforms/datascienceacademy/mod.rs b/src-tauri/src/platforms/datascienceacademy/mod.rsdeleted file mode 100644index 751ba2fe..00000000--- a/src-tauri/src/platforms/datascienceacademy/mod.rs+++ /dev/null@@ -1,69 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/eduzznutror/api.rs b/src-tauri/src/platforms/eduzznutror/api.rsdeleted file mode 100644index bc75c337..00000000--- a/src-tauri/src/platforms/eduzznutror/api.rs+++ /dev/null@@ -1,582 +0,0 @@-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 = crate::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 = crate::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/src/platforms/eduzznutror/downloader.rs b/src-tauri/src/platforms/eduzznutror/downloader.rsdeleted file mode 100644index 06eaf29b..00000000--- a/src-tauri/src/platforms/eduzznutror/downloader.rs+++ /dev/null@@ -1,349 +0,0 @@-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 crate::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 crate::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 {- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/eduzznutror/mod.rs b/src-tauri/src/platforms/eduzznutror/mod.rsdeleted file mode 100644index 84b3cc35..00000000--- a/src-tauri/src/platforms/eduzznutror/mod.rs+++ /dev/null@@ -1,65 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/entregadigital/api.rs b/src-tauri/src/platforms/entregadigital/api.rsdeleted file mode 100644index b0d60271..00000000--- a/src-tauri/src/platforms/entregadigital/api.rs+++ /dev/null@@ -1,437 +0,0 @@-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 = crate::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/src/platforms/entregadigital/downloader.rs b/src-tauri/src/platforms/entregadigital/downloader.rsdeleted file mode 100644index 84a914aa..00000000--- a/src-tauri/src/platforms/entregadigital/downloader.rs+++ /dev/null@@ -1,348 +0,0 @@-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 crate::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 crate::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 {- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/entregadigital/mod.rs b/src-tauri/src/platforms/entregadigital/mod.rsdeleted file mode 100644index 05059046..00000000--- a/src-tauri/src/platforms/entregadigital/mod.rs+++ /dev/null@@ -1,63 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/estrategia_concursos/api.rs b/src-tauri/src/platforms/estrategia_concursos/api.rsdeleted file mode 100644index 45c71327..00000000--- a/src-tauri/src/platforms/estrategia_concursos/api.rs+++ /dev/null@@ -1,424 +0,0 @@-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 = crate::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/src/platforms/estrategia_concursos/downloader.rs b/src-tauri/src/platforms/estrategia_concursos/downloader.rsdeleted file mode 100644index 188b272b..00000000--- a/src-tauri/src/platforms/estrategia_concursos/downloader.rs+++ /dev/null@@ -1,347 +0,0 @@-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 crate::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 crate::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();- crate::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"));- }-- crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/estrategia_concursos/mod.rs b/src-tauri/src/platforms/estrategia_concursos/mod.rsdeleted file mode 100644index b2a1988e..00000000--- a/src-tauri/src/platforms/estrategia_concursos/mod.rs+++ /dev/null@@ -1,73 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/estrategia_ldi/api.rs b/src-tauri/src/platforms/estrategia_ldi/api.rsdeleted file mode 100644index d2c2d121..00000000--- a/src-tauri/src/platforms/estrategia_ldi/api.rs+++ /dev/null@@ -1,682 +0,0 @@-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 = crate::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/src/platforms/estrategia_ldi/downloader.rs b/src-tauri/src/platforms/estrategia_ldi/downloader.rsdeleted file mode 100644index c8569c6a..00000000--- a/src-tauri/src/platforms/estrategia_ldi/downloader.rs+++ /dev/null@@ -1,387 +0,0 @@-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 crate::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 crate::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() {- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::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/src/platforms/estrategia_ldi/mod.rs b/src-tauri/src/platforms/estrategia_ldi/mod.rsdeleted file mode 100644index 195fda09..00000000--- a/src-tauri/src/platforms/estrategia_ldi/mod.rs+++ /dev/null@@ -1,68 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/estrategia_militares/api.rs b/src-tauri/src/platforms/estrategia_militares/api.rsdeleted file mode 100644index e3b219c8..00000000--- a/src-tauri/src/platforms/estrategia_militares/api.rs+++ /dev/null@@ -1,811 +0,0 @@-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 = crate::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/src/platforms/estrategia_militares/downloader.rs b/src-tauri/src/platforms/estrategia_militares/downloader.rsdeleted file mode 100644index 3fc7afb0..00000000--- a/src-tauri/src/platforms/estrategia_militares/downloader.rs+++ /dev/null@@ -1,410 +0,0 @@-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 crate::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 crate::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() {- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/estrategia_militares/mod.rs b/src-tauri/src/platforms/estrategia_militares/mod.rsdeleted file mode 100644index 2d610d61..00000000--- a/src-tauri/src/platforms/estrategia_militares/mod.rs+++ /dev/null@@ -1,68 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/fluencyacademy/api.rs b/src-tauri/src/platforms/fluencyacademy/api.rsdeleted file mode 100644index c8478209..00000000--- a/src-tauri/src/platforms/fluencyacademy/api.rs+++ /dev/null@@ -1,516 +0,0 @@-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 = crate::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 = crate::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/src/platforms/fluencyacademy/downloader.rs b/src-tauri/src/platforms/fluencyacademy/downloader.rsdeleted file mode 100644index 17de364a..00000000--- a/src-tauri/src/platforms/fluencyacademy/downloader.rs+++ /dev/null@@ -1,320 +0,0 @@-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 crate::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 crate::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?;- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/fluencyacademy/mod.rs b/src-tauri/src/platforms/fluencyacademy/mod.rsdeleted file mode 100644index d76f1899..00000000--- a/src-tauri/src/platforms/fluencyacademy/mod.rs+++ /dev/null@@ -1,69 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/grancursos/api.rs b/src-tauri/src/platforms/grancursos/api.rsdeleted file mode 100644index 8d7891db..00000000--- a/src-tauri/src/platforms/grancursos/api.rs+++ /dev/null@@ -1,450 +0,0 @@-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 = crate::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/src/platforms/grancursos/downloader.rs b/src-tauri/src/platforms/grancursos/downloader.rsdeleted file mode 100644index 29bda6da..00000000--- a/src-tauri/src/platforms/grancursos/downloader.rs+++ /dev/null@@ -1,311 +0,0 @@-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 crate::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 crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/grancursos/mod.rs b/src-tauri/src/platforms/grancursos/mod.rsdeleted file mode 100644index 1deb46fc..00000000--- a/src-tauri/src/platforms/grancursos/mod.rs+++ /dev/null@@ -1,69 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/greatcourses/api.rs b/src-tauri/src/platforms/greatcourses/api.rsdeleted file mode 100644index 17dfb601..00000000--- a/src-tauri/src/platforms/greatcourses/api.rs+++ /dev/null@@ -1,396 +0,0 @@-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 = crate::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 = crate::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/src/platforms/greatcourses/downloader.rs b/src-tauri/src/platforms/greatcourses/downloader.rsdeleted file mode 100644index be3b85f2..00000000--- a/src-tauri/src/platforms/greatcourses/downloader.rs+++ /dev/null@@ -1,279 +0,0 @@-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 crate::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 crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/greatcourses/mod.rs b/src-tauri/src/platforms/greatcourses/mod.rsdeleted file mode 100644index 18375b53..00000000--- a/src-tauri/src/platforms/greatcourses/mod.rs+++ /dev/null@@ -1,71 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/greennclub/api.rs b/src-tauri/src/platforms/greennclub/api.rsdeleted file mode 100644index 23bc726e..00000000--- a/src-tauri/src/platforms/greennclub/api.rs+++ /dev/null@@ -1,396 +0,0 @@-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 = crate::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¤t_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/src/platforms/greennclub/downloader.rs b/src-tauri/src/platforms/greennclub/downloader.rsdeleted file mode 100644index 31a59db1..00000000--- a/src-tauri/src/platforms/greennclub/downloader.rs+++ /dev/null@@ -1,342 +0,0 @@-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 crate::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 crate::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 {- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/greennclub/mod.rs b/src-tauri/src/platforms/greennclub/mod.rsdeleted file mode 100644index 994b0ad0..00000000--- a/src-tauri/src/platforms/greennclub/mod.rs+++ /dev/null@@ -1,63 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/gumroad/api.rs b/src-tauri/src/platforms/gumroad/api.rsdeleted file mode 100644index 59785ef3..00000000--- a/src-tauri/src/platforms/gumroad/api.rs+++ /dev/null@@ -1,353 +0,0 @@-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 = crate::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 = crate::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(¶ms)- .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/src/platforms/gumroad/downloader.rs b/src-tauri/src/platforms/gumroad/downloader.rsdeleted file mode 100644index 33b26691..00000000--- a/src-tauri/src/platforms/gumroad/downloader.rs+++ /dev/null@@ -1,245 +0,0 @@-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 crate::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 crate::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"));- }-- crate::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 = crate::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 = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/gumroad/mod.rs b/src-tauri/src/platforms/gumroad/mod.rsdeleted file mode 100644index b4ce6c96..00000000--- a/src-tauri/src/platforms/gumroad/mod.rs+++ /dev/null@@ -1,68 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/hotmart/api.rs b/src-tauri/src/platforms/hotmart/api.rsdeleted file mode 100644index a58bb513..00000000--- a/src-tauri/src/platforms/hotmart/api.rs+++ /dev/null@@ -1,491 +0,0 @@-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/src/platforms/hotmart/auth.rs b/src-tauri/src/platforms/hotmart/auth.rsdeleted file mode 100644index 5e30f19d..00000000--- a/src-tauri/src/platforms/hotmart/auth.rs+++ /dev/null@@ -1,456 +0,0 @@-#[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 = crate::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/src/platforms/hotmart/downloader.rs b/src-tauri/src/platforms/hotmart/downloader.rsdeleted file mode 100644index 83860861..00000000--- a/src-tauri/src/platforms/hotmart/downloader.rs+++ /dev/null@@ -1,832 +0,0 @@-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 crate::core::filename;-use crate::core::media_processor::MediaProcessor;-use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};-use crate::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 = crate::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 crate::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 crate::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 crate::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 crate::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<crate::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/src/platforms/hotmart/mod.rs b/src-tauri/src/platforms/hotmart/mod.rsdeleted file mode 100644index aea8d9ab..00000000--- a/src-tauri/src/platforms/hotmart/mod.rs+++ /dev/null@@ -1,4 +0,0 @@-pub mod auth;-pub mod api;-pub mod parser;-pub mod downloader;diff --git a/src-tauri/src/platforms/hotmart/parser.rs b/src-tauri/src/platforms/hotmart/parser.rsdeleted file mode 100644index 10fd2e84..00000000--- a/src-tauri/src/platforms/hotmart/parser.rs+++ /dev/null@@ -1,104 +0,0 @@-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/src/platforms/kajabi/api.rs b/src-tauri/src/platforms/kajabi/api.rsdeleted file mode 100644index 53226c91..00000000--- a/src-tauri/src/platforms/kajabi/api.rs+++ /dev/null@@ -1,645 +0,0 @@-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 = crate::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 = crate::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 = crate::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 = crate::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/src/platforms/kajabi/downloader.rs b/src-tauri/src/platforms/kajabi/downloader.rsdeleted file mode 100644index 3432408f..00000000--- a/src-tauri/src/platforms/kajabi/downloader.rs+++ /dev/null@@ -1,347 +0,0 @@-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 crate::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 crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/kajabi/mod.rs b/src-tauri/src/platforms/kajabi/mod.rsdeleted file mode 100644index 0cbb4002..00000000--- a/src-tauri/src/platforms/kajabi/mod.rs+++ /dev/null@@ -1,70 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/kirvano/api.rs b/src-tauri/src/platforms/kirvano/api.rsdeleted file mode 100644index b1edfabc..00000000--- a/src-tauri/src/platforms/kirvano/api.rs+++ /dev/null@@ -1,514 +0,0 @@-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 = crate::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 = crate::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/src/platforms/kirvano/downloader.rs b/src-tauri/src/platforms/kirvano/downloader.rsdeleted file mode 100644index 2e8644ea..00000000--- a/src-tauri/src/platforms/kirvano/downloader.rs+++ /dev/null@@ -1,275 +0,0 @@-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 crate::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 crate::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?;- crate::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"));- }-- crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/kirvano/mod.rs b/src-tauri/src/platforms/kirvano/mod.rsdeleted file mode 100644index d50e75fd..00000000--- a/src-tauri/src/platforms/kirvano/mod.rs+++ /dev/null@@ -1,70 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/kiwify/api.rs b/src-tauri/src/platforms/kiwify/api.rsdeleted file mode 100644index 8dbf3efc..00000000--- a/src-tauri/src/platforms/kiwify/api.rs+++ /dev/null@@ -1,672 +0,0 @@-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 = crate::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 = crate::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/src/platforms/kiwify/downloader.rs b/src-tauri/src/platforms/kiwify/downloader.rsdeleted file mode 100644index 7d78fcdb..00000000--- a/src-tauri/src/platforms/kiwify/downloader.rs+++ /dev/null@@ -1,364 +0,0 @@-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 crate::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 crate::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 {- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/kiwify/mod.rs b/src-tauri/src/platforms/kiwify/mod.rsdeleted file mode 100644index ccf13791..00000000--- a/src-tauri/src/platforms/kiwify/mod.rs+++ /dev/null@@ -1,72 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/masterclass/api.rs b/src-tauri/src/platforms/masterclass/api.rsdeleted file mode 100644index 6992511c..00000000--- a/src-tauri/src/platforms/masterclass/api.rs+++ /dev/null@@ -1,430 +0,0 @@-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 = crate::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/src/platforms/masterclass/downloader.rs b/src-tauri/src/platforms/masterclass/downloader.rsdeleted file mode 100644index fc75efeb..00000000--- a/src-tauri/src/platforms/masterclass/downloader.rs+++ /dev/null@@ -1,286 +0,0 @@-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 crate::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 crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/masterclass/mod.rs b/src-tauri/src/platforms/masterclass/mod.rsdeleted file mode 100644index 015ac3f0..00000000--- a/src-tauri/src/platforms/masterclass/mod.rs+++ /dev/null@@ -1,68 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/matematicaprapassar/mod.rs b/src-tauri/src/platforms/matematicaprapassar/mod.rsdeleted file mode 100644index 0a41eb2f..00000000--- a/src-tauri/src/platforms/matematicaprapassar/mod.rs+++ /dev/null@@ -1,65 +0,0 @@-use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/medcel/api.rs b/src-tauri/src/platforms/medcel/api.rsdeleted file mode 100644index e4214d62..00000000--- a/src-tauri/src/platforms/medcel/api.rs+++ /dev/null@@ -1,583 +0,0 @@-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 = crate::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 = crate::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/src/platforms/medcel/downloader.rs b/src-tauri/src/platforms/medcel/downloader.rsdeleted file mode 100644index 004aede9..00000000--- a/src-tauri/src/platforms/medcel/downloader.rs+++ /dev/null@@ -1,316 +0,0 @@-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 crate::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 crate::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 {- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/medcel/mod.rs b/src-tauri/src/platforms/medcel/mod.rsdeleted file mode 100644index 1bda2a68..00000000--- a/src-tauri/src/platforms/medcel/mod.rs+++ /dev/null@@ -1,72 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/medcof/api.rs b/src-tauri/src/platforms/medcof/api.rsdeleted file mode 100644index 174fc4b6..00000000--- a/src-tauri/src/platforms/medcof/api.rs+++ /dev/null@@ -1,391 +0,0 @@-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 = crate::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/src/platforms/medcof/downloader.rs b/src-tauri/src/platforms/medcof/downloader.rsdeleted file mode 100644index ed93d1a1..00000000--- a/src-tauri/src/platforms/medcof/downloader.rs+++ /dev/null@@ -1,273 +0,0 @@-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 crate::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 crate::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?;- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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/src/platforms/medcof/mod.rs b/src-tauri/src/platforms/medcof/mod.rsdeleted file mode 100644index a72ab5a4..00000000--- a/src-tauri/src/platforms/medcof/mod.rs+++ /dev/null@@ -1,69 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/medway/api.rs b/src-tauri/src/platforms/medway/api.rsdeleted file mode 100644index 4ca908e5..00000000--- a/src-tauri/src/platforms/medway/api.rs+++ /dev/null@@ -1,435 +0,0 @@-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 = crate::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/src/platforms/medway/downloader.rs b/src-tauri/src/platforms/medway/downloader.rsdeleted file mode 100644index bd1bb923..00000000--- a/src-tauri/src/platforms/medway/downloader.rs+++ /dev/null@@ -1,297 +0,0 @@-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 crate::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 crate::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?;- crate::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"));- }-- crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/medway/mod.rs b/src-tauri/src/platforms/medway/mod.rsdeleted file mode 100644index b1546e4c..00000000--- a/src-tauri/src/platforms/medway/mod.rs+++ /dev/null@@ -1,71 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/memberkit/api.rs b/src-tauri/src/platforms/memberkit/api.rsdeleted file mode 100644index 0250a8aa..00000000--- a/src-tauri/src/platforms/memberkit/api.rs+++ /dev/null@@ -1,555 +0,0 @@-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 = crate::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 = crate::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 §ions {- 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/src/platforms/memberkit/downloader.rs b/src-tauri/src/platforms/memberkit/downloader.rsdeleted file mode 100644index 7e212c48..00000000--- a/src-tauri/src/platforms/memberkit/downloader.rs+++ /dev/null@@ -1,292 +0,0 @@-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 crate::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 crate::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 {- crate::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"));- }-- crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/memberkit/mod.rs b/src-tauri/src/platforms/memberkit/mod.rsdeleted file mode 100644index 40d7cc22..00000000--- a/src-tauri/src/platforms/memberkit/mod.rs+++ /dev/null@@ -1,68 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/mod.rs b/src-tauri/src/platforms/mod.rsindex b05b71e5..598b6123 100644--- a/src-tauri/src/platforms/mod.rs+++ b/src-tauri/src/platforms/mod.rs@@ -6,10 +6,7 @@ pub mod tiktok;pub mod twitter;pub mod twitch;pub mod bluesky;-pub mod telegram;-#[cfg(not(target_os = "android"))]-pub mod hotmart;#[cfg(not(target_os = "android"))]pub mod instagram;#[cfg(not(target_os = "android"))]@@ -22,78 +19,5 @@ pub mod bilibili;pub mod vimeo;#[cfg(not(target_os = "android"))]pub mod generic_ytdlp;-#[cfg(not(target_os = "android"))]-pub mod udemy;pub mod magnet;pub mod p2p;--#[cfg(not(target_os = "android"))]-pub mod kiwify;-#[cfg(not(target_os = "android"))]-pub mod gumroad;-#[cfg(not(target_os = "android"))]-pub mod teachable;-#[cfg(not(target_os = "android"))]-pub mod kajabi;-#[cfg(not(target_os = "android"))]-pub mod skool;-#[cfg(not(target_os = "android"))]-pub mod pluralsight;-#[cfg(not(target_os = "android"))]-pub mod greatcourses;-#[cfg(not(target_os = "android"))]-pub mod masterclass;-#[cfg(not(target_os = "android"))]-pub mod thinkific;-#[cfg(not(target_os = "android"))]-pub mod curseduca;-#[cfg(not(target_os = "android"))]-pub mod cademi;-#[cfg(not(target_os = "android"))]-pub mod cakto;-#[cfg(not(target_os = "android"))]-pub mod kirvano;-#[cfg(not(target_os = "android"))]-pub mod memberkit;-#[cfg(not(target_os = "android"))]-pub mod rocketseat;-#[cfg(not(target_os = "android"))]-pub mod grancursos;-#[cfg(not(target_os = "android"))]-pub mod fluencyacademy;-#[cfg(not(target_os = "android"))]-pub mod datascienceacademy;-#[cfg(not(target_os = "android"))]-pub mod medcel;-#[cfg(not(target_os = "android"))]-pub mod medcof;-#[cfg(not(target_os = "android"))]-pub mod medway;-#[cfg(not(target_os = "android"))]-pub mod afyainternato;-#[cfg(not(target_os = "android"))]-pub mod alpaclass;-#[cfg(not(target_os = "android"))]-pub mod areademembros;-#[cfg(not(target_os = "android"))]-pub mod astronmembers;-#[cfg(not(target_os = "android"))]-pub mod eduzznutror;-#[cfg(not(target_os = "android"))]-pub mod entregadigital;-#[cfg(not(target_os = "android"))]-pub mod greennclub;-#[cfg(not(target_os = "android"))]-pub mod themembers;-#[cfg(not(target_os = "android"))]-pub mod voompplay;-#[cfg(not(target_os = "android"))]-pub mod estrategia_concursos;-#[cfg(not(target_os = "android"))]-pub mod estrategia_ldi;-#[cfg(not(target_os = "android"))]-pub mod estrategia_militares;-#[cfg(not(target_os = "android"))]-pub mod matematicaprapassar;-#[cfg(not(target_os = "android"))]-pub mod caktomembers;diff --git a/src-tauri/src/platforms/pluralsight/api.rs b/src-tauri/src/platforms/pluralsight/api.rsdeleted file mode 100644index 95d34f30..00000000--- a/src-tauri/src/platforms/pluralsight/api.rs+++ /dev/null@@ -1,361 +0,0 @@-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 = crate::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/src/platforms/pluralsight/downloader.rs b/src-tauri/src/platforms/pluralsight/downloader.rsdeleted file mode 100644index 684756cf..00000000--- a/src-tauri/src/platforms/pluralsight/downloader.rs+++ /dev/null@@ -1,276 +0,0 @@-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 crate::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 crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/pluralsight/mod.rs b/src-tauri/src/platforms/pluralsight/mod.rsdeleted file mode 100644index 5ccff274..00000000--- a/src-tauri/src/platforms/pluralsight/mod.rs+++ /dev/null@@ -1,68 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/rocketseat/api.rs b/src-tauri/src/platforms/rocketseat/api.rsdeleted file mode 100644index a0734306..00000000--- a/src-tauri/src/platforms/rocketseat/api.rs+++ /dev/null@@ -1,475 +0,0 @@-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 = crate::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/src/platforms/rocketseat/downloader.rs b/src-tauri/src/platforms/rocketseat/downloader.rsdeleted file mode 100644index 4206ef3c..00000000--- a/src-tauri/src/platforms/rocketseat/downloader.rs+++ /dev/null@@ -1,196 +0,0 @@-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 crate::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 crate::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"));- }-- crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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/src/platforms/rocketseat/mod.rs b/src-tauri/src/platforms/rocketseat/mod.rsdeleted file mode 100644index b7a6e529..00000000--- a/src-tauri/src/platforms/rocketseat/mod.rs+++ /dev/null@@ -1,69 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/skool/api.rs b/src-tauri/src/platforms/skool/api.rsdeleted file mode 100644index 5a2015b8..00000000--- a/src-tauri/src/platforms/skool/api.rs+++ /dev/null@@ -1,540 +0,0 @@-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 = crate::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 = crate::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/src/platforms/skool/downloader.rs b/src-tauri/src/platforms/skool/downloader.rsdeleted file mode 100644index e5857c37..00000000--- a/src-tauri/src/platforms/skool/downloader.rs+++ /dev/null@@ -1,295 +0,0 @@-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 crate::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 crate::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 {- crate::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"));- }-- crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/skool/mod.rs b/src-tauri/src/platforms/skool/mod.rsdeleted file mode 100644index 7f2c6631..00000000--- a/src-tauri/src/platforms/skool/mod.rs+++ /dev/null@@ -1,68 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/teachable/api.rs b/src-tauri/src/platforms/teachable/api.rsdeleted file mode 100644index 1cee250f..00000000--- a/src-tauri/src/platforms/teachable/api.rs+++ /dev/null@@ -1,575 +0,0 @@-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 = crate::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 = crate::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 = crate::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/src/platforms/teachable/downloader.rs b/src-tauri/src/platforms/teachable/downloader.rsdeleted file mode 100644index 2026a11c..00000000--- a/src-tauri/src/platforms/teachable/downloader.rs+++ /dev/null@@ -1,351 +0,0 @@-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 crate::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 crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/teachable/mod.rs b/src-tauri/src/platforms/teachable/mod.rsdeleted file mode 100644index e121ea3b..00000000--- a/src-tauri/src/platforms/teachable/mod.rs+++ /dev/null@@ -1,70 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/telegram/api.rs b/src-tauri/src/platforms/telegram/api.rsdeleted file mode 100644index 01101889..00000000--- a/src-tauri/src/platforms/telegram/api.rs+++ /dev/null@@ -1,659 +0,0 @@-use std::path::{Path, PathBuf};-use std::time::Duration;--use grammers_client::Client;-use grammers_client::grammers_tl_types as tl;-use grammers_client::types::Peer;-use grammers_tl_types::Serializable;-use serde::Serialize;-use tokio::sync::mpsc;-use tokio_util::sync::CancellationToken;--use super::auth::TelegramSessionHandle;--/// Maps a MIME type to a file extension (with leading dot).-/// Covers the most common Telegram media MIME types.-fn mime_to_ext(mime: &str) -> &'static str {- match mime {- // Video- "video/mp4" => ".mp4",- "video/x-matroska" => ".mkv",- "video/webm" => ".webm",- "video/quicktime" => ".mov",- "video/x-msvideo" => ".avi",- "video/mpeg" => ".mpeg",- "video/3gpp" => ".3gp",- "video/x-flv" => ".flv",- // Audio- "audio/mpeg" | "audio/mp3" => ".mp3",- "audio/ogg" => ".ogg",- "audio/x-opus+ogg" => ".opus",- "audio/flac" | "audio/x-flac" => ".flac",- "audio/x-wav" | "audio/wav" => ".wav",- "audio/aac" | "audio/x-aac" => ".aac",- "audio/mp4" | "audio/x-m4a" => ".m4a",- "audio/x-ms-wma" => ".wma",- // Image- "image/jpeg" => ".jpg",- "image/png" => ".png",- "image/gif" => ".gif",- "image/webp" => ".webp",- "image/bmp" => ".bmp",- "image/svg+xml" => ".svg",- "image/tiff" => ".tiff",- // Documents- "application/pdf" => ".pdf",- "application/zip" => ".zip",- "application/x-rar-compressed" | "application/vnd.rar" => ".rar",- "application/x-7z-compressed" => ".7z",- "application/gzip" | "application/x-gzip" => ".gz",- "application/x-tar" => ".tar",- "application/json" => ".json",- "application/xml" | "text/xml" => ".xml",- "text/plain" => ".txt",- "text/html" => ".html",- "text/csv" => ".csv",- "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => ".docx",- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => ".xlsx",- "application/vnd.openxmlformats-officedocument.presentationml.presentation" => ".pptx",- "application/msword" => ".doc",- "application/vnd.ms-excel" => ".xls",- "application/vnd.ms-powerpoint" => ".ppt",- "application/x-python-script" | "text/x-python" => ".py",- "application/javascript" | "text/javascript" => ".js",- // Fallback: try to extract from the subtype- other => {- if let Some(sub) = other.split('/').nth(1) {- // Common pattern: "video/mp4" → ".mp4"- // But we only return static strings, so we use a catch-all- match sub {- "mp4" => ".mp4",- "mpeg" => ".mpeg",- "ogg" => ".ogg",- "webm" => ".webm",- "flac" => ".flac",- "wav" => ".wav",- "jpeg" => ".jpg",- "png" => ".png",- "gif" => ".gif",- _ => "",- }- } else {- ""- }- }- }-}--/// Ensures a filename has a proper extension based on its MIME type.-/// If the file already has a known extension, keeps it.-/// If not, appends the MIME-derived extension.-fn ensure_extension(name: &str, mime_type: &str) -> String {- let path = Path::new(name);- if let Some(ext) = path.extension() {- let ext_str = ext.to_string_lossy().to_lowercase();- // Already has a recognized extension- let known = matches!(- ext_str.as_str(),- "mp4" | "mkv" | "webm" | "mov" | "avi" | "mpeg" | "3gp" | "flv"- | "mp3" | "ogg" | "opus" | "flac" | "wav" | "aac" | "m4a" | "wma"- | "jpg" | "jpeg" | "png" | "gif" | "webp" | "bmp" | "svg" | "tiff"- | "pdf" | "zip" | "rar" | "7z" | "gz" | "tar"- | "json" | "xml" | "txt" | "html" | "csv"- | "doc" | "docx" | "xls" | "xlsx" | "ppt" | "pptx"- | "py" | "js" | "ts" | "rs" | "go" | "c" | "cpp" | "h"- );- if known {- return name.to_string();- }- }-- // No extension or unknown extension — add from MIME type- let ext = mime_to_ext(mime_type);- if ext.is_empty() {- name.to_string()- } else {- format!("{}{}", name, ext)- }-}--fn parse_flood_wait(err: &str) -> Option<u64> {- for pattern in &["FLOOD_WAIT_", "FLOOD_PREMIUM_WAIT_"] {- if let Some(pos) = err.find(pattern) {- let after = &err[pos + pattern.len()..];- let digits: String = after.chars().take_while(|c| c.is_ascii_digit()).collect();- if let Ok(secs) = digits.parse::<u64>() {- return Some(secs);- }- }- }- None-}--async fn invoke_with_flood_wait<R>(client: &Client, request: &R) -> Result<R::Return, grammers_mtsender::InvocationError>-where- R: grammers_tl_types::RemoteCall + Serializable,-{- for attempt in 0..3u32 {- match client.invoke(request).await {- Ok(result) => return Ok(result),- Err(e) => {- let err_str = e.to_string();- if let Some(secs) = parse_flood_wait(&err_str) {- let wait = secs + 1;- tracing::warn!(- "[tg-api] FLOOD_WAIT_{} on attempt {}, waiting {}s",- secs, attempt + 1, wait- );- tokio::time::sleep(Duration::from_secs(wait)).await;- continue;- }- return Err(e);- }- }- }- client.invoke(request).await-}--#[derive(Debug, Clone, Serialize)]-pub struct TelegramChat {- pub id: i64,- pub title: String,- pub chat_type: String,-}--#[derive(Debug, Clone, Serialize)]-pub struct TelegramMediaItem {- pub message_id: i32,- pub file_name: String,- pub file_size: u64,- pub media_type: String,- pub date: i64,-}--fn media_filter(media_type: Option<&str>) -> tl::enums::MessagesFilter {- match media_type {- Some("photo") => tl::enums::MessagesFilter::InputMessagesFilterPhotos,- Some("video") => tl::enums::MessagesFilter::InputMessagesFilterVideo,- Some("document") => tl::enums::MessagesFilter::InputMessagesFilterDocument,- Some("audio") => tl::enums::MessagesFilter::InputMessagesFilterMusic,- _ => tl::enums::MessagesFilter::InputMessagesFilterEmpty,- }-}--fn extract_raw_media_info(media: &tl::enums::MessageMedia, fix_extensions: bool) -> Option<(String, u64, String)> {- match media {- tl::enums::MessageMedia::Photo(photo_media) => {- let photo = match photo_media.photo.as_ref()? {- tl::enums::Photo::Photo(p) => p,- tl::enums::Photo::Empty(_) => return None,- };- let name = format!("photo_{}.jpg", photo.id);- let size = photo.sizes.iter().filter_map(|s| match s {- tl::enums::PhotoSize::Size(ps) => Some(ps.size as u64),- _ => None,- }).max().unwrap_or(0);- Some((name, size, "photo".to_string()))- }- tl::enums::MessageMedia::Document(doc_media) => {- let doc = match doc_media.document.as_ref()? {- tl::enums::Document::Document(d) => d,- tl::enums::Document::Empty(_) => return None,- };- let raw_name = doc.attributes.iter().find_map(|attr| {- if let tl::enums::DocumentAttribute::Filename(f) = attr {- Some(f.file_name.clone())- } else {- None- }- }).unwrap_or_else(|| {- // No filename attribute — use ID + MIME extension (like tdl-master)- let ext = mime_to_ext(&doc.mime_type);- if ext.is_empty() {- format!("file_{}", doc.id)- } else {- format!("{}{}", doc.id, ext)- }- });- // Ensure files with names but missing extensions get the right one- let name = if fix_extensions {- ensure_extension(&raw_name, &doc.mime_type)- } else {- raw_name- };- let size = doc.size as u64;- let mt = if doc.mime_type.starts_with("video/") {- "video"- } else if doc.mime_type.starts_with("audio/") {- "audio"- } else if doc.mime_type.starts_with("image/") {- "photo"- } else {- "document"- };- Some((name, size, mt.to_string()))- }- _ => None,- }-}--pub async fn list_chats(- handle: &TelegramSessionHandle,-) -> anyhow::Result<Vec<TelegramChat>> {- let _t = std::time::Instant::now();- let guard = handle.lock().await;- let client = guard.client.as_ref()- .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?- .clone();- drop(guard);-- let fetch_dialogs = async {- let mut dialogs = client.iter_dialogs();- let mut chats = Vec::new();- let mut peer_hashes = std::collections::HashMap::new();-- while let Some(dialog) = dialogs.next().await.map_err(|e| anyhow::anyhow!("{}", e))? {- let peer = dialog.peer();- let chat_type = match peer {- Peer::User(_) => "private",- Peer::Group(_) => "group",- Peer::Channel(_) => "channel",- };- let title = peer.name().unwrap_or("Unknown").to_string();-- // PeerRef::from / PeerId::bare_id() can panic on peers with IDs- // outside the expected ranges (e.g. monoforums, corrupted sessions).- let peer_data = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- use grammers_client::session::defs::PeerRef;- let peer_ref = PeerRef::from(peer);- (peer_ref.id.bare_id(), peer_ref.auth.hash())- }));-- let (id, access_hash) = match peer_data {- Ok(data) => data,- Err(_) => {- tracing::warn!("[tg-api] skipping peer with unsupported ID (title={:?})", title);- continue;- }- };-- peer_hashes.insert(id, access_hash);-- chats.push(TelegramChat {- id,- title,- chat_type: chat_type.to_string(),- });- }-- Ok::<_, anyhow::Error>((chats, peer_hashes))- };-- let (chats, peer_hashes) = tokio::time::timeout(Duration::from_secs(30), fetch_dialogs)- .await- .map_err(|_| anyhow::anyhow!("Loading chats timed out — please try again"))??;-- tracing::info!("[tg-perf] list_chats completed in {:?}, loaded {} chats", _t.elapsed(), chats.len());-- let mut guard = handle.lock().await;- guard.peer_hashes = peer_hashes;- drop(guard);-- Ok(chats)-}--pub fn make_input_peer(chat_id: i64, chat_type: &str, access_hash: i64) -> tl::enums::InputPeer {- match chat_type {- "private" => tl::enums::InputPeer::User(tl::types::InputPeerUser {- user_id: chat_id,- access_hash,- }),- "group" => {- if access_hash != 0 {- tl::enums::InputPeer::Channel(tl::types::InputPeerChannel {- channel_id: chat_id,- access_hash,- })- } else {- tl::enums::InputPeer::Chat(tl::types::InputPeerChat {- chat_id,- })- }- }- "channel" => tl::enums::InputPeer::Channel(tl::types::InputPeerChannel {- channel_id: chat_id,- access_hash,- }),- _ => tl::enums::InputPeer::Empty,- }-}--async fn fetch_media_page(- client: &Client,- input_peer: &tl::enums::InputPeer,- media_type: Option<&str>,- query: &str,- offset: i32,- limit: i32,- fix_extensions: bool,-) -> anyhow::Result<Vec<TelegramMediaItem>> {- let filter = media_filter(media_type);- let request = tl::functions::messages::Search {- peer: input_peer.clone(),- q: query.to_string(),- from_id: None,- saved_peer_id: None,- saved_reaction: None,- top_msg_id: None,- filter,- min_date: 0,- max_date: 0,- offset_id: offset,- add_offset: 0,- limit,- max_id: 0,- min_id: 0,- hash: 0,- };-- let result = invoke_with_flood_wait(client, &request).await- .map_err(|e| anyhow::anyhow!("messages.Search failed: {}", e))?;-- let messages = match result {- tl::enums::messages::Messages::Messages(m) => m.messages,- tl::enums::messages::Messages::Slice(m) => m.messages,- tl::enums::messages::Messages::ChannelMessages(m) => m.messages,- tl::enums::messages::Messages::NotModified(_) => vec![],- };-- let mut items = Vec::new();- for raw_msg in messages {- let msg = match raw_msg {- tl::enums::Message::Message(m) => m,- _ => continue,- };- if let Some(raw_media) = msg.media {- if let Some((file_name, file_size, media_type_str)) = extract_raw_media_info(&raw_media, fix_extensions) {- items.push(TelegramMediaItem {- message_id: msg.id,- file_name,- file_size,- media_type: media_type_str,- date: msg.date as i64,- });- }- }- }-- Ok(items)-}--fn merge_dedup_media(results: [anyhow::Result<Vec<TelegramMediaItem>>; 4], limit: usize) -> Vec<TelegramMediaItem> {- let mut all_items = Vec::new();- for items in results.into_iter().flatten() {- all_items.extend(items);- }- let mut seen = std::collections::HashSet::new();- all_items.retain(|item| seen.insert(item.message_id));- all_items.sort_by(|a, b| b.date.cmp(&a.date));- all_items.truncate(limit);- all_items-}--pub async fn list_media(- handle: &TelegramSessionHandle,- chat_id: i64,- chat_type: &str,- media_type: Option<&str>,- offset: i32,- limit: u32,- fix_extensions: bool,-) -> anyhow::Result<Vec<TelegramMediaItem>> {- let _t = std::time::Instant::now();- let guard = handle.lock().await;- let client = guard.client.as_ref()- .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?- .clone();- let access_hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);- drop(guard);-- tracing::debug!(- "[tg-api] list_media: chat_id={}, type={}, hash={}, filter={:?}",- chat_id, chat_type, access_hash, media_type- );-- let input_peer = make_input_peer(chat_id, chat_type, access_hash);-- let fetch = async {- if media_type.is_none() {- let (photos, videos, docs, audio) = tokio::join!(- fetch_media_page(&client, &input_peer, Some("photo"), "", offset, limit as i32, fix_extensions),- fetch_media_page(&client, &input_peer, Some("video"), "", offset, limit as i32, fix_extensions),- fetch_media_page(&client, &input_peer, Some("document"), "", offset, limit as i32, fix_extensions),- fetch_media_page(&client, &input_peer, Some("audio"), "", offset, limit as i32, fix_extensions),- );- let items = merge_dedup_media([photos, videos, docs, audio], limit as usize);- return Ok(items);- }-- fetch_media_page(&client, &input_peer, media_type, "", offset, limit as i32, fix_extensions).await- .map_err(|e| anyhow::anyhow!("{}", e))- };-- let items = tokio::time::timeout(Duration::from_secs(30), fetch)- .await- .map_err(|_| anyhow::anyhow!("Loading media timed out — please try again"))??;-- tracing::info!("[tg-perf] list_media completed in {:?}, found {} items", _t.elapsed(), items.len());- Ok(items)-}--pub async fn search_media(- handle: &TelegramSessionHandle,- chat_id: i64,- chat_type: &str,- query: &str,- media_type: Option<&str>,- limit: u32,- fix_extensions: bool,-) -> anyhow::Result<Vec<TelegramMediaItem>> {- let _t = std::time::Instant::now();- let guard = handle.lock().await;- let client = guard.client.as_ref()- .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?- .clone();- let access_hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);- drop(guard);-- let input_peer = make_input_peer(chat_id, chat_type, access_hash);-- let fetch = async {- if media_type.is_none() {- let (photos, videos, docs, audio) = tokio::join!(- fetch_media_page(&client, &input_peer, Some("photo"), query, 0, limit as i32, fix_extensions),- fetch_media_page(&client, &input_peer, Some("video"), query, 0, limit as i32, fix_extensions),- fetch_media_page(&client, &input_peer, Some("document"), query, 0, limit as i32, fix_extensions),- fetch_media_page(&client, &input_peer, Some("audio"), query, 0, limit as i32, fix_extensions),- );- let items = merge_dedup_media([photos, videos, docs, audio], limit as usize);- return Ok(items);- }-- fetch_media_page(&client, &input_peer, media_type, query, 0, limit as i32, fix_extensions).await- .map_err(|e| anyhow::anyhow!("{}", e))- };-- let items = tokio::time::timeout(Duration::from_secs(30), fetch)- .await- .map_err(|_| anyhow::anyhow!("Search timed out — please try again"))??;-- tracing::info!("[tg-perf] search_media completed in {:?}, found {} items for query={:?}", _t.elapsed(), items.len(), query);- Ok(items)-}--pub async fn download_media(- handle: &TelegramSessionHandle,- chat_id: i64,- chat_type: &str,- message_id: i32,- output_path: &Path,- progress_tx: mpsc::Sender<f64>,- cancel_token: &CancellationToken,-) -> anyhow::Result<u64> {- let _t = std::time::Instant::now();- let guard = handle.lock().await;- if guard.client.is_none() {- tracing::warn!("[tg-perf] download_media: client is None (not authenticated)");- }- let client = guard.client.as_ref()- .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?- .clone();- let access_hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);- drop(guard);-- let is_auth = client.is_authorized().await.unwrap_or(false);- tracing::info!("[tg-diag] download_media: is_authorized={}, chat_id={}, msg_id={}", is_auth, chat_id, message_id);- if !is_auth {- tracing::error!("[tg-diag] download_media: client not authorized");- }-- let is_channel = chat_type == "channel" || (chat_type == "group" && access_hash != 0);- if is_channel && access_hash == 0 {- tracing::warn!(- "[tg-diag] download_media: access_hash=0 for channel/supergroup chat_id={}, download will likely fail",- chat_id- );- }-- if let Some(parent) = output_path.parent() {- tokio::fs::create_dir_all(parent).await?;- }-- let tmp_path = PathBuf::from(format!("{}.tmp", output_path.display()));- const MAX_REF_RETRIES: u32 = 2;-- for ref_attempt in 0..=MAX_REF_RETRIES {- let (raw_media, msg_date) = super::parallel_download::fetch_raw_media(- &client, chat_id, access_hash, is_channel, message_id,- ).await?;-- let media = super::parallel_download::media_to_location(&raw_media)- .ok_or_else(|| anyhow::anyhow!("Unsupported media type"))?;-- if ref_attempt == 0 {- tracing::info!("[tg-perf] download_media: size={}, dc={}", media.size, media.dc_id);- }-- let result = super::parallel_download::download_file(- &client, &media, &tmp_path, progress_tx.clone(), cancel_token,- ).await;-- match result {- Ok(downloaded) => {- tokio::fs::rename(&tmp_path, output_path).await?;- let ts = msg_date as i64;- if ts > 0 {- let file_time = filetime::FileTime::from_unix_time(ts, 0);- if let Err(e) = filetime::set_file_mtime(output_path, file_time) {- tracing::warn!("[tg-api] failed to set file time: {}", e);- }- }- tracing::info!("[tg-perf] download_media completed in {:?}", _t.elapsed());- return Ok(downloaded);- }- Err(e) => {- let _ = tokio::fs::remove_file(&tmp_path).await;- let err_lower = e.to_string().to_lowercase();- if err_lower.contains("file_reference") && ref_attempt < MAX_REF_RETRIES {- tracing::warn!(- "[tg-diag] download_media: FILE_REFERENCE expired, re-fetching message ({}/{})",- ref_attempt + 1, MAX_REF_RETRIES- );- continue;- }- tracing::info!("[tg-perf] download_media failed in {:?}", _t.elapsed());- return Err(e);- }- }- }-- unreachable!()-}--fn is_retryable_error(err_str: &str) -> bool {- let retryable = [- "connection reset",- "timed out",- "connection refused",- "broken pipe",- "unexpected eof",- "internal server error",- "temporarily unavailable",- "transport error",- "network",- "rpc error",- ];- let lower = err_str.to_lowercase();- retryable.iter().any(|p| lower.contains(p))-}--pub async fn download_media_with_retry(- handle: &TelegramSessionHandle,- chat_id: i64,- chat_type: &str,- message_id: i32,- output_path: &Path,- progress_tx: mpsc::Sender<f64>,- cancel_token: &CancellationToken,-) -> anyhow::Result<u64> {- let _t = std::time::Instant::now();- const MAX_RETRIES: u32 = 5;- const BASE_DELAY_SECS: u64 = 2;-- for attempt in 0..MAX_RETRIES {- let tx = progress_tx.clone();- let result = tokio::select! {- r = download_media(handle, chat_id, chat_type, message_id, output_path, tx, cancel_token) => r,- _ = cancel_token.cancelled() => return Err(anyhow::anyhow!("Download cancelled")),- };-- match result {- Ok(size) => {- tracing::info!("[tg-perf] download_media_with_retry completed in {:?}", _t.elapsed());- return Ok(size);- }- Err(e) => {- let err_str = e.to_string();-- if parse_flood_wait(&err_str).is_some() {- // Flood wait is handled inside invoke_with_flood_wait,- // but if it bubbles up, retry- tracing::warn!(- "[tg-api] flood wait error on attempt {}, retrying: {}",- attempt + 1, err_str- );- } else if !is_retryable_error(&err_str) {- tracing::info!("[tg-perf] download_media_with_retry failed (non-retryable) in {:?}", _t.elapsed());- return Err(e);- }-- if attempt + 1 < MAX_RETRIES {- let delay = BASE_DELAY_SECS * 2u64.pow(attempt);- tracing::warn!(- "[tg-api] download attempt {} failed, retrying in {}s: {}",- attempt + 1, delay, err_str- );- tokio::select! {- _ = tokio::time::sleep(Duration::from_secs(delay)) => {},- _ = cancel_token.cancelled() => return Err(anyhow::anyhow!("Download cancelled")),- }- } else {- tracing::info!("[tg-perf] download_media_with_retry failed (max retries) in {:?}", _t.elapsed());- return Err(e);- }- }- }- }-- unreachable!()-}diff --git a/src-tauri/src/platforms/telegram/auth.rs b/src-tauri/src/platforms/telegram/auth.rsdeleted file mode 100644index f46f0712..00000000--- a/src-tauri/src/platforms/telegram/auth.rs+++ /dev/null@@ -1,526 +0,0 @@-use std::collections::HashMap;-use std::path::PathBuf;-use std::sync::Arc;--use anyhow::anyhow;-use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};-use grammers_client::{Client, SignInError};-use grammers_client::grammers_tl_types as tl;-use grammers_client::types::{LoginToken, PasswordToken};-use grammers_mtsender::{ConnectionParams, SenderPool};-use grammers_session::Session;-use grammers_session::storages::SqliteSession;-use grammers_session::updates::UpdatesLike;-use qrcode::QrCode;-use qrcode::render::svg;-use tokio::sync::{Mutex, mpsc};--const API_ID: i32 = 15055931;-const API_HASH: &str = "021d433426cbb920eeb95164498fe3d3";--pub type TelegramSessionHandle = Arc<Mutex<TelegramState>>;--pub struct TelegramState {- pub client: Option<Client>,- pub phone: String,- pub login_token: Option<LoginToken>,- pub password_token: Option<PasswordToken>,- pub updates_rx: Option<mpsc::UnboundedReceiver<UpdatesLike>>,- pub peer_hashes: HashMap<i64, i64>,-}--impl Default for TelegramState {- fn default() -> Self {- Self::new()- }-}--impl TelegramState {- pub fn new() -> Self {- Self {- client: None,- phone: String::new(),- login_token: None,- password_token: None,- updates_rx: None,- peer_hashes: HashMap::new(),- }- }-}--fn session_file_path() -> anyhow::Result<PathBuf> {- let data_dir = dirs::data_dir()- .ok_or_else(|| anyhow!("Cannot find app data directory"))?;- Ok(data_dir.join("omniget").join("telegram.session"))-}--fn open_session() -> anyhow::Result<Arc<SqliteSession>> {- let path = session_file_path()?;- if let Some(parent) = path.parent() {- std::fs::create_dir_all(parent)?;- }- let session = SqliteSession::open(path)?;- Ok(Arc::new(session))-}--fn connection_params() -> ConnectionParams {- let os_version = os_info::get();- ConnectionParams {- device_model: "Desktop".to_string(),- system_version: format!("{} {}", os_version.os_type(), os_version.version()),- app_version: format!("{} x64", env!("CARGO_PKG_VERSION")),- system_lang_code: sys_locale::get_locale()- .unwrap_or_else(|| "en".to_string())- .split('-').next().unwrap_or("en").to_string(),- lang_code: "en".to_string(),- ..ConnectionParams::default()- }-}--fn create_client_with_updates() -> anyhow::Result<(Client, mpsc::UnboundedReceiver<UpdatesLike>)> {- let session = open_session()?;- let pool = SenderPool::with_configuration(session, API_ID, connection_params());- let client = Client::new(&pool);- let updates_rx = pool.updates;- tokio::spawn(pool.runner.run());- Ok((client, updates_rx))-}--pub fn create_client() -> anyhow::Result<Client> {- let (client, _updates_rx) = create_client_with_updates()?;- Ok(client)-}--pub async fn delete_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(())-}--pub async fn check_session(handle: &TelegramSessionHandle) -> anyhow::Result<String> {- let check = async {- let (existing_client, existing_phone) = {- let guard = handle.lock().await;- (guard.client.clone(), guard.phone.clone())- };-- if let Some(client) = existing_client {- if client.is_authorized().await? {- return Ok(existing_phone);- }- }-- let client = create_client()?;- if client.is_authorized().await? {- let me = client.get_me().await?;- let phone = me.phone().unwrap_or("").to_string();- let mut guard = handle.lock().await;- guard.client = Some(client);- guard.phone = phone.clone();- return Ok(phone);- }-- Err(anyhow!("not_authenticated"))- };-- tokio::time::timeout(std::time::Duration::from_secs(15), check)- .await- .map_err(|_| anyhow!("Session check timed out — please try again"))?-}--pub struct QrLoginResult {- pub qr_svg: String,- pub expires: i32,-}--fn token_to_qr(token_data: &tl::types::auth::LoginToken) -> anyhow::Result<QrLoginResult> {- let token_b64 = URL_SAFE_NO_PAD.encode(&token_data.token);- let qr_url = format!("tg://login?token={}", token_b64);-- let qr = QrCode::new(qr_url.as_bytes())- .map_err(|e| anyhow!("Failed to generate QR code: {}", e))?;- let qr_svg = qr.render::<svg::Color>()- .min_dimensions(200, 200)- .quiet_zone(false)- .build();-- Ok(QrLoginResult {- qr_svg,- expires: token_data.expires,- })-}--async fn export_login_token(client: &Client) -> anyhow::Result<tl::enums::auth::LoginToken> {- let request = tl::functions::auth::ExportLoginToken {- api_id: API_ID,- api_hash: API_HASH.to_string(),- except_ids: vec![],- };- client.invoke(&request).await- .map_err(|e| anyhow!("Failed to export login token: {}", e))-}--fn drain_for_login_token(updates_rx: &mut mpsc::UnboundedReceiver<UpdatesLike>) -> bool {- let mut found = false;- let mut count = 0;- while let Ok(update) = updates_rx.try_recv() {- count += 1;- let is_login = has_login_token_update(&update);- tracing::info!("[tg-qr] drained update #{}, is_login_token={}", count, is_login);- if is_login {- found = true;- }- }- found-}--fn has_login_token_update(updates_like: &UpdatesLike) -> bool {- match updates_like {- UpdatesLike::Updates(tl::enums::Updates::UpdateShort(short)) => {- matches!(short.update, tl::enums::Update::LoginToken)- }- UpdatesLike::Updates(tl::enums::Updates::Updates(updates)) => {- updates.updates.iter().any(|u| matches!(u, tl::enums::Update::LoginToken))- }- UpdatesLike::Updates(tl::enums::Updates::Combined(combined)) => {- combined.updates.iter().any(|u| matches!(u, tl::enums::Update::LoginToken))- }- _ => false,- }-}--enum MigrateResult {- NewToken(tl::types::auth::LoginToken),- Success { phone: String },- PasswordRequired { hint: String },-}--async fn handle_migrate(- handle: &TelegramSessionHandle,- old_client: &Client,- migrate: tl::types::auth::LoginTokenMigrateTo,-) -> anyhow::Result<MigrateResult> {- tracing::info!("[tg-qr] handling DC migration to DC {}", migrate.dc_id);- old_client.disconnect();-- let session = open_session()?;- session.set_home_dc_id(migrate.dc_id);-- let (new_client, new_updates_rx) = create_client_with_updates()?;-- let mut guard = handle.lock().await;- guard.client = Some(new_client.clone());- guard.updates_rx = Some(new_updates_rx);- drop(guard);-- let import_req = tl::functions::auth::ImportLoginToken {- token: migrate.token,- };-- match new_client.invoke(&import_req).await {- Ok(tl::enums::auth::LoginToken::Token(token_data)) => {- Ok(MigrateResult::NewToken(token_data))- }- Ok(tl::enums::auth::LoginToken::Success(_)) => {- let me = new_client.get_me().await?;- let phone = me.phone().unwrap_or("").to_string();- let mut guard = handle.lock().await;- guard.phone = phone.clone();- Ok(MigrateResult::Success { phone })- }- Ok(tl::enums::auth::LoginToken::MigrateTo(_)) => {- Err(anyhow!("Multiple DC migrations"))- }- Err(e) => {- let err_str = e.to_string();- if err_str.contains("SESSION_PASSWORD_NEEDED") {- tracing::info!("[tg-qr] SESSION_PASSWORD_NEEDED after DC migration");- let password: tl::types::account::Password = new_client- .invoke(&tl::functions::account::GetPassword {})- .await- .map_err(|e| anyhow!("Failed to get password info: {}", e))?- .into();- let hint = password.hint.clone().unwrap_or_default();- let pw_token = PasswordToken::new(password);- let mut guard = handle.lock().await;- guard.password_token = Some(pw_token);- guard.updates_rx = None;- Ok(MigrateResult::PasswordRequired { hint })- } else {- Err(anyhow!("Import after DC migration failed: {}", err_str))- }- }- }-}--pub async fn qr_login_start(handle: &TelegramSessionHandle) -> anyhow::Result<QrLoginResult> {- tracing::info!("[tg-qr] qr_login_start: creating client");- let existing_client = {- let guard = handle.lock().await;- guard.client.clone()- };-- if let Some(client) = existing_client {- if client.is_authorized().await.unwrap_or(false) {- let phone = client- .get_me()- .await- .ok()- .and_then(|me| me.phone().map(str::to_string))- .unwrap_or_default();- let mut guard = handle.lock().await;- if !phone.is_empty() {- guard.phone = phone;- }- return Err(anyhow!("already_authenticated"));- }- }-- let mut guard = handle.lock().await;- if let Some(old_client) = guard.client.take() {- old_client.disconnect();- }- guard.updates_rx = None;-- let (client, updates_rx) = create_client_with_updates()?;- guard.client = Some(client.clone());- guard.updates_rx = Some(updates_rx);- drop(guard);-- tracing::info!("[tg-qr] qr_login_start: calling ExportLoginToken");- let result = export_login_token(&client).await?;-- match result {- tl::enums::auth::LoginToken::Token(token_data) => {- token_to_qr(&token_data)- }- tl::enums::auth::LoginToken::Success(_) => {- let me = client.get_me().await?;- let phone = me.phone().unwrap_or("").to_string();- let mut guard = handle.lock().await;- guard.phone = phone;- Err(anyhow!("already_authenticated"))- }- tl::enums::auth::LoginToken::MigrateTo(migrate) => {- match handle_migrate(handle, &client, migrate).await? {- MigrateResult::NewToken(token_data) => token_to_qr(&token_data),- MigrateResult::Success { .. } => Err(anyhow!("already_authenticated")),- MigrateResult::PasswordRequired { .. } => Err(anyhow!("already_authenticated")),- }- }- }-}--pub enum QrPollStatus {- Waiting,- Success { phone: String },- PasswordRequired { hint: String },-}--pub async fn qr_login_poll(handle: &TelegramSessionHandle) -> anyhow::Result<QrPollStatus> {- let mut guard = handle.lock().await;- let client = guard.client.as_ref()- .ok_or_else(|| anyhow!("No active client"))?- .clone();-- let got_update = if let Some(ref mut rx) = guard.updates_rx {- drain_for_login_token(rx)- } else {- false- };- drop(guard);-- if !got_update {- return Ok(QrPollStatus::Waiting);- }-- tracing::info!("[tg-qr] updateLoginToken received, calling ExportLoginToken to finalize");-- match export_login_token(&client).await {- Ok(tl::enums::auth::LoginToken::Success(success)) => {- let phone = extract_phone_from_auth(&success.authorization);- tracing::info!("[tg-qr] login success, phone={}", phone);- let mut guard = handle.lock().await;- guard.phone = phone.clone();- guard.updates_rx = None;- Ok(QrPollStatus::Success { phone })- }- Ok(tl::enums::auth::LoginToken::Token(_)) => {- tracing::info!("[tg-qr] got new token after update (not success yet), waiting");- Ok(QrPollStatus::Waiting)- }- Ok(tl::enums::auth::LoginToken::MigrateTo(migrate)) => {- tracing::info!("[tg-qr] got MigrateTo after update, migrating DC");- match handle_migrate(handle, &client, migrate).await? {- MigrateResult::NewToken(_) => {- tracing::info!("[tg-qr] migration gave new token, waiting");- Ok(QrPollStatus::Waiting)- }- MigrateResult::Success { phone } => {- tracing::info!("[tg-qr] migration + login success, phone={}", phone);- Ok(QrPollStatus::Success { phone })- }- MigrateResult::PasswordRequired { hint } => {- tracing::info!("[tg-qr] migration → 2FA required");- Ok(QrPollStatus::PasswordRequired { hint })- }- }- }- Err(e) => {- let err_str = e.to_string();- if err_str.contains("SESSION_PASSWORD_NEEDED") {- tracing::info!("[tg-qr] SESSION_PASSWORD_NEEDED, fetching password info for 2FA");- let password: tl::types::account::Password = client- .invoke(&tl::functions::account::GetPassword {})- .await- .map_err(|e| anyhow!("Failed to get password info: {}", e))?- .into();- let hint = password.hint.clone().unwrap_or_default();- let pw_token = PasswordToken::new(password);- tracing::info!("[tg-qr] got password token, hint={:?}", hint);- let mut guard = handle.lock().await;- guard.password_token = Some(pw_token);- guard.updates_rx = None;- Ok(QrPollStatus::PasswordRequired { hint })- } else {- tracing::error!("[tg-qr] poll error: {}", err_str);- Err(anyhow!("Poll error: {}", err_str))- }- }- }-}--fn extract_phone_from_auth(auth: &tl::enums::auth::Authorization) -> String {- match auth {- tl::enums::auth::Authorization::Authorization(a) => {- match &a.user {- tl::enums::User::User(u) => {- u.phone.clone().unwrap_or_default()- }- tl::enums::User::Empty(_) => String::new(),- }- }- tl::enums::auth::Authorization::SignUpRequired(_) => String::new(),- }-}--pub async fn send_code(handle: &TelegramSessionHandle, phone: &str) -> anyhow::Result<()> {- let mut guard = handle.lock().await;- let client = if let Some(ref c) = guard.client {- c.clone()- } else {- let c = create_client()?;- guard.client = Some(c.clone());- c- };- guard.phone = phone.to_string();- drop(guard);-- let token = client.request_login_code(phone, API_HASH).await- .map_err(|e| anyhow!("Failed to send code: {}", e))?;-- let mut guard = handle.lock().await;- guard.login_token = Some(token);- Ok(())-}--pub async fn verify_code(- handle: &TelegramSessionHandle,- code: &str,-) -> Result<String, VerifyError> {- let guard = handle.lock().await;- let client = guard.client.as_ref()- .ok_or(VerifyError::NoSession)?- .clone();- drop(guard);-- let mut guard = handle.lock().await;- let token = guard.login_token.take()- .ok_or(VerifyError::Other("No login token available".to_string()))?;- drop(guard);-- match client.sign_in(&token, code).await {- Ok(user) => {- let phone = user.phone().unwrap_or("").to_string();- let mut guard = handle.lock().await;- guard.phone = phone.clone();- guard.password_token = None;- Ok(phone)- }- Err(SignInError::PasswordRequired(pw_token)) => {- let hint = pw_token.hint().unwrap_or("").to_string();- let mut guard = handle.lock().await;- guard.password_token = Some(pw_token);- Err(VerifyError::PasswordRequired { hint })- }- Err(SignInError::InvalidCode) => {- let mut guard = handle.lock().await;- guard.login_token = Some(token);- Err(VerifyError::InvalidCode)- }- Err(e) => {- Err(VerifyError::Other(e.to_string()))- }- }-}--pub async fn verify_password(- handle: &TelegramSessionHandle,- password: &str,-) -> anyhow::Result<String> {- let guard = handle.lock().await;- let client = guard.client.as_ref()- .ok_or_else(|| anyhow!("No active session"))?- .clone();- drop(guard);-- let mut guard = handle.lock().await;- let pw_token = guard.password_token.take()- .ok_or_else(|| anyhow!("No password token available"))?;- drop(guard);-- let pw_token_backup = pw_token.clone();-- match client.check_password(pw_token, password.as_bytes()).await {- Ok(user) => {- let phone = user.phone().unwrap_or("").to_string();- let mut guard = handle.lock().await;- guard.phone = phone.clone();- Ok(phone)- }- Err(SignInError::InvalidPassword) => {- let mut guard = handle.lock().await;- guard.password_token = Some(pw_token_backup);- Err(anyhow!("invalid_password"))- }- Err(e) => {- Err(anyhow!("{}", e))- }- }-}--pub async fn logout(handle: &TelegramSessionHandle) -> anyhow::Result<()> {- let mut guard = handle.lock().await;- if let Some(client) = guard.client.take() {- let _ = client.sign_out().await;- client.disconnect();- }- guard.phone.clear();- guard.login_token = None;- guard.password_token = None;- guard.updates_rx = None;- drop(guard);- delete_session().await?;- Ok(())-}--pub enum VerifyError {- InvalidCode,- PasswordRequired {- hint: String,- },- NoSession,- Other(String),-}diff --git a/src-tauri/src/platforms/telegram/downloader.rs b/src-tauri/src/platforms/telegram/downloader.rsdeleted file mode 100644index 58fe712c..00000000--- a/src-tauri/src/platforms/telegram/downloader.rs+++ /dev/null@@ -1,297 +0,0 @@-use async_trait::async_trait;-use grammers_client::types::Peer;-use tokio::sync::mpsc;--use super::auth::TelegramSessionHandle;-use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};-use crate::models::settings::default_filename_template;-use crate::platforms::traits::PlatformDownloader;--pub struct TelegramDownloader {- session: TelegramSessionHandle,-}--impl TelegramDownloader {- pub fn new(session: TelegramSessionHandle) -> Self {- Self { session }- }-- fn parse_tme_url(url: &str) -> Option<(String, Option<i32>)> {- let parsed = url::Url::parse(url).ok()?;- let host = parsed.host_str()?.to_lowercase();- if host != "t.me" && !host.ends_with("telegram.me") && !host.ends_with("telegram.org") {- return None;- }- let segments: Vec<&str> = parsed- .path_segments()?- .filter(|s| !s.is_empty())- .collect();-- if segments.is_empty() {- return None;- }-- if segments.len() >= 2 {- if segments[0] == "c" && segments.len() >= 3 {- let channel = format!("c/{}", segments[1]);- let msg_id = segments[2].parse::<i32>().ok();- return Some((channel, msg_id));- }- let username = segments[0].to_string();- let msg_id = segments[1].parse::<i32>().ok();- return Some((username, msg_id));- }-- let first = segments[0];- if !["joinchat", "addstickers", "login", "share"].contains(&first) {- return Some((first.to_string(), None));- }-- None- }-}--#[async_trait]-impl PlatformDownloader for TelegramDownloader {- fn name(&self) -> &str {- "telegram"- }-- fn can_handle(&self, url: &str) -> bool {- Self::parse_tme_url(url).is_some()- }-- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {- let (username, msg_id) = Self::parse_tme_url(url)- .ok_or_else(|| anyhow::anyhow!("Invalid Telegram URL"))?;-- let msg_id = msg_id- .ok_or_else(|| anyhow::anyhow!("URL must point to a specific message (e.g., t.me/channel/123)"))?;-- let guard = self.session.lock().await;- let client = guard- .client- .as_ref()- .ok_or_else(|| anyhow::anyhow!("Not authenticated to Telegram"))?- .clone();- drop(guard);-- let peer = if username.starts_with("c/") {- let id_str = username.strip_prefix("c/").unwrap();- let channel_id: i64 = id_str- .parse()- .map_err(|_| anyhow::anyhow!("Invalid channel ID"))?;- use grammers_client::session::defs::{PeerAuth, PeerId, PeerRef};- let peer_ref = PeerRef {- id: PeerId::channel(channel_id),- auth: PeerAuth::default(),- };- client- .resolve_peer(peer_ref)- .await- .map_err(|e| anyhow::anyhow!("Cannot resolve channel: {}", e))?- } else {- client- .resolve_username(&username)- .await- .map_err(|e| anyhow::anyhow!("Cannot resolve username: {}", e))?- .ok_or_else(|| anyhow::anyhow!("Channel @{} not found", username))?- };-- let messages = client- .get_messages_by_id(&peer, &[msg_id])- .await- .map_err(|e| anyhow::anyhow!("Cannot fetch message: {}", e))?;-- let message = messages- .into_iter()- .next()- .flatten()- .ok_or_else(|| anyhow::anyhow!("Message {} not found", msg_id))?;-- let media = message- .media()- .ok_or_else(|| anyhow::anyhow!("Message has no downloadable media"))?;-- let (file_name, _file_size, media_type, format) = match &media {- grammers_client::types::Media::Photo(photo) => {- let name = format!("photo_{}", photo.id());- let size = photo.size().max(0) as u64;- (name, size, MediaType::Photo, "jpg".to_string())- }- grammers_client::types::Media::Document(doc) => {- let raw_name = doc.name().to_string();- let name = if raw_name.is_empty() {- format!("file_{}", doc.id())- } else {- raw_name- .rsplit_once('.')- .map(|(n, _)| n.to_string())- .unwrap_or(raw_name.clone())- };- let size = doc.size().max(0) as u64;- let (mt, fmt) = match doc.mime_type() {- Some(m) if m.starts_with("video/") => (MediaType::Video, "mp4".to_string()),- Some(m) if m.starts_with("audio/") => (MediaType::Audio, "mp3".to_string()),- Some(m) if m.starts_with("image/") => (MediaType::Photo, "jpg".to_string()),- _ => {- let ext = raw_name- .rsplit_once('.')- .map(|(_, e)| e.to_string())- .unwrap_or_else(|| "bin".to_string());- (MediaType::Video, ext)- }- };- (name, size, mt, fmt)- }- _ => return Err(anyhow::anyhow!("Unsupported media type")),- };-- let channel_name = peer.name().unwrap_or("Telegram").to_string();-- Ok(MediaInfo {- title: file_name,- author: channel_name,- platform: "telegram".to_string(),- duration_seconds: None,- thumbnail_url: None,- available_qualities: vec![VideoQuality {- label: "original".to_string(),- width: 0,- height: 0,- url: format!("tg://{}:{}", username, msg_id),- format,- }],- media_type,- file_size_bytes: None,- })- }-- async fn download(- &self,- info: &MediaInfo,- opts: &DownloadOptions,- progress: mpsc::Sender<f64>,- ) -> anyhow::Result<DownloadResult> {- let _t = std::time::Instant::now();- let quality = info- .available_qualities- .first()- .ok_or_else(|| anyhow::anyhow!("No quality available"))?;-- let tg_ref = quality- .url- .strip_prefix("tg://")- .ok_or_else(|| anyhow::anyhow!("Invalid internal reference"))?;- let (username, msg_id_str) = tg_ref- .rsplit_once(':')- .ok_or_else(|| anyhow::anyhow!("Invalid internal reference format"))?;- let msg_id: i32 = msg_id_str.parse()?;- tracing::info!("[tg-dl] download: username={}, msg_id={}", username, msg_id);-- let guard = self.session.lock().await;- let client = guard- .client- .as_ref()- .ok_or_else(|| anyhow::anyhow!("Not authenticated to Telegram"))?- .clone();- drop(guard);-- let peer = if username.starts_with("c/") {- let id_str = username.strip_prefix("c/").unwrap();- let channel_id: i64 = id_str.parse()?;- use grammers_client::session::defs::{PeerAuth, PeerId, PeerRef};- let peer_ref = PeerRef {- id: PeerId::channel(channel_id),- auth: PeerAuth::default(),- };- client- .resolve_peer(peer_ref)- .await- .map_err(|e| anyhow::anyhow!("Cannot resolve channel: {}", e))?- } else {- client- .resolve_username(username)- .await- .map_err(|e| anyhow::anyhow!("Cannot resolve username: {}", e))?- .ok_or_else(|| anyhow::anyhow!("Channel not found"))?- };-- let is_channel = matches!(&peer, Peer::Channel(_));- use grammers_client::session::defs::PeerRef;- let (bare_id, peer_access_hash) = std::panic::catch_unwind(- std::panic::AssertUnwindSafe(|| {- let peer_ref = PeerRef::from(peer);- (peer_ref.id.bare_id(), peer_ref.auth.hash())- }),- )- .map_err(|_| anyhow::anyhow!("Peer has an unsupported ID"))?;-- let use_prefix = opts- .filename_template- .as_deref()- .is_none_or(|t| t == default_filename_template());- let prefix = if use_prefix { "omniget-" } else { "" };- let filename = format!(- "{}{}.{}",- prefix,- sanitize_filename::sanitize(&info.title),- quality.format- );- let output_path = opts.output_dir.join(&filename);- tokio::fs::create_dir_all(&opts.output_dir).await?;-- let tmp_path = std::path::PathBuf::from(format!("{}.tmp", output_path.display()));- const MAX_REF_RETRIES: u32 = 2;-- for ref_attempt in 0..=MAX_REF_RETRIES {- let (raw_media, _msg_date) = super::parallel_download::fetch_raw_media(- &client, bare_id, peer_access_hash, is_channel, msg_id,- )- .await?;-- let media = super::parallel_download::media_to_location(&raw_media)- .ok_or_else(|| anyhow::anyhow!("Unsupported media type for download"))?;-- if ref_attempt == 0 {- tracing::info!("[tg-dl] download: size={}, dc={}", media.size, media.dc_id);- }-- let result = super::parallel_download::download_file(- &client, &media, &tmp_path, progress.clone(), &opts.cancel_token,- )- .await;-- match result {- Ok(size) => {- tokio::fs::rename(&tmp_path, &output_path).await?;- let _ = progress.send(100.0).await;- tracing::info!(- "[tg-dl] download completed in {:?}, {} bytes",- _t.elapsed(), size- );- return Ok(DownloadResult {- file_path: output_path,- file_size_bytes: size,- duration_seconds: 0.0,- torrent_id: None,- });- }- Err(e) => {- let _ = tokio::fs::remove_file(&tmp_path).await;- let err_str = e.to_string().to_lowercase();- if err_str.contains("file_reference") && ref_attempt < MAX_REF_RETRIES {- tracing::warn!(- "[tg-dl] FILE_REFERENCE expired, re-fetching ({}/{})",- ref_attempt + 1, MAX_REF_RETRIES- );- continue;- }- return Err(e);- }- }- }-- unreachable!()- }-}diff --git a/src-tauri/src/platforms/telegram/mod.rs b/src-tauri/src/platforms/telegram/mod.rsdeleted file mode 100644index 3050460c..00000000--- a/src-tauri/src/platforms/telegram/mod.rs+++ /dev/null@@ -1,5 +0,0 @@-pub mod api;-pub mod auth;-pub mod downloader;-pub mod parallel_download;-pub mod thumbnail_cache;diff --git a/src-tauri/src/platforms/telegram/parallel_download.rs b/src-tauri/src/platforms/telegram/parallel_download.rsdeleted file mode 100644index 70b243cb..00000000--- a/src-tauri/src/platforms/telegram/parallel_download.rs+++ /dev/null@@ -1,261 +0,0 @@-use std::path::Path;-use std::sync::{Arc, OnceLock};--use grammers_client::Client;-use grammers_client::grammers_tl_types as tl;-use tokio::io::AsyncWriteExt;-use tokio::sync::{mpsc, Mutex};-use tokio_util::sync::CancellationToken;--pub struct MediaLocation {- pub location: tl::enums::InputFileLocation,- pub size: u64,- pub dc_id: i32,-}--pub fn media_to_location(media: &tl::enums::MessageMedia) -> Option<MediaLocation> {- match media {- tl::enums::MessageMedia::Document(doc_media) => {- let doc = match doc_media.document.as_ref()? {- tl::enums::Document::Document(d) => d,- tl::enums::Document::Empty(_) => return None,- };- let location = tl::enums::InputFileLocation::InputDocumentFileLocation(- tl::types::InputDocumentFileLocation {- id: doc.id,- access_hash: doc.access_hash,- file_reference: doc.file_reference.clone(),- thumb_size: String::new(),- },- );- Some(MediaLocation {- location,- size: doc.size as u64,- dc_id: doc.dc_id,- })- }- tl::enums::MessageMedia::Photo(photo_media) => {- let photo = match photo_media.photo.as_ref()? {- tl::enums::Photo::Photo(p) => p,- tl::enums::Photo::Empty(_) => return None,- };- let largest = photo- .sizes- .iter()- .filter_map(|s| match s {- tl::enums::PhotoSize::Size(ps) => Some(ps),- _ => None,- })- .max_by_key(|ps| ps.size)?;-- let location = tl::enums::InputFileLocation::InputPhotoFileLocation(- tl::types::InputPhotoFileLocation {- id: photo.id,- access_hash: photo.access_hash,- file_reference: photo.file_reference.clone(),- thumb_size: largest.r#type.clone(),- },- );- Some(MediaLocation {- location,- size: largest.size as u64,- dc_id: photo.dc_id,- })- }- _ => None,- }-}--fn extract_messages(result: tl::enums::messages::Messages) -> Vec<tl::enums::Message> {- match result {- tl::enums::messages::Messages::Messages(m) => m.messages,- tl::enums::messages::Messages::Slice(m) => m.messages,- tl::enums::messages::Messages::ChannelMessages(m) => m.messages,- tl::enums::messages::Messages::NotModified(_) => vec![],- }-}--pub async fn fetch_raw_media(- client: &Client,- chat_id: i64,- access_hash: i64,- is_channel: bool,- message_id: i32,-) -> anyhow::Result<(tl::enums::MessageMedia, i32)> {- let msg_input = vec![tl::enums::InputMessage::Id(tl::types::InputMessageId {- id: message_id,- })];-- let raw_messages = if is_channel {- let request = tl::functions::channels::GetMessages {- channel: tl::enums::InputChannel::Channel(tl::types::InputChannel {- channel_id: chat_id,- access_hash,- }),- id: msg_input,- };- let result = client- .invoke(&request)- .await- .map_err(|e| anyhow::anyhow!("channels.getMessages: {}", e))?;- extract_messages(result)- } else {- let request = tl::functions::messages::GetMessages { id: msg_input };- let result = client- .invoke(&request)- .await- .map_err(|e| anyhow::anyhow!("messages.getMessages: {}", e))?;- extract_messages(result)- };-- let raw_msg = raw_messages- .into_iter()- .find_map(|m| match m {- tl::enums::Message::Message(msg) => Some(msg),- _ => None,- })- .ok_or_else(|| anyhow::anyhow!("Message {} not found", message_id))?;-- let raw_media = raw_msg- .media- .ok_or_else(|| anyhow::anyhow!("Message {} has no media", message_id))?;-- Ok((raw_media, raw_msg.date))-}--const MAX_CHUNK_SIZE: i32 = 512 * 1024;-const FILE_MIGRATE_ERROR: i32 = 303;--fn auth_copied_dcs() -> &'static Arc<Mutex<Vec<i32>>> {- static INSTANCE: OnceLock<Arc<Mutex<Vec<i32>>>> = OnceLock::new();- INSTANCE.get_or_init(|| Arc::new(Mutex::new(Vec::new())))-}--async fn ensure_auth_on_dc(client: &Client, target_dc_id: i32) -> anyhow::Result<()> {- {- let copied = auth_copied_dcs().lock().await;- if copied.contains(&target_dc_id) {- return Ok(());- }- }-- tracing::info!("[tg-dl] copying auth to DC {}", target_dc_id);-- let tl::enums::auth::ExportedAuthorization::Authorization(exported) = client- .invoke(&tl::functions::auth::ExportAuthorization {- dc_id: target_dc_id,- })- .await- .map_err(|e| anyhow::anyhow!("ExportAuthorization to DC {}: {}", target_dc_id, e))?;-- let _: tl::enums::auth::Authorization = client- .invoke_in_dc(- target_dc_id,- &tl::functions::auth::ImportAuthorization {- id: exported.id,- bytes: exported.bytes,- },- )- .await- .map_err(|e| anyhow::anyhow!("ImportAuthorization on DC {}: {}", target_dc_id, e))?;-- {- let mut copied = auth_copied_dcs().lock().await;- if !copied.contains(&target_dc_id) {- copied.push(target_dc_id);- }- }-- tracing::info!("[tg-dl] auth copied to DC {} successfully", target_dc_id);- Ok(())-}--pub async fn download_file(- client: &Client,- media: &MediaLocation,- output_path: &Path,- progress_tx: mpsc::Sender<f64>,- cancel_token: &CancellationToken,-) -> anyhow::Result<u64> {- tracing::info!(- "[tg-dl] starting download: size={}, dc={}, path={}",- media.size, media.dc_id, output_path.display()- );-- let mut dc = media.dc_id;-- ensure_auth_on_dc(client, dc).await?;-- let mut file = tokio::fs::File::create(output_path).await?;- let mut downloaded: u64 = 0;- let mut offset: i64 = 0;-- loop {- if cancel_token.is_cancelled() {- drop(file);- let _ = tokio::fs::remove_file(output_path).await;- return Err(anyhow::anyhow!("Download cancelled"));- }-- let request = tl::functions::upload::GetFile {- precise: true,- cdn_supported: false,- location: media.location.clone(),- offset,- limit: MAX_CHUNK_SIZE,- };-- match client.invoke_in_dc(dc, &request).await {- Ok(tl::enums::upload::File::File(f)) => {- if f.bytes.is_empty() {- break;- }-- file.write_all(&f.bytes).await?;- downloaded += f.bytes.len() as u64;- offset += MAX_CHUNK_SIZE as i64;-- if media.size > 0 {- let percent = (downloaded as f64 / media.size as f64) * 100.0;- let _ = progress_tx.send(percent.min(100.0)).await;- }-- if f.bytes.len() < MAX_CHUNK_SIZE as usize {- break;- }- }- Ok(tl::enums::upload::File::CdnRedirect(_)) => {- return Err(anyhow::anyhow!("CDN redirect not supported"));- }- Err(grammers_mtsender::InvocationError::Rpc(ref err))- if err.name == "AUTH_KEY_UNREGISTERED" =>- {- tracing::warn!("[tg-dl] AUTH_KEY_UNREGISTERED on DC {}, re-copying auth", dc);- {- let mut copied = auth_copied_dcs().lock().await;- copied.retain(|&d| d != dc);- }- ensure_auth_on_dc(client, dc).await?;- continue;- }- Err(grammers_mtsender::InvocationError::Rpc(ref err))- if err.code == FILE_MIGRATE_ERROR =>- {- let new_dc = err.value.map(|v| v as i32).unwrap_or(dc);- tracing::info!("[tg-dl] FILE_MIGRATE to DC {}", new_dc);- dc = new_dc;- ensure_auth_on_dc(client, dc).await?;- continue;- }- Err(e) => {- drop(file);- let _ = tokio::fs::remove_file(output_path).await;- return Err(anyhow::anyhow!("upload.getFile failed: {}", e));- }- }- }-- file.flush().await?;- tracing::info!("[tg-dl] download complete: {} bytes, dc={}", downloaded, dc);- Ok(downloaded)-}diff --git a/src-tauri/src/platforms/telegram/thumbnail_cache.rs b/src-tauri/src/platforms/telegram/thumbnail_cache.rsdeleted file mode 100644index be275a01..00000000--- a/src-tauri/src/platforms/telegram/thumbnail_cache.rs+++ /dev/null@@ -1,404 +0,0 @@-use std::collections::HashMap;-use std::sync::OnceLock;-use std::time::Instant;--use grammers_client::Client;-use grammers_client::grammers_tl_types as tl;-use tokio::sync::Mutex;--use super::auth::TelegramSessionHandle;-use super::parallel_download::fetch_raw_media;--const TTL_SECS: u64 = 120;-const MAX_BYTES: u64 = 30 * 1024 * 1024;--struct CacheEntry {- data: Vec<u8>,- inserted_at: Instant,-}--struct ThumbnailCache {- entries: HashMap<(i64, i32), CacheEntry>,- total_bytes: u64,-}--impl ThumbnailCache {- fn new() -> Self {- Self {- entries: HashMap::new(),- total_bytes: 0,- }- }-- fn get(&mut self, key: &(i64, i32)) -> Option<Vec<u8>> {- self.evict_expired();- self.entries.get(key).map(|e| e.data.clone())- }-- fn insert(&mut self, key: (i64, i32), data: Vec<u8>) {- let data_len = data.len() as u64;-- if let Some(old) = self.entries.remove(&key) {- self.total_bytes -= old.data.len() as u64;- }-- self.total_bytes += data_len;- self.entries.insert(key, CacheEntry {- data,- inserted_at: Instant::now(),- });-- if self.total_bytes > MAX_BYTES {- self.evict_expired();- self.evict_to_target();- }- }-- fn clear(&mut self) {- self.entries.clear();- self.total_bytes = 0;- }-- fn evict_expired(&mut self) {- let now = Instant::now();- let expired: Vec<(i64, i32)> = self- .entries- .iter()- .filter(|(_, v)| now.duration_since(v.inserted_at).as_secs() > TTL_SECS)- .map(|(k, _)| *k)- .collect();-- if expired.is_empty() {- return;- }-- let mut freed: u64 = 0;- let count = expired.len();- for key in expired {- if let Some(entry) = self.entries.remove(&key) {- freed += entry.data.len() as u64;- self.total_bytes -= entry.data.len() as u64;- }- }-- tracing::info!(- "[tg-cache] evicted {} expired entries, freed {} bytes, remaining {} bytes",- count,- freed,- self.total_bytes- );- }-- fn evict_to_target(&mut self) {- let target = MAX_BYTES * 3 / 4;- if self.total_bytes <= target {- return;- }-- let mut by_age: Vec<(i64, i32)> = self.entries.keys().copied().collect();- by_age.sort_by_key(|k| self.entries[k].inserted_at);-- let mut freed: u64 = 0;- let mut count: usize = 0;- for key in by_age {- if self.total_bytes <= target {- break;- }- if let Some(entry) = self.entries.remove(&key) {- freed += entry.data.len() as u64;- self.total_bytes -= entry.data.len() as u64;- count += 1;- }- }-- tracing::info!(- "[tg-cache] evicted {} entries for capacity, freed {} bytes, remaining {} bytes",- count,- freed,- self.total_bytes- );- }-}--static CACHE: OnceLock<Mutex<ThumbnailCache>> = OnceLock::new();--fn cache() -> &'static Mutex<ThumbnailCache> {- CACHE.get_or_init(|| Mutex::new(ThumbnailCache::new()))-}--fn extract_thumbnail_location(- media: &tl::enums::MessageMedia,-) -> Option<(tl::enums::InputFileLocation, u64)> {- match media {- tl::enums::MessageMedia::Photo(photo_media) => {- let photo = match photo_media.photo.as_ref()? {- tl::enums::Photo::Photo(p) => p,- tl::enums::Photo::Empty(_) => return None,- };- let smallest = photo- .sizes- .iter()- .filter_map(|s| match s {- tl::enums::PhotoSize::Size(ps) => Some(ps),- _ => None,- })- .min_by_key(|ps| ps.size)?;-- let location = tl::enums::InputFileLocation::InputPhotoFileLocation(- tl::types::InputPhotoFileLocation {- id: photo.id,- access_hash: photo.access_hash,- file_reference: photo.file_reference.clone(),- thumb_size: smallest.r#type.clone(),- },- );- Some((location, smallest.size as u64))- }- tl::enums::MessageMedia::Document(doc_media) => {- let doc = match doc_media.document.as_ref()? {- tl::enums::Document::Document(d) => d,- tl::enums::Document::Empty(_) => return None,- };- let thumbs = doc.thumbs.as_ref()?;- let smallest = thumbs- .iter()- .filter_map(|s| match s {- tl::enums::PhotoSize::Size(ps) => Some(ps),- _ => None,- })- .min_by_key(|ps| ps.size)?;-- let location = tl::enums::InputFileLocation::InputDocumentFileLocation(- tl::types::InputDocumentFileLocation {- id: doc.id,- access_hash: doc.access_hash,- file_reference: doc.file_reference.clone(),- thumb_size: smallest.r#type.clone(),- },- );- Some((location, smallest.size as u64))- }- _ => None,- }-}--async fn download_to_memory(- client: &Client,- location: tl::enums::InputFileLocation,- total_size: u64,-) -> anyhow::Result<Vec<u8>> {- const PART_SIZE: i32 = 512 * 1024;- let mut data = Vec::with_capacity(total_size as usize);- let mut offset: i64 = 0;-- loop {- let request = tl::functions::upload::GetFile {- precise: true,- cdn_supported: false,- location: location.clone(),- offset,- limit: PART_SIZE,- };-- let response = client- .invoke(&request)- .await- .map_err(|e| anyhow::anyhow!("upload.GetFile thumbnail: {}", e))?;-- let bytes = match response {- tl::enums::upload::File::File(f) => f.bytes,- tl::enums::upload::File::CdnRedirect(_) => {- return Err(anyhow::anyhow!("CDN redirect not supported"));- }- };-- if bytes.is_empty() {- break;- }-- let len = bytes.len();- data.extend_from_slice(&bytes);- offset += len as i64;-- if (len as i32) < PART_SIZE {- break;- }- }-- Ok(data)-}--pub async fn get_thumbnail(- handle: &TelegramSessionHandle,- chat_id: i64,- chat_type: &str,- message_id: i32,-) -> anyhow::Result<Vec<u8>> {- let key = (chat_id, message_id);-- {- let mut c = cache().lock().await;- if let Some(data) = c.get(&key) {- return Ok(data);- }- }-- let guard = handle.lock().await;- let client = guard- .client- .as_ref()- .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?- .clone();- let access_hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);- drop(guard);-- let is_channel = chat_type == "channel" || (chat_type == "group" && access_hash != 0);-- let (raw_media, _date) =- fetch_raw_media(&client, chat_id, access_hash, is_channel, message_id).await?;-- let (location, total_size) = extract_thumbnail_location(&raw_media)- .ok_or_else(|| anyhow::anyhow!("No thumbnail available"))?;-- let data = download_to_memory(&client, location, total_size).await?;-- {- let mut c = cache().lock().await;- c.insert(key, data.clone());- }-- Ok(data)-}--async fn fetch_chat_photo_id(- client: &Client,- chat_id: i64,- chat_type: &str,- access_hash: i64,-) -> anyhow::Result<i64> {- match chat_type {- "private" => {- let request = tl::functions::users::GetUsers {- id: vec![tl::enums::InputUser::User(tl::types::InputUser {- user_id: chat_id,- access_hash,- })],- };- let users = client- .invoke(&request)- .await- .map_err(|e| anyhow::anyhow!("users.GetUsers: {}", e))?;- for user in users {- if let tl::enums::User::User(u) = user {- if u.id == chat_id {- if let Some(tl::enums::UserProfilePhoto::Photo(photo)) =- u.photo- {- return Ok(photo.photo_id);- }- }- }- }- Err(anyhow::anyhow!("User has no photo"))- }- _ => {- if access_hash != 0 {- let request = tl::functions::channels::GetChannels {- id: vec![tl::enums::InputChannel::Channel(tl::types::InputChannel {- channel_id: chat_id,- access_hash,- })],- };- let result = client- .invoke(&request)- .await- .map_err(|e| anyhow::anyhow!("channels.GetChannels: {}", e))?;- let chats = match result {- tl::enums::messages::Chats::Chats(c) => c.chats,- tl::enums::messages::Chats::Slice(c) => c.chats,- };- for chat in chats {- match chat {- tl::enums::Chat::Channel(c) if c.id == chat_id => {- if let tl::enums::ChatPhoto::Photo(photo) = c.photo {- return Ok(photo.photo_id);- }- }- _ => {}- }- }- Err(anyhow::anyhow!("Channel has no photo"))- } else {- let request = tl::functions::messages::GetChats {- id: vec![chat_id],- };- let result = client- .invoke(&request)- .await- .map_err(|e| anyhow::anyhow!("messages.GetChats: {}", e))?;- let chats = match result {- tl::enums::messages::Chats::Chats(c) => c.chats,- tl::enums::messages::Chats::Slice(c) => c.chats,- };- for chat in chats {- if let tl::enums::Chat::Chat(c) = chat {- if c.id == chat_id {- if let tl::enums::ChatPhoto::Photo(photo) = c.photo {- return Ok(photo.photo_id);- }- }- }- }- Err(anyhow::anyhow!("Chat has no photo"))- }- }- }-}--pub async fn get_chat_photo(- handle: &TelegramSessionHandle,- chat_id: i64,- chat_type: &str,-) -> anyhow::Result<Vec<u8>> {- let key = (chat_id, 0i32);-- {- let mut c = cache().lock().await;- if let Some(data) = c.get(&key) {- return Ok(data);- }- }-- let guard = handle.lock().await;- let client = guard- .client- .as_ref()- .ok_or_else(|| anyhow::anyhow!("Not authenticated"))?- .clone();- let access_hash = guard.peer_hashes.get(&chat_id).copied().unwrap_or(0);- drop(guard);-- let input_peer = super::api::make_input_peer(chat_id, chat_type, access_hash);- let photo_id = fetch_chat_photo_id(&client, chat_id, chat_type, access_hash).await?;-- let location = tl::enums::InputFileLocation::InputPeerPhotoFileLocation(- tl::types::InputPeerPhotoFileLocation {- big: false,- peer: input_peer,- photo_id,- },- );-- let data = download_to_memory(&client, location, 0).await?;-- {- let mut c = cache().lock().await;- c.insert(key, data.clone());- }-- Ok(data)-}--pub async fn clear_cache() {- cache().lock().await.clear();-}diff --git a/src-tauri/src/platforms/themembers/api.rs b/src-tauri/src/platforms/themembers/api.rsdeleted file mode 100644index 3ef75404..00000000--- a/src-tauri/src/platforms/themembers/api.rs+++ /dev/null@@ -1,586 +0,0 @@-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 = crate::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 = crate::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 = crate::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 = crate::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/src/platforms/themembers/downloader.rs b/src-tauri/src/platforms/themembers/downloader.rsdeleted file mode 100644index c9e74893..00000000--- a/src-tauri/src/platforms/themembers/downloader.rs+++ /dev/null@@ -1,362 +0,0 @@-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 crate::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 crate::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 {- crate::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();- }-- if let Some(ref pdf_url) = detail.url_pdf {- crate::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"));- }-- crate::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 crate::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 = crate::core::ytdlp::ensure_ytdlp().await?;- let out_dir = Path::new(output_dir);- let (tx, _rx) = mpsc::channel(8);-- let result = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/themembers/mod.rs b/src-tauri/src/platforms/themembers/mod.rsdeleted file mode 100644index ba91b332..00000000--- a/src-tauri/src/platforms/themembers/mod.rs+++ /dev/null@@ -1,63 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/thinkific/api.rs b/src-tauri/src/platforms/thinkific/api.rsdeleted file mode 100644index 2067dd7d..00000000--- a/src-tauri/src/platforms/thinkific/api.rs+++ /dev/null@@ -1,681 +0,0 @@-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 = crate::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/src/platforms/thinkific/downloader.rs b/src-tauri/src/platforms/thinkific/downloader.rsdeleted file mode 100644index 3d8665dc..00000000--- a/src-tauri/src/platforms/thinkific/downloader.rs+++ /dev/null@@ -1,308 +0,0 @@-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 crate::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 crate::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"));- }-- crate::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 = crate::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 = crate::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);-- crate::core::direct_downloader::download_direct(- client,- url,- out,- tx,- Some(cancel_token),- )- .await-}diff --git a/src-tauri/src/platforms/thinkific/mod.rs b/src-tauri/src/platforms/thinkific/mod.rsdeleted file mode 100644index 2cb1fa76..00000000--- a/src-tauri/src/platforms/thinkific/mod.rs+++ /dev/null@@ -1,68 +0,0 @@-pub mod api;-pub mod downloader;--use anyhow::anyhow;-use async_trait::async_trait;-use tokio::sync::mpsc;--use crate::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/src/platforms/udemy/api.rs b/src-tauri/src/platforms/udemy/api.rsdeleted file mode 100644index a022ff5b..00000000--- a/src-tauri/src/platforms/udemy/api.rs+++ /dev/null@@ -1,441 +0,0 @@-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/src/platforms/udemy/auth.rs b/src-tauri/src/platforms/udemy/auth.rsdeleted file mode 100644index 29049722..00000000--- a/src-tauri/src/platforms/udemy/auth.rs+++ /dev/null@@ -1,626 +0,0 @@-#[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 = crate::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 = crate::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/src/platforms/udemy/downloader.rs b/src-tauri/src/platforms/udemy/downloader.rsdeleted file mode 100644index 00e95a67..00000000--- a/src-tauri/src/platforms/udemy/downloader.rs+++ /dev/null@@ -1,719 +0,0 @@-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 crate::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 = crate::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/src/platforms/udemy/mod.rs b/src-tauri/src/platforms/udemy/mod.rsdeleted file mode 100644index 40571cdd..00000000--- a/src-tauri/src/platforms/udemy/mod.rs+++ /dev/null@@ -1,4 +0,0 @@-pub mod auth;-pub mod api;-pub mod downloader;-pub mod webview_api;diff --git a/src-tauri/src/platforms/voompplay/api.rs b/src-tauri/src/platforms/voompplay/api.rsdeleted file mode 100644index 8caf8a20..00000000--- a/src-tauri/src/platforms/voompplay/api.rs+++ /dev/null@@ -1,419 +0,0 @@-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 = crate::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¤t_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(())-}