Skip to content

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

Remove debug

Tonhoe4d04faa6bba
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 9d0ce724..c6ea66a7 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -4838,26 +4838,18 @@ dependencies = [
"dirs",
"filetime",
"futures",
- "grammers-client",
- "grammers-mtsender",
- "grammers-session",
- "grammers-tl-types",
"iroh",
"libloading 0.8.9",
"librqbit",
"m3u8-rs",
"omniget-core",
- "omniget-plugin-courses",
"omniget-plugin-sdk",
- "omniget-plugin-telegram",
"open",
"os_info",
- "qrcode",
"rand 0.10.0",
"regex",
"reqwest 0.12.28",
"sanitize-filename",
- "scraper",
"serde",
"serde_json",
"sha2",
@@ -4933,56 +4925,6 @@ dependencies = [
"zip 2.4.2",
]
-[[package]]
-name = "omniget-plugin-convert"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "omniget-core",
- "omniget-plugin-sdk",
- "serde",
- "serde_json",
- "tokio",
- "tokio-util",
- "tracing",
-]
-
-[[package]]
-name = "omniget-plugin-courses"
-version = "0.1.0"
-dependencies = [
- "aes",
- "anyhow",
- "async-trait",
- "base64 0.22.1",
- "cbc",
- "chromiumoxide",
- "chrono",
- "dirs",
- "filetime",
- "futures",
- "m3u8-rs",
- "omniget-core",
- "rand 0.10.0",
- "regex",
- "reqwest 0.12.28",
- "sanitize-filename",
- "scraper",
- "serde",
- "serde_json",
- "sha2",
- "tauri",
- "tauri-plugin-store",
- "tokio",
- "tokio-util",
- "tracing",
- "unicode-normalization",
- "url",
- "urlencoding",
- "webview2-com",
- "windows-core 0.61.2",
-]
-
[[package]]
name = "omniget-plugin-sdk"
version = "0.1.0"
@@ -4993,34 +4935,6 @@ dependencies = [
"serde_json",
]
-[[package]]
-name = "omniget-plugin-telegram"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "async-trait",
- "base64 0.22.1",
- "dirs",
- "filetime",
- "grammers-client",
- "grammers-mtsender",
- "grammers-session",
- "grammers-tl-types",
- "omniget-core",
- "os_info",
- "qrcode",
- "sanitize-filename",
- "serde",
- "serde_json",
- "sys-locale",
- "tauri",
- "tauri-plugin-store",
- "tokio",
- "tokio-util",
- "tracing",
- "url",
-]
-
[[package]]
name = "once_cell"
version = "1.21.3"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 7ee733e9..eab9e9d2 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,5 +1,5 @@
[workspace]
-members = [".", "omniget-core", "omniget-plugin-sdk", "omniget-plugin-courses", "omniget-plugin-telegram", "omniget-plugin-convert"]
+members = [".", "omniget-core", "omniget-plugin-sdk"]
resolver = "2"
[package]
@@ -30,7 +30,6 @@ async-trait = "0.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
chromiumoxide = { git = "https://github.com/mattsse/chromiumoxide", rev = "6f2392f", default-features = false, features = ["tokio-runtime"] }
-scraper = "0.21"
regex = "1"
m3u8-rs = "6"
aes = "0.8"
@@ -48,11 +47,6 @@ url = "2"
urlencoding = "2"
rand = "0.10.0"
base64 = "0.22.1"
-grammers-client = "0.8"
-grammers-session = "0.8"
-grammers-tl-types = "0.8"
-grammers-mtsender = "0.8"
-qrcode = { version = "0.14", default-features = false, features = ["svg"] }
os_info = "3"
sys-locale = "0.3"
filetime = "0.2.27"
@@ -63,8 +57,6 @@ sha2 = "0.10"
open = "5"
omniget-core = { path = "omniget-core", features = ["desktop"] }
omniget-plugin-sdk = { path = "omniget-plugin-sdk" }
-omniget-plugin-courses = { path = "omniget-plugin-courses" }
-omniget-plugin-telegram = { path = "omniget-plugin-telegram" }
libloading = "0.8"
which = "7"
librqbit = "8.1.1"
diff --git a/src-tauri/omniget-plugin-convert/.github/workflows/release.yml b/src-tauri/omniget-plugin-convert/.github/workflows/release.yml
deleted file mode 100644
index f0c9e6be..00000000
--- a/src-tauri/omniget-plugin-convert/.github/workflows/release.yml
+++ /dev/null
@@ -1,58 +0,0 @@
-name: Release
-on:
- push:
- tags: ['v*']
-
-jobs:
- build:
- strategy:
- matrix:
- include:
- - os: windows-latest
- target: x86_64-pc-windows-msvc
- artifact: windows-x86_64
- - os: ubuntu-22.04
- target: x86_64-unknown-linux-gnu
- artifact: linux-x86_64
- - os: macos-latest
- target: aarch64-apple-darwin
- artifact: macos-aarch64
- - os: macos-13
- target: x86_64-apple-darwin
- artifact: macos-x86_64
-
- runs-on: ${{ matrix.os }}
- permissions:
- contents: write
-
- steps:
- - uses: actions/checkout@v4
-
- - uses: dtolnay/rust-toolchain@stable
- with:
- targets: ${{ matrix.target }}
-
- - name: Install Linux deps
- if: runner.os == 'Linux'
- run: |
- sudo apt-get update
- sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libssl-dev libayatana-appindicator3-dev librsvg2-dev
-
- - name: Build
- run: cargo build --release --target ${{ matrix.target }}
-
- - name: Package
- shell: bash
- run: |
- mkdir -p dist
- cp plugin.json dist/
- cp target/${{ matrix.target }}/release/*.dll dist/ 2>/dev/null || true
- cp target/${{ matrix.target }}/release/*.so dist/ 2>/dev/null || true
- cp target/${{ matrix.target }}/release/*.dylib dist/ 2>/dev/null || true
- if [ -d frontend ]; then cp -r frontend dist/frontend; fi
- if [ -d assets ]; then cp -r assets dist/assets; fi
- cd dist && zip -r ../omniget-plugin-convert-${{ github.ref_name }}-${{ matrix.artifact }}.zip .
-
- - uses: softprops/action-gh-release@v2
- with:
- files: omniget-plugin-convert-*.zip
diff --git a/src-tauri/omniget-plugin-convert/Cargo.toml b/src-tauri/omniget-plugin-convert/Cargo.toml
deleted file mode 100644
index 04a93a6d..00000000
--- a/src-tauri/omniget-plugin-convert/Cargo.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-[package]
-name = "omniget-plugin-convert"
-version = "0.1.0"
-edition = "2021"
-
-[lib]
-crate-type = ["cdylib", "rlib"]
-
-[dependencies]
-tokio = { version = "1", features = ["full"] }
-serde = { version = "1", features = ["derive"] }
-serde_json = "1"
-anyhow = "1"
-tracing = "0.1"
-tokio-util = { version = "0.7", features = ["rt"] }
-omniget-core = { path = "../omniget-core", features = ["desktop"] }
-omniget-plugin-sdk = { path = "../omniget-plugin-sdk" }
diff --git a/src-tauri/omniget-plugin-convert/README.md b/src-tauri/omniget-plugin-convert/README.md
deleted file mode 100644
index d4c1e603..00000000
--- a/src-tauri/omniget-plugin-convert/README.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# OmniGet Media Converter Plugin
-
-Convert videos and audio between formats.
-
-## Features
-
-- Convert between video formats (MP4, MKV, WebM, AVI, MOV)
-- Extract audio (MP3, AAC, FLAC, WAV, OGG)
-- GPU hardware acceleration (NVIDIA NVENC, AMD AMF, Intel QSV)
-- Probe media files for format/codec info
-- Real-time progress with cancel support
-
-## Install
-
-This plugin is bundled with OmniGet. It can also be installed from the in-app Marketplace.
-
-## Development
-
-```bash
-cargo check -p omniget-plugin-convert
-```
diff --git a/src-tauri/omniget-plugin-convert/plugin.json b/src-tauri/omniget-plugin-convert/plugin.json
deleted file mode 100644
index e8a40913..00000000
--- a/src-tauri/omniget-plugin-convert/plugin.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "id": "convert",
- "name": "Media Converter",
- "version": "0.1.0",
- "min_omniget_version": "0.4.0",
- "description": "Convert videos and audio between formats with FFmpeg and GPU hardware acceleration.",
- "author": "tonhowtf",
- "license": "GPL-3.0",
- "homepage": "https://github.com/tonhowtf/omniget-plugin-convert",
- "icon": "assets/icon.png",
- "nav": [
- {
- "route": "/convert",
- "label": { "en": "Convert", "pt": "Converter", "zh": "转换", "ja": "変換", "fr": "Convertir", "it": "Converti", "el": "Μετατροπή" },
- "icon_svg": "M20 10H4l4-4 M4 14h16l-4 4",
- "group": "secondary",
- "order": 25
- }
- ],
- "events": {
- "progress": ["convert-progress"],
- "complete": ["convert-complete"]
- },
- "capabilities": [
- "core:events",
- "core:toast",
- "core:tools"
- ]
-}
diff --git a/src-tauri/omniget-plugin-convert/src/lib.rs b/src-tauri/omniget-plugin-convert/src/lib.rs
deleted file mode 100644
index ac831e4f..00000000
--- a/src-tauri/omniget-plugin-convert/src/lib.rs
+++ /dev/null
@@ -1,144 +0,0 @@
-use std::collections::HashMap;
-use std::sync::Arc;
-use tokio::sync::mpsc;
-use tokio_util::sync::CancellationToken;
-use omniget_plugin_sdk::{OmnigetPlugin, PluginHost};
-
-pub struct ConvertPlugin {
- host: Option<Arc<dyn PluginHost>>,
- active_conversions: Arc<tokio::sync::Mutex<HashMap<u64, CancellationToken>>>,
-}
-
-impl ConvertPlugin {
- pub fn new() -> Self {
- Self {
- host: None,
- active_conversions: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
- }
- }
-}
-
-impl OmnigetPlugin for ConvertPlugin {
- fn id(&self) -> &str { "convert" }
- fn name(&self) -> &str { "Media Converter" }
- fn version(&self) -> &str { env!("CARGO_PKG_VERSION") }
-
- fn initialize(&mut self, host: Arc<dyn PluginHost>) -> anyhow::Result<()> {
- self.host = Some(host);
- Ok(())
- }
-
- fn handle_command(
- &self,
- command: String,
- args: serde_json::Value,
- ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<serde_json::Value, String>> + Send + 'static>> {
- let host = self.host.clone();
- let active = self.active_conversions.clone();
- Box::pin(async move {
- match command.as_str() {
- "probe_file" => {
- let path: String = serde_json::from_value(
- args.get("path").cloned().ok_or("missing 'path'")?
- ).map_err(|e| e.to_string())?;
- let info = omniget_core::core::ffmpeg::probe(std::path::Path::new(&path))
- .await
- .map_err(|e| e.to_string())?;
- serde_json::to_value(info).map_err(|e| e.to_string())
- }
-
- "convert_file" => {
- let options: omniget_core::core::ffmpeg::ConversionOptions =
- serde_json::from_value(
- args.get("options").cloned().ok_or("missing 'options'")?
- ).map_err(|e| e.to_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();
- active.lock().await.insert(conversion_id, cancel_token.clone());
-
- let host = host.clone().ok_or("Plugin not initialized")?;
- let active = active.clone();
-
- tokio::spawn(async move {
- let (tx, mut rx) = mpsc::channel::<f64>(32);
-
- let host_progress = host.clone();
- let cid = conversion_id;
- let progress_forwarder = tokio::spawn(async move {
- while let Some(percent) = rx.recv().await {
- let _ = host_progress.emit_event(
- "convert-progress",
- serde_json::json!({ "id": cid, "percent": percent }),
- );
- }
- });
-
- let result = omniget_core::core::ffmpeg::convert(&options, cancel_token, tx).await;
- let _ = progress_forwarder.await;
- active.lock().await.remove(&conversion_id);
-
- match result {
- Ok(conv_result) => {
- let _ = host.emit_event("convert-complete", serde_json::json!({
- "id": conversion_id,
- "success": conv_result.success,
- "result": conv_result,
- "error": conv_result.error,
- }));
- }
- Err(e) => {
- let _ = host.emit_event("convert-complete", serde_json::json!({
- "id": conversion_id,
- "success": false,
- "result": null,
- "error": e.to_string(),
- }));
- }
- }
- });
-
- serde_json::to_value(conversion_id).map_err(|e| e.to_string())
- }
-
- "cancel_conversion" => {
- let conversion_id: u64 = serde_json::from_value(
- args.get("conversionId").or(args.get("conversion_id")).cloned()
- .ok_or("missing 'conversionId'")?
- ).map_err(|e| e.to_string())?;
-
- let mut map = active.lock().await;
- match map.remove(&conversion_id) {
- Some(token) => {
- token.cancel();
- Ok(serde_json::json!("Conversion cancelled"))
- }
- None => Err("No active conversion for this ID".to_string()),
- }
- }
-
- "get_hwaccel_info" => {
- let info = omniget_core::core::hwaccel::detect_hwaccel().await;
- serde_json::to_value(info).map_err(|e| e.to_string())
- }
-
- _ => Err(format!("Unknown command: {}", command)),
- }
- })
- }
-
- fn commands(&self) -> Vec<String> {
- vec![
- "probe_file".into(),
- "convert_file".into(),
- "cancel_conversion".into(),
- "get_hwaccel_info".into(),
- ]
- }
-}
-
-omniget_plugin_sdk::export_plugin!(ConvertPlugin::new());
diff --git a/src-tauri/omniget-plugin-courses/.github/workflows/release.yml b/src-tauri/omniget-plugin-courses/.github/workflows/release.yml
deleted file mode 100644
index 2fdfabd1..00000000
--- a/src-tauri/omniget-plugin-courses/.github/workflows/release.yml
+++ /dev/null
@@ -1,58 +0,0 @@
-name: Release
-on:
- push:
- tags: ['v*']
-
-jobs:
- build:
- strategy:
- matrix:
- include:
- - os: windows-latest
- target: x86_64-pc-windows-msvc
- artifact: windows-x86_64
- - os: ubuntu-22.04
- target: x86_64-unknown-linux-gnu
- artifact: linux-x86_64
- - os: macos-latest
- target: aarch64-apple-darwin
- artifact: macos-aarch64
- - os: macos-13
- target: x86_64-apple-darwin
- artifact: macos-x86_64
-
- runs-on: ${{ matrix.os }}
- permissions:
- contents: write
-
- steps:
- - uses: actions/checkout@v4
-
- - uses: dtolnay/rust-toolchain@stable
- with:
- targets: ${{ matrix.target }}
-
- - name: Install Linux deps
- if: runner.os == 'Linux'
- run: |
- sudo apt-get update
- sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libssl-dev libayatana-appindicator3-dev librsvg2-dev
-
- - name: Build
- run: cargo build --release --target ${{ matrix.target }}
-
- - name: Package
- shell: bash
- run: |
- mkdir -p dist
- cp plugin.json dist/
- cp target/${{ matrix.target }}/release/*.dll dist/ 2>/dev/null || true
- cp target/${{ matrix.target }}/release/*.so dist/ 2>/dev/null || true
- cp target/${{ matrix.target }}/release/*.dylib dist/ 2>/dev/null || true
- if [ -d frontend ]; then cp -r frontend dist/frontend; fi
- if [ -d assets ]; then cp -r assets dist/assets; fi
- cd dist && zip -r ../omniget-plugin-courses-${{ github.ref_name }}-${{ matrix.artifact }}.zip .
-
- - uses: softprops/action-gh-release@v2
- with:
- files: omniget-plugin-courses-*.zip
diff --git a/src-tauri/omniget-plugin-courses/Cargo.toml b/src-tauri/omniget-plugin-courses/Cargo.toml
deleted file mode 100644
index 511c47e6..00000000
--- a/src-tauri/omniget-plugin-courses/Cargo.toml
+++ /dev/null
@@ -1,38 +0,0 @@
-[package]
-name = "omniget-plugin-courses"
-version = "0.1.0"
-edition = "2021"
-
-[dependencies]
-tauri = { version = "2", features = [] }
-tokio = { version = "1", features = ["full"] }
-reqwest = { version = "0.12", default-features = false, features = ["json", "cookies", "stream", "http2", "gzip", "brotli", "deflate", "rustls-tls", "socks"] }
-futures = "0.3"
-async-trait = "0.1"
-serde = { version = "1", features = ["derive"] }
-serde_json = "1"
-chromiumoxide = { git = "https://github.com/mattsse/chromiumoxide", rev = "6f2392f", default-features = false, features = ["tokio-runtime"] }
-scraper = "0.21"
-regex = "1"
-m3u8-rs = "6"
-aes = "0.8"
-cbc = "0.1"
-anyhow = "1"
-tracing = "0.1"
-chrono = { version = "0.4", features = ["serde"] }
-rand = "0.10.0"
-dirs = "6"
-sanitize-filename = "0.6"
-unicode-normalization = "0.1"
-tokio-util = { version = "0.7", features = ["rt"] }
-url = "2"
-urlencoding = "2"
-base64 = "0.22.1"
-sha2 = "0.10"
-filetime = "0.2.27"
-tauri-plugin-store = "2"
-omniget-core = { path = "../omniget-core", features = ["desktop"] }
-
-[target.'cfg(windows)'.dependencies]
-webview2-com = "0.38"
-windows-core = "0.61"
diff --git a/src-tauri/omniget-plugin-courses/README.md b/src-tauri/omniget-plugin-courses/README.md
deleted file mode 100644
index 76d1d2a1..00000000
--- a/src-tauri/omniget-plugin-courses/README.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# OmniGet Course Downloader Plugin
-
-Download full courses from 35+ education platforms.
-
-## Supported Platforms
-
-| Platform | Auth | Region |
-|----------|------|--------|
-| Hotmart | Email + Password | BR / Global |
-| Udemy | Email + Cookies | Global |
-| Kiwify | Email + Password / Token | BR |
-| Gumroad | Email + Password / Token | Global |
-| Teachable | OTP (Email) | Global |
-| Kajabi | OTP (Email) | Global |
-| Skool | Email + Password | Global |
-| Pluralsight | Browser Cookies | Global |
-| MasterClass | Browser Cookies | Global |
-| Wondrium | Email + Password / Token | US |
-| Thinkific | Browser Cookies | Global |
-| Rocketseat | Browser Cookies | BR |
-| + 23 more Brazilian platforms | Various | BR |
-
-## Install
-
-This plugin is bundled with OmniGet. It can also be installed from the in-app Marketplace.
-
-## Development
-
-```bash
-cargo check -p omniget-plugin-courses
-```
diff --git a/src-tauri/omniget-plugin-courses/plugin.json b/src-tauri/omniget-plugin-courses/plugin.json
deleted file mode 100644
index 911ae508..00000000
--- a/src-tauri/omniget-plugin-courses/plugin.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "id": "courses",
- "name": "Course Downloader",
- "version": "0.1.0",
- "min_omniget_version": "0.4.0",
- "description": "Download full courses from 35+ education platforms including Hotmart, Udemy, Kiwify, Teachable, Kajabi, and more.",
- "author": "tonhowtf",
- "license": "GPL-3.0",
- "homepage": "https://github.com/tonhowtf/omniget-plugin-courses",
- "icon": "assets/icon.png",
- "nav": [
- {
- "route": "/courses",
- "label": { "en": "Courses", "pt": "Cursos", "zh": "课程", "ja": "コース", "fr": "Cours", "it": "Corsi", "el": "Μαθήματα" },
- "icon_svg": "M4 19.5A2.5 2.5 0 016.5 17H20 M6.5 2H20v20H6.5A2.5 2.5 0 014 19.5v-15A2.5 2.5 0 016.5 2z M8 7h8 M8 11h6",
- "group": "primary",
- "order": 30
- }
- ],
- "events": {
- "progress": ["download-progress", "udemy-download-progress"],
- "complete": ["download-complete", "udemy-download-complete"]
- },
- "capabilities": [
- "core:events",
- "core:toast",
- "core:settings",
- "core:filesystem",
- "core:proxy",
- "core:tools",
- "core:download-queue"
- ]
-}
diff --git a/src-tauri/omniget-plugin-courses/src/commands/afya.rs b/src-tauri/omniget-plugin-courses/src/commands/afya.rs
deleted file mode 100644
index 48d9c6e2..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::AfyaCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn afya_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/alpaclass.rs b/src-tauri/omniget-plugin-courses/src/commands/alpaclass.rs
deleted file mode 100644
index 27b429eb..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::AlpaclassCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn alpaclass_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/areademembros.rs b/src-tauri/omniget-plugin-courses/src/commands/areademembros.rs
deleted file mode 100644
index 4e80a08c..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_cookie_input(&cookies, "session");
-
- let session = AreaDeMembrosSession {
- cookies: parsed.cookie_string.clone(),
- site_url: clean_url.clone(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::AreaDeMembrosCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn areademembros_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/astronmembers.rs b/src-tauri/omniget-plugin-courses/src/commands/astronmembers.rs
deleted file mode 100644
index be796201..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_cookie_input(&cookies, "session");
-
- let session = AstronSession {
- cookies: parsed.cookie_string.clone(),
- site_url: clean_url.clone(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::AstronCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn astron_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/auth.rs b/src-tauri/omniget-plugin-courses/src/commands/auth.rs
deleted file mode 100644
index e310f472..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);
-
-#[tauri::command]
-pub async fn hotmart_login(
- app: tauri::AppHandle,
- state: tauri::State<'_, CoursesState>,
- 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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/omniget-plugin-courses/src/commands/cademi_cmd.rs b/src-tauri/omniget-plugin-courses/src/commands/cademi_cmd.rs
deleted file mode 100644
index 56a6ee7c..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_cookie_input(&cookie, "app_v4_session");
-
- let session = CademiSession {
- cookies: parsed.token.clone(),
- site_url: trimmed_url.clone(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::CademiCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn cademi_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/cakto.rs b/src-tauri/omniget-plugin-courses/src/commands/cakto.rs
deleted file mode 100644
index 955f92d5..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_cookie_input(&cookie, "__Secure-better-auth.session_token");
-
- let session = CaktoSession {
- cookie: parsed.token.clone(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::CaktoCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn cakto_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/caktomembers.rs b/src-tauri/omniget-plugin-courses/src/commands/caktomembers.rs
deleted file mode 100644
index be9cf76c..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::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 = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::CaktoMembersCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn caktomembers_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/courses.rs b/src-tauri/omniget-plugin-courses/src/commands/courses.rs
deleted file mode 100644
index b15fa85c..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::{CoursesState, CoursesCache};
-
-const COURSES_CACHE_TTL: Duration = Duration::from_secs(10 * 60);
-
-async fn fetch_courses_from_api(state: &tauri::State<'_, CoursesState>) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/curseduca.rs b/src-tauri/omniget-plugin-courses/src/commands/curseduca.rs
deleted file mode 100644
index ffdafbea..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = CurseducaSession {
- token: parsed_token.clone(),
- api_key: api_key.clone(),
- site_url: clean_url,
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::CurseducaCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn curseduca_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/downloads.rs b/src-tauri/omniget-plugin-courses/src/commands/downloads.rs
deleted file mode 100644
index c929ccf7..00000000
--- a/src-tauri/omniget-plugin-courses/src/commands/downloads.rs
+++ /dev/null
@@ -1,122 +0,0 @@
-use serde::Serialize;
-use tauri::Emitter;
-use tokio::sync::mpsc;
-use tokio_util::sync::CancellationToken;
-
-use crate::platforms::hotmart::api::Course;
-use crate::platforms::hotmart::downloader::HotmartDownloader;
-use crate::state::CoursesState;
-use crate::settings_helper;
-
-#[derive(Clone, Serialize)]
-struct DownloadCompleteEvent {
- course_name: String,
- success: bool,
- error: Option<String>,
-}
-
-#[tauri::command]
-pub async fn start_course_download(
- app: tauri::AppHandle,
- state: tauri::State<'_, CoursesState>,
- course_json: String,
- output_dir: String,
-) -> Result<String, String> {
- let course: Course =
- serde_json::from_str(&course_json).map_err(|e| format!("Invalid JSON: {}", e))?;
-
- let course_name = course.name.clone();
- let course_id = course.id;
- let session = state.hotmart_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 settings = settings_helper::load_settings(&app);
-
- tokio::spawn(async move {
- let downloader = HotmartDownloader::new(
- session,
- settings.download,
- settings.advanced.max_concurrent_segments,
- settings.advanced.max_retries,
- settings.advanced.concurrent_fragments,
- );
- 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("download-progress", &progress);
- }
- });
-
- let result = downloader
- .download_full_course(&course, &output_dir, tx, cancel_token)
- .await;
-
- let _ = progress_forwarder.await;
-
- {
- let mut map = active.lock().await;
- map.remove(&course_id);
- }
-
- match result {
- Ok(()) => {
- let _ = app.emit(
- "download-complete",
- &DownloadCompleteEvent {
- course_name: course.name,
- success: true,
- error: None,
- },
- );
- }
- Err(e) => {
- tracing::error!("Download error for '{}': {}", course.name, e);
- let _ = app.emit(
- "download-complete",
- &DownloadCompleteEvent {
- course_name: course.name,
- success: false,
- error: Some(e.to_string()),
- },
- );
- }
- }
- });
-
- Ok(format!("Download started: {}", course_name))
-}
-
-#[tauri::command]
-pub async fn cancel_course_download(
- state: tauri::State<'_, CoursesState>,
- course_id: u64,
-) -> Result<String, String> {
- let mut map = state.active_downloads.lock().await;
- match map.remove(&course_id) {
- Some(token) => {
- token.cancel();
- Ok("Download cancelled".to_string())
- }
- None => Err("No active download for this course".to_string()),
- }
-}
-
-#[tauri::command]
-pub async fn get_active_downloads(
- state: tauri::State<'_, CoursesState>,
-) -> Result<Vec<u64>, String> {
- let map = state.active_downloads.lock().await;
- Ok(map.keys().copied().collect())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/commands/dsa.rs b/src-tauri/omniget-plugin-courses/src/commands/dsa.rs
deleted file mode 100644
index 15d2c6b9..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = DsaSession {
- token: parsed_token.clone(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::DsaCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn dsa_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/entregadigital.rs b/src-tauri/omniget-plugin-courses/src/commands/entregadigital.rs
deleted file mode 100644
index 07513410..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::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: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::EntregaDigitalCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn entregadigital_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/estrategia_concursos.rs b/src-tauri/omniget-plugin-courses/src/commands/estrategia_concursos.rs
deleted file mode 100644
index 2ce25f7a..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_cookie_input(&token, "__Secure-SID");
-
- let client = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::EstrategiaConcursosCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn estrategia_concursos_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/estrategia_ldi.rs b/src-tauri/omniget-plugin-courses/src/commands/estrategia_ldi.rs
deleted file mode 100644
index fe84e5b3..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_cookie_input(&token, "__Secure-SID");
-
- let client = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::EstrategiaLdiCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn estrategia_ldi_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/estrategia_militares.rs b/src-tauri/omniget-plugin-courses/src/commands/estrategia_militares.rs
deleted file mode 100644
index c102f727..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_cookie_input(&token, "__Secure-SID");
-
- let client = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::EstrategiaMilitaresCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn estrategia_militares_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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::state::EstrategiaMilitaresCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn estrategia_militares_refresh_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/fluencyacademy.rs b/src-tauri/omniget-plugin-courses/src/commands/fluencyacademy.rs
deleted file mode 100644
index 4a8a68a2..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = FluencySession {
- token: parsed_token.clone(),
- email: String::new(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::FluencyCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn fluency_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/grancursos.rs b/src-tauri/omniget-plugin-courses/src/commands/grancursos.rs
deleted file mode 100644
index f3fff0e9..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_cookie_input(&cookies, "laravel_session");
-
- let client = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::GranCursosCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn grancursos_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/greatcourses.rs b/src-tauri/omniget-plugin-courses/src/commands/greatcourses.rs
deleted file mode 100644
index 0c69bec6..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = WondriumSession {
- token: parsed_token.clone(),
- email: String::new(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::WondriumCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn wondrium_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/greenn.rs b/src-tauri/omniget-plugin-courses/src/commands/greenn.rs
deleted file mode 100644
index 4f2434bd..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = GreennSession {
- token: parsed_token.clone(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::GreennCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn greenn_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/gumroad.rs b/src-tauri/omniget-plugin-courses/src/commands/gumroad.rs
deleted file mode 100644
index e541de81..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = GumroadSession {
- token: parsed_token.clone(),
- email: String::new(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::GumroadCoursesCache {
- products: products.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(products)
-}
-
-#[tauri::command]
-pub async fn gumroad_list_products(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/kajabi.rs b/src-tauri/omniget-plugin-courses/src/commands/kajabi.rs
deleted file mode 100644
index 7fb49e21..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let client = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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 = omniget_core::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<'_, CoursesState>,
-) -> 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::state::KajabiCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn kajabi_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/kirvano.rs b/src-tauri/omniget-plugin-courses/src/commands/kirvano.rs
deleted file mode 100644
index 7afb4ac0..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = KirvanoSession {
- token: parsed_token.clone(),
- email: String::new(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::KirvanoCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn kirvano_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/kiwify.rs b/src-tauri/omniget-plugin-courses/src/commands/kiwify.rs
deleted file mode 100644
index 38e15514..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = KiwifySession {
- token: parsed_token.clone(),
- email: String::new(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::KiwifyCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn kiwify_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/masterclass.rs b/src-tauri/omniget-plugin-courses/src/commands/masterclass.rs
deleted file mode 100644
index c7e1b3cf..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::MasterClassCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn masterclass_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/medcel.rs b/src-tauri/omniget-plugin-courses/src/commands/medcel.rs
deleted file mode 100644
index 46893753..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::MedcelCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn medcel_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/medcof.rs b/src-tauri/omniget-plugin-courses/src/commands/medcof.rs
deleted file mode 100644
index 060483cd..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = MedcofSession {
- token: parsed_token.clone(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::MedcofCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn medcof_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/medway.rs b/src-tauri/omniget-plugin-courses/src/commands/medway.rs
deleted file mode 100644
index a6ebd5ac..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let client = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::MedwayCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn medway_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/memberkit_cmd.rs b/src-tauri/omniget-plugin-courses/src/commands/memberkit_cmd.rs
deleted file mode 100644
index f1d6116c..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_cookie_input(&cookie, "_memberkit_session");
-
- let session = MemberkitSession {
- cookies: parsed.token.clone(),
- site_url: trimmed_url.clone(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::MemberkitCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn memberkit_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/mod.rs b/src-tauri/omniget-plugin-courses/src/commands/mod.rs
deleted file mode 100644
index 3cb720ed..00000000
--- a/src-tauri/omniget-plugin-courses/src/commands/mod.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-pub mod auth;
-pub mod courses;
-pub mod downloads;
-pub mod kiwify;
-pub mod skool;
-pub mod udemy_auth;
-pub mod udemy_courses;
-pub mod udemy_downloads;
-pub mod afya;
-pub mod alpaclass;
-pub mod areademembros;
-pub mod astronmembers;
-pub mod cademi_cmd;
-pub mod cakto;
-pub mod caktomembers;
-pub mod curseduca;
-pub mod dsa;
-pub mod entregadigital;
-pub mod estrategia_concursos;
-pub mod estrategia_ldi;
-pub mod estrategia_militares;
-pub mod fluencyacademy;
-pub mod grancursos;
-pub mod greatcourses;
-pub mod greenn;
-pub mod gumroad;
-pub mod kajabi;
-pub mod kirvano;
-pub mod masterclass;
-pub mod medcel;
-pub mod medcof;
-pub mod medway;
-pub mod memberkit_cmd;
-pub mod nutror;
-pub mod pluralsight;
-pub mod rocketseat;
-pub mod teachable;
-pub mod themembers;
-pub mod thinkific;
-pub mod voomp;
diff --git a/src-tauri/omniget-plugin-courses/src/commands/nutror.rs b/src-tauri/omniget-plugin-courses/src/commands/nutror.rs
deleted file mode 100644
index e4b5cf6b..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = NutrorSession {
- token: parsed_token.clone(),
- refresh_token: refresh_token.clone(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::NutrorCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn nutror_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/pluralsight.rs b/src-tauri/omniget-plugin-courses/src/commands/pluralsight.rs
deleted file mode 100644
index 7013b514..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::PluralsightCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn pluralsight_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/rocketseat.rs b/src-tauri/omniget-plugin-courses/src/commands/rocketseat.rs
deleted file mode 100644
index 1cf9e760..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::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 = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::RocketseatCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn rocketseat_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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::state::RocketseatCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn rocketseat_refresh_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/skool.rs b/src-tauri/omniget-plugin-courses/src/commands/skool.rs
deleted file mode 100644
index 21fb22a6..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_cookie_input(&token, "skooltok");
-
- let client = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::SkoolCoursesCache {
- groups: groups.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(groups)
-}
-
-#[tauri::command]
-pub async fn skool_list_groups(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/teachable.rs b/src-tauri/omniget-plugin-courses/src/commands/teachable.rs
deleted file mode 100644
index d909b586..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let client = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::TeachableCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn teachable_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/themembers.rs b/src-tauri/omniget-plugin-courses/src/commands/themembers.rs
deleted file mode 100644
index 3dcb4a01..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::TheMembersCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn themembers_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/thinkific.rs b/src-tauri/omniget-plugin-courses/src/commands/thinkific.rs
deleted file mode 100644
index ed556f68..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::ThinkificCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn thinkific_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/udemy_auth.rs b/src-tauri/omniget-plugin-courses/src/commands/udemy_auth.rs
deleted file mode 100644
index 17ce7024..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-const SESSION_COOLDOWN: Duration = Duration::from_secs(5 * 60);
-
-#[tauri::command]
-pub async fn udemy_login(
- app: tauri::AppHandle,
- state: tauri::State<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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/omniget-plugin-courses/src/commands/udemy_courses.rs b/src-tauri/omniget-plugin-courses/src/commands/udemy_courses.rs
deleted file mode 100644
index b94c29c2..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::{CoursesState, UdemyCoursesCache};
-
-const COURSES_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(10 * 60);
-
-async fn get_portal(state: &tauri::State<'_, CoursesState>) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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/omniget-plugin-courses/src/commands/udemy_downloads.rs b/src-tauri/omniget-plugin-courses/src/commands/udemy_downloads.rs
deleted file mode 100644
index 0980ae91..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-use crate::settings_helper;
-
-#[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<'_, CoursesState>,
- 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<'_, CoursesState>,
- 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 = settings_helper::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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/commands/voomp.rs b/src-tauri/omniget-plugin-courses/src/commands/voomp.rs
deleted file mode 100644
index 85e0d8f7..00000000
--- a/src-tauri/omniget-plugin-courses/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::state::CoursesState;
-
-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<'_, CoursesState>,
- 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 = omniget_core::core::cookie_parser::parse_bearer_input(&token);
-
- let session = VoompSession {
- token: parsed_token.clone(),
- client: omniget_core::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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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::state::VoompCoursesCache {
- courses: courses.clone(),
- fetched_at: Instant::now(),
- });
-
- Ok(courses)
-}
-
-#[tauri::command]
-pub async fn voomp_list_courses(
- state: tauri::State<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
-) -> 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<'_, CoursesState>,
- 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/omniget-plugin-courses/src/lib.rs b/src-tauri/omniget-plugin-courses/src/lib.rs
deleted file mode 100644
index 0f47b500..00000000
--- a/src-tauri/omniget-plugin-courses/src/lib.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-pub mod commands;
-pub mod platforms;
-pub mod settings_helper;
-pub mod state;
-
-pub mod models {
- pub use omniget_core::models::*;
-}
-
-use state::CoursesState;
-use tauri::{
- plugin::{Builder, TauriPlugin},
- Manager, Runtime,
-};
-
-pub fn init<R: Runtime>() -> TauriPlugin<R> {
- Builder::new("courses")
- .setup(|app, _api| {
- app.manage(CoursesState::default());
- Ok(())
- })
- .build()
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/afyainternato/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/afyainternato/api.rs
deleted file mode 100644
index c134ed5d..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::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/omniget-plugin-courses/src/platforms/afyainternato/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/afyainternato/downloader.rs
deleted file mode 100644
index bbcf86c7..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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 omniget_core::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 {
- omniget_core::core::course_utils::save_description(&lesson_dir, desc, "txt").await.ok();
- }
-
- if lesson.type_id == "videoClass" || lesson.type_id.contains("video") {
- match api::get_video_url(session, &lesson.id, &lesson.product_id).await {
- Ok(video_url) => {
- let video_path = format!(
- "{}/{}. {}.mp4",
- lesson_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[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"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://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 = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://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);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/afyainternato/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/afyainternato/mod.rs
deleted file mode 100644
index 684e988c..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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/omniget-plugin-courses/src/platforms/alpaclass/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/alpaclass/api.rs
deleted file mode 100644
index 40b3a394..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("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/omniget-plugin-courses/src/platforms/alpaclass/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/alpaclass/downloader.rs
deleted file mode 100644
index 6d370cb3..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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 omniget_core::core::course_utils::is_course_complete(&course_dir) {
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &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 {
- omniget_core::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"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- referer: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- &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 = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some(&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);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/alpaclass/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/alpaclass/mod.rs
deleted file mode 100644
index 2390d769..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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/omniget-plugin-courses/src/platforms/areademembros/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/areademembros/api.rs
deleted file mode 100644
index 2b872ef0..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("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/omniget-plugin-courses/src/platforms/areademembros/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/areademembros/downloader.rs
deleted file mode 100644
index 8ea8ce6d..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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 omniget_core::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?;
- omniget_core::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"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- None,
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/areademembros/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/areademembros/mod.rs
deleted file mode 100644
index f812e3d1..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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/omniget-plugin-courses/src/platforms/astronmembers/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/astronmembers/api.rs
deleted file mode 100644
index f4b53874..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("astron_session.json"))
-}
-
-pub async fn authenticate(site_url: &str, login: &str, password: &str) -> anyhow::Result<AstronSession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .cookie_store(true)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let login_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/omniget-plugin-courses/src/platforms/astronmembers/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/astronmembers/downloader.rs
deleted file mode 100644
index e0dfd0d3..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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 omniget_core::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?;
- omniget_core::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"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- None,
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/astronmembers/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/astronmembers/mod.rs
deleted file mode 100644
index b0000bf1..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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/omniget-plugin-courses/src/platforms/cademi/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/cademi/api.rs
deleted file mode 100644
index 10a1d138..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("cademi_session.json"))
-}
-
-pub async fn authenticate(
- email: &str,
- password: &str,
- site_url: &str,
-) -> anyhow::Result<CademiSession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .cookie_store(true)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let login_page_url = format!("{}/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 &sections {
- 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/omniget-plugin-courses/src/platforms/cademi/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/cademi/downloader.rs
deleted file mode 100644
index b73d2326..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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 omniget_core::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?;
- omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
- }
-
- if let Some(ref video_url) = detail.video_url {
- let video_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"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- None,
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/cademi/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/cademi/mod.rs
deleted file mode 100644
index 3b043c1b..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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/omniget-plugin-courses/src/platforms/cakto/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/cakto/api.rs
deleted file mode 100644
index 0bc4c343..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("cakto_session.json"))
-}
-
-pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<CaktoSession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "email": email,
- "password": password,
- "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/omniget-plugin-courses/src/platforms/cakto/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/cakto/downloader.rs
deleted file mode 100644
index b1bd6789..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::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 omniget_core::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 {
- omniget_core::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"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://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);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/cakto/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/cakto/mod.rs
deleted file mode 100644
index f2f1ef36..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct CaktoDownloader;
-
-impl Default for CaktoDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl CaktoDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for CaktoDownloader {
- fn name(&self) -> &str {
- "cakto"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "cakto.com.br"
- || host == "aluno.cakto.com.br"
- || host == "app.cakto.com.br";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Cakto".to_string(),
- author: String::new(),
- platform: "cakto".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "Original".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Cakto"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/api.rs
deleted file mode 100644
index bf858fce..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn build_cookie_client(cookie: &str) -> anyhow::Result<reqwest::Client> {
- let mut headers = HeaderMap::new();
- headers.insert(
- "Cookie",
- HeaderValue::from_str(&format!("sessionid={}", cookie))?,
- );
- headers.insert("Accept", HeaderValue::from_static("application/json"));
-
- let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("caktomembers_session.json"))
-}
-
-pub async fn fetch_access_token(cookie: &str) -> anyhow::Result<String> {
- let cookie_client = build_cookie_client(cookie)?;
-
- let url = format!("{}/api/members/courses/token/", API_BASE);
- let resp = cookie_client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "fetch_access_token returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let token = body
- .get("accessToken")
- .or_else(|| body.get("access_token"))
- .or_else(|| body.get("token"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("No accessToken in response"))?
- .to_string();
-
- Ok(token)
-}
-
-pub async fn validate_token(session: &CaktoMembersSession) -> anyhow::Result<bool> {
- let url = format!("{}/api/members/courses/", API_BASE);
- let resp = session.client.get(&url).send().await?;
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &CaktoMembersSession) -> anyhow::Result<Vec<CaktoMembersCourse>> {
- let url = format!("{}/api/members/courses/", API_BASE);
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let courses_arr = if body.is_array() {
- body.as_array().cloned().unwrap_or_default()
- } else {
- body.get("results")
- .or_else(|| body.get("courses"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default()
- };
-
- let mut courses = Vec::new();
-
- for item in &courses_arr {
- let id = item
- .get("externalId")
- .or_else(|| item.get("id"))
- .map(|v| match v {
- serde_json::Value::String(s) => s.clone(),
- serde_json::Value::Number(n) => n.to_string(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let name = item
- .get("nome")
- .or_else(|| item.get("name"))
- .or_else(|| item.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if !id.is_empty() {
- courses.push(CaktoMembersCourse { id, name });
- }
-
- if let Some(modulos) = item.get("modulos").and_then(|v| v.as_array()) {
- let _ = modulos;
- }
- }
-
- Ok(courses)
-}
-
-pub async fn get_course_content(
- session: &CaktoMembersSession,
- course_id: &str,
-) -> anyhow::Result<Vec<CaktoMembersModule>> {
- let url = format!("{}/api/members/courses/", API_BASE);
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let courses_arr = if body.is_array() {
- body.as_array().cloned().unwrap_or_default()
- } else {
- body.get("results")
- .or_else(|| body.get("courses"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default()
- };
-
- let course_data = courses_arr
- .iter()
- .find(|c| {
- let eid = c.get("externalId").or_else(|| c.get("id"));
- if let Some(v) = eid {
- match v {
- serde_json::Value::String(s) => s == course_id,
- serde_json::Value::Number(n) => n.to_string() == course_id,
- _ => false,
- }
- } else {
- false
- }
- })
- .ok_or_else(|| anyhow!("Course not found in response"))?;
-
- let modulos = course_data
- .get("modulos")
- .or_else(|| course_data.get("modules"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for (mi, mod_val) in modulos.iter().enumerate() {
- let mod_id = mod_val
- .get("id")
- .map(|v| match v {
- serde_json::Value::String(s) => s.clone(),
- serde_json::Value::Number(n) => n.to_string(),
- _ => format!("{}", mi),
- })
- .unwrap_or_else(|| format!("{}", mi));
-
- let mod_name = mod_val
- .get("nome")
- .or_else(|| mod_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let aulas = mod_val
- .get("aulas")
- .or_else(|| mod_val.get("lessons"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (li, lesson_val) in aulas.iter().enumerate() {
- let lesson_id = lesson_val
- .get("id")
- .map(|v| match v {
- serde_json::Value::String(s) => s.clone(),
- serde_json::Value::Number(n) => n.to_string(),
- _ => format!("{}", li),
- })
- .unwrap_or_else(|| format!("{}", li));
-
- let lesson_name = lesson_val
- .get("nome")
- .or_else(|| lesson_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let video_uuid = lesson_val
- .get("video")
- .or_else(|| lesson_val.get("video_uuid"))
- .or_else(|| lesson_val.get("videoUuid"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let description = lesson_val
- .get("descricao")
- .or_else(|| lesson_val.get("description"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(String::from);
-
- lessons.push(CaktoMembersLesson {
- id: lesson_id,
- name: lesson_name,
- order: li as i64,
- video_uuid,
- description,
- });
- }
-
- modules.push(CaktoMembersModule {
- id: mod_id,
- name: mod_name,
- order: mi as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-pub async fn get_lesson_video_url(
- session: &CaktoMembersSession,
- lesson_id: &str,
- video_uuid: Option<&str>,
-) -> anyhow::Result<Option<String>> {
- if let Some(uuid) = video_uuid {
- if !uuid.is_empty() {
- let hls_url = format!("https://stream.cakto.com.br/{}/playlist.m3u8", uuid);
- return Ok(Some(hls_url));
- }
- }
-
- let url = format!(
- "https://us-central1-cakto2.cloudfunctions.net/api/aulas/{}/assistir",
- lesson_id
- );
- let resp = session.client.get(&url).send().await?;
-
- if resp.status().is_success() {
- let body_text = resp.text().await?;
- if let Ok(body) = serde_json::from_str::<serde_json::Value>(&body_text) {
- if let Some(url) = body.get("video_url")
- .or_else(|| body.get("url"))
- .or_else(|| body.get("videoUrl"))
- .and_then(|v| v.as_str())
- {
- return Ok(Some(url.to_string()));
- }
- }
- }
-
- Ok(None)
-}
-
-pub async fn save_session(session: &CaktoMembersSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- cookie: session.cookie.clone(),
- access_token: session.access_token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[caktomembers] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<CaktoMembersSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.access_token)?;
-
- tracing::info!("[caktomembers] session loaded");
-
- Ok(Some(CaktoMembersSession {
- cookie: saved.cookie,
- access_token: saved.access_token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/downloader.rs
deleted file mode 100644
index ee5c552e..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, CaktoMembersCourse, CaktoMembersSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct CaktoMembersDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &CaktoMembersSession,
- course: &CaktoMembersCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, &course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[caktomembers] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &CaktoMembersDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
-
- if let Some(ref desc) = lesson.description {
- let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_desc_dir).await?;
- omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
- }
-
- let video_url = match api::get_lesson_video_url(session, &lesson.id, lesson.video_uuid.as_deref()).await {
- Ok(Some(url)) => url,
- Ok(None) => {
- tracing::warn!("[caktomembers] No video found for lesson '{}'", lesson.name);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &CaktoMembersDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- Err(e) => {
- tracing::error!("[caktomembers] Failed to get video URL for '{}': {}", lesson.name, e);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &CaktoMembersDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- let video_path = format!(
- "{}/{}. {}.mp4",
- mod_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[caktomembers] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &CaktoMembersDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if video_url.contains(".m3u8") {
- match download_hls_video(&video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[caktomembers] HLS download failed for '{}': {}", lesson.name, e);
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[caktomembers] yt-dlp download failed for '{}': {}", lesson.name, e);
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &CaktoMembersDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://app.cakto.com.br/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = std::path::Path::new(output_dir);
- let (tx, _rx) = tokio::sync::mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://app.cakto.com.br/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/caktomembers/mod.rs
deleted file mode 100644
index fac3e892..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct CaktoMembersDownloader;
-
-impl Default for CaktoMembersDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl CaktoMembersDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for CaktoMembersDownloader {
- fn name(&self) -> &str {
- "caktomembers"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "app.cakto.com.br";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Cakto Members".to_string(),
- author: String::new(),
- platform: "caktomembers".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Cakto Members courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/curseduca/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/curseduca/api.rs
deleted file mode 100644
index b812d5b4..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("curseduca_session.json"))
-}
-
-pub async fn discover_api_key(site_url: &str) -> anyhow::Result<String> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let clean_url = site_url.trim_end_matches('/');
-
- let resp = temp_client
- .get("https://application.curseduca.pro/platform-by-url")
- .query(&[("url", clean_url)])
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "discover_api_key returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let key = body
- .get("key")
- .or_else(|| body.get("apiKey"))
- .or_else(|| body.get("api_key"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("No API key in platform discovery response"))?
- .to_string();
-
- Ok(key)
-}
-
-pub async fn authenticate(site_url: &str, username: &str, password: &str) -> anyhow::Result<CurseducaSession> {
- let api_key = discover_api_key(site_url).await?;
-
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "username": username,
- "password": password,
- });
-
- let resp = temp_client
- .post("https://prof.curseduca.pro/login")
- .header("api_key", &api_key)
- .header("Content-Type", "application/json")
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Authentication failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let token = body
- .get("accessToken")
- .or_else(|| body.get("token"))
- .or_else(|| body.get("access_token"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("No access token in login response"))?
- .to_string();
-
- let client = build_client(&token, &api_key)?;
-
- Ok(CurseducaSession {
- token,
- api_key,
- site_url: site_url.to_string(),
- client,
- })
-}
-
-pub async fn validate_token(session: &CurseducaSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://prof.curseduca.pro/me/access")
- .send()
- .await?;
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &CurseducaSession) -> anyhow::Result<Vec<CurseducaCourse>> {
- let resp = session
- .client
- .get("https://prof.curseduca.pro/me/access")
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let courses_arr = if body.is_array() {
- body.as_array().cloned().unwrap_or_default()
- } else {
- body.get("courses")
- .or_else(|| body.get("data"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default()
- };
-
- let mut courses = Vec::new();
-
- for item in &courses_arr {
- let id = item
- .get("id")
- .map(|v| match v {
- serde_json::Value::String(s) => s.clone(),
- serde_json::Value::Number(n) => n.to_string(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let name = item
- .get("name")
- .or_else(|| item.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let slug = item
- .get("slug")
- .and_then(|v| v.as_str())
- .unwrap_or(&id)
- .to_string();
-
- if !id.is_empty() {
- courses.push(CurseducaCourse { id, name, slug });
- }
- }
-
- Ok(courses)
-}
-
-pub async fn get_course_content(
- session: &CurseducaSession,
- course_slug: &str,
-) -> anyhow::Result<Vec<CurseducaModule>> {
- let url = format!("{}/m/lessons/{}", session.site_url.trim_end_matches('/'), course_slug);
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let mut modules = Vec::new();
- let mut module_order = 0i64;
-
- let mut search_pos = 0;
- while let Some(script_start) = body_text[search_pos..].find("<script") {
- let abs_start = search_pos + script_start;
- if let Some(script_end) = body_text[abs_start..].find("</script>") {
- let script_content = &body_text[abs_start..abs_start + script_end];
- search_pos = abs_start + script_end + 9;
-
- if script_content.contains("modules") || script_content.contains("lessons") {
- if let Some(json_start) = script_content.find('{') {
- let json_str = &script_content[json_start..];
- if let Some(end) = find_matching_brace(json_str) {
- if let Ok(data) = serde_json::from_str::<serde_json::Value>(&json_str[..=end]) {
- if let Some(mods) = extract_modules_from_data(&data) {
- for m in mods {
- modules.push(m);
- }
- }
- }
- }
- }
- }
- } else {
- break;
- }
- }
-
- if modules.is_empty() {
- if let Ok(data) = serde_json::from_str::<serde_json::Value>(&body_text) {
- if let Some(mods) = extract_modules_from_data(&data) {
- modules = mods;
- }
- }
- }
-
- for m in &mut modules {
- module_order += 1;
- m.order = module_order;
- }
-
- Ok(modules)
-}
-
-fn find_matching_brace(s: &str) -> Option<usize> {
- let mut depth = 0i32;
- for (i, ch) in s.char_indices() {
- match ch {
- '{' => depth += 1,
- '}' => {
- depth -= 1;
- if depth == 0 {
- return Some(i);
- }
- }
- _ => {}
- }
- }
- None
-}
-
-fn extract_modules_from_data(data: &serde_json::Value) -> Option<Vec<CurseducaModule>> {
- let modules_arr = data.get("modules")
- .or_else(|| data.get("content"))
- .and_then(|v| v.as_array())?;
-
- let mut modules = Vec::new();
-
- for (mi, mod_val) in modules_arr.iter().enumerate() {
- let mod_id = mod_val.get("id")
- .map(|v| match v {
- serde_json::Value::String(s) => s.clone(),
- serde_json::Value::Number(n) => n.to_string(),
- _ => format!("{}", mi),
- })
- .unwrap_or_else(|| format!("{}", mi));
-
- let mod_name = mod_val.get("name")
- .or_else(|| mod_val.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lessons_arr = mod_val.get("lessons")
- .or_else(|| mod_val.get("aulas"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (li, lesson_val) in lessons_arr.iter().enumerate() {
- let lesson_id = lesson_val.get("id")
- .map(|v| match v {
- serde_json::Value::String(s) => s.clone(),
- serde_json::Value::Number(n) => n.to_string(),
- _ => format!("{}", li),
- })
- .unwrap_or_else(|| format!("{}", li));
-
- let lesson_name = lesson_val.get("name")
- .or_else(|| lesson_val.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let uuid = lesson_val.get("uuid")
- .or_else(|| lesson_val.get("externalId"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let video_type = lesson_val.get("type")
- .or_else(|| lesson_val.get("videoType"))
- .and_then(|v| v.as_i64());
-
- let description = lesson_val.get("description")
- .or_else(|| lesson_val.get("content"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(String::from);
-
- lessons.push(CurseducaLesson {
- id: lesson_id,
- name: lesson_name,
- order: li as i64,
- uuid,
- video_type,
- description,
- });
- }
-
- modules.push(CurseducaModule {
- id: mod_id,
- name: mod_name,
- order: mi as i64,
- lessons,
- });
- }
-
- Some(modules)
-}
-
-pub async fn get_lesson_video_url(
- session: &CurseducaSession,
- lesson_uuid: &str,
-) -> anyhow::Result<Option<String>> {
- let url = format!("https://clas.curseduca.pro/bff/aulas/{}/watch", lesson_uuid);
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lesson_video_url returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let video_url = body
- .get("url")
- .or_else(|| body.get("videoUrl"))
- .or_else(|| body.get("video_url"))
- .or_else(|| body.get("playbackUrl"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- if video_url.is_some() {
- return Ok(video_url);
- }
-
- let video_type = body.get("type").and_then(|v| v.as_i64()).unwrap_or(0);
-
- match video_type {
- 4 => {
- if let Some(vid_id) = body.get("externalId").or_else(|| body.get("videoId")).and_then(|v| v.as_str()) {
- return Ok(Some(format!("https://www.youtube.com/watch?v={}", vid_id)));
- }
- }
- 7 => {
- if let Some(vid_id) = body.get("externalId").or_else(|| body.get("videoId")).and_then(|v| v.as_str()) {
- return Ok(Some(format!("https://player.vimeo.com/video/{}", vid_id)));
- }
- }
- 20 => {
- if let Some(hls) = body.get("hlsUrl").or_else(|| body.get("streamUrl")).and_then(|v| v.as_str()) {
- return Ok(Some(hls.to_string()));
- }
- }
- 22 => {
- if let Some(url) = body.get("scaleupUrl").or_else(|| body.get("playerUrl")).and_then(|v| v.as_str()) {
- return Ok(Some(url.to_string()));
- }
- }
- _ => {}
- }
-
- Ok(None)
-}
-
-pub async fn save_session(session: &CurseducaSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- api_key: session.api_key.clone(),
- site_url: session.site_url.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[curseduca] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<CurseducaSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token, &saved.api_key)?;
-
- tracing::info!("[curseduca] session loaded");
-
- Ok(Some(CurseducaSession {
- token: saved.token,
- api_key: saved.api_key,
- site_url: saved.site_url,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/curseduca/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/curseduca/downloader.rs
deleted file mode 100644
index aa7a24eb..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, CurseducaCourse, CurseducaSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct CurseducaDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &CurseducaSession,
- course: &CurseducaCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, &course.slug).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[curseduca] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &CurseducaDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
-
- if let Some(ref desc) = lesson.description {
- let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_desc_dir).await?;
- omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
- }
-
- let lesson_uuid = lesson.uuid.as_deref().unwrap_or(&lesson.id);
-
- let video_url = match api::get_lesson_video_url(session, lesson_uuid).await {
- Ok(Some(url)) => url,
- Ok(None) => {
- tracing::warn!("[curseduca] No video found for lesson '{}'", lesson.name);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &CurseducaDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- Err(e) => {
- tracing::error!("[curseduca] Failed to get video URL for '{}': {}", lesson.name, e);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &CurseducaDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- let video_path = format!(
- "{}/{}. {}.mp4",
- mod_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[curseduca] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &CurseducaDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if video_url.contains(".m3u8") {
- match download_hls_video(&video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[curseduca] HLS download failed for '{}': {}", lesson.name, e);
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[curseduca] yt-dlp download failed for '{}': {}", lesson.name, e);
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &CurseducaDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- None,
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/curseduca/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/curseduca/mod.rs
deleted file mode 100644
index cdc5196d..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct CurseducaDownloader;
-
-impl Default for CurseducaDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl CurseducaDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for CurseducaDownloader {
- fn name(&self) -> &str {
- "curseduca"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "curseduca.pro"
- || host.ends_with(".curseduca.pro")
- || host == "curseduca.com";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Curseduca Course".to_string(),
- author: String::new(),
- platform: "curseduca".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Curseduca courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/api.rs
deleted file mode 100644
index 1a940e4a..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("dsa_session.json"))
-}
-
-pub async fn validate_token(session: &DsaSession) -> anyhow::Result<bool> {
- let url = format!("{}/api/products_all", API_BASE);
-
- let resp = session.client.get(&url).send().await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &DsaSession) -> anyhow::Result<Vec<DsaCourse>> {
- let url = format!("{}/api/products_all", API_BASE);
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let courses_map = body
- .get("courses")
- .and_then(|v| v.as_object())
- .cloned()
- .unwrap_or_default();
-
- let allowed_ids: Vec<String> = body
- .get("allowedCourseIds")
- .and_then(|v| v.as_array())
- .map(|arr| {
- arr.iter()
- .filter_map(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
- .collect()
- })
- .unwrap_or_default();
-
- let mut enrolled_ids: Vec<String> = Vec::new();
- let progress_url = format!("{}/api/user/courses-progress", API_BASE);
- if let Ok(progress_resp) = session.client.get(&progress_url).send().await {
- if progress_resp.status().is_success() {
- if let Ok(progress_text) = progress_resp.text().await {
- if let Ok(progress_body) = serde_json::from_str::<serde_json::Value>(&progress_text) {
- if let Some(user_courses) = progress_body.get("userCourses").and_then(|v| v.as_array()) {
- for uc in user_courses {
- let me = uc.get("me").unwrap_or(&serde_json::Value::Null);
- let is_premium = me.get("premium").and_then(|v| v.as_bool()).unwrap_or(false);
- let is_registered = me.get("registered").and_then(|v| v.as_bool()).unwrap_or(false);
- if is_premium || is_registered {
- if let Some(cid) = uc.get("courseId") {
- enrolled_ids.push(cid.to_string().trim_matches('"').to_string());
- }
- }
- }
- }
- }
- }
- }
- }
-
- let mut result = Vec::new();
-
- for (cid, course) in &courses_map {
- let me = course.get("me").unwrap_or(&serde_json::Value::Null);
- let course_id = course
- .get("id")
- .map(|v| v.to_string().trim_matches('"').to_string())
- .unwrap_or_else(|| cid.clone());
-
- let is_registered = me.get("registered").and_then(|v| v.as_bool()).unwrap_or(false);
- let is_allowed = allowed_ids.contains(&course_id) || allowed_ids.contains(cid);
- let is_free = course.get("status").and_then(|v| v.as_str()) == Some("free");
- let is_enrolled = enrolled_ids.contains(&course_id);
-
- if !is_registered && !is_allowed && !is_free && !is_enrolled {
- continue;
- }
-
- let name = course
- .get("title")
- .and_then(|v| v.as_str())
- .unwrap_or("Course")
- .to_string();
-
- let slug = course
- .get("titleId")
- .and_then(|v| v.as_str())
- .unwrap_or(cid)
- .to_string();
-
- result.push(DsaCourse {
- id: course_id,
- name,
- slug,
- });
- }
-
- result.sort_by(|a, b| a.name.cmp(&b.name));
-
- Ok(result)
-}
-
-pub async fn get_course_content(
- session: &DsaSession,
- slug: &str,
-) -> anyhow::Result<Vec<DsaModule>> {
- let url = format!("{}/api/course/{}?contents", API_BASE, slug);
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let course_data = body.get("course").unwrap_or(&body);
- let sections = course_data.get("sections");
- let videos = course_data
- .get("videos")
- .and_then(|v| v.as_object())
- .cloned()
- .unwrap_or_default();
-
- let sections_list: Vec<serde_json::Value> = match sections {
- Some(serde_json::Value::Object(map)) => map.values().cloned().collect(),
- Some(serde_json::Value::Array(arr)) => arr.clone(),
- _ => Vec::new(),
- };
-
- let mut modules = Vec::new();
-
- for (section_index, section) in sections_list.iter().enumerate() {
- let title = resolve_title(
- section.get("titles").or_else(|| section.get("title")),
- &format!("Module {}", section_index + 1),
- );
-
- let learning_path = section
- .get("learningPath")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (lesson_index, item) in learning_path.iter().enumerate() {
- let unit_id = item
- .get("id")
- .map(|v| v.to_string().trim_matches('"').to_string())
- .unwrap_or_else(|| format!("{}-{}", section_index + 1, lesson_index + 1));
-
- let unit_type = item
- .get("type")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_lowercase();
-
- let mut lesson_title = String::new();
-
- if (unit_type == "ivideo" || unit_type == "video") && videos.contains_key(&unit_id) {
- if let Some(vid) = videos.get(&unit_id) {
- lesson_title = vid
- .get("title")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
- }
- }
-
- if lesson_title.is_empty() || lesson_title == "Untitled" {
- lesson_title = resolve_title(
- item.get("titles").or_else(|| item.get("unitTitle")),
- &format!("Lesson {}", lesson_index + 1),
- );
- }
-
- let vimeo_id = if (unit_type == "ivideo" || unit_type == "video") && videos.contains_key(&unit_id) {
- videos
- .get(&unit_id)
- .and_then(|vid| vid.get("vimeoid"))
- .and_then(|v| v.as_str())
- .map(String::from)
- } else {
- None
- };
-
- let description = item
- .get("description")
- .or_else(|| item.get("content"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(String::from);
-
- lessons.push(DsaLesson {
- id: unit_id,
- name: lesson_title,
- order: (lesson_index + 1) as i64,
- item_type: unit_type,
- vimeo_id,
- description,
- });
- }
-
- let section_id = section
- .get("titleId")
- .or_else(|| section.get("id"))
- .map(|v| v.to_string().trim_matches('"').to_string())
- .unwrap_or_else(|| format!("{}", section_index + 1));
-
- modules.push(DsaModule {
- id: section_id,
- name: title,
- order: (section_index + 1) as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-fn resolve_title(raw: Option<&serde_json::Value>, fallback: &str) -> String {
- match raw {
- Some(serde_json::Value::Object(map)) => {
- for key in &["pt-BR", "pt", "en", "title"] {
- if let Some(val) = map.get(*key).and_then(|v| v.as_str()) {
- let trimmed = val.trim();
- if !trimmed.is_empty() {
- return trimmed.to_string();
- }
- }
- }
- for val in map.values() {
- if let Some(s) = val.as_str() {
- let trimmed = s.trim();
- if !trimmed.is_empty() {
- return trimmed.to_string();
- }
- }
- }
- fallback.to_string()
- }
- Some(serde_json::Value::Array(arr)) => {
- for entry in arr {
- if let Some(s) = entry.as_str() {
- let trimmed = s.trim();
- if !trimmed.is_empty() {
- return trimmed.to_string();
- }
- }
- }
- fallback.to_string()
- }
- Some(serde_json::Value::String(s)) => {
- let trimmed = s.trim();
- if !trimmed.is_empty() {
- trimmed.to_string()
- } else {
- fallback.to_string()
- }
- }
- _ => fallback.to_string(),
- }
-}
-
-pub async fn save_session(session: &DsaSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[dsa] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<DsaSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[dsa] session loaded");
-
- Ok(Some(DsaSession {
- token: saved.token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/downloader.rs
deleted file mode 100644
index e1ba0c22..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, DsaCourse, DsaSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct DsaCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &DsaSession,
- course: &DsaCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, &course.slug).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[dsa] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &DsaCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
-
- if let Some(ref desc) = lesson.description {
- let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_desc_dir).await?;
- omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
- }
-
- if lesson.item_type == "ivideo" || lesson.item_type == "video" {
- if let Some(ref vimeo_id) = lesson.vimeo_id {
- if vimeo_id.is_empty() {
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &DsaCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
-
- let video_path = format!(
- "{}/{}. {}.mp4",
- mod_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[dsa] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &DsaCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- let vimeo_url = format!("https://player.vimeo.com/video/{}", vimeo_id);
-
- match download_with_ytdlp(&vimeo_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[dsa] yt-dlp download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &DsaCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://www.datascienceacademy.com.br/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/datascienceacademy/mod.rs
deleted file mode 100644
index 14239aa6..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct DataScienceAcademyDownloader;
-
-impl Default for DataScienceAcademyDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl DataScienceAcademyDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for DataScienceAcademyDownloader {
- fn name(&self) -> &str {
- "datascienceacademy"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "datascienceacademy.com.br"
- || host == "www.datascienceacademy.com.br";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Data Science Academy".to_string(),
- author: String::new(),
- platform: "datascienceacademy".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "Original".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Data Science Academy"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/api.rs
deleted file mode 100644
index ed82c72f..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("nutror_session.json"))
-}
-
-pub async fn refresh_token(session: &NutrorSession) -> anyhow::Result<NutrorSession> {
- let refresh = session
- .refresh_token
- .as_deref()
- .ok_or_else(|| anyhow!("No refresh token available"))?;
-
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let resp = temp_client
- .post("https://learner-api.nutror.com/oauth/refresh?startWhen=requestFailed")
- .header("Authorization", format!("Bearer {}", session.token))
- .header("RefreshToken", refresh)
- .header("Accept", "application/json")
- .header("FrontVersion", "1458")
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Token refresh failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let new_token = body
- .get("token")
- .or_else(|| body.get("access_token"))
- .or_else(|| body.get("newAuthToken"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("No token in refresh response"))?
- .to_string();
-
- let new_refresh = body
- .get("refreshToken")
- .or_else(|| body.get("refresh_token"))
- .and_then(|v| v.as_str())
- .map(String::from)
- .or_else(|| session.refresh_token.clone());
-
- let client = build_client(&new_token)?;
-
- Ok(NutrorSession {
- token: new_token,
- refresh_token: new_refresh,
- client,
- })
-}
-
-pub async fn validate_token(session: &NutrorSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://learner-api.nutror.com/learner/course/search?page=1&size=1&status=seeAll&showShelf=true")
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &NutrorSession) -> anyhow::Result<Vec<NutrorCourse>> {
- let mut all_courses = Vec::new();
- let mut page = 1u32;
-
- loop {
- let url = format!(
- "https://learner-api.nutror.com/learner/course/search?page={}&size=20&status=seeAll&showShelf=true",
- page
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let data = body
- .get("data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- if data.is_empty() {
- break;
- }
-
- for item in &data {
- let id = item
- .get("id")
- .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
- .unwrap_or_default();
-
- let name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let hash = item
- .get("hash")
- .or_else(|| item.get("courseHash"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- all_courses.push(NutrorCourse {
- id,
- name,
- hash,
- });
- }
-
- let total_pages = body
- .get("totalPages")
- .or_else(|| body.get("total_pages"))
- .and_then(|v| v.as_u64())
- .unwrap_or(1);
-
- if page as u64 >= total_pages {
- break;
- }
-
- page += 1;
- }
-
- Ok(all_courses)
-}
-
-pub async fn get_modules(
- session: &NutrorSession,
- course_hash: &str,
-) -> anyhow::Result<Vec<NutrorModule>> {
- let url = format!(
- "https://learner-api.nutror.com/learner/course/{}/lessons/v2",
- course_hash
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_modules returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let data = body
- .get("data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_else(|| {
- body.as_array().cloned().unwrap_or_default()
- });
-
- let mut modules = Vec::new();
-
- for (i, item) in data.iter().enumerate() {
- let id = item
- .get("id")
- .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
- .unwrap_or_default();
-
- let name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let order = item
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(i as i64);
-
- let mut lessons = Vec::new();
-
- let lessons_arr = item
- .get("lessons")
- .or_else(|| item.get("items"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for (j, lesson_val) in lessons_arr.iter().enumerate() {
- let lesson_id = lesson_val
- .get("id")
- .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
- .unwrap_or_default();
-
- let lesson_name = lesson_val
- .get("title")
- .or_else(|| lesson_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_hash = lesson_val
- .get("hash")
- .or_else(|| lesson_val.get("lessonHash"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_order = lesson_val
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(j as i64);
-
- lessons.push(NutrorLesson {
- id: lesson_id,
- name: lesson_name,
- hash: lesson_hash,
- order: lesson_order,
- });
- }
-
- lessons.sort_by_key(|l| l.order);
-
- modules.push(NutrorModule {
- id,
- name,
- order,
- lessons,
- });
- }
-
- modules.sort_by_key(|m| m.order);
-
- Ok(modules)
-}
-
-pub async fn get_lesson_detail(
- session: &NutrorSession,
- lesson_hash: &str,
-) -> anyhow::Result<NutrorLessonDetail> {
- let url = format!(
- "https://learner-api.nutror.com/learner/lessons/{}",
- lesson_hash
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lesson_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let lesson = body.get("data").unwrap_or(&body);
-
- let id = lesson
- .get("id")
- .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
- .unwrap_or_default();
-
- let name = lesson
- .get("title")
- .or_else(|| lesson.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let mut video_url: Option<String> = None;
- let mut files = Vec::new();
- let mut description: Option<String> = None;
-
- let contents = lesson
- .get("contents")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for content in &contents {
- let type_obj = content.get("type");
- let type_id = type_obj
- .and_then(|t| t.get("id").and_then(|v| v.as_i64()))
- .unwrap_or(0);
-
- let embed = content
- .get("content")
- .or_else(|| content.get("embed"))
- .or_else(|| content.get("url"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if type_id == 4 && description.is_none() && !embed.trim().is_empty() {
- description = Some(embed.to_string());
- }
-
- if video_url.is_none() {
- match type_id {
- 1 => {
- let yt_id = extract_youtube_id(embed);
- if let Some(yt_id) = yt_id {
- video_url = Some(format!("https://www.youtube.com/watch?v={}", yt_id));
- }
- }
- 9 => {
- let safe_url = extract_safevideo_url(embed);
- if let Some(url) = safe_url {
- video_url = Some(url);
- }
- }
- _ => {
- if embed.contains("youtube.com") || embed.contains("youtu.be") {
- video_url = Some(embed.to_string());
- } else if embed.contains("vimeo.com") {
- video_url = Some(embed.to_string());
- } else if embed.contains(".mp4") || embed.contains(".m3u8") {
- video_url = Some(embed.to_string());
- }
- }
- }
- }
- }
-
- let lesson_files = lesson
- .get("lesson_files")
- .or_else(|| lesson.get("files"))
- .or_else(|| lesson.get("attachments"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for file in &lesson_files {
- let file_name = file
- .get("name")
- .or_else(|| file.get("title"))
- .or_else(|| file.get("filename"))
- .and_then(|v| v.as_str())
- .unwrap_or("file")
- .to_string();
-
- let file_url = file
- .get("url")
- .or_else(|| file.get("download_url"))
- .or_else(|| file.get("path"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if !file_url.is_empty() {
- files.push(NutrorFile {
- name: file_name,
- url: file_url,
- });
- }
- }
-
- if description.is_none() {
- description = lesson
- .get("description")
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(String::from);
- }
-
- Ok(NutrorLessonDetail {
- id,
- name,
- video_url,
- files,
- description,
- })
-}
-
-fn extract_youtube_id(embed: &str) -> Option<String> {
- if let Some(pos) = embed.find("youtube.com/embed/") {
- let rest = &embed[pos + 18..];
- let end = rest.find(|c: char| c == '"' || c == '?' || c == '&' || c == '\'').unwrap_or(rest.len());
- let id = &rest[..end];
- if !id.is_empty() {
- return Some(id.to_string());
- }
- }
- if let Some(pos) = embed.find("watch?v=") {
- let rest = &embed[pos + 8..];
- let end = rest.find(|c: char| c == '&' || c == '"' || c == '\'').unwrap_or(rest.len());
- let id = &rest[..end];
- if !id.is_empty() {
- return Some(id.to_string());
- }
- }
- if let Some(pos) = embed.find("youtu.be/") {
- let rest = &embed[pos + 9..];
- let end = rest.find(|c: char| c == '?' || c == '"' || c == '\'').unwrap_or(rest.len());
- let id = &rest[..end];
- if !id.is_empty() {
- return Some(id.to_string());
- }
- }
- None
-}
-
-fn extract_safevideo_url(embed: &str) -> Option<String> {
- if let Some(pos) = embed.find("src=\"") {
- let rest = &embed[pos + 5..];
- let end = rest.find('"').unwrap_or(rest.len());
- let url = &rest[..end];
- if !url.is_empty() {
- return Some(url.to_string());
- }
- }
- if let Some(pos) = embed.find("src='") {
- let rest = &embed[pos + 5..];
- let end = rest.find('\'').unwrap_or(rest.len());
- let url = &rest[..end];
- if !url.is_empty() {
- return Some(url.to_string());
- }
- }
- if embed.starts_with("http") && !embed.contains('<') {
- return Some(embed.to_string());
- }
- None
-}
-
-pub async fn save_session(session: &NutrorSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- refresh_token: session.refresh_token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[nutror] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<NutrorSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[nutror] session loaded");
-
- Ok(Some(NutrorSession {
- token: saved.token,
- refresh_token: saved.refresh_token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/downloader.rs
deleted file mode 100644
index afbe38a6..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, NutrorCourse, NutrorSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct NutrorCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &NutrorSession,
- course: &NutrorCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_modules(session, &course.hash).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[nutror] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &NutrorCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- let detail = match api::get_lesson_detail(session, &lesson.hash).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[nutror] Failed to get lesson detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &NutrorCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if let Some(ref desc) = detail.description {
- omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
- }
-
- if let Some(ref video_url) = detail.video_url {
- let video_ext = if video_url.contains(".m3u8") {
- "mp4"
- } else {
- video_url
- .rsplit('.')
- .next()
- .and_then(|e| {
- let e = e.split('?').next().unwrap_or(e);
- if e.len() <= 4 {
- Some(e)
- } else {
- None
- }
- })
- .unwrap_or("mp4")
- };
-
- let video_path = format!(
- "{}/{}. {}.{}",
- lesson_dir,
- li + 1,
- lesson_name,
- video_ext
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[nutror] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &NutrorCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if video_url.contains(".m3u8") {
- match download_hls_video(video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[nutror] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[nutror] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[nutror] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
-
- for file in &detail.files {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let file_name = filename::sanitize_path_component(&file.name);
- let file_path = format!("{}/{}", lesson_dir, file_name);
-
- if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&file_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match download_file_direct(&session.client, &file.url, &file_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[nutror] File download failed for '{}': {}",
- file.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &NutrorCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://nutror.com/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://nutror.com/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/eduzznutror/mod.rs
deleted file mode 100644
index 980dcffc..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct EduzzNutrorDownloader;
-
-impl EduzzNutrorDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for EduzzNutrorDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for EduzzNutrorDownloader {
- fn name(&self) -> &str {
- "eduzznutror"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "nutror.com"
- || host.ends_with(".nutror.com")
- || host == "eduzz.com"
- || host.ends_with(".eduzz.com");
- }
- }
- false
- }
-
- async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Eduzz Nutror".to_string(),
- author: String::new(),
- platform: "eduzznutror".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Eduzz Nutror"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/api.rs
deleted file mode 100644
index fa773bb8..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("entregadigital_session.json"))
-}
-
-pub async fn validate_token(session: &EntregaDigitalSession) -> anyhow::Result<bool> {
- let url = format!("{}/products", session.api_base);
-
- let resp = session
- .client
- .get(&url)
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &EntregaDigitalSession) -> anyhow::Result<Vec<EntregaDigitalCourse>> {
- let url = format!("{}/products", session.api_base);
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let products = body
- .as_array()
- .cloned()
- .unwrap_or_default();
-
- let mut courses = Vec::new();
-
- for item in &products {
- let id = item
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = item
- .get("name")
- .or_else(|| item.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- courses.push(EntregaDigitalCourse { id, name });
- }
-
- Ok(courses)
-}
-
-pub async fn get_course_content(
- session: &EntregaDigitalSession,
- course_id: i64,
-) -> anyhow::Result<Vec<EntregaDigitalModule>> {
- let url = format!("{}/products/{}", session.api_base, course_id);
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let modules_arr = body
- .get("modules")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for (mi, module_val) in modules_arr.iter().enumerate() {
- let mod_id = module_val
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let mod_name = module_val
- .get("name")
- .or_else(|| module_val.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let mod_order = module_val
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(mi as i64);
-
- let lessons_arr = module_val
- .get("lessons")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (li, lesson_val) in lessons_arr.iter().enumerate() {
- let lesson_id = lesson_val
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let lesson_name = lesson_val
- .get("name")
- .or_else(|| lesson_val.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_order = lesson_val
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(li as i64);
-
- lessons.push(EntregaDigitalLesson {
- id: lesson_id,
- name: lesson_name,
- order: lesson_order,
- });
- }
-
- lessons.sort_by_key(|l| l.order);
-
- modules.push(EntregaDigitalModule {
- id: mod_id,
- name: mod_name,
- order: mod_order,
- lessons,
- });
- }
-
- modules.sort_by_key(|m| m.order);
-
- Ok(modules)
-}
-
-pub async fn get_lesson_detail(
- session: &EntregaDigitalSession,
- lesson_id: i64,
-) -> anyhow::Result<EntregaDigitalLessonDetail> {
- let url = format!("{}/lessons/{}/auth", session.api_base, lesson_id);
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lesson_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let name = body
- .get("name")
- .or_else(|| body.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let description = body
- .get("description")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let detail = body.get("detail");
-
- let video_url = detail
- .and_then(|d| {
- d.get("panda")
- .and_then(|p| p.get("video_hls"))
- .and_then(|v| v.as_str())
- .map(String::from)
- })
- .or_else(|| {
- detail.and_then(|d| {
- d.get("panda-live")
- .and_then(|p| p.get("video_hls"))
- .and_then(|v| v.as_str())
- .map(String::from)
- })
- })
- .or_else(|| {
- body.get("video_player")
- .and_then(|v| v.as_str())
- .map(String::from)
- })
- .or_else(|| {
- body.get("action")
- .and_then(|a| a.get("url"))
- .and_then(|v| v.as_str())
- .map(String::from)
- });
-
- let attachments = body
- .get("attachments")
- .and_then(|v| v.as_array())
- .map(|arr| {
- arr.iter()
- .filter_map(|a| {
- let att_url = a
- .get("url")
- .and_then(|v| v.as_str())?
- .to_string();
-
- let att_name = a
- .get("name")
- .or_else(|| a.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("attachment")
- .to_string();
-
- let size = a
- .get("size")
- .and_then(|v| v.as_u64());
-
- Some(EntregaDigitalAttachment {
- url: att_url,
- name: att_name,
- size,
- })
- })
- .collect()
- })
- .unwrap_or_default();
-
- Ok(EntregaDigitalLessonDetail {
- id: lesson_id,
- name,
- description,
- video_url,
- attachments,
- })
-}
-
-pub async fn save_session(session: &EntregaDigitalSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- api_base: session.api_base.clone(),
- app_version: session.app_version.clone(),
- device_id: session.device_id.clone(),
- os_value: session.os_value.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[entregadigital] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<EntregaDigitalSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token, &saved.app_version, &saved.device_id, &saved.os_value)?;
-
- tracing::info!("[entregadigital] session loaded");
-
- Ok(Some(EntregaDigitalSession {
- token: saved.token,
- api_base: saved.api_base,
- app_version: saved.app_version,
- device_id: saved.device_id,
- os_value: saved.os_value,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/downloader.rs
deleted file mode 100644
index d8785f70..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, EntregaDigitalCourse, EntregaDigitalSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct EntregaDigitalCourseDownloadProgress {
- pub course_id: i64,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &EntregaDigitalSession,
- course: &EntregaDigitalCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &EntregaDigitalCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- let detail = match api::get_lesson_detail(session, lesson.id).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[entregadigital] Failed to get lesson detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &EntregaDigitalCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if let Some(ref desc) = detail.description {
- omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
- }
-
- if let Some(ref video_url) = detail.video_url {
- let video_ext = if video_url.contains(".m3u8") {
- "mp4"
- } else {
- video_url
- .rsplit('.')
- .next()
- .and_then(|e| {
- let e = e.split('?').next().unwrap_or(e);
- if e.len() <= 4 {
- Some(e)
- } else {
- None
- }
- })
- .unwrap_or("mp4")
- };
-
- let video_path = format!(
- "{}/{}. {}.{}",
- lesson_dir,
- li + 1,
- lesson_name,
- video_ext
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[entregadigital] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &EntregaDigitalCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if video_url.contains(".m3u8") {
- match download_hls_video(video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[entregadigital] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[entregadigital] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[entregadigital] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
-
- for attachment in &detail.attachments {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let att_name = filename::sanitize_path_component(&attachment.name);
- let att_path = format!("{}/{}", lesson_dir, att_name);
-
- if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&att_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match download_file_direct(&session.client, &attachment.url, &att_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[entregadigital] Attachment download failed for '{}': {}",
- attachment.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &EntregaDigitalCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://entregadigital.app.br/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://entregadigital.app.br/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/entregadigital/mod.rs
deleted file mode 100644
index 1208be6a..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct EntregaDigitalDownloader;
-
-impl EntregaDigitalDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for EntregaDigitalDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for EntregaDigitalDownloader {
- fn name(&self) -> &str {
- "entregadigital"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "entregadigital.app.br"
- || host.ends_with(".entregadigital.app.br");
- }
- }
- false
- }
-
- async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Entrega Digital".to_string(),
- author: String::new(),
- platform: "entregadigital".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Entrega Digital"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/api.rs
deleted file mode 100644
index 7b6fe0e4..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("estrategia_concursos_session.json"))
-}
-
-pub async fn validate_token(session: &EstrategiaConcursosSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get(format!("{}/perfil/detalhes", API_BASE))
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &EstrategiaConcursosSession) -> anyhow::Result<Vec<EstrategiaConcursosCourse>> {
- let resp = session
- .client
- .get(format!("{}/curso", API_BASE))
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let mut courses = Vec::new();
-
- let concursos = body
- .get("data")
- .and_then(|d| d.get("concursos"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for concurso in &concursos {
- let cursos = concurso
- .get("cursos")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for curso in &cursos {
- let id = curso
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = curso
- .get("nome")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let total_aulas = curso
- .get("total_aulas")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- courses.push(EstrategiaConcursosCourse {
- id,
- name,
- total_aulas,
- });
- }
- }
-
- Ok(courses)
-}
-
-pub async fn get_course_content(
- session: &EstrategiaConcursosSession,
- course_id: i64,
-) -> anyhow::Result<Vec<EstrategiaConcursosModule>> {
- let resp = session
- .client
- .get(format!("{}/curso/{}", API_BASE, course_id))
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let aulas = body
- .get("data")
- .and_then(|d| d.get("aulas"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (i, aula) in aulas.iter().enumerate() {
- let id = aula
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = aula
- .get("nome")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let is_disponivel = aula
- .get("is_disponivel")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
-
- lessons.push(EstrategiaConcursosLesson {
- id,
- name,
- order: i as i64,
- is_disponivel,
- });
- }
-
- let module = EstrategiaConcursosModule {
- id: course_id.to_string(),
- name: "Aulas".to_string(),
- order: 0,
- lessons,
- };
-
- Ok(vec![module])
-}
-
-pub async fn get_lesson_detail(
- session: &EstrategiaConcursosSession,
- lesson_id: i64,
-) -> anyhow::Result<EstrategiaConcursosLessonDetail> {
- let resp = session
- .client
- .get(format!("{}/aula/{}", API_BASE, lesson_id))
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lesson_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let data = body.get("data").unwrap_or(&body);
-
- let name = data
- .get("nome")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let mut videos = Vec::new();
-
- let videos_arr = data
- .get("videos")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for video in &videos_arr {
- let resolucoes = video
- .get("resolucoes")
- .and_then(|v| v.as_object());
-
- if let Some(res_map) = resolucoes {
- let best = pick_best_quality(res_map);
- if let Some((quality, url)) = best {
- let audio_url = video
- .get("audio")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from);
-
- let slide_url = video
- .get("slide")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from);
-
- videos.push(EstrategiaConcursosVideo {
- quality,
- url,
- audio_url,
- slide_url,
- });
- }
- }
- }
-
- let pdf_url = data
- .get("pdf")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from);
-
- let pdf_grifado_url = data
- .get("pdf_grifado")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from);
-
- let pdf_simplificado_url = data
- .get("pdf_simplificado")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from);
-
- let description = extract_description(data);
-
- Ok(EstrategiaConcursosLessonDetail {
- id: lesson_id,
- name,
- description,
- videos,
- pdf_url,
- pdf_grifado_url,
- pdf_simplificado_url,
- })
-}
-
-pub fn extract_description(data: &serde_json::Value) -> String {
- let mut parts = Vec::new();
-
- if let Some(desc) = data.get("descricao").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) {
- parts.push(desc.to_string());
- }
-
- if let Some(conteudo) = data.get("conteudo").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) {
- parts.push(conteudo.to_string());
- }
-
- if let Some(html) = data.get("html").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) {
- if parts.is_empty() {
- parts.push(html.to_string());
- }
- }
-
- parts.join("\n\n")
-}
-
-fn pick_best_quality(resolucoes: &serde_json::Map<String, serde_json::Value>) -> Option<(String, String)> {
- let priority = ["720", "480", "360", "1080", "240"];
-
- for q in &priority {
- if let Some(url) = resolucoes.get(*q).and_then(|v| v.as_str()) {
- if !url.is_empty() {
- return Some((q.to_string(), url.to_string()));
- }
- }
- }
-
- resolucoes.iter().next().and_then(|(k, v)| {
- v.as_str().map(|u| (k.clone(), u.to_string()))
- })
-}
-
-pub async fn save_session(session: &EstrategiaConcursosSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[estrategia_concursos] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<EstrategiaConcursosSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[estrategia_concursos] session loaded");
-
- Ok(Some(EstrategiaConcursosSession {
- token: saved.token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/downloader.rs
deleted file mode 100644
index e4d75ba4..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, EstrategiaConcursosCourse, EstrategiaConcursosSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct EstrategiaConcursosCourseDownloadProgress {
- pub course_id: i64,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &EstrategiaConcursosSession,
- course: &EstrategiaConcursosCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[estrategia_concursos] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &EstrategiaConcursosCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- if !lesson.is_disponivel {
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &EstrategiaConcursosCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
-
- let detail = match api::get_lesson_detail(session, lesson.id).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[estrategia_concursos] Failed to get lesson detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &EstrategiaConcursosCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if !detail.description.is_empty() {
- let desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&desc_dir).await.ok();
- omniget_core::core::course_utils::save_description(&desc_dir, &detail.description, "html").await.ok();
- }
-
- for (vi, video) in detail.videos.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let suffix = if detail.videos.len() > 1 {
- format!(" ({})", vi + 1)
- } else {
- String::new()
- };
-
- let video_path = format!(
- "{}/{}. {}{}.mp4",
- mod_dir,
- li + 1,
- lesson_name,
- suffix
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[estrategia_concursos] Skipping existing: {}", video_path);
- continue;
- }
- }
-
- match download_file_direct(&session.client, &video.url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_concursos] Video download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
-
- if let Some(ref audio_url) = video.audio_url {
- let audio_path = format!(
- "{}/{}. Audio - {}{}.mp3",
- mod_dir,
- li + 1,
- lesson_name,
- suffix
- );
-
- if !tokio::fs::try_exists(&audio_path).await.unwrap_or(false) {
- match download_file_direct(&session.client, audio_url, &audio_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_concursos] Audio download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
- }
-
- if let Some(ref slide_url) = video.slide_url {
- let slide_ext = slide_url
- .rsplit('.')
- .next()
- .and_then(|e| e.split('?').next())
- .filter(|e| e.len() <= 5)
- .unwrap_or("pdf");
- let slide_path = format!(
- "{}/{}. Slide - {}{}.{}",
- mod_dir,
- li + 1,
- lesson_name,
- suffix,
- slide_ext
- );
-
- if !tokio::fs::try_exists(&slide_path).await.unwrap_or(false) {
- match download_file_direct(&session.client, slide_url, &slide_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_concursos] Slide download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
- }
- }
-
- if let Some(ref pdf_url) = detail.pdf_url {
- let pdf_path = format!("{}/{}. {}.pdf", mod_dir, li + 1, lesson_name);
- if !tokio::fs::try_exists(&pdf_path).await.unwrap_or(false) {
- match download_file_direct(&session.client, pdf_url, &pdf_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_concursos] PDF download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
- }
-
- if let Some(ref pdf_url) = detail.pdf_grifado_url {
- let pdf_path = format!("{}/{}. {} (grifado).pdf", mod_dir, li + 1, lesson_name);
- if !tokio::fs::try_exists(&pdf_path).await.unwrap_or(false) {
- match download_file_direct(&session.client, pdf_url, &pdf_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_concursos] PDF grifado download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
- }
-
- if let Some(ref pdf_url) = detail.pdf_simplificado_url {
- let pdf_path = format!("{}/{}. {} (simplificado).pdf", mod_dir, li + 1, lesson_name);
- if !tokio::fs::try_exists(&pdf_path).await.unwrap_or(false) {
- match download_file_direct(&session.client, pdf_url, &pdf_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_concursos] PDF simplificado download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &EstrategiaConcursosCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_concursos/mod.rs
deleted file mode 100644
index 5255bdf5..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct EstrategiaConcursosDownloader;
-
-impl Default for EstrategiaConcursosDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl EstrategiaConcursosDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for EstrategiaConcursosDownloader {
- fn name(&self) -> &str {
- "estrategia_concursos"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- if host == "estrategiaconcursos.com.br" || host == "www.estrategiaconcursos.com.br" {
- return true;
- }
- if (host == "estrategia.com" || host == "www.estrategia.com") && parsed.path().contains("concursos") {
- return true;
- }
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Estratégia Concursos".to_string(),
- author: String::new(),
- platform: "estrategia_concursos".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Estratégia Concursos courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/api.rs
deleted file mode 100644
index 9ee77615..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("estrategia_ldi_session.json"))
-}
-
-pub async fn validate_token(session: &EstrategiaLdiSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get(format!("{}/bff/goals/shelves?page=1&per_page=1", API_BASE))
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn search_courses(session: &EstrategiaLdiSession, query: &str) -> anyhow::Result<Vec<EstrategiaLdiCourse>> {
- let mut courses = Vec::new();
- let mut page = 1u32;
-
- loop {
- let url = format!(
- "{}/bff/goals/shelves?page={}&per_page=20&name={}",
- API_BASE,
- page,
- urlencoding::encode(query)
- );
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "search_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let goals = body
- .get("goals")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- if goals.is_empty() {
- break;
- }
-
- for goal in &goals {
- let id = goal
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let name = goal
- .get("title")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if !id.is_empty() {
- courses.push(EstrategiaLdiCourse { id, name });
- }
- }
-
- page += 1;
- if page > 50 {
- break;
- }
- }
-
- Ok(courses)
-}
-
-pub async fn list_courses(session: &EstrategiaLdiSession) -> anyhow::Result<Vec<EstrategiaLdiCourse>> {
- search_courses(session, "").await
-}
-
-pub async fn get_course_content(
- session: &EstrategiaLdiSession,
- goal_id: &str,
-) -> anyhow::Result<Vec<EstrategiaLdiModule>> {
- let url = format!("{}/bff/goals/{}/contents/ldi", API_BASE, goal_id);
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let chapters = body
- .get("chapters")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_else(|| {
- body.as_array().cloned().unwrap_or_default()
- });
-
- let mut modules = Vec::new();
-
- for (ci, chapter) in chapters.iter().enumerate() {
- let chapter_name = chapter
- .get("title")
- .or_else(|| chapter.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("Chapter")
- .to_string();
-
- let chapter_id = chapter
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", ci),
- })
- .unwrap_or_else(|| format!("{}", ci));
-
- let items = chapter
- .get("items")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (ii, item) in items.iter().enumerate() {
- let item_id = item
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}-{}", ci, ii),
- })
- .unwrap_or_else(|| format!("{}-{}", ci, ii));
-
- let item_name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- lessons.push(EstrategiaLdiLesson {
- id: item_id,
- name: item_name,
- order: ii as i64,
- });
- }
-
- modules.push(EstrategiaLdiModule {
- id: chapter_id,
- name: chapter_name,
- order: ci as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-pub async fn get_item_detail(
- session: &EstrategiaLdiSession,
- item_id: &str,
-) -> anyhow::Result<serde_json::Value> {
- let mut all_sub_blocks = Vec::new();
- let mut page = 1u32;
-
- loop {
- let url = format!("{}/v3/mci/items/{}", API_BASE, item_id);
-
- let resp = session.client.get(&url)
- .query(&[
- ("page", page.to_string().as_str()),
- ("order", "asc"),
- ("per_page", "30"),
- ("view_mode", "complete"),
- ("should_load_metadata", "true"),
- ("video_only", "false"),
- ("text_only", "false"),
- ("question_only", "false"),
- ("cast_only", "false"),
- ("attachment_only", "false"),
- ])
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- if all_sub_blocks.is_empty() {
- return Err(anyhow!(
- "get_item_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
- break;
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
- let item_data = body.get("data").unwrap_or(&body);
-
- if let Some(blocks) = item_data.get("sub_blocks").and_then(|v| v.as_array()) {
- all_sub_blocks.extend(blocks.clone());
- }
-
- let total_pages = body
- .get("meta")
- .and_then(|m| m.get("last_page"))
- .and_then(|v| v.as_u64())
- .unwrap_or(1) as u32;
-
- if page >= total_pages {
- break;
- }
- page += 1;
- }
-
- let result = serde_json::json!({
- "sub_blocks": all_sub_blocks
- });
- Ok(result)
-}
-
-pub async fn get_track_info(
- session: &EstrategiaLdiSession,
- track_id: &str,
-) -> anyhow::Result<EstrategiaLdiTrack> {
- let url = format!("{}/v2/tracks/{}", API_BASE, track_id);
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_track_info returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
- let track_data = body.get("data").unwrap_or(&body);
-
- let mut video_files: Vec<(i64, String)> = Vec::new();
- if let Some(files) = track_data.get("video_files").and_then(|v| v.as_array()) {
- for vf in files {
- let height = vf.get("height").and_then(|v| v.as_i64()).unwrap_or(0);
- let link = vf.get("link").and_then(|v| v.as_str()).unwrap_or("").to_string();
- if !link.is_empty() {
- video_files.push((height, link));
- }
- }
- }
-
- video_files.sort_by(|a, b| b.0.cmp(&a.0));
-
- let track_url = if let Some((_, best_url)) = video_files.first() {
- best_url.clone()
- } else {
- track_data
- .get("url")
- .or_else(|| track_data.get("source"))
- .or_else(|| track_data.get("link"))
- .or_else(|| body.get("url"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string()
- };
-
- let duration = track_data
- .get("duration")
- .and_then(|v| v.as_f64());
-
- let audio_url = track_data
- .get("audio_url")
- .or_else(|| track_data.get("audio"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from);
-
- let title = track_data
- .get("name")
- .or_else(|| track_data.get("title"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- if track_url.is_empty() {
- return Err(anyhow!("No URL found in track response for track_id={}", track_id));
- }
-
- Ok(EstrategiaLdiTrack {
- url: track_url,
- audio_url,
- title,
- duration,
- })
-}
-
-pub fn extract_track_ids(item_detail: &serde_json::Value) -> Vec<String> {
- let mut track_ids = Vec::new();
-
- let sub_blocks = item_detail
- .get("sub_blocks")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for block in &sub_blocks {
- let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
-
- if block_type == "cast" {
- let data = block.get("data")
- .or_else(|| block.get("simple_data"))
- .cloned()
- .unwrap_or_default();
-
- let track_type = data.get("type").and_then(|v| v.as_str()).unwrap_or("");
- let track_value = data.get("value").and_then(|v| v.as_str()).unwrap_or("");
-
- if track_type == "track" && !track_value.is_empty() {
- track_ids.push(track_value.to_string());
- }
- } else if block_type == "videoMyDocuments" {
- let data = block.get("data")
- .or_else(|| block.get("simple_data"))
- .cloned()
- .unwrap_or_default();
-
- let resolved = data.get("resolved").cloned().unwrap_or_default();
- let video_url = resolved.get("data")
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if !video_url.is_empty() {
- track_ids.push(format!("direct:{}", video_url));
- }
- }
- }
-
- if track_ids.is_empty() {
- let tracks = item_detail
- .get("tracks")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for track in &tracks {
- if let Some(id) = track.get("id").map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- }) {
- if !id.is_empty() {
- track_ids.push(id);
- }
- }
- }
- }
-
- if track_ids.is_empty() {
- if let Some(track_id) = item_detail.get("track_id").map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- }) {
- if !track_id.is_empty() {
- track_ids.push(track_id);
- }
- }
- }
-
- track_ids
-}
-
-pub fn extract_attachment_urls(item_detail: &serde_json::Value) -> Vec<(String, String)> {
- let mut attachments = Vec::new();
-
- let sub_blocks = item_detail
- .get("sub_blocks")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for block in &sub_blocks {
- let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
-
- if block_type == "attachment" || block_type == "pdfMyDocuments" {
- let data = block.get("data")
- .or_else(|| block.get("simple_data"))
- .cloned()
- .unwrap_or_default();
-
- let resolved = data.get("resolved").cloned().unwrap_or(data.clone());
-
- let url = resolved.get("url")
- .or_else(|| resolved.get("data"))
- .or_else(|| resolved.get("file"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let name = resolved.get("name")
- .or_else(|| resolved.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("attachment")
- .to_string();
-
- if !url.is_empty() {
- attachments.push((name, url));
- }
- }
- }
-
- let atts = item_detail
- .get("attachments")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for att in &atts {
- let url = att
- .get("url")
- .or_else(|| att.get("file"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let name = att
- .get("name")
- .or_else(|| att.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("attachment")
- .to_string();
-
- if !url.is_empty() {
- attachments.push((name, url));
- }
- }
-
- attachments
-}
-
-pub fn extract_description(item_detail: &serde_json::Value) -> String {
- let sub_blocks = item_detail.get("sub_blocks").and_then(|v| v.as_array()).cloned().unwrap_or_default();
- let mut parts = Vec::new();
-
- for block in &sub_blocks {
- let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
-
- if block_type == "tiptap" {
- let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
- if let Some(content) = data.get("content").and_then(|v| v.as_str()) {
- parts.push(content.to_string());
- } else if let Some(html) = data.as_str() {
- parts.push(html.to_string());
- }
- } else if block_type == "question" {
- let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
- let resolved = data.get("resolved").cloned().unwrap_or(data.clone());
-
- let statement = resolved.get("statement")
- .or_else(|| resolved.get("enunciado"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if !statement.is_empty() {
- let mut q = format!("<div class=\"question\"><p><strong>Questao:</strong> {}</p>", statement);
-
- if let Some(alts) = resolved.get("alternatives").and_then(|v| v.as_array()) {
- q.push_str("<ol type=\"A\">");
- for alt in alts {
- let text = alt.get("text")
- .or_else(|| alt.get("content"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
- let is_correct = alt.get("is_correct")
- .or_else(|| alt.get("correct"))
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
- if is_correct {
- q.push_str(&format!("<li><strong>{}</strong></li>", text));
- } else {
- q.push_str(&format!("<li>{}</li>", text));
- }
- }
- q.push_str("</ol>");
- }
-
- let answer = resolved.get("answer")
- .or_else(|| resolved.get("resposta"))
- .or_else(|| resolved.get("gabarito"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
- if !answer.is_empty() {
- q.push_str(&format!("<p><strong>Resposta:</strong> {}</p>", answer));
- }
-
- let explanation = resolved.get("explanation")
- .or_else(|| resolved.get("explicacao"))
- .or_else(|| resolved.get("comment"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
- if !explanation.is_empty() {
- q.push_str(&format!("<p><strong>Explicacao:</strong> {}</p>", explanation));
- }
-
- q.push_str("</div>");
- parts.push(q);
- }
- }
- }
-
- parts.join("\n\n")
-}
-
-pub fn extract_audio_urls(item_detail: &serde_json::Value) -> Vec<(String, String)> {
- let sub_blocks = item_detail.get("sub_blocks").and_then(|v| v.as_array()).cloned().unwrap_or_default();
- let mut audios = Vec::new();
-
- for block in &sub_blocks {
- let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
-
- if block_type == "cast" {
- let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
- let track_type = data.get("type").and_then(|v| v.as_str()).unwrap_or("");
- let track_value = data.get("value").and_then(|v| v.as_str()).unwrap_or("");
-
- if track_type == "track" && !track_value.is_empty() {
- audios.push(("track".to_string(), track_value.to_string()));
- }
- }
- }
-
- audios
-}
-
-pub async fn save_session(session: &EstrategiaLdiSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[estrategia_ldi] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<EstrategiaLdiSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[estrategia_ldi] session loaded");
-
- Ok(Some(EstrategiaLdiSession {
- token: saved.token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/downloader.rs
deleted file mode 100644
index b653c7ba..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, EstrategiaLdiCourse, EstrategiaLdiSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct EstrategiaLdiCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &EstrategiaLdiSession,
- course: &EstrategiaLdiCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, &course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[estrategia_ldi] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &EstrategiaLdiCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
-
- let item_detail = match api::get_item_detail(session, &lesson.id).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[estrategia_ldi] Failed to get item detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &EstrategiaLdiCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- let description = api::extract_description(&item_detail);
- if !description.is_empty() {
- omniget_core::core::course_utils::save_description(&mod_dir, &description, "html").await.ok();
- }
-
- let track_ids = api::extract_track_ids(&item_detail);
-
- for (ti, track_id) in track_ids.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let (video_url, audio_url, track_title) = if let Some(direct_url) = track_id.strip_prefix("direct:") {
- (direct_url.to_string(), None, None)
- } else {
- match api::get_track_info(session, track_id).await {
- Ok(t) => (t.url, t.audio_url, t.title),
- Err(e) => {
- tracing::error!(
- "[estrategia_ldi] Failed to get track '{}': {}",
- track_id,
- e
- );
- continue;
- }
- }
- };
-
- let suffix = if track_ids.len() > 1 {
- format!(" ({})", ti + 1)
- } else {
- String::new()
- };
-
- let video_path = format!(
- "{}/{}. {}{}.mp4",
- mod_dir,
- li + 1,
- lesson_name,
- suffix
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[estrategia_ldi] Skipping existing: {}", video_path);
- } else {
- download_video_ldi(session, &video_url, &video_path, &mod_dir, &lesson.name, &cancel_token, &total_bytes).await;
- }
- } else {
- download_video_ldi(session, &video_url, &video_path, &mod_dir, &lesson.name, &cancel_token, &total_bytes).await;
- }
-
- if let Some(ref a_url) = audio_url {
- let audio_name = track_title.as_deref().unwrap_or(&lesson.name);
- let safe_audio = filename::sanitize_path_component(audio_name);
- let audio_path = format!("{}/{}. Audio - {}{}.mp3", mod_dir, li + 1, safe_audio, suffix);
-
- if !tokio::fs::try_exists(&audio_path).await.unwrap_or(false) {
- match download_file_direct(&session.client, a_url, &audio_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[estrategia_ldi] audio download failed: {}", e);
- }
- }
- }
- }
- }
-
- let attachments = api::extract_attachment_urls(&item_detail);
- for (att_name, att_url) in &attachments {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let safe_name = filename::sanitize_path_component(att_name);
- let ext = att_url.rsplit('.').next().unwrap_or("pdf");
- let ext = ext.split('?').next().unwrap_or(ext);
- let att_path = format!("{}/{}.{}", mod_dir, safe_name, ext);
-
- if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&att_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match download_file_direct(&session.client, att_url, &att_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_ldi] Attachment download failed for '{}': {}",
- att_name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &EstrategiaLdiCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://concursos.estrategia.com/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://concursos.estrategia.com/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
-
-async fn download_video_ldi(
- session: &api::EstrategiaLdiSession,
- video_url: &str,
- video_path: &str,
- mod_dir: &str,
- lesson_name: &str,
- cancel_token: &CancellationToken,
- total_bytes: &Arc<AtomicU64>,
-) {
- let is_direct_url = video_url.contains(".mp4")
- || video_url.contains("vimeocdn")
- || video_url.contains("akamaized")
- || video_url.contains("cloudfront")
- || video_url.contains("player.vimeo.com/progressive");
-
- if video_url.contains(".m3u8") {
- match download_hls_video(video_url, video_path, cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[estrategia_ldi] HLS download failed for '{}': {}", lesson_name, e);
- let _ = tokio::fs::remove_file(video_path).await;
- }
- }
- } else if is_direct_url {
- match download_file_direct(&session.client, video_url, video_path, cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[estrategia_ldi] Direct download failed for '{}': {}, trying yt-dlp", lesson_name, e);
- match download_with_ytdlp(video_url, mod_dir, cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!("[estrategia_ldi] All methods failed for '{}': {}", lesson_name, e2);
- }
- }
- }
- }
- } else {
- match download_with_ytdlp(video_url, mod_dir, cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[estrategia_ldi] yt-dlp failed for '{}': {}, trying direct", lesson_name, e);
- match download_file_direct(&session.client, video_url, video_path, cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!("[estrategia_ldi] Direct download also failed for '{}': {}", lesson_name, e2);
- }
- }
- }
- }
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_ldi/mod.rs
deleted file mode 100644
index 28ab7d8c..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct EstrategiaLdiDownloader;
-
-impl Default for EstrategiaLdiDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl EstrategiaLdiDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for EstrategiaLdiDownloader {
- fn name(&self) -> &str {
- "estrategia_ldi"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "concursos.estrategia.com";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Estratégia LDI".to_string(),
- author: String::new(),
- platform: "estrategia_ldi".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Estratégia LDI courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/api.rs
deleted file mode 100644
index 97f8b0bb..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("estrategia_militares_session.json"))
-}
-
-pub async fn validate_token(session: &EstrategiaMilitaresSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get(format!("{}/bff/goals/shelves?page=1&per_page=1&name=test", API_BASE))
- .send()
- .await?;
-
- let status = resp.status();
- let body = resp.text().await.unwrap_or_default();
- tracing::info!("[estrategia_militares] validate_token status={} body_preview={}", status, &body[..body.len().min(500)]);
-
- Ok(status.is_success())
-}
-
-async fn fetch_ldi_courses_for_goal(session: &EstrategiaMilitaresSession, goal_id: &str) -> Vec<EstrategiaMilitaresCourse> {
- let url = format!("{}/bff/goals/{}/contents/ldi?page=1&per_page=50", API_BASE, goal_id);
-
- let resp = match session.client.get(&url).send().await {
- Ok(r) => r,
- Err(e) => {
- tracing::warn!("[estrategia_militares] failed to fetch LDI for goal {}: {}", goal_id, e);
- return Vec::new();
- }
- };
-
- let body_text = match resp.text().await {
- Ok(t) => t,
- Err(_) => return Vec::new(),
- };
-
- let body: serde_json::Value = match serde_json::from_str(&body_text) {
- Ok(v) => v,
- Err(_) => return Vec::new(),
- };
-
- let contents = body
- .get("data")
- .and_then(|d| d.get("contents"))
- .and_then(|c| c.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut courses = Vec::new();
- for c in &contents {
- let id = c.get("id").map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- }).unwrap_or_default();
-
- let name = c.get("title")
- .or(c.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let slug = c.get("slug")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if !id.is_empty() && !slug.is_empty() {
- courses.push(EstrategiaMilitaresCourse {
- id,
- name,
- slug,
- goal_id: goal_id.to_string(),
- });
- }
- }
-
- courses
-}
-
-pub async fn search_courses(session: &EstrategiaMilitaresSession, query: &str) -> anyhow::Result<Vec<EstrategiaMilitaresCourse>> {
- if query.trim().is_empty() {
- return Ok(Vec::new());
- }
-
- let url = format!(
- "{}/bff/goals/shelves?page=1&per_page=20&name={}",
- API_BASE,
- urlencoding::encode(query.trim())
- );
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- tracing::info!("[estrategia_militares] search status={} body_len={}", status, body_text.len());
-
- if !status.is_success() {
- return Err(anyhow!(
- "search_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
- let mut all_goal_ids = Vec::new();
-
- let result_data = body.get("data").unwrap_or(&body);
-
- if let Some(shelves) = result_data.get("shelves").and_then(|v| v.as_object()) {
- for (_shelf_name, goals_val) in shelves {
- let goals = goals_val.as_array().cloned().unwrap_or_default();
- for goal in &goals {
- let goal_id = goal.get("id").map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- }).unwrap_or_default();
-
- if !goal_id.is_empty() {
- all_goal_ids.push(goal_id);
- }
- }
- }
- }
-
- if let Some(highlights) = result_data.get("highlights") {
- let highlight_goals = highlights.get("goals").and_then(|v| v.as_array()).cloned().unwrap_or_default();
- for goal in &highlight_goals {
- let goal_id = goal.get("id").map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- }).unwrap_or_default();
-
- if !goal_id.is_empty() && !all_goal_ids.contains(&goal_id) {
- all_goal_ids.push(goal_id);
- }
- }
- }
-
- let mut courses = Vec::new();
- let mut seen_ids = std::collections::HashSet::new();
-
- for goal_id in &all_goal_ids {
- let ldi_courses = fetch_ldi_courses_for_goal(session, goal_id).await;
- for c in ldi_courses {
- if seen_ids.insert(c.id.clone()) {
- courses.push(c);
- }
- }
- }
-
- tracing::info!("[estrategia_militares] found {} courses across {} goals for query '{}'", courses.len(), all_goal_ids.len(), query);
- Ok(courses)
-}
-
-pub async fn list_courses(session: &EstrategiaMilitaresSession) -> anyhow::Result<Vec<EstrategiaMilitaresCourse>> {
- search_courses(session, "militar").await
-}
-
-pub async fn get_course_content(
- session: &EstrategiaMilitaresSession,
- course_slug: &str,
-) -> anyhow::Result<Vec<EstrategiaMilitaresModule>> {
- let url = format!("{}/v3/mci/courses/slug/{}", API_BASE, course_slug);
-
- let resp = session.client.get(&url)
- .header("cache-control", "no-cache")
- .send()
- .await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- tracing::info!("[estrategia_militares] get_course_content slug={} status={} len={}", course_slug, status, body_text.len());
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let course_data = body.get("data").unwrap_or(&body);
-
- let chapters = course_data
- .get("chapters")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for (ci, chapter) in chapters.iter().enumerate() {
- let chapter_name = chapter
- .get("title")
- .or_else(|| chapter.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("Chapter")
- .to_string();
-
- let chapter_id = chapter
- .get("chapter_id")
- .or(chapter.get("id"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", ci),
- })
- .unwrap_or_else(|| format!("{}", ci));
-
- let items = chapter
- .get("items")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (ii, item) in items.iter().enumerate() {
- let item_id = item
- .get("item_id")
- .or(item.get("id"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}-{}", ci, ii),
- })
- .unwrap_or_else(|| format!("{}-{}", ci, ii));
-
- let item_name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- lessons.push(EstrategiaMilitaresLesson {
- id: item_id,
- name: item_name,
- order: ii as i64,
- });
- }
-
- modules.push(EstrategiaMilitaresModule {
- id: chapter_id,
- name: chapter_name,
- order: ci as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-pub async fn get_item_detail(
- session: &EstrategiaMilitaresSession,
- item_id: &str,
-) -> anyhow::Result<serde_json::Value> {
- let mut all_sub_blocks = Vec::new();
- let mut page = 1u32;
-
- loop {
- let url = format!("{}/v3/mci/items/{}", API_BASE, item_id);
-
- let resp = session.client.get(&url)
- .query(&[
- ("page", page.to_string().as_str()),
- ("order", "asc"),
- ("per_page", "30"),
- ("view_mode", "complete"),
- ("should_load_metadata", "true"),
- ("video_only", "false"),
- ("text_only", "false"),
- ("question_only", "false"),
- ("cast_only", "false"),
- ("attachment_only", "false"),
- ])
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- if all_sub_blocks.is_empty() {
- return Err(anyhow!(
- "get_item_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
- break;
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
- let item_data = body.get("data").unwrap_or(&body);
-
- if let Some(blocks) = item_data.get("sub_blocks").and_then(|v| v.as_array()) {
- all_sub_blocks.extend(blocks.clone());
- }
-
- let total_pages = body
- .get("meta")
- .and_then(|m| m.get("last_page"))
- .and_then(|v| v.as_u64())
- .unwrap_or(1) as u32;
-
- if page >= total_pages {
- break;
- }
- page += 1;
- }
-
- let result = serde_json::json!({
- "sub_blocks": all_sub_blocks
- });
- Ok(result)
-}
-
-pub async fn get_track_info(
- session: &EstrategiaMilitaresSession,
- track_id: &str,
-) -> anyhow::Result<EstrategiaMilitaresTrack> {
- let url = format!("{}/v2/tracks/{}", API_BASE, track_id);
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_track_info returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
- let track_data = body.get("data").unwrap_or(&body);
-
- let mut video_files: Vec<(i64, String)> = Vec::new();
- if let Some(files) = track_data.get("video_files").and_then(|v| v.as_array()) {
- for vf in files {
- let height = vf.get("height").and_then(|v| v.as_i64()).unwrap_or(0);
- let link = vf.get("link").and_then(|v| v.as_str()).unwrap_or("").to_string();
- if !link.is_empty() {
- video_files.push((height, link));
- }
- }
- }
-
- video_files.sort_by(|a, b| b.0.cmp(&a.0));
-
- let track_url = if let Some((_, best_url)) = video_files.first() {
- best_url.clone()
- } else {
- track_data
- .get("url")
- .or_else(|| track_data.get("source"))
- .or_else(|| track_data.get("link"))
- .or_else(|| body.get("url"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string()
- };
-
- let duration = track_data
- .get("duration")
- .and_then(|v| v.as_f64());
-
- let audio_url = track_data
- .get("audio_url")
- .or_else(|| track_data.get("audio"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from);
-
- let title = track_data
- .get("name")
- .or_else(|| track_data.get("title"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- tracing::info!("[estrategia_militares] track {} url_len={} has_video_files={} has_audio={}", track_id, track_url.len(), !video_files.is_empty(), audio_url.is_some());
-
- if track_url.is_empty() {
- return Err(anyhow!("No URL found in track response for track_id={}", track_id));
- }
-
- Ok(EstrategiaMilitaresTrack {
- url: track_url,
- audio_url,
- title,
- duration,
- })
-}
-
-pub fn extract_track_ids(item_detail: &serde_json::Value) -> Vec<String> {
- let mut track_ids = Vec::new();
-
- let sub_blocks = item_detail
- .get("sub_blocks")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for block in &sub_blocks {
- let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
-
- if block_type == "cast" {
- let data = block.get("data")
- .or_else(|| block.get("simple_data"))
- .cloned()
- .unwrap_or_default();
-
- let track_type = data.get("type").and_then(|v| v.as_str()).unwrap_or("");
- let track_value = data.get("value").and_then(|v| v.as_str()).unwrap_or("");
-
- if track_type == "track" && !track_value.is_empty() {
- track_ids.push(track_value.to_string());
- }
- } else if block_type == "videoMyDocuments" {
- let data = block.get("data")
- .or_else(|| block.get("simple_data"))
- .cloned()
- .unwrap_or_default();
-
- let resolved = data.get("resolved").cloned().unwrap_or_default();
- let video_url = resolved.get("data")
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if !video_url.is_empty() {
- track_ids.push(format!("direct:{}", video_url));
- }
- }
- }
-
- if track_ids.is_empty() {
- let tracks = item_detail
- .get("tracks")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for track in &tracks {
- if let Some(id) = track.get("id").map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- }) {
- if !id.is_empty() {
- track_ids.push(id);
- }
- }
- }
- }
-
- track_ids
-}
-
-pub fn extract_attachment_urls(item_detail: &serde_json::Value) -> Vec<(String, String)> {
- let mut attachments = Vec::new();
-
- let sub_blocks = item_detail
- .get("sub_blocks")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for block in &sub_blocks {
- let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
-
- if block_type == "attachment" || block_type == "pdfMyDocuments" {
- let data = block.get("data")
- .or_else(|| block.get("simple_data"))
- .cloned()
- .unwrap_or_default();
-
- let resolved = data.get("resolved").cloned().unwrap_or(data.clone());
-
- let url = resolved.get("url")
- .or_else(|| resolved.get("data"))
- .or_else(|| resolved.get("file"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let name = resolved.get("name")
- .or_else(|| resolved.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("attachment")
- .to_string();
-
- if !url.is_empty() {
- attachments.push((name, url));
- }
- }
- }
-
- let atts = item_detail
- .get("attachments")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for att in &atts {
- let url = att
- .get("url")
- .or_else(|| att.get("file"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let name = att
- .get("name")
- .or_else(|| att.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("attachment")
- .to_string();
-
- if !url.is_empty() {
- attachments.push((name, url));
- }
- }
-
- attachments
-}
-
-pub fn extract_description(item_detail: &serde_json::Value) -> String {
- let sub_blocks = item_detail.get("sub_blocks").and_then(|v| v.as_array()).cloned().unwrap_or_default();
- let mut parts = Vec::new();
-
- for block in &sub_blocks {
- let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
-
- if block_type == "tiptap" {
- let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
- if let Some(content) = data.get("content").and_then(|v| v.as_str()) {
- parts.push(content.to_string());
- } else if let Some(html) = data.as_str() {
- parts.push(html.to_string());
- }
- } else if block_type == "question" {
- let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
- let resolved = data.get("resolved").cloned().unwrap_or(data.clone());
-
- let statement = resolved.get("statement")
- .or_else(|| resolved.get("enunciado"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if !statement.is_empty() {
- let mut q = format!("<div class=\"question\"><p><strong>Questao:</strong> {}</p>", statement);
-
- if let Some(alts) = resolved.get("alternatives").and_then(|v| v.as_array()) {
- q.push_str("<ol type=\"A\">");
- for alt in alts {
- let text = alt.get("text")
- .or_else(|| alt.get("content"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
- let is_correct = alt.get("is_correct")
- .or_else(|| alt.get("correct"))
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
- if is_correct {
- q.push_str(&format!("<li><strong>{}</strong> ✓</li>", text));
- } else {
- q.push_str(&format!("<li>{}</li>", text));
- }
- }
- q.push_str("</ol>");
- }
-
- let answer = resolved.get("answer")
- .or_else(|| resolved.get("resposta"))
- .or_else(|| resolved.get("gabarito"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
- if !answer.is_empty() {
- q.push_str(&format!("<p><strong>Resposta:</strong> {}</p>", answer));
- }
-
- let explanation = resolved.get("explanation")
- .or_else(|| resolved.get("explicacao"))
- .or_else(|| resolved.get("comment"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
- if !explanation.is_empty() {
- q.push_str(&format!("<p><strong>Explicacao:</strong> {}</p>", explanation));
- }
-
- q.push_str("</div>");
- parts.push(q);
- }
- }
- }
-
- parts.join("\n\n")
-}
-
-pub fn extract_audio_urls(item_detail: &serde_json::Value) -> Vec<(String, String)> {
- let sub_blocks = item_detail.get("sub_blocks").and_then(|v| v.as_array()).cloned().unwrap_or_default();
- let mut audios = Vec::new();
-
- for block in &sub_blocks {
- let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
-
- if block_type == "cast" {
- let data = block.get("data").or_else(|| block.get("simple_data")).cloned().unwrap_or_default();
- let track_type = data.get("type").and_then(|v| v.as_str()).unwrap_or("");
- let track_value = data.get("value").and_then(|v| v.as_str()).unwrap_or("");
-
- if track_type == "track" && !track_value.is_empty() {
- audios.push(("track".to_string(), track_value.to_string()));
- }
- }
- }
-
- audios
-}
-
-pub async fn save_session(session: &EstrategiaMilitaresSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- cookie_string: session.cookie_string.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[estrategia_militares] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<EstrategiaMilitaresSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token, &saved.cookie_string)?;
-
- tracing::info!("[estrategia_militares] session loaded");
-
- Ok(Some(EstrategiaMilitaresSession {
- token: saved.token,
- cookie_string: saved.cookie_string,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/downloader.rs
deleted file mode 100644
index c04c342d..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, EstrategiaMilitaresCourse, EstrategiaMilitaresSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct EstrategiaMilitaresCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &EstrategiaMilitaresSession,
- course: &EstrategiaMilitaresCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, &course.slug).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &EstrategiaMilitaresCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
-
- let item_detail = match api::get_item_detail(session, &lesson.id).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[estrategia_militares] Failed to get item detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &EstrategiaMilitaresCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- let description = api::extract_description(&item_detail);
- if !description.is_empty() {
- omniget_core::core::course_utils::save_description(&mod_dir, &description, "html").await.ok();
- }
-
- let track_ids = api::extract_track_ids(&item_detail);
-
- for (ti, track_id) in track_ids.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let video_url = if let Some(direct_url) = track_id.strip_prefix("direct:") {
- direct_url.to_string()
- } else {
- match api::get_track_info(session, track_id).await {
- Ok(t) => t.url,
- Err(e) => {
- tracing::error!(
- "[estrategia_militares] Failed to get track '{}': {}",
- track_id,
- e
- );
- continue;
- }
- }
- };
-
- let (audio_url, track_title) = if !track_id.starts_with("direct:") {
- match api::get_track_info(session, track_id).await {
- Ok(ref t) => (t.audio_url.clone(), t.title.clone()),
- Err(_) => (None, None),
- }
- } else {
- (None, None)
- };
-
- let track_info = api::EstrategiaMilitaresTrack {
- url: video_url,
- audio_url: audio_url.clone(),
- title: track_title.clone(),
- duration: None,
- };
-
- let suffix = if track_ids.len() > 1 {
- format!(" ({})", ti + 1)
- } else {
- String::new()
- };
-
- let video_path = format!(
- "{}/{}. {}{}.mp4",
- mod_dir,
- li + 1,
- lesson_name,
- suffix
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[estrategia_militares] Skipping existing: {}", video_path);
- continue;
- }
- }
-
- let is_direct_url = track_info.url.contains(".mp4")
- || track_info.url.contains("vimeocdn")
- || track_info.url.contains("akamaized")
- || track_info.url.contains("cloudfront")
- || track_info.url.contains("player.vimeo.com/progressive");
-
- if track_info.url.contains(".m3u8") {
- match download_hls_video(&track_info.url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_militares] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else if is_direct_url {
- tracing::info!("[estrategia_militares] Direct download for '{}'", lesson.name);
- match download_file_direct(&session.client, &track_info.url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_militares] Direct download failed for '{}': {}, trying yt-dlp",
- lesson.name,
- e
- );
- match download_with_ytdlp(&track_info.url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[estrategia_militares] All methods failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- } else {
- match download_with_ytdlp(&track_info.url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_militares] yt-dlp failed for '{}': {}, trying direct",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, &track_info.url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[estrategia_militares] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
-
- if let Some(ref a_url) = audio_url {
- let audio_name = track_title.as_deref().unwrap_or(&lesson.name);
- let safe_audio = filename::sanitize_path_component(audio_name);
- let audio_path = format!("{}/{}. Audio - {}{}.mp3", mod_dir, li + 1, safe_audio, suffix);
-
- if !tokio::fs::try_exists(&audio_path).await.unwrap_or(false) {
- match download_file_direct(&session.client, a_url, &audio_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[estrategia_militares] audio download failed: {}", e);
- }
- }
- }
- }
- }
-
- let attachments = api::extract_attachment_urls(&item_detail);
- for (att_name, att_url) in &attachments {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let safe_name = filename::sanitize_path_component(att_name);
- let ext = att_url.rsplit('.').next().unwrap_or("pdf");
- let ext = ext.split('?').next().unwrap_or(ext);
- let att_path = format!("{}/{}.{}", mod_dir, safe_name, ext);
-
- if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&att_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match download_file_direct(&session.client, att_url, &att_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[estrategia_militares] Attachment download failed for '{}': {}",
- att_name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &EstrategiaMilitaresCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://militares.estrategia.com/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://militares.estrategia.com/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/estrategia_militares/mod.rs
deleted file mode 100644
index f3b41d3b..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct EstrategiaMilitaresDownloader;
-
-impl Default for EstrategiaMilitaresDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl EstrategiaMilitaresDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for EstrategiaMilitaresDownloader {
- fn name(&self) -> &str {
- "estrategia_militares"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "militares.estrategia.com";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Estratégia Militares".to_string(),
- author: String::new(),
- platform: "estrategia_militares".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Estratégia Militares courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/api.rs
deleted file mode 100644
index bf3066ee..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("fluency_session.json"))
-}
-
-pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<FluencySession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "email": email,
- "password": password,
- });
-
- let resp = temp_client
- .post("https://accounts-api.fluency.io/auth/sign-in/")
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Authentication failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let token = body
- .get("access_token")
- .or_else(|| body.get("accessToken"))
- .or_else(|| body.get("token"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("access_token not found in login response"))?
- .to_string();
-
- let client = build_client(&token)?;
-
- Ok(FluencySession {
- token,
- email: email.to_string(),
- client,
- })
-}
-
-pub async fn validate_token(session: &FluencySession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://bifrost.fluencyacademy.io/programs")
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &FluencySession) -> anyhow::Result<Vec<FluencyCourse>> {
- let resp = session
- .client
- .get("https://bifrost.fluencyacademy.io/programs")
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_programs returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let programs: serde_json::Value = serde_json::from_str(&body_text)?;
- let programs_arr = programs.as_array().cloned().unwrap_or_default();
-
- let mut all_courses = Vec::new();
-
- for program in &programs_arr {
- let program_id = program
- .get("id")
- .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
- .unwrap_or_default();
-
- let program_name = program
- .get("name")
- .or_else(|| program.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- for endpoint in &["main", "complement"] {
- let url = format!(
- "https://bifrost.fluencyacademy.io/programs/{}/courses/{}",
- program_id, endpoint
- );
-
- let resp = session.client.get(&url).send().await;
-
- if let Ok(resp) = resp {
- if resp.status().is_success() {
- let text = resp.text().await.unwrap_or_default();
- let courses: serde_json::Value =
- serde_json::from_str(&text).unwrap_or_default();
-
- let courses_arr = courses.as_array().cloned().unwrap_or_default();
-
- for course in &courses_arr {
- let id = course
- .get("id")
- .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
- .unwrap_or_default();
-
- let name = course
- .get("name")
- .or_else(|| course.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let display_name = if program_name.is_empty() {
- name
- } else {
- format!("{} - {}", program_name, name)
- };
-
- all_courses.push(FluencyCourse {
- id,
- name: display_name,
- program_id: program_id.clone(),
- });
- }
- }
- }
- }
- }
-
- Ok(all_courses)
-}
-
-pub async fn get_modules(
- session: &FluencySession,
- course_id: &str,
-) -> anyhow::Result<Vec<FluencyModule>> {
- let url = format!(
- "https://bifrost.fluencyacademy.io/courses/{}/learning-path?size=50",
- course_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_modules returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let content_arr = body
- .get("content")
- .or_else(|| body.get("modules"))
- .or_else(|| body.get("units"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_else(|| {
- if body.is_array() {
- body.as_array().cloned().unwrap_or_default()
- } else {
- Vec::new()
- }
- });
-
- let mut modules = Vec::new();
-
- for (i, item) in content_arr.iter().enumerate() {
- let id = item
- .get("id")
- .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
- .unwrap_or_default();
-
- let name = item
- .get("name")
- .or_else(|| item.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let order = item
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(i as i64);
-
- let mut lessons = Vec::new();
-
- let lessons_arr = item
- .get("lessons")
- .or_else(|| item.get("units"))
- .or_else(|| item.get("items"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for (j, lesson_val) in lessons_arr.iter().enumerate() {
- let lesson_id = lesson_val
- .get("id")
- .and_then(|v| v.as_str().map(String::from).or_else(|| Some(v.to_string())))
- .unwrap_or_default();
-
- let lesson_name = lesson_val
- .get("name")
- .or_else(|| lesson_val.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_order = lesson_val
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(j as i64);
-
- lessons.push(FluencyLesson {
- id: lesson_id,
- name: lesson_name,
- order: lesson_order,
- });
- }
-
- lessons.sort_by_key(|l| l.order);
-
- modules.push(FluencyModule {
- id,
- name,
- order,
- lessons,
- });
- }
-
- modules.sort_by_key(|m| m.order);
-
- Ok(modules)
-}
-
-pub async fn get_lesson_detail(
- session: &FluencySession,
- lesson_id: &str,
-) -> anyhow::Result<FluencyLessonDetail> {
- let url = format!(
- "https://bifrost.fluencyacademy.io/lessons/{}/tasks",
- lesson_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lesson_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let tasks = body
- .as_array()
- .or_else(|| body.get("tasks").and_then(|v| v.as_array()))
- .cloned()
- .unwrap_or_default();
-
- let mut video_url: Option<String> = None;
- let mut lesson_name = String::new();
- let mut description: Option<String> = None;
-
- for task in &tasks {
- if lesson_name.is_empty() {
- if let Some(n) = task.get("name").or_else(|| task.get("title")).and_then(|v| v.as_str()) {
- lesson_name = n.to_string();
- }
- }
-
- let meta = task.get("meta");
-
- if let Some(meta) = meta {
- let sources = meta.get("sources").and_then(|v| v.as_array());
-
- if let Some(sources) = sources {
- let mut best_mp4: Option<String> = None;
- let mut best_height: u64 = 0;
- let mut hls_url: Option<String> = None;
-
- for source in sources {
- let src_url = source
- .get("src")
- .or_else(|| source.get("url"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- let src_type = source
- .get("type")
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- let quality = source
- .get("quality")
- .or_else(|| source.get("label"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- let height: u64 = quality
- .chars()
- .filter(|c| c.is_ascii_digit())
- .collect::<String>()
- .parse()
- .unwrap_or(0);
-
- if src_type.contains("mp4") || src_url.contains(".mp4") {
- if height > best_height {
- best_height = height;
- best_mp4 = Some(src_url.to_string());
- }
- } else if src_type.contains("m3u8")
- || src_type.contains("hls")
- || src_url.contains(".m3u8")
- {
- hls_url = Some(src_url.to_string());
- }
- }
-
- if best_mp4.is_some() {
- video_url = best_mp4;
- } else if hls_url.is_some() {
- video_url = hls_url;
- }
- }
-
- if video_url.is_none() {
- if let Some(url) = meta.get("url").or_else(|| meta.get("video_url")).and_then(|v| v.as_str()) {
- if !url.is_empty() {
- video_url = Some(url.to_string());
- }
- }
- }
- }
-
- if description.is_none() {
- if let Some(desc) = task.get("description") {
- let text = desc
- .get("content")
- .and_then(|v| v.as_str())
- .or_else(|| desc.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(String::from);
- if text.is_some() {
- description = text;
- }
- }
- }
-
- if video_url.is_some() && description.is_some() {
- break;
- }
- }
-
- Ok(FluencyLessonDetail {
- id: lesson_id.to_string(),
- name: lesson_name,
- video_url,
- description,
- })
-}
-
-pub async fn save_session(session: &FluencySession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- email: session.email.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[fluency] session saved for {}", session.email);
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<FluencySession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[fluency] session loaded for {}", saved.email);
-
- Ok(Some(FluencySession {
- token: saved.token,
- email: saved.email,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/downloader.rs
deleted file mode 100644
index aa032bb9..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, FluencyCourse, FluencySession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct FluencyCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &FluencySession,
- course: &FluencyCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_modules(session, &course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[fluency] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &FluencyCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
-
- let detail = match api::get_lesson_detail(session, &lesson.id).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[fluency] Failed to get lesson detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &FluencyCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if let Some(ref desc) = detail.description {
- let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_desc_dir).await?;
- omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
- }
-
- if let Some(ref video_url) = detail.video_url {
- let video_ext = if video_url.contains(".m3u8") {
- "mp4"
- } else {
- video_url
- .rsplit('.')
- .next()
- .and_then(|e| {
- let e = e.split('?').next().unwrap_or(e);
- if e.len() <= 4 {
- Some(e)
- } else {
- None
- }
- })
- .unwrap_or("mp4")
- };
-
- let video_path = format!(
- "{}/{}. {}.{}",
- mod_dir,
- li + 1,
- lesson_name,
- video_ext
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[fluency] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &FluencyCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if video_url.contains(".m3u8") {
- match download_hls_video(video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[fluency] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(video_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[fluency] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[fluency] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &FluencyCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://academy.fluency.io/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://academy.fluency.io/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/fluencyacademy/mod.rs
deleted file mode 100644
index 9ef940d3..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct FluencyAcademyDownloader;
-
-impl Default for FluencyAcademyDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl FluencyAcademyDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for FluencyAcademyDownloader {
- fn name(&self) -> &str {
- "fluencyacademy"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "fluency.io"
- || host == "academy.fluency.io";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Fluency Academy".to_string(),
- author: String::new(),
- platform: "fluencyacademy".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "Original".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Fluency Academy"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/grancursos/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/grancursos/api.rs
deleted file mode 100644
index 4c4aa173..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("grancursos_session.json"))
-}
-
-pub async fn validate_token(session: &GranCursosSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .post(format!("{}/aluno/api/assinatura/buscar-cursos", BASE_URL))
- .json(&serde_json::json!({"termo": ""}))
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn search_courses(session: &GranCursosSession, query: &str) -> anyhow::Result<(Vec<GranCursosCourse>, Option<String>)> {
- let resp = session
- .client
- .post(format!("{}/aluno/api/assinatura/buscar-cursos", BASE_URL))
- .json(&serde_json::json!({"termo": query}))
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "search_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let mut courses = Vec::new();
- let mut contract_id = None;
-
- let items = body
- .get("data")
- .or(Some(&body))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_else(|| {
- body.get("cursos")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default()
- });
-
- for item in &items {
- let id = item
- .get("codigo")
- .or_else(|| item.get("id"))
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = item
- .get("nome")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if contract_id.is_none() {
- contract_id = item
- .get("contrato_id")
- .or_else(|| item.get("contratoId"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .filter(|s| !s.is_empty());
- }
-
- if id > 0 {
- courses.push(GranCursosCourse { id, name });
- }
- }
-
- Ok((courses, contract_id))
-}
-
-pub async fn list_courses(session: &GranCursosSession) -> anyhow::Result<Vec<GranCursosCourse>> {
- let (courses, _) = search_courses(session, "").await?;
- Ok(courses)
-}
-
-pub async fn get_disciplines(
- session: &GranCursosSession,
- course_id: i64,
-) -> anyhow::Result<Vec<GranCursosDiscipline>> {
- let url = format!(
- "{}/aluno/curso/listar-conteudo-aula/codigo/{}/tipo/video",
- BASE_URL, course_id
- );
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_disciplines returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let items = body
- .get("data")
- .or(Some(&body))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_else(|| {
- body.get("disciplinas")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default()
- });
-
- let mut disciplines = Vec::new();
-
- for item in &items {
- let id = item
- .get("id")
- .or_else(|| item.get("codigo"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let name = item
- .get("nome")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if !id.is_empty() {
- disciplines.push(GranCursosDiscipline { id, name });
- }
- }
-
- Ok(disciplines)
-}
-
-pub async fn get_discipline_content(
- session: &GranCursosSession,
- course_id: i64,
- discipline_id: &str,
-) -> anyhow::Result<Vec<GranCursosModule>> {
- let url = format!(
- "{}/aluno/curso/listar-conteudo-aula/codigo/{}/tipo/video/disciplina/{}",
- BASE_URL, course_id, discipline_id
- );
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_discipline_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let items = body
- .get("data")
- .or(Some(&body))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_else(|| {
- body.get("conteudos")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default()
- });
-
- let mut modules = Vec::new();
-
- for (ci, content) in items.iter().enumerate() {
- let content_id = content
- .get("id")
- .or_else(|| content.get("codigo"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", ci),
- })
- .unwrap_or_else(|| format!("{}", ci));
-
- let content_name = content
- .get("nome")
- .or_else(|| content.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("Content")
- .to_string();
-
- let aulas = content
- .get("aulas")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (ai, aula) in aulas.iter().enumerate() {
- let aula_id = aula
- .get("id")
- .or_else(|| aula.get("codigo"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}-{}", ci, ai),
- })
- .unwrap_or_else(|| format!("{}-{}", ci, ai));
-
- let aula_name = aula
- .get("nome")
- .or_else(|| aula.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let video_id = aula
- .get("video_id")
- .or_else(|| aula.get("videoId"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .filter(|s| !s.is_empty());
-
- lessons.push(GranCursosLesson {
- id: aula_id,
- name: aula_name,
- order: ai as i64,
- video_id,
- });
- }
-
- modules.push(GranCursosModule {
- id: content_id,
- name: content_name,
- order: ci as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-pub async fn get_video_url(
- session: &GranCursosSession,
- course_id: i64,
- video_id: &str,
- contract_id: &str,
-) -> anyhow::Result<String> {
- let url = format!(
- "{}/aluno/sala-de-aula/video/co/{}/a/{}/c/{}",
- BASE_URL, course_id, video_id, contract_id
- );
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_video_url returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let sources = body
- .get("player")
- .and_then(|p| p.get("sources"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_else(|| {
- body.get("sources")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default()
- });
-
- for source in &sources {
- let file = source
- .get("file")
- .or_else(|| source.get("src"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if !file.is_empty() {
- return Ok(file.to_string());
- }
- }
-
- let direct_url = body
- .get("url")
- .or_else(|| body.get("video_url"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if !direct_url.is_empty() {
- return Ok(direct_url.to_string());
- }
-
- Err(anyhow!("No video URL found in response"))
-}
-
-pub async fn save_session(session: &GranCursosSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- cookies: session.cookies.clone(),
- contract_id: session.contract_id.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[grancursos] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<GranCursosSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.cookies)?;
-
- tracing::info!("[grancursos] session loaded");
-
- Ok(Some(GranCursosSession {
- cookies: saved.cookies,
- contract_id: saved.contract_id,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/grancursos/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/grancursos/downloader.rs
deleted file mode 100644
index 473f56ad..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, GranCursosCourse, GranCursosSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct GranCursosCourseDownloadProgress {
- pub course_id: i64,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &GranCursosSession,
- course: &GranCursosCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let contract_id = session
- .contract_id
- .as_deref()
- .unwrap_or("0");
-
- let disciplines = api::get_disciplines(session, course.id).await?;
-
- if disciplines.is_empty() {
- return Err(anyhow!(
- "'{}' has no disciplines available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[grancursos] course already complete, skipping");
- return Ok(());
- }
-
- let mut all_modules = Vec::new();
-
- for discipline in &disciplines {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let modules = api::get_discipline_content(session, course.id, &discipline.id).await?;
-
- for module in modules {
- let prefixed_name = format!("{} - {}", discipline.name, module.name);
- all_modules.push(super::api::GranCursosModule {
- id: module.id,
- name: prefixed_name,
- order: module.order,
- lessons: module.lessons,
- });
- }
- }
-
- if all_modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no content available for download",
- course.name
- ));
- }
-
- let total_lessons: usize = all_modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = all_modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &GranCursosCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in all_modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
-
- if let Some(ref vid_id) = lesson.video_id {
- let video_path = format!(
- "{}/{}. {}.mp4",
- mod_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[grancursos] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &GranCursosCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- match api::get_video_url(session, course.id, vid_id, contract_id).await {
- Ok(video_url) => {
- if video_url.contains(".m3u8") {
- match download_hls_video(&video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[grancursos] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[grancursos] yt-dlp failed for '{}': {}, trying direct",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, &video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[grancursos] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
- Err(e) => {
- tracing::error!(
- "[grancursos] Failed to get video URL for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &GranCursosCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://www.grancursosonline.com.br/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://www.grancursosonline.com.br/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/grancursos/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/grancursos/mod.rs
deleted file mode 100644
index 436b32e6..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct GrancursosDownloader;
-
-impl Default for GrancursosDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl GrancursosDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for GrancursosDownloader {
- fn name(&self) -> &str {
- "grancursos"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "grancursosonline.com.br"
- || host == "www.grancursosonline.com.br";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Gran Cursos".to_string(),
- author: String::new(),
- platform: "grancursos".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "Original".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Gran Cursos"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/api.rs
deleted file mode 100644
index fc8cef98..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("wondrium_session.json"))
-}
-
-pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<WondriumSession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "username": email,
- "password": password,
- });
-
- let resp = temp_client
- .post("https://www.thegreatcoursesplus.com/rest/V1/integration/customer/token")
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Authentication failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let token = body_text.trim().trim_matches('"').to_string();
-
- if token.is_empty() {
- return Err(anyhow!("Empty token in login response"));
- }
-
- let client = build_client(&token)?;
-
- Ok(WondriumSession {
- token,
- email: email.to_string(),
- client,
- })
-}
-
-pub async fn validate_token(session: &WondriumSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://www.thegreatcoursesplus.com/rest/all/V2/watchlist/mine/items")
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &WondriumSession) -> anyhow::Result<Vec<WondriumCourse>> {
- let resp = session
- .client
- .get("https://www.thegreatcoursesplus.com/rest/all/V2/watchlist/mine/items")
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let mut courses = Vec::new();
-
- let items = body
- .get("items")
- .and_then(|v| v.as_array())
- .or_else(|| body.as_array())
- .cloned()
- .unwrap_or_default();
-
- for item in &items {
- let id = item
- .get("product_id")
- .or_else(|| item.get("id"))
- .or_else(|| item.get("sku"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let name = item
- .get("name")
- .or_else(|| item.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if !id.is_empty() && !name.is_empty() {
- courses.push(WondriumCourse { id, name });
- }
- }
-
- Ok(courses)
-}
-
-pub async fn get_course_content(
- session: &WondriumSession,
- course_id: &str,
-) -> anyhow::Result<Vec<WondriumModule>> {
- let url = format!(
- "https://m2api.thegreatcourses.com/rest/all/V1/dlo_products/{}",
- course_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let lectures = body
- .get("lectures")
- .or_else(|| body.get("episodes"))
- .or_else(|| body.get("items"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
- let mut current_module: Option<WondriumModule> = None;
- let mut module_index = 0;
-
- for (li, lecture) in lectures.iter().enumerate() {
- let lecture_id = lecture
- .get("id")
- .or_else(|| lecture.get("lecture_id"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", li),
- })
- .unwrap_or_else(|| format!("{}", li));
-
- let lecture_name = lecture
- .get("title")
- .or_else(|| lecture.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let video_id = lecture
- .get("video_id")
- .or_else(|| lecture.get("videoId"))
- .or_else(|| lecture.get("media_id"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .filter(|s| !s.is_empty());
-
- let guidebook_url = lecture
- .get("guidebook_url")
- .or_else(|| lecture.get("pdf_url"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let section = lecture
- .get("section")
- .or_else(|| lecture.get("part"))
- .and_then(|v| v.as_str())
- .unwrap_or("Lectures");
-
- let lesson = WondriumLesson {
- id: lecture_id,
- name: lecture_name,
- order: li as i64,
- video_id,
- guidebook_url,
- };
-
- match &mut current_module {
- Some(m) if m.name == section => {
- m.lessons.push(lesson);
- }
- _ => {
- if let Some(m) = current_module.take() {
- modules.push(m);
- }
- module_index += 1;
- current_module = Some(WondriumModule {
- id: format!("{}", module_index),
- name: section.to_string(),
- order: module_index as i64 - 1,
- lessons: vec![lesson],
- });
- }
- }
- }
-
- if let Some(m) = current_module {
- modules.push(m);
- }
-
- if modules.is_empty() && !lectures.is_empty() {
- let mut all_lessons = Vec::new();
- for (li, lecture) in lectures.iter().enumerate() {
- let lecture_id = lecture
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", li),
- })
- .unwrap_or_else(|| format!("{}", li));
-
- let lecture_name = lecture
- .get("title")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let video_id = lecture
- .get("video_id")
- .or_else(|| lecture.get("media_id"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .filter(|s| !s.is_empty());
-
- let guidebook_url = lecture
- .get("guidebook_url")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- all_lessons.push(WondriumLesson {
- id: lecture_id,
- name: lecture_name,
- order: li as i64,
- video_id,
- guidebook_url,
- });
- }
-
- modules.push(WondriumModule {
- id: "1".to_string(),
- name: "Lectures".to_string(),
- order: 0,
- lessons: all_lessons,
- });
- }
-
- Ok(modules)
-}
-
-pub fn get_video_url(video_id: &str) -> String {
- format!(
- "https://link.theplatform.com/s/jESqeC/media/guid/2140042498/{}?manifest=m3u",
- video_id
- )
-}
-
-pub async fn save_session(session: &WondriumSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- email: session.email.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[wondrium] session saved for {}", session.email);
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<WondriumSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[wondrium] session loaded for {}", saved.email);
-
- Ok(Some(WondriumSession {
- token: saved.token,
- email: saved.email,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/downloader.rs
deleted file mode 100644
index e7a62c34..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, WondriumCourse, WondriumSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct WondriumCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &WondriumSession,
- course: &WondriumCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, &course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[wondrium] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &WondriumCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
-
- if let Some(ref vid_id) = lesson.video_id {
- let video_path = format!(
- "{}/{}. {}.mp4",
- mod_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[wondrium] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &WondriumCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- let video_url = api::get_video_url(vid_id);
-
- match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[wondrium] yt-dlp failed for '{}': {}, trying HLS",
- lesson.name,
- e
- );
- match download_hls_video(&video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[wondrium] HLS download also failed for '{}': {}",
- lesson.name,
- e2
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- }
- }
- }
-
- if let Some(ref pdf_url) = lesson.guidebook_url {
- let pdf_path = format!(
- "{}/{}. {}.pdf",
- mod_dir,
- li + 1,
- lesson_name
- );
-
- if !tokio::fs::try_exists(&pdf_path).await.unwrap_or(false) {
- match download_file_direct(&session.client, pdf_url, &pdf_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[wondrium] PDF download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &WondriumCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://www.thegreatcoursesplus.com/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://www.thegreatcoursesplus.com/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &["--force-generic-extractor".to_string()],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/greatcourses/mod.rs
deleted file mode 100644
index b8775a70..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct GreatCoursesDownloader;
-
-impl Default for GreatCoursesDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl GreatCoursesDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for GreatCoursesDownloader {
- fn name(&self) -> &str {
- "greatcourses"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "thegreatcoursesplus.com"
- || host == "www.thegreatcoursesplus.com"
- || host == "wondrium.com"
- || host == "www.wondrium.com";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Wondrium Course".to_string(),
- author: String::new(),
- platform: "greatcourses".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Wondrium courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greennclub/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/greennclub/api.rs
deleted file mode 100644
index fcf1c981..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("greenn_session.json"))
-}
-
-pub async fn validate_token(session: &GreennSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://api.greenn.club/home")
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &GreennSession) -> anyhow::Result<Vec<GreennCourse>> {
- let resp = session
- .client
- .get("https://api.greenn.club/home")
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let courses_arr = body
- .get("courses")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut all_courses = Vec::new();
-
- for item in &courses_arr {
- let has_access = item
- .get("has_access")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
-
- if !has_access {
- continue;
- }
-
- let id = item
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lessons_count = item
- .get("lessons_count")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- all_courses.push(GreennCourse {
- id,
- name,
- lessons_count,
- });
- }
-
- Ok(all_courses)
-}
-
-pub async fn get_modules(
- session: &GreennSession,
- course_id: i64,
-) -> anyhow::Result<Vec<GreennModule>> {
- let url = format!(
- "https://api.greenn.club/course/{}/watch?data[]=course&data[]=modules",
- course_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_modules returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let modules_arr = body
- .get("modules")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for item in &modules_arr {
- let id = item
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let order = item
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- modules.push(GreennModule {
- id,
- name,
- order,
- lessons: Vec::new(),
- });
- }
-
- modules.sort_by_key(|m| m.order);
-
- Ok(modules)
-}
-
-pub async fn get_lessons(
- session: &GreennSession,
- course_id: i64,
- module_id: i64,
-) -> anyhow::Result<Vec<GreennLesson>> {
- let url = format!(
- "https://api.greenn.club/course/{}/watch?data[]=currentModuleLessons&current_module_id={}",
- course_id, module_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lessons returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let lessons_arr = body
- .get("currentModuleLessons")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for item in &lessons_arr {
- let id = item
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let order = item
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let media_type = item
- .get("mediaType")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let source = item
- .get("source")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let content = item
- .get("content")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let duration = item
- .get("duration")
- .and_then(|v| v.as_f64());
-
- let attachments = item
- .get("attachments")
- .and_then(|v| v.as_array())
- .map(|arr| {
- arr.iter()
- .filter_map(|a| {
- let url = a
- .get("cdn_url")
- .or_else(|| a.get("path"))
- .and_then(|v| v.as_str())?
- .to_string();
-
- let att_name = a
- .get("title")
- .or_else(|| a.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("attachment")
- .to_string();
-
- let size = a
- .get("size")
- .and_then(|v| v.as_u64());
-
- Some(GreennAttachment {
- url,
- name: att_name,
- size,
- })
- })
- .collect()
- })
- .unwrap_or_default();
-
- lessons.push(GreennLesson {
- id,
- name,
- order,
- media_type,
- source,
- content,
- duration,
- attachments,
- });
- }
-
- lessons.sort_by_key(|l| l.order);
-
- Ok(lessons)
-}
-
-pub fn extract_panda_video_id(source: &str) -> Option<String> {
- let re = regex::Regex::new(r"[?&]v=([a-f0-9-]+)").ok()?;
- re.captures(source).map(|c| c[1].to_string())
-}
-
-pub async fn save_session(session: &GreennSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[greenn] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<GreennSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[greenn] session loaded");
-
- Ok(Some(GreennSession {
- token: saved.token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greennclub/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/greennclub/downloader.rs
deleted file mode 100644
index a6526f0e..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, GreennCourse, GreennSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct GreennCourseDownloadProgress {
- pub course_id: i64,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &GreennSession,
- course: &GreennCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let mut modules = api::get_modules(session, course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- for module in &mut modules {
- let lessons = api::get_lessons(session, course.id, module.id).await?;
- module.lessons = lessons;
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &GreennCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- if let Some(ref content) = lesson.content {
- omniget_core::core::course_utils::save_description(&lesson_dir, content, "html").await.ok();
- }
-
- let mut video_url: Option<String> = None;
-
- if let Some(ref source) = lesson.source {
- if let Some(ref mt) = lesson.media_type {
- if mt.contains("panda") {
- if let Some(_vid) = api::extract_panda_video_id(source) {
- video_url = Some(source.clone());
- }
- }
- }
-
- if video_url.is_none()
- && (source.contains("http://") || source.contains("https://"))
- {
- video_url = Some(source.clone());
- }
- }
-
- if let Some(ref url) = video_url {
- let video_ext = if url.contains(".m3u8") {
- "mp4"
- } else {
- url.rsplit('.')
- .next()
- .and_then(|e| {
- let e = e.split('?').next().unwrap_or(e);
- if e.len() <= 4 {
- Some(e)
- } else {
- None
- }
- })
- .unwrap_or("mp4")
- };
-
- let video_path = format!(
- "{}/{}. {}.{}",
- lesson_dir,
- li + 1,
- lesson_name,
- video_ext
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[greenn] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &GreennCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if url.contains(".m3u8") {
- match download_hls_video(url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[greenn] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(url, &lesson_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[greenn] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[greenn] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
-
- for attachment in &lesson.attachments {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let att_name = filename::sanitize_path_component(&attachment.name);
- let att_path = format!("{}/{}", lesson_dir, att_name);
-
- if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&att_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match download_file_direct(&session.client, &attachment.url, &att_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[greenn] Attachment download failed for '{}': {}",
- attachment.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &GreennCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://greenn.club/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://greenn.club/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/greennclub/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/greennclub/mod.rs
deleted file mode 100644
index f6180295..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct GreennClubDownloader;
-
-impl GreennClubDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for GreennClubDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for GreennClubDownloader {
- fn name(&self) -> &str {
- "greennclub"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "greenn.club"
- || host.ends_with(".greenn.club");
- }
- }
- false
- }
-
- async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Greenn Club".to_string(),
- author: String::new(),
- platform: "greennclub".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Greenn Club"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/gumroad/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/gumroad/api.rs
deleted file mode 100644
index 2d2cdbb4..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("gumroad_session.json"))
-}
-
-pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<GumroadSession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let params = [
- ("grant_type", "password"),
- ("username", email),
- ("password", password),
- ("scope", "mobile_api creator_api"),
- ("client_id", CLIENT_ID),
- ("client_secret", CLIENT_SECRET),
- ];
-
- let resp = temp_client
- .post("https://gumroad.com/oauth/token")
- .form(&params)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Authentication failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let token = body
- .get("access_token")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("access_token not found in login response"))?
- .to_string();
-
- let client = build_client(&token)?;
-
- Ok(GumroadSession {
- token,
- email: email.to_string(),
- client,
- })
-}
-
-pub async fn validate_token(session: &GumroadSession) -> anyhow::Result<bool> {
- let url = format!(
- "https://api.gumroad.com/mobile/purchases/index.json?include_subscriptions=true&include_mobile_unfriendly_products=true&mobile_token={}",
- MOBILE_TOKEN
- );
-
- let resp = session.client.get(&url).send().await?;
-
- if !resp.status().is_success() {
- return Ok(false);
- }
-
- let body: serde_json::Value = resp.json().await?;
- Ok(body.get("success").and_then(|v| v.as_bool()).unwrap_or(false))
-}
-
-pub async fn list_products(session: &GumroadSession) -> anyhow::Result<Vec<GumroadProduct>> {
- let url = format!(
- "https://api.gumroad.com/mobile/purchases/index.json?include_subscriptions=true&include_mobile_unfriendly_products=true&mobile_token={}",
- MOBILE_TOKEN
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_products returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let success = body.get("success").and_then(|v| v.as_bool()).unwrap_or(false);
- if !success {
- return Err(anyhow!("API returned success=false"));
- }
-
- let products = body
- .get("products")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut result = Vec::new();
-
- for p in &products {
- if p.get("refunded").and_then(|v| v.as_bool()).unwrap_or(false) {
- continue;
- }
- if p.get("partially_refunded").and_then(|v| v.as_bool()).unwrap_or(false) {
- continue;
- }
- if p.get("chargedback").and_then(|v| v.as_bool()).unwrap_or(false) {
- continue;
- }
- if p.get("is_archived").and_then(|v| v.as_bool()).unwrap_or(false) {
- continue;
- }
-
- let id = p.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
- let name = p.get("name").and_then(|v| v.as_str()).unwrap_or("unnamed").to_string();
- let creator_name = p.get("creator_name").and_then(|v| v.as_str()).unwrap_or("").to_string();
- let preview_url = p.get("preview_url").and_then(|v| v.as_str()).map(String::from);
- let url_redirect_token = p
- .get("url_redirect_token")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let file_count = p
- .get("file_data")
- .and_then(|v| v.as_array())
- .map(|a| a.len())
- .unwrap_or(0);
-
- result.push(GumroadProduct {
- id,
- name,
- creator_name,
- preview_url,
- url_redirect_token,
- file_count,
- });
- }
-
- Ok(result)
-}
-
-pub async fn get_product_files(
- _session: &GumroadSession,
- product_json: &serde_json::Value,
-) -> Vec<GumroadFile> {
- let file_data = product_json
- .get("file_data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut files = Vec::new();
-
- for f in &file_data {
- let id = f.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string();
- let name = f.get("name").and_then(|v| v.as_str()).unwrap_or("file").to_string();
- let filetype = f
- .get("filetype")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_lowercase();
- let filegroup = f
- .get("filegroup")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_lowercase();
- let download_url = f.get("download_url").and_then(|v| v.as_str()).map(String::from);
- let size = f.get("size").and_then(|v| v.as_u64()).unwrap_or(0);
-
- files.push(GumroadFile {
- id,
- name,
- filetype,
- filegroup,
- download_url,
- size,
- });
- }
-
- files
-}
-
-pub fn is_media_file(file: &GumroadFile) -> bool {
- if file.filegroup == "video" || file.filegroup == "audio" {
- return true;
- }
- MEDIA_EXTENSIONS.contains(&file.filetype.as_str())
-}
-
-pub async fn get_stream_url(
- session: &GumroadSession,
- url_redirect_token: &str,
- file_id: &str,
-) -> anyhow::Result<String> {
- let url = format!(
- "https://api.gumroad.com/mobile/url_redirects/stream/{}/{}?mobile_token={}",
- url_redirect_token, file_id, MOBILE_TOKEN
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_stream_url returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let playlist_url = body
- .get("playlist_url")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("No playlist_url in stream response"))?
- .to_string();
-
- Ok(playlist_url)
-}
-
-pub fn get_direct_download_url(url_redirect_token: &str, file_id: &str) -> String {
- format!(
- "https://api.gumroad.com/mobile/url_redirects/download/{}/{}?mobile_token={}",
- url_redirect_token, file_id, MOBILE_TOKEN
- )
-}
-
-pub async fn save_session(session: &GumroadSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- email: session.email.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[gumroad] session saved for {}", session.email);
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<GumroadSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[gumroad] session loaded for {}", saved.email);
-
- Ok(Some(GumroadSession {
- token: saved.token,
- email: saved.email,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/gumroad/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/gumroad/downloader.rs
deleted file mode 100644
index a3c3ddaa..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, GumroadProduct, GumroadSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct GumroadDownloadProgress {
- pub product_id: String,
- pub product_name: String,
- pub percent: f64,
- pub current_file: String,
- pub downloaded_bytes: u64,
- pub total_files: u32,
- pub completed_files: u32,
-}
-
-pub async fn download_product(
- app: &tauri::AppHandle,
- session: &GumroadSession,
- product: &GumroadProduct,
- product_raw: &serde_json::Value,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let files = api::get_product_files(session, product_raw).await;
-
- if files.is_empty() {
- return Err(anyhow!(
- "'{}' has no files available for download",
- product.name
- ));
- }
-
- let product_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&product.name)
- );
- tokio::fs::create_dir_all(&product_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&product_dir) {
- return Ok(());
- }
-
- let total_files = files.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &GumroadDownloadProgress {
- product_id: product.id.clone(),
- product_name: product.name.clone(),
- percent: 0.0,
- current_file: "Starting...".to_string(),
- downloaded_bytes: 0,
- total_files: total_files as u32,
- completed_files: 0,
- },
- );
-
- for (_i, file) in files.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let file_name = filename::sanitize_path_component(&file.name);
- let dest_path = format!("{}/{}", product_dir, file_name);
-
- if tokio::fs::try_exists(&dest_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&dest_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[gumroad] Skipping existing: {}", dest_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &GumroadDownloadProgress {
- product_id: product.id.clone(),
- product_name: product.name.clone(),
- percent: done as f64 / total_files as f64 * 100.0,
- current_file: file.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_files: total_files as u32,
- completed_files: done as u32,
- },
- );
- continue;
- }
- }
-
- if api::is_media_file(file) {
- match api::get_stream_url(session, &product.url_redirect_token, &file.id).await {
- Ok(playlist_url) => {
- match download_with_ytdlp(
- &playlist_url,
- &product_dir,
- &session.token,
- &cancel_token,
- )
- .await
- {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[gumroad] yt-dlp download failed for '{}': {}",
- file.name,
- e
- );
- }
- }
- }
- Err(e) => {
- tracing::error!(
- "[gumroad] Failed to get stream URL for '{}': {}, trying direct download",
- file.name,
- e
- );
- let download_url = file
- .download_url
- .clone()
- .unwrap_or_else(|| api::get_direct_download_url(&product.url_redirect_token, &file.id));
- match download_file_direct(&session.client, &download_url, &dest_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[gumroad] Direct download also failed for '{}': {}",
- file.name,
- e2
- );
- }
- }
- }
- }
- } else {
- let download_url = file
- .download_url
- .clone()
- .unwrap_or_else(|| api::get_direct_download_url(&product.url_redirect_token, &file.id));
- match download_file_direct(&session.client, &download_url, &dest_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[gumroad] File download failed for '{}': {}",
- file.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &GumroadDownloadProgress {
- product_id: product.id.clone(),
- product_name: product.name.clone(),
- percent: done as f64 / total_files as f64 * 100.0,
- current_file: file.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_files: total_files as u32,
- completed_files: done as u32,
- },
- );
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&product_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- token: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let auth_header = format!("Authorization: Bearer {}", token);
- let extra_args: Vec<String> = vec![
- "--add-header".to_string(),
- auth_header,
- "--add-header".to_string(),
- "User-Agent: okhttp/4.8.1".to_string(),
- ];
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://gumroad.com/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &extra_args,
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/gumroad/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/gumroad/mod.rs
deleted file mode 100644
index e151c7cb..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct GumroadDownloader;
-
-impl Default for GumroadDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl GumroadDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for GumroadDownloader {
- fn name(&self) -> &str {
- "gumroad"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "gumroad.com" || host.ends_with(".gumroad.com");
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Gumroad Course".to_string(),
- author: String::new(),
- platform: "gumroad".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Gumroad courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/hotmart/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/api.rs
deleted file mode 100644
index a58bb513..00000000
--- a/src-tauri/omniget-plugin-courses/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/omniget-plugin-courses/src/platforms/hotmart/auth.rs b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/auth.rs
deleted file mode 100644
index a89f31ab..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
- .cookie_provider(Arc::new(jar))
- .default_headers(default_headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(300))
- .build()?;
-
- Ok(client)
-}
-
-pub async fn save_session(session: &HotmartSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- email: session.email.clone(),
- cookies: session.cookies.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[session] saved for {}, {} cookies", session.email, session.cookies.len());
- Ok(())
-}
-
-pub async fn load_saved_session() -> anyhow::Result<HotmartSession> {
- let path = session_file_path()?;
- let json = tokio::fs::read_to_string(&path).await?;
- let saved: SavedSession = serde_json::from_str(&json)?;
-
- tracing::info!("[session] loaded for {}, {} cookies", saved.email, saved.cookies.len());
-
- let client = build_client_from_saved(&saved)?;
-
- Ok(HotmartSession {
- token: saved.token,
- email: saved.email,
- cookies: saved.cookies,
- client,
- })
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if path.exists() {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
-
-#[cfg(windows)]
-const COOKIE_URIS: &[&str] = &[
- "https://hotmart.com",
- "https://sso.hotmart.com",
- "https://consumer.hotmart.com",
- "https://api-sec-vlc.hotmart.com",
-];
-
-#[cfg(windows)]
-async fn extract_webview_cookies_for_uri(
- window: &tauri::WebviewWindow,
- uri: &str,
-) -> anyhow::Result<Vec<(String, String)>> {
- use webview2_com::GetCookiesCompletedHandler;
- use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2_2;
- use windows_core::{Interface, HSTRING, PCWSTR, PWSTR};
-
- let (tx, rx) = tokio::sync::oneshot::channel::<Vec<(String, String)>>();
- let uri_owned = uri.to_string();
-
- window
- .with_webview(move |webview| {
- unsafe {
- let core = webview.controller().CoreWebView2().unwrap();
- let core2: ICoreWebView2_2 = core.cast().unwrap();
- let manager = core2.CookieManager().unwrap();
- let uri_hstring = HSTRING::from(uri_owned);
-
- let _ = manager.GetCookies(
- PCWSTR::from_raw(uri_hstring.as_ptr()),
- &GetCookiesCompletedHandler::create(Box::new(
- move |error_code, cookie_list| {
- let mut result = Vec::new();
- if error_code.is_ok() {
- if let Some(list) = cookie_list {
- let mut count = 0u32;
- list.Count(&mut count)?;
- for i in 0..count {
- let cookie = list.GetValueAtIndex(i)?;
- let mut name = PWSTR::null();
- let mut value = PWSTR::null();
- cookie.Name(&mut name)?;
- cookie.Value(&mut value)?;
- result.push((
- webview2_com::take_pwstr(name),
- webview2_com::take_pwstr(value),
- ));
- }
- }
- }
- let _ = tx.send(result);
- Ok(())
- },
- )),
- );
- }
- })
- .map_err(|e| anyhow!("{}", e))?;
-
- let cookies = tokio::time::timeout(Duration::from_secs(10), rx)
- .await
- .map_err(|_| anyhow!("Timeout ao obter cookies do WebView."))?
- .map_err(|_| anyhow!("Canal de cookies fechado."))?;
-
- Ok(cookies)
-}
-
-#[cfg(windows)]
-async fn extract_webview_cookies(
- window: &tauri::WebviewWindow,
-) -> anyhow::Result<Vec<(String, String)>> {
- let mut seen = HashMap::<String, String>::new();
-
- for uri in COOKIE_URIS {
- match extract_webview_cookies_for_uri(window, uri).await {
- Ok(cookies) => {
- let names: Vec<&str> = cookies.iter().map(|(n, _)| n.as_str()).collect();
- tracing::info!("[cookies] {} → {} cookies: {:?}", uri, cookies.len(), names);
- for (name, value) in cookies {
- seen.insert(name, value);
- }
- }
- Err(e) => {
- tracing::warn!("[cookies] {} → error: {}", uri, e);
- }
- }
- }
-
- let cookies: Vec<(String, String)> = seen.into_iter().collect();
- tracing::info!("[cookies] total unique: {}", cookies.len());
-
- Ok(cookies)
-}
-
-#[allow(dead_code)]
-fn parse_document_cookie(s: &str) -> Vec<(String, String)> {
- s.split(';')
- .filter_map(|pair| {
- let pair = pair.trim();
- if pair.is_empty() {
- return None;
- }
- let (name, value) = pair.split_once('=')?;
- Some((name.trim().to_string(), value.trim().to_string()))
- })
- .collect()
-}
-
-#[cfg(not(windows))]
-async fn extract_webview_cookies_js(
- window: &tauri::WebviewWindow,
- cookie_data: &Arc<std::sync::Mutex<Option<String>>>,
-) -> anyhow::Result<Vec<(String, String)>> {
- *cookie_data.lock().unwrap() = None;
-
- window
- .eval(
- "window.location.href = 'https://omniget-cookie-extract.local/?cookies=' + encodeURIComponent(document.cookie)",
- )
- .map_err(|e| anyhow!("JS eval failed: {}", e))?;
-
- let start = std::time::Instant::now();
- let timeout = Duration::from_secs(5);
- loop {
- if let Some(cookie_str) = cookie_data.lock().unwrap().take() {
- let cookies = parse_document_cookie(&cookie_str);
- let names: Vec<&str> = cookies.iter().map(|(n, _)| n.as_str()).collect();
- tracing::info!("[cookies] document.cookie → {} cookies: {:?}", cookies.len(), names);
- return Ok(cookies);
- }
- if start.elapsed() > timeout {
- tracing::warn!("[cookies] timeout waiting for document.cookie response");
- return Ok(Vec::new());
- }
- tokio::time::sleep(Duration::from_millis(50)).await;
- }
-}
-
-pub async fn authenticate(
- app: &tauri::AppHandle,
- email: &str,
- password: &str,
-) -> anyhow::Result<HotmartSession> {
- use tauri::Emitter;
-
- let post_login_detected = Arc::new(std::sync::atomic::AtomicBool::new(false));
- let post_login_flag = post_login_detected.clone();
-
- let captcha_detected = Arc::new(std::sync::atomic::AtomicBool::new(false));
- let captcha_flag = captcha_detected.clone();
-
- #[cfg(not(windows))]
- let cookie_data = Arc::new(std::sync::Mutex::new(Option::<String>::None));
- #[cfg(not(windows))]
- let cookie_data_nav = cookie_data.clone();
-
- let email_json = serde_json::to_string(email)?;
- let password_json = serde_json::to_string(password)?;
-
- let init_script = format!(
- r#"(function() {{
- if (window.location.hostname !== 'sso.hotmart.com') return;
- var filled = false;
- function dismissCookies() {{
- try {{
- var el = document.querySelector('#hotmart-cookie-policy');
- if (el && el.shadowRoot) {{
- var btn = el.shadowRoot.querySelector('button.cookie-policy-accept-all');
- if (btn) btn.click();
- }}
- }} catch(e) {{}}
- }}
- function fillForm() {{
- if (filled) return;
- var u = document.querySelector('#username');
- var p = document.querySelector('#password');
- if (!u || !p) return;
- filled = true;
- var s = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
- s.call(u, {email_json});
- u.dispatchEvent(new Event('input', {{ bubbles: true }}));
- u.dispatchEvent(new Event('change', {{ bubbles: true }}));
- s.call(p, {password_json});
- p.dispatchEvent(new Event('input', {{ bubbles: true }}));
- p.dispatchEvent(new Event('change', {{ bubbles: true }}));
- setTimeout(function() {{
- var btn = document.querySelector('[name=submit]');
- if (btn) btn.click();
- }}, 500);
- }}
- dismissCookies();
- setTimeout(dismissCookies, 1000);
- setTimeout(fillForm, 1500);
- setInterval(fillForm, 500);
- }})()"#
- );
-
- if let Some(existing) = app.get_webview_window("hotmart-login") {
- let _ = existing.close();
- tokio::time::sleep(Duration::from_millis(500)).await;
- }
-
- let login_url = "https://sso.hotmart.com/login?redirect=https%3A%2F%2Fconsumer.hotmart.com";
-
- let login_window = tauri::WebviewWindowBuilder::new(
- app,
- "hotmart-login",
- tauri::WebviewUrl::External(login_url.parse().unwrap()),
- )
- .title("Hotmart Login")
- .inner_size(500.0, 700.0)
- .initialization_script(&init_script)
- .on_navigation(move |url| {
- let host = url.host_str().unwrap_or("");
- let url_str = url.as_str();
-
- tracing::info!("[auth] navigation → {} (host={})", url_str, host);
-
- if host == "consumer.hotmart.com"
- || host.ends_with(".club.hotmart.com")
- || url_str.contains("dashboard")
- || (host.ends_with(".hotmart.com") && host != "sso.hotmart.com")
- {
- post_login_flag.store(true, std::sync::atomic::Ordering::Relaxed);
- }
-
- if url_str.contains("captcha") || url_str.contains("challenge") {
- captcha_flag.store(true, std::sync::atomic::Ordering::Relaxed);
- }
-
- #[cfg(not(windows))]
- {
- if host == "omniget-cookie-extract.local" {
- for (key, value) in url.query_pairs() {
- if key == "cookies" {
- *cookie_data_nav.lock().unwrap() = Some(value.to_string());
- break;
- }
- }
- return false;
- }
- }
-
- true
- })
- .build()
- .map_err(|e| anyhow!("Falha ao criar janela de login: {}", e))?;
-
- let start = std::time::Instant::now();
- let timeout = Duration::from_secs(120);
- let poll_start_delay = Duration::from_secs(5);
- let mut last_log_secs: u64 = 0;
-
- loop {
- if start.elapsed() > timeout {
- let _ = login_window.close();
- return Err(anyhow!("Timeout esperando login. Verifique credenciais."));
- }
-
- if captcha_detected.swap(false, std::sync::atomic::Ordering::Relaxed) {
- let _ = app.emit("hotmart-auth-captcha", ());
- }
-
- let nav_detected = post_login_detected.load(std::sync::atomic::Ordering::Relaxed);
- let should_poll = nav_detected || start.elapsed() > poll_start_delay;
-
- if should_poll {
- #[cfg(windows)]
- let cookies = extract_webview_cookies(&login_window).await?;
- #[cfg(not(windows))]
- let cookies = extract_webview_cookies_js(&login_window, &cookie_data).await?;
-
- let has_token = cookies.iter().any(|(name, _)| name == "hmVlcIntegration");
-
- if has_token {
- tracing::info!(
- "[auth] hmVlcIntegration found after {:.1}s (nav_detected={})",
- start.elapsed().as_secs_f64(),
- nav_detected
- );
- let _ = login_window.close();
-
- let token = cookies
- .iter()
- .find(|(name, _)| name == "hmVlcIntegration")
- .map(|(_, value)| value.clone())
- .unwrap();
-
- let saved = SavedSession {
- token: token.clone(),
- email: email.to_string(),
- cookies: cookies.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let client = build_client_from_saved(&saved)?;
-
- return Ok(HotmartSession {
- token,
- email: email.to_string(),
- client,
- cookies,
- });
- }
-
- let elapsed_secs = start.elapsed().as_secs();
- if elapsed_secs >= last_log_secs + 5 {
- last_log_secs = elapsed_secs;
- let cookie_names: Vec<&str> =
- cookies.iter().map(|(n, _)| n.as_str()).collect();
- tracing::info!(
- "[auth] polling at {}s, {} cookies: {:?}",
- elapsed_secs,
- cookies.len(),
- cookie_names
- );
- }
- }
-
- let sleep_ms = if nav_detected { 500 } else { 2000 };
- tokio::time::sleep(Duration::from_millis(sleep_ms)).await;
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/hotmart/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/downloader.rs
deleted file mode 100644
index 2faa1f47..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-use omniget_core::core::media_processor::MediaProcessor;
-use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
-use omniget_core::models::settings::{self, DownloadSettings};
-use crate::platforms::traits::PlatformDownloader;
-
-use super::api::{self, Course, Lesson};
-use super::auth::HotmartSession;
-use super::parser::{self, DetectedPlayer};
-
-const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct CourseDownloadProgress {
- pub course_id: u64,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- pub current_page: String,
- pub downloaded_bytes: u64,
- pub total_pages: u32,
- pub completed_pages: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-#[derive(serde::Serialize, serde::Deserialize)]
-struct DoneManifest {
- file: String,
- size: u64,
- segments: usize,
- completed_at: String,
-}
-
-fn done_path(file_path: &str) -> PathBuf {
- let p = PathBuf::from(file_path);
- let file_name = p.file_name().unwrap_or_default().to_string_lossy();
- let manifest_name = format!("{}.omniget.done", file_name);
- p.with_file_name(manifest_name)
-}
-
-async fn write_done_manifest(file_path: &str, size: u64, segments: usize) -> anyhow::Result<()> {
- let p = PathBuf::from(file_path);
- let file_name = p
- .file_name()
- .unwrap_or_default()
- .to_string_lossy()
- .to_string();
- let manifest = DoneManifest {
- file: file_name,
- size,
- segments,
- completed_at: chrono::Utc::now().to_rfc3339(),
- };
- let json = serde_json::to_string_pretty(&manifest)?;
- tokio::fs::write(done_path(file_path), json).await?;
- Ok(())
-}
-
-async fn is_hls_file_valid(file_path: &str) -> bool {
- let dp = done_path(file_path);
-
- let manifest_bytes = match tokio::fs::read(&dp).await {
- Ok(b) => b,
- Err(_) => return false,
- };
-
- let manifest: DoneManifest = match serde_json::from_slice(&manifest_bytes) {
- Ok(m) => m,
- Err(_) => return false,
- };
-
- let meta = match tokio::fs::metadata(file_path).await {
- Ok(m) => m,
- Err(_) => return false,
- };
-
- meta.len() == manifest.size
-}
-
-const CONCURRENT_LESSONS: usize = 3;
-
-#[derive(Clone)]
-pub struct HotmartDownloader {
- session: Arc<Mutex<Option<HotmartSession>>>,
- download_settings: DownloadSettings,
- max_concurrent_segments: u32,
- max_retries: u32,
- concurrent_fragments: u32,
- hls_client: reqwest::Client,
-}
-
-impl HotmartDownloader {
- pub fn new(
- session: Arc<Mutex<Option<HotmartSession>>>,
- download_settings: DownloadSettings,
- max_concurrent_segments: u32,
- max_retries: u32,
- concurrent_fragments: u32,
- ) -> Self {
- let hls_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .danger_accept_invalid_certs(true)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(300))
- .pool_max_idle_per_host(50)
- .pool_idle_timeout(Duration::from_secs(30))
- .build()
- .unwrap();
-
- Self {
- session,
- download_settings,
- max_concurrent_segments,
- max_retries,
- concurrent_fragments,
- hls_client,
- }
- }
-
- fn filename_prefix(&self) -> &str {
- if self.download_settings.filename_template == settings::default_filename_template() {
- "omniget-"
- } else {
- ""
- }
- }
-
- pub async fn download_lesson(
- &self,
- session: &HotmartSession,
- lesson: &Lesson,
- output_dir: &str,
- referer: &str,
- bytes_tx: tokio::sync::mpsc::UnboundedSender<u64>,
- cancel_token: &CancellationToken,
- ) -> anyhow::Result<Vec<PathBuf>> {
- let mut results = Vec::new();
-
- tokio::fs::create_dir_all(output_dir).await?;
-
- if lesson.has_media {
- let prefix = self.filename_prefix().to_string();
- let media_futures: Vec<_> = lesson.medias.iter().enumerate().map(|(i, media)| {
- let media = media.clone();
- let session = session.clone();
- let output_dir = output_dir.to_string();
- let bytes_tx = bytes_tx.clone();
- let cancel_token = cancel_token.clone();
- let hls_client = self.hls_client.clone();
- let max_concurrent_segments = self.max_concurrent_segments;
- let max_retries = self.max_retries;
- let prefix = prefix.clone();
-
- async move {
- let mut paths: Vec<PathBuf> = Vec::new();
-
- if cancel_token.is_cancelled() {
- return paths;
- }
-
- let assets = match parser::fetch_player_media_assets(&media.url, &session).await {
- Ok(a) => a,
- Err(_) => return paths,
- };
-
- if media.media_type.to_uppercase().contains("VIDEO") {
- let m3u8_url = match assets.first().and_then(|a| a.get("url")).and_then(|v| v.as_str()) {
- Some(url) => url.to_string(),
- None => return paths,
- };
-
- let out = format!("{}/{}{}. Aula.mp4", output_dir, prefix, i + 1);
-
- if is_hls_file_valid(&out).await {
- return paths;
- }
-
- if tokio::fs::try_exists(done_path(&out)).await.unwrap_or(false) {
- let _ = tokio::fs::remove_file(&out).await;
- let _ = tokio::fs::remove_file(done_path(&out)).await;
- }
-
- let hls_result = retry_hls_download(
- &m3u8_url,
- &out,
- "https://cf-embed.play.hotmart.com/",
- Some(bytes_tx.clone()),
- &cancel_token,
- max_concurrent_segments,
- max_retries,
- 3,
- Some(hls_client),
- )
- .await;
-
- match hls_result {
- Ok(hls_result) => {
- let _ = write_done_manifest(&out, hls_result.file_size, hls_result.segments).await;
- paths.push(hls_result.path);
- }
- Err(e) => {
- tracing::error!("[download] Falha ao baixar vídeo '{}': {}", out, e);
- let _ = tokio::fs::remove_file(&out).await;
- }
- }
- } else if media.media_type.to_uppercase().contains("AUDIO") {
- for asset in &assets {
- let content_type = asset
- .get("contentType")
- .and_then(|v| v.as_str())
- .unwrap_or("");
- if !content_type.to_lowercase().contains("audio") {
- continue;
- }
- let audio_url = match asset.get("url").and_then(|v| v.as_str()) {
- Some(url) => url,
- None => continue,
- };
-
- let safe_name = filename::sanitize_path_component(&media.name);
- let out = format!(
- "{}/{}{}. {}",
- output_dir,
- prefix,
- i + 1,
- if safe_name.is_empty() { "Audio.mp4".to_string() } else { safe_name }
- );
-
- if tokio::fs::try_exists(&out).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&out).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match session.client.get(audio_url).send().await {
- Ok(resp) => match resp.bytes().await {
- Ok(bytes) => {
- let _ = bytes_tx.send(bytes.len() as u64);
- if tokio::fs::write(&out, &bytes).await.is_ok() {
- paths.push(PathBuf::from(out));
- }
- }
- Err(e) => tracing::error!("[download] Falha ao baixar áudio: {}", e),
- },
- Err(e) => tracing::error!("[download] Falha ao baixar áudio: {}", e),
- }
- }
- }
-
- paths
- }
- }).collect();
-
- let all_media_results = futures::future::join_all(media_futures).await;
- for media_result in all_media_results {
- results.extend(media_result);
- }
- }
-
- if let Some(html) = &lesson.content {
- let players = parser::detect_players_from_html(html);
- let prefix2 = self.filename_prefix().to_string();
- let player_futures: Vec<_> = players.into_iter().enumerate().map(|(i, player)| {
- let bytes_tx = bytes_tx.clone();
- let cancel_token = cancel_token.clone();
- let hls_client = self.hls_client.clone();
- let max_concurrent_segments = self.max_concurrent_segments;
- let max_retries = self.max_retries;
- let concurrent_fragments = self.concurrent_fragments;
- let output_dir = output_dir.to_string();
- let referer = referer.to_string();
- let prefix = prefix2.clone();
-
- async move {
- let mut paths: Vec<PathBuf> = Vec::new();
-
- if cancel_token.is_cancelled() {
- return paths;
- }
-
- let out = format!("{}/{}{}. Aula.mp4", output_dir, prefix, i + 1);
-
- match player {
- DetectedPlayer::Vimeo { embed_url } => {
- if tokio::fs::try_exists(&out).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&out).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- return paths;
- }
- }
-
- match omniget_core::core::ytdlp::ensure_ytdlp().await {
- Ok(ytdlp_path) => {
- let out_dir = std::path::Path::new(&out).parent()
- .unwrap_or(std::path::Path::new("."));
- let (vtx, _vrx) = mpsc::channel(8);
- match omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- &embed_url,
- out_dir,
- None,
- vtx,
- None,
- None,
- None,
- Some(&referer),
- cancel_token.clone(),
- None,
- concurrent_fragments,
- false,
- &[],
- ).await {
- Ok(result) => {
- let _ = bytes_tx.send(result.file_size_bytes);
- paths.push(result.file_path);
- }
- Err(e) => {
- tracing::error!("[download] Falha Vimeo: {}", e);
- cleanup_part_files(out_dir).await;
- }
- }
- }
- Err(e) => {
- tracing::error!("[download] yt-dlp indisponível para Vimeo: {}", e);
- }
- }
- }
- DetectedPlayer::PandaVideo { m3u8_url, .. } => {
- if is_hls_file_valid(&out).await {
- return paths;
- }
-
- if tokio::fs::try_exists(done_path(&out)).await.unwrap_or(false) {
- let _ = tokio::fs::remove_file(&out).await;
- let _ = tokio::fs::remove_file(done_path(&out)).await;
- }
-
- let panda_referer = m3u8_url
- .split("com.br")
- .next()
- .unwrap_or("")
- .to_string()
- + "com.br";
- match retry_hls_download(&m3u8_url, &out, &panda_referer, Some(bytes_tx.clone()), &cancel_token, max_concurrent_segments, max_retries, 3, Some(hls_client)).await {
- Ok(hls_result) => {
- let _ = write_done_manifest(&out, hls_result.file_size, hls_result.segments).await;
- paths.push(hls_result.path);
- }
- Err(e) => {
- tracing::error!("[download] Falha PandaVideo: {}", e);
- let _ = tokio::fs::remove_file(&out).await;
- }
- }
- }
- DetectedPlayer::YouTube { video_id, .. } => {
- if tokio::fs::try_exists(&out).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&out).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- return paths;
- }
- }
-
- let yt_url = format!("https://www.youtube.com/watch?v={}", video_id);
- match omniget_core::core::ytdlp::ensure_ytdlp().await {
- Ok(ytdlp_path) => {
- let out_dir = std::path::Path::new(&out).parent()
- .unwrap_or(std::path::Path::new("."));
- let (ytx, _yrx) = mpsc::channel(8);
- match omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- &yt_url,
- out_dir,
- None,
- ytx,
- None,
- None,
- None,
- None,
- cancel_token.clone(),
- None,
- concurrent_fragments,
- false,
- &[],
- ).await {
- Ok(result) => {
- let _ = bytes_tx.send(result.file_size_bytes);
- paths.push(result.file_path);
- }
- Err(e) => {
- tracing::error!("[download] Falha YouTube: {}", e);
- cleanup_part_files(out_dir).await;
- }
- }
- }
- Err(e) => {
- tracing::error!("[download] yt-dlp indisponível: {}", e);
- }
- }
- }
- DetectedPlayer::HotmartNative { .. } => {}
- DetectedPlayer::Unknown { .. } => {}
- }
-
- paths
- }
- }).collect();
-
- let all_player_results = futures::future::join_all(player_futures).await;
- for player_result in all_player_results {
- results.extend(player_result);
- }
- }
-
- if cancel_token.is_cancelled() {
- anyhow::bail!("Download cancelled by user");
- }
-
- if self.download_settings.download_attachments && !lesson.attachments.is_empty() {
- let mat_dir = format!("{}/Materiais", output_dir);
- tokio::fs::create_dir_all(&mat_dir).await?;
-
- let att_futures: Vec<_> = lesson.attachments.iter().map(|att| {
- let session = session.clone();
- let safe_name = filename::sanitize_path_component(&att.file_name);
- let att_path = format!("{}/{}", mat_dir, safe_name);
- let file_membership_id = att.file_membership_id.clone();
-
- async move {
- if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
- return None;
- }
- match download_attachment(&session, &file_membership_id, &att_path).await {
- Ok(()) => Some(PathBuf::from(att_path)),
- Err(_) => None,
- }
- }
- }).collect();
-
- let att_results = futures::future::join_all(att_futures).await;
- for path in att_results.into_iter().flatten() {
- results.push(path);
- }
- }
-
- if self.download_settings.download_descriptions {
- if let Some(content) = &lesson.content {
- if !content.trim().is_empty() {
- let desc_path = format!("{}/Description.html", output_dir);
- if !tokio::fs::try_exists(&desc_path).await.unwrap_or(false) {
- tokio::fs::write(&desc_path, content).await?;
- }
- }
- }
-
- if let Some(readings) = &lesson.complementary_readings {
- if !readings.is_empty() {
- let reading_path = format!("{}/Leitura complementar.html", output_dir);
- if !tokio::fs::try_exists(&reading_path).await.unwrap_or(false) {
- let mut html = String::new();
- for link in readings {
- let title = link.title.as_deref().unwrap_or("");
- let url = link.url.as_deref().unwrap_or("#");
- html.push_str(&format!("<a href=\"{}\">{}</a><br>\n", url, title));
- }
- tokio::fs::write(&reading_path, &html).await?;
- }
- }
- }
- }
-
- Ok(results)
- }
-
- pub async fn download_full_course(
- &self,
- course: &Course,
- base_dir: &str,
- progress: mpsc::Sender<CourseDownloadProgress>,
- cancel_token: CancellationToken,
- ) -> anyhow::Result<()> {
- if course.external_platform {
- return Err(anyhow!("Curso hospedado em plataforma externa"));
- }
-
- let slug = course
- .slug
- .as_deref()
- .or(course.subdomain.as_deref())
- .ok_or_else(|| anyhow!("Curso sem slug/subdomain: {}", course.name))?;
-
- let session = {
- let guard = self.session.lock().await;
- guard
- .as_ref()
- .ok_or_else(|| anyhow!("Not authenticated"))?
- .clone()
- };
-
- let modules = api::get_modules(&session, slug, course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!("'{}' has no modules available for download", course.name));
- }
-
- let course_dir = format!(
- "{}/{} - {}",
- base_dir,
- filename::sanitize_path_component(&course.name),
- filename::sanitize_path_component(&course.seller)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- let total_pages: usize = modules.iter().map(|m| m.pages.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let done = Arc::new(AtomicUsize::new(0));
-
- let _ = progress
- .send(CourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Iniciando...".to_string(),
- current_page: String::new(),
- downloaded_bytes: 0,
- total_pages: total_pages as u32,
- completed_pages: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- })
- .await;
-
- let referer = format!("https://{}.club.hotmart.com/", slug);
- let slug_owned = slug.to_string();
-
- struct PageTask {
- module_index: usize,
- module_name: String,
- page_hash: String,
- page_name: String,
- page_dir: String,
- }
-
- let mut all_pages = Vec::new();
- for (mi, module) in modules.iter().enumerate() {
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- for (pi, page) in module.pages.iter().enumerate() {
- let page_name_sanitized = filename::sanitize_path_component(&page.name);
- let page_dir = format!("{}/{}. {}", mod_dir, pi + 1, page_name_sanitized);
- all_pages.push(PageTask {
- module_index: mi,
- module_name: module.name.clone(),
- page_hash: page.hash.clone(),
- page_name: page.name.clone(),
- page_dir,
- });
- }
- }
-
- stream::iter(all_pages)
- .for_each_concurrent(CONCURRENT_LESSONS, |task| {
- let downloader = self.clone();
- let session = session.clone();
- let cancel_token = cancel_token.clone();
- let progress = progress.clone();
- let total_bytes = total_bytes.clone();
- let done = done.clone();
- let course_id = course.id;
- let course_name = course.name.clone();
- let referer = referer.clone();
- let slug = slug_owned.clone();
-
- async move {
- if cancel_token.is_cancelled() {
- return;
- }
-
- if let Err(e) = tokio::fs::create_dir_all(&task.page_dir).await {
- tracing::error!("Falha ao criar diretório '{}': {}", task.page_dir, e);
- done.fetch_add(1, Ordering::Relaxed);
- return;
- }
-
- let lesson = match api::get_lesson(&session, &slug, course_id, &task.page_hash).await {
- Ok(l) => l,
- Err(e) => {
- tracing::error!("Falha ao carregar lição '{}': {}. Continuando...", task.page_name, e);
- let completed = done.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = progress
- .send(CourseDownloadProgress {
- course_id,
- course_name,
- percent: completed as f64 / total_pages as f64 * 100.0,
- current_module: task.module_name,
- current_page: task.page_name,
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_pages: total_pages as u32,
- completed_pages: completed as u32,
- total_modules: total_modules as u32,
- current_module_index: (task.module_index + 1) as u32,
- })
- .await;
- return;
- }
- };
-
- let (lesson_bytes_tx, mut lesson_bytes_rx) =
- tokio::sync::mpsc::unbounded_channel::<u64>();
- let total_bytes_ref = total_bytes.clone();
- let accumulator = tokio::spawn(async move {
- while let Some(n) = lesson_bytes_rx.recv().await {
- total_bytes_ref.fetch_add(n, Ordering::Relaxed);
- }
- });
-
- let lesson_result = downloader
- .download_lesson(&session, &lesson, &task.page_dir, &referer, lesson_bytes_tx, &cancel_token)
- .await;
-
- let _ = accumulator.await;
-
- if let Err(e) = lesson_result {
- if !cancel_token.is_cancelled() {
- tracing::error!(
- "Error downloading page '{}': {}. Continuing...",
- task.page_name,
- e
- );
- }
- }
-
- let completed = done.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = progress
- .send(CourseDownloadProgress {
- course_id,
- course_name,
- percent: completed as f64 / total_pages as f64 * 100.0,
- current_module: task.module_name,
- current_page: task.page_name,
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_pages: total_pages as u32,
- completed_pages: completed as u32,
- total_modules: total_modules as u32,
- current_module_index: (task.module_index + 1) as u32,
- })
- .await;
- }
- })
- .await;
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- Ok(())
- }
-}
-
-#[allow(clippy::too_many_arguments)]
-async fn retry_hls_download(
- m3u8_url: &str,
- output_path: &str,
- referer: &str,
- bytes_tx: Option<tokio::sync::mpsc::UnboundedSender<u64>>,
- cancel_token: &CancellationToken,
- max_concurrent_segments: u32,
- max_retries: u32,
- max_attempts: u32,
- hls_client: Option<reqwest::Client>,
-) -> anyhow::Result<omniget_core::core::hls_downloader::HlsDownloadResult> {
- let mut last_err = None;
- for attempt in 0..max_attempts {
- if cancel_token.is_cancelled() {
- anyhow::bail!("Download cancelled by user");
- }
- match MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- referer,
- bytes_tx.clone(),
- cancel_token.clone(),
- max_concurrent_segments,
- max_retries,
- hls_client.clone(),
- )
- .await
- {
- Ok(result) => {
- let meta = tokio::fs::metadata(output_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- return Ok(result);
- }
- last_err = Some(anyhow!("Output file empty after HLS download"));
- }
- Err(e) => {
- if cancel_token.is_cancelled() {
- return Err(e);
- }
- last_err = Some(e);
- }
- }
- if attempt < max_attempts - 1 {
- let _ = tokio::fs::remove_file(output_path).await;
- let backoff = std::time::Duration::from_secs(2u64.pow(attempt));
- tracing::warn!(
- "[hls-retry] Tentativa {}/{} falhou para '{}', retentando em {:?}",
- attempt + 1,
- max_attempts,
- output_path,
- backoff
- );
- tokio::time::sleep(backoff).await;
- }
- }
- Err(last_err.unwrap_or_else(|| anyhow!("HLS download failed after {} attempts", max_attempts)))
-}
-
-async fn cleanup_part_files(dir: &std::path::Path) {
- let mut entries = match tokio::fs::read_dir(dir).await {
- Ok(e) => e,
- Err(_) => return,
- };
- while let Ok(Some(entry)) = entries.next_entry().await {
- let path = entry.path();
- if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
- if name.ends_with(".part") || name.ends_with(".ytdl") {
- let _ = tokio::fs::remove_file(&path).await;
- }
- }
- }
-}
-
-async fn download_attachment(
- session: &HotmartSession,
- file_membership_id: &str,
- output_path: &str,
-) -> anyhow::Result<()> {
- let info = api::get_attachment_url(session, file_membership_id).await?;
-
- if !info.is_drm {
- if info.url.is_empty() {
- return Err(anyhow!("URL de download vazia para attachment {}", file_membership_id));
- }
- let bytes = reqwest::get(&info.url).await?.bytes().await?;
- tokio::fs::write(output_path, &bytes).await?;
- } else {
- let lambda_url = info
- .lambda_url
- .as_deref()
- .ok_or_else(|| anyhow!("lambdaUrl not found for DRM"))?;
- let drm_token = info
- .token
- .as_deref()
- .ok_or_else(|| anyhow!("DRM token not found"))?;
-
- let signed_url = session
- .client
- .get(lambda_url)
- .header("token", drm_token)
- .header("User-Agent", USER_AGENT)
- .send()
- .await?
- .text()
- .await?;
-
- if signed_url.is_empty() || signed_url.contains("500") {
- return Err(anyhow!("DRM attachment unavailable (empty response or error 500)"));
- }
-
- let bytes = reqwest::get(&signed_url).await?.bytes().await?;
- let drm_output = format!(
- "{}/drm_{}",
- std::path::Path::new(output_path)
- .parent()
- .map(|p| p.to_str().unwrap_or("."))
- .unwrap_or("."),
- std::path::Path::new(output_path)
- .file_name()
- .map(|f| f.to_str().unwrap_or("file"))
- .unwrap_or("file")
- );
- tokio::fs::write(&drm_output, &bytes).await?;
- }
-
- Ok(())
-}
-
-#[async_trait]
-impl PlatformDownloader for HotmartDownloader {
- fn name(&self) -> &str {
- "hotmart"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- url.contains("hotmart.com") || url.contains("club.hotmart.com")
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: format!("Hotmart course: {}", url),
- author: String::new(),
- platform: "hotmart".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Hotmart downloads use start_course_download, not the generic download trait"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/hotmart/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/mod.rs
deleted file mode 100644
index aea8d9ab..00000000
--- a/src-tauri/omniget-plugin-courses/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/omniget-plugin-courses/src/platforms/hotmart/parser.rs b/src-tauri/omniget-plugin-courses/src/platforms/hotmart/parser.rs
deleted file mode 100644
index 10fd2e84..00000000
--- a/src-tauri/omniget-plugin-courses/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/omniget-plugin-courses/src/platforms/kajabi/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/kajabi/api.rs
deleted file mode 100644
index 4a1e415d..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn build_auth_client(token: &str) -> anyhow::Result<reqwest::Client> {
- let mut headers = HeaderMap::new();
- headers.insert(
- "Authorization",
- HeaderValue::from_str(&format!("Bearer {}", token))?,
- );
- headers.insert(
- "Kjb-App-Id",
- HeaderValue::from_static("Kajabi"),
- );
- headers.insert(
- "KJB-DP",
- HeaderValue::from_static("ANDROID"),
- );
- headers.insert("Accept", HeaderValue::from_static("application/json"));
-
- let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("kajabi_session.json"))
-}
-
-pub async fn request_login_link(email: &str) -> anyhow::Result<String> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "email": email,
- });
-
- let resp = temp_client
- .post(&format!("{}/login_links", AUTH_BASE))
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Login link request failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let login_token = body
- .get("token")
- .or_else(|| body.get("login_token"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("token not found in login_links response"))?
- .to_string();
-
- Ok(login_token)
-}
-
-pub async fn verify_login(email: &str, confirmation_code: &str, login_token: &str) -> anyhow::Result<String> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "email": email,
- "confirmation_code": confirmation_code,
- "token": login_token,
- });
-
- let resp = temp_client
- .post(&format!("{}/authentication", AUTH_BASE))
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Authentication failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let bearer_token = body
- .get("bearerToken")
- .or_else(|| body.get("bearer_token"))
- .or_else(|| body.get("token"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("bearerToken not found in authentication response"))?
- .to_string();
-
- Ok(bearer_token)
-}
-
-pub async fn validate_token(session: &KajabiSession) -> anyhow::Result<bool> {
- let client = build_auth_client(&session.token)?;
-
- let resp = client
- .get(&format!("{}/sites", AUTH_BASE))
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_sites(token: &str) -> anyhow::Result<Vec<KajabiSite>> {
- let client = build_auth_client(token)?;
-
- let resp = client
- .get(&format!("{}/sites", AUTH_BASE))
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_sites returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let sites_arr = body
- .as_array()
- .or_else(|| body.get("sites").and_then(|v| v.as_array()))
- .cloned()
- .unwrap_or_default();
-
- let mut sites = Vec::new();
-
- for item in &sites_arr {
- let id = item
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let title = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- sites.push(KajabiSite { id, title });
- }
-
- Ok(sites)
-}
-
-pub async fn list_courses(session: &KajabiSession) -> anyhow::Result<Vec<KajabiCourse>> {
- let mut all_courses = Vec::new();
- let mut page = 1u32;
-
- loop {
- let url = format!(
- "{}/sites/{}/courses?page={}&per_page=50",
- BASE_URL, session.site_id, page
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let courses_arr = body
- .get("data")
- .and_then(|v| v.as_array())
- .or_else(|| body.as_array())
- .cloned()
- .unwrap_or_default();
-
- if courses_arr.is_empty() {
- break;
- }
-
- for item in &courses_arr {
- let id = item
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let name = item
- .get("name")
- .or_else(|| item.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let thumbnail_url = item
- .get("thumbnail_url")
- .or_else(|| item.get("image_url"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- all_courses.push(KajabiCourse {
- id,
- name,
- thumbnail_url,
- site_id: session.site_id.clone(),
- });
- }
-
- page += 1;
- }
-
- Ok(all_courses)
-}
-
-pub async fn get_categories(
- session: &KajabiSession,
- product_id: &str,
-) -> anyhow::Result<Vec<KajabiModule>> {
- let url = format!(
- "{}/sites/{}/products/{}/categories",
- BASE_URL, session.site_id, product_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_categories returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let categories_arr = body
- .get("data")
- .and_then(|v| v.get("categories"))
- .and_then(|v| v.as_array())
- .or_else(|| body.get("categories").and_then(|v| v.as_array()))
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for (i, cat) in categories_arr.iter().enumerate() {
- let cat_id = cat
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", i),
- })
- .unwrap_or_else(|| format!("{}", i));
-
- let cat_name = cat
- .get("name")
- .or_else(|| cat.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let posts_arr = cat
- .get("posts")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (j, post) in posts_arr.iter().enumerate() {
- let post_id = post
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", j),
- })
- .unwrap_or_else(|| format!("{}", j));
-
- let post_name = post
- .get("name")
- .or_else(|| post.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- lessons.push(KajabiLesson {
- id: post_id,
- name: post_name,
- order: j as i64,
- });
- }
-
- modules.push(KajabiModule {
- id: cat_id,
- name: cat_name,
- order: i as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-pub async fn get_post_detail(
- session: &KajabiSession,
- product_id: &str,
- post_id: &str,
-) -> anyhow::Result<KajabiLessonDetail> {
- let url = format!(
- "{}/sites/{}/products/{}/posts/{}",
- BASE_URL, session.site_id, product_id, post_id
- );
-
- let mut last_err = anyhow!("Failed after retries");
-
- for attempt in 0..3u32 {
- if attempt > 0 {
- tokio::time::sleep(Duration::from_secs(3)).await;
- }
-
- let resp = match session.client.get(&url).send().await {
- Ok(r) => r,
- Err(e) => {
- last_err = e.into();
- continue;
- }
- };
-
- let status = resp.status();
-
- if status.as_u16() == 403 || status.as_u16() == 429 {
- let body_text = resp.text().await.unwrap_or_default();
- last_err = anyhow!(
- "get_post_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- );
- continue;
- }
-
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_post_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let data = body.get("data").unwrap_or(&body);
-
- let id = data
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => post_id.to_string(),
- })
- .unwrap_or_else(|| post_id.to_string());
-
- let name = data
- .get("name")
- .or_else(|| data.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let video_url = data
- .get("video_url")
- .and_then(|v| v.as_str())
- .map(String::from)
- .or_else(|| {
- data.get("video")
- .and_then(|v| v.get("url"))
- .and_then(|v| v.as_str())
- .map(String::from)
- })
- .or_else(|| {
- data.get("wistia_video")
- .and_then(|v| v.get("url"))
- .and_then(|v| v.as_str())
- .map(String::from)
- })
- .or_else(|| {
- data.get("content_videos")
- .and_then(|v| v.as_array())
- .and_then(|arr| arr.first())
- .and_then(|v| v.get("url"))
- .and_then(|v| v.as_str())
- .map(String::from)
- })
- .or_else(|| {
- data.get("media")
- .and_then(|m| m.get("assets"))
- .and_then(|a| a.as_array())
- .and_then(|arr| {
- arr.iter().find(|a| {
- a.get("type")
- .and_then(|v| v.as_str())
- .map(|t| t == "HdMp4VideoFile")
- .unwrap_or(false)
- })
- })
- .and_then(|a| a.get("url"))
- .and_then(|v| v.as_str())
- .map(String::from)
- });
-
- let mut files = Vec::new();
-
- if let Some(downloads) = data.get("downloads").and_then(|v| v.as_array()) {
- for dl in downloads {
- let file_id = dl
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let file_name = dl
- .get("name")
- .or_else(|| dl.get("filename"))
- .and_then(|v| v.as_str())
- .unwrap_or("file")
- .to_string();
-
- let file_url = dl
- .get("url")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- files.push(KajabiFile {
- id: file_id,
- name: file_name,
- url: file_url,
- });
- }
- }
-
- return Ok(KajabiLessonDetail {
- id,
- name,
- video_url,
- files,
- });
- }
-
- Err(last_err)
-}
-
-pub async fn save_session(session: &KajabiSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- site_id: session.site_id.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[kajabi] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<KajabiSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token, &saved.site_id)?;
-
- tracing::info!("[kajabi] session loaded");
-
- Ok(Some(KajabiSession {
- token: saved.token,
- site_id: saved.site_id,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kajabi/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/kajabi/downloader.rs
deleted file mode 100644
index 1f7d9837..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, KajabiCourse, KajabiSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct KajabiCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &KajabiSession,
- course: &KajabiCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_categories(session, &course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[kajabi] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &KajabiCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- let detail = match api::get_post_detail(session, &course.id, &lesson.id).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[kajabi] Failed to get post detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &KajabiCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if let Some(ref video_url) = detail.video_url {
- let video_ext = if video_url.contains(".m3u8") {
- "mp4"
- } else {
- video_url
- .rsplit('.')
- .next()
- .and_then(|e| {
- let e = e.split('?').next().unwrap_or(e);
- if e.len() <= 4 {
- Some(e)
- } else {
- None
- }
- })
- .unwrap_or("mp4")
- };
-
- let video_path = format!(
- "{}/{}. {}.{}",
- lesson_dir,
- li + 1,
- lesson_name,
- video_ext
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[kajabi] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &KajabiCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if video_url.contains(".m3u8") {
- match download_hls_video(video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[kajabi] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[kajabi] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[kajabi] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
-
- for file in &detail.files {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let file_name = filename::sanitize_path_component(&file.name);
- let file_path = format!("{}/{}", lesson_dir, file_name);
-
- if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&file_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- if let Some(ref url) = file.url {
- match download_file_direct(&session.client, url, &file_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[kajabi] File download failed for '{}': {}",
- file.name,
- e
- );
- }
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &KajabiCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://app.kajabi.com/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://app.kajabi.com/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kajabi/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/kajabi/mod.rs
deleted file mode 100644
index 4aaa81a2..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct KajabiDownloader;
-
-impl Default for KajabiDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl KajabiDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for KajabiDownloader {
- fn name(&self) -> &str {
- "kajabi"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "kajabi.com"
- || host.ends_with(".kajabi.com")
- || host == "app.kajabi.com";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Kajabi Course".to_string(),
- author: String::new(),
- platform: "kajabi".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Kajabi courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kirvano/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/kirvano/api.rs
deleted file mode 100644
index 6bb720fd..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("kirvano_session.json"))
-}
-
-pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<KirvanoSession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "email": email,
- "password": password,
- "source": "app-web",
- "fingerprint": null,
- });
-
- let resp = temp_client
- .post("https://app-api.kirvano.com/users/login/otp")
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Authentication failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let token = body
- .get("token")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("token not found in login response"))?
- .to_string();
-
- let client = build_client(&token)?;
-
- Ok(KirvanoSession {
- token,
- email: email.to_string(),
- client,
- })
-}
-
-pub async fn validate_token(session: &KirvanoSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://app-api.kirvano.com/purchases?page=1&pageSize=1")
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &KirvanoSession) -> anyhow::Result<Vec<KirvanoCourse>> {
- let mut all_courses = Vec::new();
- let mut page = 1u32;
-
- loop {
- let url = format!(
- "https://app-api.kirvano.com/purchases?page={}&pageSize=99",
- page
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let items = body
- .get("data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- if items.is_empty() {
- break;
- }
-
- for item in &items {
- let purchase_uuid = item
- .get("uuid")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let name = item
- .get("product")
- .and_then(|v| v.as_str())
- .unwrap_or("Unnamed")
- .to_string();
-
- let image_url = item.get("photo").and_then(|v| v.as_str()).map(String::from);
-
- let seller = item
- .get("sellerName")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let course_uuid = item
- .get("courseUuid")
- .or_else(|| item.get("productUuid"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if course_uuid.is_empty() {
- let detail_url = format!(
- "https://app-api.kirvano.com/purchases/{}",
- purchase_uuid
- );
- if let Ok(detail_resp) = session.client.get(&detail_url).send().await {
- if detail_resp.status().is_success() {
- if let Ok(detail_text) = detail_resp.text().await {
- if let Ok(detail_body) = serde_json::from_str::<serde_json::Value>(&detail_text) {
- let resolved_uuid = detail_body
- .get("courseUuid")
- .or_else(|| detail_body.get("productUuid"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let resolved_seller = detail_body
- .get("sellerName")
- .and_then(|v| v.as_str())
- .unwrap_or(&seller)
- .to_string();
-
- if !resolved_uuid.is_empty() {
- all_courses.push(KirvanoCourse {
- id: purchase_uuid,
- name: name.clone(),
- seller: resolved_seller,
- image_url: image_url.clone(),
- course_uuid: resolved_uuid,
- });
- continue;
- }
- }
- }
- }
- }
- continue;
- }
-
- all_courses.push(KirvanoCourse {
- id: purchase_uuid,
- name,
- seller,
- image_url,
- course_uuid,
- });
- }
-
- let meta = body.get("meta");
- let current_page = meta
- .and_then(|m| m.get("page"))
- .and_then(|v| v.as_u64())
- .unwrap_or(page as u64);
- let total_pages = meta
- .and_then(|m| m.get("pages"))
- .and_then(|v| v.as_u64())
- .unwrap_or(1);
-
- if current_page >= total_pages {
- break;
- }
-
- page += 1;
- }
-
- Ok(all_courses)
-}
-
-pub async fn get_course_modules(
- session: &KirvanoSession,
- course_uuid: &str,
-) -> anyhow::Result<Vec<KirvanoModule>> {
- let mut all_modules = Vec::new();
- let mut page = 1u32;
-
- loop {
- let url = format!(
- "https://members-api.kirvano.com/v1/courses/{}/lessons/modules?page={}&pageSize=99",
- course_uuid, page
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_modules returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let items = body
- .get("data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- if items.is_empty() {
- break;
- }
-
- for item in &items {
- let mod_uuid = item
- .get("uuid")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let mod_name = item
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("Module")
- .to_string();
-
- let mod_order = item
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let lessons = get_module_lessons(session, course_uuid, &mod_uuid).await?;
-
- all_modules.push(KirvanoModule {
- id: mod_uuid,
- name: mod_name,
- order: mod_order,
- lessons,
- });
- }
-
- let meta = body.get("meta");
- let current_page = meta
- .and_then(|m| m.get("page"))
- .and_then(|v| v.as_u64())
- .unwrap_or(page as u64);
- let total_pages = meta
- .and_then(|m| m.get("pages"))
- .and_then(|v| v.as_u64())
- .unwrap_or(1);
-
- if current_page >= total_pages {
- break;
- }
-
- page += 1;
- }
-
- all_modules.sort_by_key(|m| m.order);
-
- Ok(all_modules)
-}
-
-async fn get_module_lessons(
- session: &KirvanoSession,
- course_uuid: &str,
- module_uuid: &str,
-) -> anyhow::Result<Vec<KirvanoLesson>> {
- let mut all_lessons = Vec::new();
- let mut page = 1u32;
-
- loop {
- let url = format!(
- "https://members-api.kirvano.com/v1/courses/{}/lessons/modules/{}/contents?page={}&pageSize=99",
- course_uuid, module_uuid, page
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_module_lessons returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let items = body
- .get("data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- if items.is_empty() {
- break;
- }
-
- for item in &items {
- let lesson_uuid = item
- .get("uuid")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_name = item
- .get("name")
- .or_else(|| item.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("Lesson")
- .to_string();
-
- let lesson_order = item
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let available = item
- .get("available")
- .and_then(|v| v.as_bool())
- .unwrap_or(true);
-
- let video_url = item
- .get("videoUrl")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let description = item
- .get("description")
- .or_else(|| item.get("content"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(String::from);
-
- all_lessons.push(KirvanoLesson {
- id: lesson_uuid,
- name: lesson_name,
- order: lesson_order,
- available,
- video_url,
- description,
- });
- }
-
- let meta = body.get("meta");
- let current_page = meta
- .and_then(|m| m.get("page"))
- .and_then(|v| v.as_u64())
- .unwrap_or(page as u64);
- let total_pages = meta
- .and_then(|m| m.get("pages"))
- .and_then(|v| v.as_u64())
- .unwrap_or(1);
-
- if current_page >= total_pages {
- break;
- }
-
- page += 1;
- }
-
- all_lessons.sort_by_key(|l| l.order);
-
- Ok(all_lessons)
-}
-
-pub async fn save_session(session: &KirvanoSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- email: session.email.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[kirvano] session saved for {}", session.email);
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<KirvanoSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[kirvano] session loaded for {}", saved.email);
-
- Ok(Some(KirvanoSession {
- token: saved.token,
- email: saved.email,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kirvano/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/kirvano/downloader.rs
deleted file mode 100644
index cf0d8fd7..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, KirvanoCourse, KirvanoSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct KirvanoCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &KirvanoSession,
- course: &KirvanoCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_modules(session, &course.course_uuid).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[kirvano] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &KirvanoCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- if !lesson.available {
- tracing::info!("[kirvano] Skipping unavailable lesson: {}", lesson.name);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &KirvanoCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
-
- if let Some(ref desc) = lesson.description {
- let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, filename::sanitize_path_component(&lesson.name));
- tokio::fs::create_dir_all(&lesson_desc_dir).await?;
- omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
- }
-
- if let Some(ref video_url) = lesson.video_url {
- if video_url.is_empty() {
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &KirvanoCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let video_path = format!(
- "{}/{}. {}.mp4",
- mod_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[kirvano] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &KirvanoCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- match download_with_ytdlp(video_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[kirvano] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[kirvano] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &KirvanoCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://app.kirvano.com/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kirvano/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/kirvano/mod.rs
deleted file mode 100644
index add839ad..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct KirvanoDownloader;
-
-impl Default for KirvanoDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl KirvanoDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for KirvanoDownloader {
- fn name(&self) -> &str {
- "kirvano"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "kirvano.com"
- || host == "app-api.kirvano.com"
- || host == "members-api.kirvano.com";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Kirvano".to_string(),
- author: String::new(),
- platform: "kirvano".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "Original".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Kirvano"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kiwify/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/kiwify/api.rs
deleted file mode 100644
index 1fe29c21..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("kiwify_session.json"))
-}
-
-pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<KiwifySession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "email": email,
- "password": password,
- "returnSecureToken": true,
- });
-
- let resp = temp_client
- .post("https://admin-api.kiwify.com.br/v1/handleAuth/login")
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Authentication failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let token = body
- .get("idToken")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("idToken not found in login response"))?
- .to_string();
-
- let client = build_client(&token)?;
-
- Ok(KiwifySession {
- token,
- email: email.to_string(),
- client,
- })
-}
-
-pub async fn validate_token(session: &KiwifySession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://admin-api.kiwify.com.br/v1/viewer/schools/courses?page=1&archived=false")
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &KiwifySession) -> anyhow::Result<Vec<KiwifyCourse>> {
- let mut all_courses = Vec::new();
- let mut page = 1u32;
-
- loop {
- let url = format!(
- "https://admin-api.kiwify.com.br/v1/viewer/schools/courses?page={}&archived=false",
- page
- );
-
- tracing::info!("[kiwify] fetching courses page {}", page);
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- tracing::info!("[kiwify] page {} status={} body_len={}", page, status, body_text.len());
-
- if !status.is_success() {
- if all_courses.is_empty() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
- break;
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let courses_arr = body
- .get("courses")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let total_count = body.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
- let page_size = body.get("page_size").and_then(|v| v.as_i64()).unwrap_or(10);
-
- tracing::info!("[kiwify] page {} returned {} courses (total={}, page_size={})", page, courses_arr.len(), total_count, page_size);
-
- if courses_arr.is_empty() {
- break;
- }
-
- for item in &courses_arr {
- let course_in_school = item
- .get("course_in_school")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
-
- let (info_obj, is_school) = if course_in_school {
- (
- item.get("school_info").unwrap_or(item),
- true,
- )
- } else {
- (
- item.get("course_info").unwrap_or(item),
- false,
- )
- };
-
- let id = info_obj
- .get("id")
- .and_then(|v| v.as_i64())
- .or_else(|| item.get("id").and_then(|v| v.as_i64()))
- .unwrap_or(0);
-
- let name = info_obj
- .get("name")
- .and_then(|v| v.as_str())
- .or_else(|| item.get("name").and_then(|v| v.as_str()))
- .unwrap_or("")
- .to_string();
-
- let seller = info_obj
- .get("producer")
- .and_then(|p| p.get("name").and_then(|n| n.as_str()))
- .or_else(|| {
- item.get("producer")
- .and_then(|p| p.get("name").and_then(|n| n.as_str()))
- })
- .unwrap_or("")
- .to_string();
-
- let image_url = info_obj
- .get("image")
- .and_then(|v| v.as_str())
- .or_else(|| info_obj.get("thumbnail").and_then(|v| v.as_str()))
- .map(String::from);
-
- all_courses.push(KiwifyCourse {
- id,
- name,
- seller,
- image_url,
- is_school,
- });
- }
-
- if total_count > 0 && (page as i64 * page_size) >= total_count {
- break;
- }
-
- if page >= 50 {
- tracing::warn!("[kiwify] safety limit reached at page 50");
- break;
- }
-
- page += 1;
- }
-
- tracing::info!("[kiwify] total courses found: {}", all_courses.len());
- Ok(all_courses)
-}
-
-pub async fn get_course_content(
- session: &KiwifySession,
- course_id: i64,
-) -> anyhow::Result<Vec<KiwifyModule>> {
- let club_url = format!(
- "https://admin-api.kiwify.com/v1/viewer/clubs/{}/content?caipirinha=true",
- course_id
- );
-
- let body = match session.client.get(&club_url).send().await {
- Ok(resp) if resp.status().is_success() => {
- let text = resp.text().await?;
- serde_json::from_str::<serde_json::Value>(&text)?
- }
- _ => {
- let fallback_url = format!(
- "https://admin-api.kiwify.com.br/v1/viewer/courses/{}",
- course_id
- );
- let resp = session.client.get(&fallback_url).send().await?;
- let status = resp.status();
- let text = resp.text().await?;
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &text[..text.len().min(300)]
- ));
- }
- serde_json::from_str::<serde_json::Value>(&text)?
- }
- };
-
- let modules_obj = body
- .get("modules")
- .or_else(|| body.get("content"))
- .ok_or_else(|| anyhow!("No modules found in course content response"))?;
-
- let mut modules = Vec::new();
-
- match modules_obj {
- serde_json::Value::Object(map) => {
- let mut entries: Vec<_> = map.iter().collect();
- entries.sort_by_key(|(_, v)| {
- v.get("order").and_then(|o| o.as_i64()).unwrap_or(0)
- });
-
- for (key, module_val) in entries {
- let module_name = module_val
- .get("title")
- .or_else(|| module_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or(key)
- .to_string();
-
- let module_order = module_val
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let mut lessons = Vec::new();
-
- let lessons_obj = module_val
- .get("lessons")
- .or_else(|| module_val.get("classes"));
-
- if let Some(serde_json::Value::Object(lessons_map)) = lessons_obj {
- let mut lesson_entries: Vec<_> = lessons_map.iter().collect();
- lesson_entries.sort_by_key(|(_, v)| {
- v.get("order").and_then(|o| o.as_i64()).unwrap_or(0)
- });
-
- for (lesson_key, lesson_val) in lesson_entries {
- let lesson_name = lesson_val
- .get("title")
- .or_else(|| lesson_val.get("name"))
- .or_else(|| lesson_val.get("ref"))
- .and_then(|v| v.as_str())
- .unwrap_or(lesson_key)
- .to_string();
-
- let lesson_order = lesson_val
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- lessons.push(KiwifyLesson {
- id: lesson_key.clone(),
- name: lesson_name,
- order: lesson_order,
- });
- }
- } else if let Some(serde_json::Value::Array(lessons_arr)) = lessons_obj {
- for (i, lesson_val) in lessons_arr.iter().enumerate() {
- let lesson_id = lesson_val
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_name = lesson_val
- .get("title")
- .or_else(|| lesson_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_order = lesson_val
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(i as i64);
-
- lessons.push(KiwifyLesson {
- id: if lesson_id.is_empty() {
- format!("{}", i)
- } else {
- lesson_id
- },
- name: lesson_name,
- order: lesson_order,
- });
- }
- }
-
- modules.push(KiwifyModule {
- id: key.clone(),
- name: module_name,
- order: module_order,
- lessons,
- });
- }
- }
- serde_json::Value::Array(arr) => {
- for (i, module_val) in arr.iter().enumerate() {
- let module_id = module_val
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let module_name = module_val
- .get("title")
- .or_else(|| module_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let module_order = module_val
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(i as i64);
-
- let mut lessons = Vec::new();
-
- if let Some(serde_json::Value::Array(lessons_arr)) =
- module_val.get("lessons").or_else(|| module_val.get("classes"))
- {
- for (j, lesson_val) in lessons_arr.iter().enumerate() {
- let lesson_id = lesson_val
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_name = lesson_val
- .get("title")
- .or_else(|| lesson_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_order = lesson_val
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(j as i64);
-
- lessons.push(KiwifyLesson {
- id: if lesson_id.is_empty() {
- format!("{}", j)
- } else {
- lesson_id
- },
- name: lesson_name,
- order: lesson_order,
- });
- }
- }
-
- modules.push(KiwifyModule {
- id: if module_id.is_empty() {
- format!("{}", i)
- } else {
- module_id
- },
- name: module_name,
- order: module_order,
- lessons,
- });
- }
- }
- _ => {
- return Err(anyhow!("Unexpected modules format in course content"));
- }
- }
-
- modules.sort_by_key(|m| m.order);
- for m in &mut modules {
- m.lessons.sort_by_key(|l| l.order);
- }
-
- Ok(modules)
-}
-
-pub async fn get_lesson_detail(
- session: &KiwifySession,
- course_id: i64,
- lesson_id: &str,
-) -> anyhow::Result<KiwifyLessonDetail> {
- let url = format!(
- "https://admin-api.kiwify.com/v1/viewer/courses/{}/lesson/{}",
- course_id, lesson_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lesson_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let lesson = body.get("lesson").unwrap_or(&body);
-
- let id = lesson
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or(lesson_id)
- .to_string();
-
- let name = lesson
- .get("title")
- .or_else(|| lesson.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let description = lesson
- .get("description")
- .or_else(|| lesson.get("content"))
- .or_else(|| lesson.get("body"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(String::from);
-
- let video_url = lesson
- .get("stream_link")
- .or_else(|| lesson.get("video_url"))
- .or_else(|| lesson.get("video"))
- .and_then(|v| v.as_str())
- .map(|url| {
- if url.starts_with('/') {
- format!("{}{}", CDN_BASE, url)
- } else {
- url.to_string()
- }
- });
-
- let files = lesson
- .get("files")
- .and_then(|v| v.as_array())
- .map(|arr| {
- arr.iter()
- .map(|f| {
- let file_id = f
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let file_name = f
- .get("name")
- .or_else(|| f.get("filename"))
- .and_then(|v| v.as_str())
- .unwrap_or("file")
- .to_string();
-
- let file_url = f.get("url").and_then(|v| v.as_str()).map(String::from);
-
- KiwifyFile {
- id: file_id,
- name: file_name,
- url: file_url,
- }
- })
- .collect()
- })
- .unwrap_or_default();
-
- Ok(KiwifyLessonDetail {
- id,
- name,
- description,
- video_url,
- files,
- })
-}
-
-pub async fn get_file_download_url(
- session: &KiwifySession,
- course_id: i64,
- file_id: &str,
-) -> anyhow::Result<String> {
- let url = format!(
- "https://admin-api.kiwify.com.br/v1/viewer/courses/{}/files/{}?forceDownload=true",
- course_id, file_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_file_download_url returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let download_url = body
- .get("url")
- .or_else(|| body.get("download_url"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("No download URL in file response"))?
- .to_string();
-
- Ok(download_url)
-}
-
-pub async fn save_session(session: &KiwifySession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- email: session.email.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[kiwify] session saved for {}", session.email);
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<KiwifySession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[kiwify] session loaded for {}", saved.email);
-
- Ok(Some(KiwifySession {
- token: saved.token,
- email: saved.email,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kiwify/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/kiwify/downloader.rs
deleted file mode 100644
index 3ef5ce4d..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, KiwifyCourse, KiwifySession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct KiwifyCourseDownloadProgress {
- pub course_id: i64,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &KiwifySession,
- course: &KiwifyCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &KiwifyCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- let detail = match api::get_lesson_detail(session, course.id, &lesson.id).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[kiwify] Failed to get lesson detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &KiwifyCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if let Some(ref desc) = detail.description {
- omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
- }
-
- if let Some(ref video_url) = detail.video_url {
- let video_ext = if video_url.contains(".m3u8") {
- "mp4"
- } else {
- video_url
- .rsplit('.')
- .next()
- .and_then(|e| {
- let e = e.split('?').next().unwrap_or(e);
- if e.len() <= 4 {
- Some(e)
- } else {
- None
- }
- })
- .unwrap_or("mp4")
- };
-
- let video_path = format!(
- "{}/{}. {}.{}",
- lesson_dir,
- li + 1,
- lesson_name,
- video_ext
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[kiwify] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &KiwifyCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if video_url.contains(".m3u8") {
- match download_hls_video(video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[kiwify] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[kiwify] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[kiwify] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
-
- for file in &detail.files {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let file_name = filename::sanitize_path_component(&file.name);
- let file_path = format!("{}/{}", lesson_dir, file_name);
-
- if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&file_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- let download_url = if let Some(ref url) = file.url {
- url.clone()
- } else {
- match api::get_file_download_url(session, course.id, &file.id).await {
- Ok(url) => url,
- Err(e) => {
- tracing::error!(
- "[kiwify] Failed to get download URL for file '{}': {}",
- file.name,
- e
- );
- continue;
- }
- }
- };
-
- match download_file_direct(&session.client, &download_url, &file_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[kiwify] File download failed for '{}': {}",
- file.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &KiwifyCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://admin.kiwify.com.br/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://admin.kiwify.com.br/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/kiwify/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/kiwify/mod.rs
deleted file mode 100644
index e4686333..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct KiwifyDownloader;
-
-impl Default for KiwifyDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl KiwifyDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for KiwifyDownloader {
- fn name(&self) -> &str {
- "kiwify"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "kiwify.com.br"
- || host.ends_with(".kiwify.com.br")
- || host == "admin.kiwify.com.br";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Kiwify Course".to_string(),
- author: String::new(),
- platform: "kiwify".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!(
- "Use the courses interface to download Kiwify courses"
- ))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/masterclass/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/masterclass/api.rs
deleted file mode 100644
index c81ea5d1..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("masterclass_session.json"))
-}
-
-pub async fn authenticate_cookies(cookies: &str) -> anyhow::Result<MasterClassSession> {
- let client = build_client(cookies)?;
-
- let session = MasterClassSession {
- cookies: cookies.to_string(),
- profile_id: None,
- client,
- };
-
- let profile_id = fetch_profile_id(&session).await.ok();
-
- Ok(MasterClassSession {
- cookies: cookies.to_string(),
- profile_id,
- client: session.client,
- })
-}
-
-async fn fetch_profile_id(session: &MasterClassSession) -> anyhow::Result<String> {
- let resp = session
- .client
- .get("https://www.masterclass.com/jsonapi/v1/watch-list-items?deep=true&page%5Bsize%5D=1")
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!("Failed to fetch profile: status {}", status));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let profile_id = body
- .get("meta")
- .and_then(|m| m.get("profile_id").or_else(|| m.get("profileId")))
- .or_else(|| body.get("profile_id"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .filter(|s| !s.is_empty())
- .ok_or_else(|| anyhow!("profile_id not found in response"))?;
-
- Ok(profile_id)
-}
-
-pub async fn validate_token(session: &MasterClassSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://www.masterclass.com/jsonapi/v1/watch-list-items?deep=true&page%5Bsize%5D=1")
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &MasterClassSession) -> anyhow::Result<Vec<MasterClassCourse>> {
- let resp = session
- .client
- .get("https://www.masterclass.com/jsonapi/v1/watch-list-items?deep=true")
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let mut courses = Vec::new();
-
- let items = body
- .get("data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for item in &items {
- let attrs = item.get("attributes").unwrap_or(item);
-
- let id = item
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let name = attrs
- .get("title")
- .or_else(|| attrs.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let instructor = attrs
- .get("instructor_name")
- .or_else(|| attrs.get("instructor"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let slug = attrs
- .get("slug")
- .or_else(|| attrs.get("url_slug"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if !id.is_empty() && !name.is_empty() {
- courses.push(MasterClassCourse {
- id,
- name,
- instructor,
- slug,
- });
- }
- }
-
- Ok(courses)
-}
-
-pub async fn get_course_uuid(
- session: &MasterClassSession,
- slug: &str,
-) -> anyhow::Result<String> {
- let url = format!(
- "https://www.masterclass.com/api/v3/unique-identifiers/courses/{}",
- slug
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_uuid returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let uuid = body
- .get("uuid")
- .or_else(|| body.get("id"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("uuid not found in response"))?
- .to_string();
-
- Ok(uuid)
-}
-
-pub async fn get_course_content(
- session: &MasterClassSession,
- slug: &str,
-) -> anyhow::Result<Vec<MasterClassModule>> {
- let uuid = get_course_uuid(session, slug).await?;
-
- let url = format!(
- "https://www.masterclass.com/api/v3/watch-bundles/{}",
- uuid
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let chapters = body
- .get("chapters")
- .or_else(|| body.get("episodes"))
- .or_else(|| body.get("lessons"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for (ci, chapter) in chapters.iter().enumerate() {
- let chapter_id = chapter
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", ci),
- })
- .unwrap_or_else(|| format!("{}", ci));
-
- let chapter_name = chapter
- .get("title")
- .or_else(|| chapter.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let media_uuid = chapter
- .get("media_uuid")
- .or_else(|| chapter.get("mediaUuid"))
- .or_else(|| chapter.get("video_uuid"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let lessons = vec![MasterClassLesson {
- id: chapter_id.clone(),
- name: chapter_name.clone(),
- order: ci as i64,
- media_uuid,
- }];
-
- modules.push(MasterClassModule {
- id: chapter_id,
- name: chapter_name,
- order: ci as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-pub async fn get_video_metadata(
- session: &MasterClassSession,
- media_uuid: &str,
-) -> anyhow::Result<String> {
- let url = format!(
- "https://edge.masterclass.com/api/v1/media/metadata/{}",
- media_uuid
- );
-
- let profile_id = session
- .profile_id
- .as_deref()
- .unwrap_or("");
-
- let resp = session
- .client
- .get(&url)
- .header("X-Api-Key", MC_API_KEY)
- .header("Mc-Profile-Id", profile_id)
- .header("Origin", "https://www.masterclass.com")
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_video_metadata returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let sources = body
- .get("sources")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for source in &sources {
- let src = source
- .get("src")
- .or_else(|| source.get("url"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if !src.is_empty() {
- return Ok(src.to_string());
- }
- }
-
- let direct_url = body
- .get("url")
- .or_else(|| body.get("src"))
- .or_else(|| body.get("source"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if !direct_url.is_empty() {
- return Ok(direct_url.to_string());
- }
-
- Err(anyhow!("No video URL found in metadata response"))
-}
-
-pub async fn save_session(session: &MasterClassSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- cookies: session.cookies.clone(),
- profile_id: session.profile_id.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[masterclass] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<MasterClassSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.cookies)?;
-
- tracing::info!("[masterclass] session loaded");
-
- Ok(Some(MasterClassSession {
- cookies: saved.cookies,
- profile_id: saved.profile_id,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/masterclass/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/masterclass/downloader.rs
deleted file mode 100644
index a43f6291..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, MasterClassCourse, MasterClassSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct MasterClassCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &MasterClassSession,
- course: &MasterClassCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let slug = if course.slug.is_empty() {
- &course.id
- } else {
- &course.slug
- };
-
- let modules = api::get_course_content(session, slug).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_label = if course.instructor.is_empty() {
- course.name.clone()
- } else {
- format!("{} - {}", course.instructor, course.name)
- };
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course_label)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[masterclass] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &MasterClassCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- for (_li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let video_path = format!(
- "{}/{}. {}.mp4",
- course_dir,
- mi + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[masterclass] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MasterClassCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if let Some(ref media_uuid) = lesson.media_uuid {
- match api::get_video_metadata(session, media_uuid).await {
- Ok(video_url) => {
- if video_url.contains(".m3u8") {
- match download_hls_video(&video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[masterclass] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(&video_url, &course_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[masterclass] yt-dlp failed for '{}': {}, trying direct",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, &video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[masterclass] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
- Err(e) => {
- tracing::error!(
- "[masterclass] Failed to get video URL for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MasterClassCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://www.masterclass.com/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://www.masterclass.com/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/masterclass/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/masterclass/mod.rs
deleted file mode 100644
index 7beb38ea..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct MasterClassDownloader;
-
-impl Default for MasterClassDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl MasterClassDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for MasterClassDownloader {
- fn name(&self) -> &str {
- "masterclass"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "masterclass.com" || host == "www.masterclass.com";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "MasterClass Course".to_string(),
- author: String::new(),
- platform: "masterclass".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download MasterClass courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/matematicaprapassar/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/matematicaprapassar/mod.rs
deleted file mode 100644
index 05aeaa98..00000000
--- a/src-tauri/omniget-plugin-courses/src/platforms/matematicaprapassar/mod.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-use anyhow::anyhow;
-use async_trait::async_trait;
-use tokio::sync::mpsc;
-
-use omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct MatematicaPraPassarDownloader;
-
-impl Default for MatematicaPraPassarDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl MatematicaPraPassarDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for MatematicaPraPassarDownloader {
- fn name(&self) -> &str {
- "matematicaprapassar"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "matematicaprapassar.com.br" || host == "www.matematicaprapassar.com.br";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Matemática Pra Passar".to_string(),
- author: String::new(),
- platform: "matematicaprapassar".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Matemática Pra Passar courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcel/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcel/api.rs
deleted file mode 100644
index bef27a25..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-pub fn build_client_with_origin(token: &str, api_key: &str, origin: &str) -> anyhow::Result<reqwest::Client> {
- build_client(token, api_key, origin)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("medcel_session.json"))
-}
-
-pub async fn authenticate(email: &str, password: &str, api_key: &str) -> anyhow::Result<MedcelSession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let mut headers = HeaderMap::new();
- headers.insert(
- "X-Api-Key",
- HeaderValue::from_str(api_key)?,
- );
- headers.insert(
- "Referer",
- HeaderValue::from_str(&format!("{}/", ORIGIN_URL))?,
- );
- headers.insert(
- "Origin",
- HeaderValue::from_str(ORIGIN_URL)?,
- );
-
- let payload = serde_json::json!({
- "email": email,
- "password": password,
- });
-
- let resp = temp_client
- .post(format!("{}/m1/students/auth", API_BASE))
- .headers(headers)
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Authentication failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let student_id = body
- .get("_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let session_token = body
- .get("sessionToken")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("sessionToken not found in auth response"))?
- .to_string();
-
- let client = build_client(&session_token, api_key, ORIGIN_URL)?;
-
- Ok(MedcelSession {
- token: session_token,
- api_key: api_key.to_string(),
- student_id,
- client,
- })
-}
-
-pub async fn validate_token(session: &MedcelSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get(format!("{}/m1/contracts/getContractsByStudent?_id=me", API_BASE))
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn fetch_student_id(session: &MedcelSession) -> anyhow::Result<String> {
- let resp = session
- .client
- .get(format!("{}/m1/contracts/getContractsByStudent?_id=me", API_BASE))
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!("fetch_student_id failed (status {})", status));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let id = body
- .get("_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- Ok(id)
-}
-
-pub async fn list_courses(session: &MedcelSession) -> anyhow::Result<Vec<MedcelCourse>> {
- let url = format!(
- "{}/m1/contracts/getContractsByStudent?_id={}",
- API_BASE, session.student_id
- );
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let contracts = body
- .get("contracts")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut courses = Vec::new();
-
- for contract in &contracts {
- let product = match contract.get("product") {
- Some(p) => p,
- None => continue,
- };
-
- let product_id = match product.get("_id").and_then(|v| v.as_str()) {
- Some(id) => id.to_string(),
- None => continue,
- };
-
- let product_name = product
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("Curso")
- .to_string();
-
- let content_available = contract
- .get("overallStatus")
- .and_then(|s| s.get("content"))
- .and_then(|c| c.get("available"))
- .and_then(|v| v.as_bool())
- .unwrap_or(true);
-
- if !content_available {
- continue;
- }
-
- courses.push(MedcelCourse {
- id: product_id.clone(),
- name: product_name,
- product_id,
- });
- }
-
- Ok(courses)
-}
-
-pub async fn get_modules(session: &MedcelSession, product_id: &str) -> anyhow::Result<Vec<MedcelModule>> {
- let mut all_playlists = Vec::new();
- let mut page = 1u32;
- let limit = 100u32;
-
- loop {
- let url = format!(
- "{}/m9/subjectPlaylists/getSubjectPlaylists?studentId={}&productId={}&specialtyId=&sortMode=incidence&trial=false&page={}&limit={}",
- API_BASE, session.student_id, product_id, page, limit
- );
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_modules returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let items = body
- .get("items")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- if items.is_empty() {
- break;
- }
-
- all_playlists.extend(items);
-
- let total_pages = body
- .get("pagination")
- .and_then(|p| p.get("pageTotal"))
- .and_then(|v| v.as_u64())
- .unwrap_or(1);
-
- if page as u64 >= total_pages {
- break;
- }
- page += 1;
- }
-
- let mut modules = Vec::new();
-
- for (i, playlist) in all_playlists.iter().enumerate() {
- let playlist_id = match playlist.get("_id").and_then(|v| v.as_str()) {
- Some(id) => id.to_string(),
- None => continue,
- };
-
- let name = playlist
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
-
- let order = playlist
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(i as i64 + 1);
-
- let lessons = get_playlist_lessons(session, &playlist_id, product_id).await?;
-
- modules.push(MedcelModule {
- id: playlist_id,
- name,
- order,
- lessons,
- });
- }
-
- modules.sort_by_key(|m| m.order);
-
- Ok(modules)
-}
-
-async fn get_playlist_lessons(
- session: &MedcelSession,
- playlist_id: &str,
- product_id: &str,
-) -> anyhow::Result<Vec<MedcelLesson>> {
- let url = format!(
- "{}/m9/subjectPlaylists/getPlaylistContents?playlistId={}&studentId={}",
- API_BASE, playlist_id, session.student_id
- );
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_playlist_lessons returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let playlist_contents = body
- .get("playlistContents")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (ci, content) in playlist_contents.iter().enumerate() {
- let content_name = content
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
-
- let classes = content
- .get("classes")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- if classes.is_empty() {
- continue;
- }
-
- let mut video_class: Option<&serde_json::Value> = None;
- let mut all_materials = Vec::new();
-
- for class_item in &classes {
- let type_id = class_item
- .get("subTypeLearningObject")
- .and_then(|s| s.get("id"))
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if let Some(mats) = class_item.get("complementMaterial").and_then(|v| v.as_array()) {
- for mat in mats {
- let mat_url = mat.get("location").and_then(|v| v.as_str()).unwrap_or("");
- let mat_title = mat.get("title").and_then(|v| v.as_str()).unwrap_or("Material");
- let mat_key = mat.get("key").and_then(|v| v.as_str()).unwrap_or("");
-
- if !mat_url.is_empty() {
- all_materials.push(MedcelMaterial {
- key: mat_key.to_string(),
- title: mat_title.to_string(),
- url: mat_url.to_string(),
- });
- }
- }
- }
-
- if type_id == "videoClass" && video_class.is_none() {
- video_class = Some(class_item);
- }
- }
-
- let chosen = video_class.unwrap_or(&classes[0]);
-
- let class_id = chosen
- .get("id")
- .or_else(|| chosen.get("_id"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if class_id.is_empty() {
- continue;
- }
-
- let type_id = chosen
- .get("subTypeLearningObject")
- .and_then(|s| s.get("id"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let description = content
- .get("description")
- .or_else(|| chosen.get("description"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(String::from);
-
- lessons.push(MedcelLesson {
- id: class_id,
- name: content_name,
- order: (ci + 1) as i64,
- type_id,
- product_id: product_id.to_string(),
- materials: all_materials,
- description,
- });
- }
-
- Ok(lessons)
-}
-
-pub async fn get_video_url(
- session: &MedcelSession,
- class_id: &str,
- product_id: &str,
-) -> anyhow::Result<String> {
- let url = format!(
- "{}/m2/videos/getVideoToPlay?id={}&student={}&product={}",
- API_BASE, class_id, session.student_id, product_id
- );
-
- let resp = session
- .client
- .get(&url)
- .header("X-Host-Origin", ORIGIN_URL)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_video_url returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let data = body.get("data").unwrap_or(&body);
-
- let uri = data
- .get("uri")
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- let signature = data
- .get("signature")
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- let video_url = format!("{}{}", uri, signature);
-
- if video_url.is_empty() {
- return Err(anyhow!("No video URL found in response"));
- }
-
- Ok(video_url)
-}
-
-pub async fn save_session(session: &MedcelSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- api_key: session.api_key.clone(),
- student_id: session.student_id.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[medcel] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<MedcelSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token, &saved.api_key, ORIGIN_URL)?;
-
- tracing::info!("[medcel] session loaded");
-
- Ok(Some(MedcelSession {
- token: saved.token,
- api_key: saved.api_key,
- student_id: saved.student_id,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcel/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcel/downloader.rs
deleted file mode 100644
index bf144657..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, MedcelCourse, MedcelSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct MedcelCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &MedcelSession,
- course: &MedcelCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_modules(session, &course.product_id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[medcel] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &MedcelCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- if let Some(ref desc) = lesson.description {
- omniget_core::core::course_utils::save_description(&lesson_dir, desc, "txt").await.ok();
- }
-
- if lesson.type_id == "videoClass" || lesson.type_id.contains("video") {
- match api::get_video_url(session, &lesson.id, &lesson.product_id).await {
- Ok(video_url) => {
- let video_path = format!(
- "{}/{}. {}.mp4",
- lesson_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[medcel] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MedcelCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if video_url.contains(".m3u8") {
- match download_hls_video(&video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[medcel] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(&video_url, &lesson_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[medcel] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, &video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[medcel] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
- Err(e) => {
- tracing::error!(
- "[medcel] Failed to get video URL for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
-
- for material in &lesson.materials {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let ext = material.url.rsplit('.').next().unwrap_or("pdf");
- let ext = ext.split('?').next().unwrap_or(ext);
- let mat_name = filename::sanitize_path_component(&material.title);
- let mat_path = format!("{}/{}.{}", lesson_dir, mat_name, ext);
-
- if tokio::fs::try_exists(&mat_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&mat_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match download_file_direct(&session.client, &material.url, &mat_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[medcel] Material download failed for '{}': {}",
- material.title,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MedcelCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://areaaluno.medcel.com.br/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://areaaluno.medcel.com.br/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcel/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcel/mod.rs
deleted file mode 100644
index db0c72a0..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct MedcelDownloader;
-
-impl Default for MedcelDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl MedcelDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for MedcelDownloader {
- fn name(&self) -> &str {
- "medcel"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "medcel.com.br"
- || host == "areaaluno.medcel.com.br"
- || host == "service.medcel.com.br";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Medcel Course".to_string(),
- author: String::new(),
- platform: "medcel".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!(
- "Use the courses interface to download Medcel courses"
- ))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcof/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcof/api.rs
deleted file mode 100644
index a425a328..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("medcof_session.json"))
-}
-
-pub async fn validate_token(session: &MedcofSession) -> anyhow::Result<bool> {
- let url = format!("{}/auth/v1/me", API_BASE);
- let resp = session.client.get(&url).send().await?;
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &MedcofSession) -> anyhow::Result<Vec<MedcofCourse>> {
- let url = format!("{}/auth/v1/me", API_BASE);
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let products = body
- .get("products")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut courses = Vec::new();
-
- for item in &products {
- let is_active = item
- .get("isActive")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
-
- if !is_active {
- continue;
- }
-
- let id = item
- .get("identifier")
- .or_else(|| item.get("id"))
- .map(|v| match v {
- serde_json::Value::String(s) => s.clone(),
- serde_json::Value::Number(n) => n.to_string(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let name = item
- .get("name")
- .or_else(|| item.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if !id.is_empty() {
- courses.push(MedcofCourse { id, name });
- }
- }
-
- Ok(courses)
-}
-
-pub async fn switch_product(session: &MedcofSession, product_id: &str) -> anyhow::Result<()> {
- let url = format!("{}/user/use/product", API_BASE);
- let payload = serde_json::json!({
- "productId": product_id,
- });
-
- let resp = session.client.patch(&url).json(&payload).send().await?;
-
- if !resp.status().is_success() {
- let body_text = resp.text().await?;
- return Err(anyhow!(
- "switch_product failed: {}",
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- Ok(())
-}
-
-pub async fn get_course_content(session: &MedcofSession, product_id: &str) -> anyhow::Result<Vec<MedcofModule>> {
- switch_product(session, product_id).await?;
-
- let url = format!("{}/product/user/progress", API_BASE);
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let blocks = body
- .get("blocks")
- .or_else(|| body.get("data"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_else(|| {
- if body.is_array() {
- body.as_array().cloned().unwrap_or_default()
- } else {
- Vec::new()
- }
- });
-
- let mut modules = Vec::new();
-
- for (bi, block) in blocks.iter().enumerate() {
- let block_number = block
- .get("blockNumber")
- .or_else(|| block.get("number"))
- .or_else(|| block.get("id"))
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", bi + 1),
- })
- .unwrap_or_else(|| format!("{}", bi + 1));
-
- let block_name = block
- .get("name")
- .or_else(|| block.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or(&block_number)
- .to_string();
-
- let aqfm_url = format!("{}/aqfm/by-block-number/{}", API_BASE, block_number);
- let aqfm_resp = match session.client.get(&aqfm_url).send().await {
- Ok(r) => r,
- Err(e) => {
- tracing::error!("[medcof] Failed to fetch block {}: {}", block_number, e);
- continue;
- }
- };
-
- if !aqfm_resp.status().is_success() {
- continue;
- }
-
- let aqfm_text = aqfm_resp.text().await?;
- let aqfm_body: serde_json::Value = match serde_json::from_str(&aqfm_text) {
- Ok(v) => v,
- Err(_) => continue,
- };
-
- let specialties = aqfm_body
- .get("specialties")
- .or_else(|| aqfm_body.get("data"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_else(|| {
- if aqfm_body.is_array() {
- aqfm_body.as_array().cloned().unwrap_or_default()
- } else {
- Vec::new()
- }
- });
-
- let mut lessons = Vec::new();
- let mut lesson_order = 0i64;
-
- for specialty in &specialties {
- let aqfms = specialty
- .get("aqfms")
- .or_else(|| specialty.get("items"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for aqfm in &aqfms {
- let videos = aqfm
- .get("videos")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for video in &videos {
- lesson_order += 1;
-
- let vid_id = video
- .get("id")
- .map(|v| match v {
- serde_json::Value::String(s) => s.clone(),
- serde_json::Value::Number(n) => n.to_string(),
- _ => format!("{}", lesson_order),
- })
- .unwrap_or_else(|| format!("{}", lesson_order));
-
- let vid_name = video
- .get("name")
- .or_else(|| video.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let vimeo_id = video
- .get("vimeoId")
- .or_else(|| video.get("externalId"))
- .map(|v| match v {
- serde_json::Value::String(s) => s.clone(),
- serde_json::Value::Number(n) => n.to_string(),
- _ => String::new(),
- })
- .filter(|s| !s.is_empty());
-
- let description = video
- .get("description")
- .or_else(|| video.get("content"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(String::from);
-
- lessons.push(MedcofLesson {
- id: vid_id,
- name: vid_name,
- order: lesson_order,
- vimeo_id,
- description,
- });
- }
- }
- }
-
- if !lessons.is_empty() {
- modules.push(MedcofModule {
- id: block_number,
- name: block_name,
- order: (bi + 1) as i64,
- lessons,
- });
- }
- }
-
- Ok(modules)
-}
-
-pub async fn get_vimeo_playback_url(session: &MedcofSession, vimeo_id: &str) -> anyhow::Result<String> {
- let url = format!("{}/vimeo/get/{}", API_BASE, vimeo_id);
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_vimeo_playback_url returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let playback_url = body
- .get("playbackUrl")
- .or_else(|| body.get("url"))
- .or_else(|| body.get("link"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("No playback URL in vimeo response"))?
- .to_string();
-
- Ok(playback_url)
-}
-
-pub async fn save_session(session: &MedcofSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[medcof] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<MedcofSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[medcof] session loaded");
-
- Ok(Some(MedcofSession {
- token: saved.token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcof/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcof/downloader.rs
deleted file mode 100644
index a5302d93..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, MedcofCourse, MedcofSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct MedcofDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &MedcofSession,
- course: &MedcofCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, &course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[medcof] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &MedcofDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
-
- if let Some(ref desc) = lesson.description {
- let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_desc_dir).await?;
- omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "txt").await.ok();
- }
-
- if lesson.vimeo_id.is_none() {
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MedcofDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
-
- let vimeo_id = lesson.vimeo_id.as_ref().unwrap();
-
- let video_path = format!(
- "{}/{}. {}.mp4",
- mod_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[medcof] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MedcofDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- let video_url = match api::get_vimeo_playback_url(session, vimeo_id).await {
- Ok(url) => url,
- Err(e) => {
- tracing::error!("[medcof] Failed to get playback URL for '{}': {}", lesson.name, e);
- let vimeo_url = format!("https://player.vimeo.com/video/{}", vimeo_id);
- vimeo_url
- }
- };
-
- if video_url.contains(".m3u8") {
- match download_hls_video(&video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[medcof] HLS download failed for '{}': {}, trying yt-dlp", lesson.name, e);
- let _ = tokio::fs::remove_file(&video_path).await;
- let vimeo_url = format!("https://player.vimeo.com/video/{}", vimeo_id);
- match download_with_ytdlp(&vimeo_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!("[medcof] yt-dlp fallback also failed for '{}': {}", lesson.name, e2);
- }
- }
- }
- }
- } else {
- match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!("[medcof] yt-dlp download failed for '{}': {}", lesson.name, e);
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MedcofDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- None,
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medcof/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/medcof/mod.rs
deleted file mode 100644
index 56313521..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct MedcofDownloader;
-
-impl Default for MedcofDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl MedcofDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for MedcofDownloader {
- fn name(&self) -> &str {
- "medcof"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "medcof.com.br"
- || host == "aulas-prime.medcof.com.br";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Medcof".to_string(),
- author: String::new(),
- platform: "medcof".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "Original".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Medcof"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medway/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/medway/api.rs
deleted file mode 100644
index a03ac0d4..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("medway_session.json"))
-}
-
-pub async fn validate_token(session: &MedwaySession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get(format!("{}/student_group/", API_BASE))
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &MedwaySession) -> anyhow::Result<Vec<MedwayCourse>> {
- let mut courses = Vec::new();
- let mut next_url: Option<String> = Some(format!("{}/student_group/", API_BASE));
-
- while let Some(url) = next_url {
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let results = body
- .get("results")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for item in &results {
- let id = item
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = item
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("Curso")
- .to_string();
-
- courses.push(MedwayCourse { id, name });
- }
-
- next_url = body
- .get("next")
- .and_then(|v| v.as_str())
- .map(String::from);
- }
-
- Ok(courses)
-}
-
-pub async fn get_modules(session: &MedwaySession, course_id: i64) -> anyhow::Result<Vec<MedwayModule>> {
- let subjects = fetch_subjects(session, course_id).await?;
- let mut modules = Vec::new();
-
- for (si, subject) in subjects.iter().enumerate() {
- let subject_id = subject
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let subject_name = subject
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let subject_order = subject
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(si as i64 + 1);
-
- let sub_modules = fetch_subject_modules(session, subject_id).await?;
-
- for module in &sub_modules {
- let module_id = module
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let module_name = module
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("Module")
- .to_string();
-
- let module_order = module
- .get("order")
- .or_else(|| module.get("lesson_order"))
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let title = if module_order > 0 {
- format!("{}. {} - {}. {}", subject_order, subject_name, module_order, module_name)
- } else {
- format!("{}. {} - {}", subject_order, subject_name, module_name)
- };
-
- let lessons = fetch_module_lessons(session, module_id).await?;
-
- modules.push(MedwayModule {
- id: module_id.to_string(),
- name: title,
- order: subject_order * 1000 + module_order,
- lessons,
- });
- }
- }
-
- modules.sort_by_key(|m| m.order);
-
- Ok(modules)
-}
-
-async fn fetch_subjects(session: &MedwaySession, course_id: i64) -> anyhow::Result<Vec<serde_json::Value>> {
- let mut subjects = Vec::new();
- let mut next_url: Option<String> = Some(format!(
- "{}/lesson-subject/?ordering=order&studentgroup={}",
- API_BASE, course_id
- ));
-
- while let Some(url) = next_url {
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "fetch_subjects returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let results = body
- .get("results")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- subjects.extend(results);
-
- next_url = body
- .get("next")
- .and_then(|v| v.as_str())
- .map(String::from);
- }
-
- Ok(subjects)
-}
-
-async fn fetch_subject_modules(session: &MedwaySession, subject_id: i64) -> anyhow::Result<Vec<serde_json::Value>> {
- let url = format!("{}/lesson-subject/{}/modules/", API_BASE, subject_id);
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "fetch_subject_modules returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- match body {
- serde_json::Value::Array(arr) => Ok(arr),
- _ => Ok(vec![body]),
- }
-}
-
-async fn fetch_module_lessons(session: &MedwaySession, module_id: i64) -> anyhow::Result<Vec<MedwayLesson>> {
- let url = format!("{}/lesson-module/{}/", API_BASE, module_id);
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "fetch_module_lessons returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let items = body
- .get("module_items")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (i, item) in items.iter().enumerate() {
- let id = item
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}-{}", module_id, i),
- })
- .unwrap_or_else(|| format!("{}-{}", module_id, i));
-
- let name = item
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let order = item
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(i as i64 + 1);
-
- let item_type = item
- .get("type")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let video_url = item
- .get("url_lesson")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let document_id = item
- .get("object_id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- });
-
- let description = item
- .get("description")
- .or_else(|| item.get("content"))
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(String::from);
-
- lessons.push(MedwayLesson {
- id,
- name,
- order,
- item_type,
- video_url,
- document_id,
- description,
- });
- }
-
- lessons.sort_by_key(|l| l.order);
-
- Ok(lessons)
-}
-
-pub async fn get_document_url(session: &MedwaySession, document_id: &str) -> anyhow::Result<(String, String)> {
- let url = format!("{}/lesson-document/{}/", API_BASE, document_id);
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_document_url returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let doc_url = body
- .get("document")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let doc_name = body
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("Document")
- .to_string();
-
- if doc_url.is_empty() {
- return Err(anyhow!("No document URL found in response"));
- }
-
- Ok((doc_url, doc_name))
-}
-
-pub fn resolve_video_url(url: &str) -> String {
- if url.contains("vimeo.com") && !url.contains("player.vimeo.com") {
- let video_id = url.trim_end_matches('/').rsplit('/').next().unwrap_or("");
- if !video_id.is_empty() {
- return format!("https://player.vimeo.com/video/{}?autoplay=1&app_id=122963", video_id);
- }
- }
- url.to_string()
-}
-
-pub async fn save_session(session: &MedwaySession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[medway] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<MedwaySession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[medway] session loaded");
-
- Ok(Some(MedwaySession {
- token: saved.token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medway/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/medway/downloader.rs
deleted file mode 100644
index a2e2e840..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, MedwayCourse, MedwaySession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct MedwayCourseDownloadProgress {
- pub course_id: i64,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &MedwaySession,
- course: &MedwayCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_modules(session, course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[medway] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &MedwayCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- if let Some(ref desc) = lesson.description {
- let lesson_desc_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_desc_dir).await?;
- omniget_core::core::course_utils::save_description(&lesson_desc_dir, desc, "html").await.ok();
- }
-
- let item_type = lesson.item_type.to_lowercase();
-
- if item_type.contains("v\u{00ed}deoaula") || item_type.contains("video") {
- if let Some(ref raw_url) = lesson.video_url {
- if !raw_url.is_empty() {
- let video_url = api::resolve_video_url(raw_url);
- let video_path = format!(
- "{}/{}. {}.mp4",
- mod_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[medway] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MedwayCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- match download_with_ytdlp(&video_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[medway] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, &video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[medway] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
- } else if item_type.contains("documento") {
- if let Some(ref doc_id) = lesson.document_id {
- if !doc_id.is_empty() {
- match api::get_document_url(session, doc_id).await {
- Ok((doc_url, doc_name)) => {
- let ext = doc_url.rsplit('.').next().unwrap_or("pdf");
- let ext = ext.split('?').next().unwrap_or(ext);
- let safe_name = filename::sanitize_path_component(&doc_name);
- let doc_path = format!("{}/{}. {}.{}", mod_dir, li + 1, safe_name, ext);
-
- if tokio::fs::try_exists(&doc_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&doc_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MedwayCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- match download_file_direct(&session.client, &doc_url, &doc_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[medway] Document download failed for '{}': {}",
- doc_name,
- e
- );
- }
- }
- }
- Err(e) => {
- tracing::error!(
- "[medway] Failed to get document URL for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MedwayCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://app.medway.com.br/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/medway/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/medway/mod.rs
deleted file mode 100644
index 86a955b6..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct MedwayDownloader;
-
-impl MedwayDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for MedwayDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for MedwayDownloader {
- fn name(&self) -> &str {
- "medway"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "medway.com.br"
- || host.ends_with(".medway.com.br");
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Medway Course".to_string(),
- author: String::new(),
- platform: "medway".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!(
- "Use the courses interface to download Medway courses"
- ))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/memberkit/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/memberkit/api.rs
deleted file mode 100644
index 2958c83e..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("memberkit_session.json"))
-}
-
-pub async fn authenticate(
- email: &str,
- password: &str,
- site_url: &str,
-) -> anyhow::Result<MemberkitSession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .cookie_store(true)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let login_page_url = format!("{}/users/sign_in", site_url.trim_end_matches('/'));
- let resp = temp_client.get(&login_page_url).send().await?;
- let login_html = resp.text().await?;
-
- let csrf_token = extract_meta_csrf(&login_html)
- .or_else(|| extract_input_value(&login_html, "authenticity_token"))
- .ok_or_else(|| anyhow!("Could not find CSRF token on login page"))?;
-
- let form_url = format!("{}/users/sign_in", site_url.trim_end_matches('/'));
- let resp = temp_client
- .post(&form_url)
- .form(&[
- ("authenticity_token", csrf_token.as_str()),
- ("user[email]", email),
- ("user[password]", password),
- ])
- .send()
- .await?;
-
- let status = resp.status();
- let resp_url = resp.url().to_string();
- let _body = resp.text().await?;
-
- if resp_url.contains("/sign_in") {
- if !status.is_success() && !status.is_redirection() {
- return Err(anyhow!("Authentication failed (status {})", status));
- }
- return Err(anyhow!("Authentication failed - invalid credentials"));
- }
-
- let root_resp = temp_client
- .get(site_url.trim_end_matches('/'))
- .send()
- .await?;
-
- if !root_resp.status().is_success() {
- return Err(anyhow!("Authentication failed - cannot access member area"));
- }
-
- let cookies_header = root_resp
- .headers()
- .get_all("set-cookie")
- .iter()
- .filter_map(|v| v.to_str().ok())
- .filter_map(|s| {
- if s.contains("_memberkit_session=") {
- let start = s.find("_memberkit_session=")? + 19;
- let end = s[start..].find(';').map(|e| e + start).unwrap_or(s.len());
- Some(s[start..end].to_string())
- } else {
- None
- }
- })
- .last();
-
- let session_cookie = cookies_header
- .ok_or_else(|| anyhow!("Could not extract session cookie after login"))?;
-
- let client = build_client(&session_cookie, site_url)?;
-
- Ok(MemberkitSession {
- cookies: session_cookie,
- site_url: site_url.trim_end_matches('/').to_string(),
- client,
- })
-}
-
-pub async fn validate_token(session: &MemberkitSession) -> anyhow::Result<bool> {
- let resp = session.client.get(&session.site_url).send().await?;
-
- let url = resp.url().to_string();
- if url.contains("/sign_in") || url.contains("/login") {
- return Ok(false);
- }
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &MemberkitSession) -> anyhow::Result<Vec<MemberkitCourse>> {
- let resp = session.client.get(&session.site_url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let mut courses = Vec::new();
-
- let card_re = regex::Regex::new(
- r#"(?s)data-id="(\d+)"[^>]*>.*?<a[^>]+class="[^"]*text-base[^"]*"[^>]+href="([^"]+)"[^>]*>([^<]+)"#
- )?;
-
- for cap in card_re.captures_iter(&body_text) {
- let id = cap[1].to_string();
- let href = cap[2].to_string();
- let name = cap[3].trim().to_string();
-
- let slug = href
- .rsplit('/')
- .next()
- .unwrap_or("")
- .to_string();
-
- if courses.iter().any(|c: &MemberkitCourse| c.id == id) {
- continue;
- }
-
- courses.push(MemberkitCourse { id, name, slug });
- }
-
- if courses.is_empty() {
- let link_re = regex::Regex::new(
- r#"<a[^>]+href="([^"]*(/courses?/[^"]+))"[^>]*>([^<]+)"#
- )?;
-
- for cap in link_re.captures_iter(&body_text) {
- let href = cap[1].to_string();
- let name = cap[3].trim().to_string();
-
- let slug = href
- .rsplit('/')
- .next()
- .unwrap_or("")
- .to_string();
-
- let id = slug.clone();
-
- if courses.iter().any(|c: &MemberkitCourse| c.slug == slug) {
- continue;
- }
-
- courses.push(MemberkitCourse { id, name, slug });
- }
- }
-
- Ok(courses)
-}
-
-pub async fn get_modules(
- session: &MemberkitSession,
- course_slug: &str,
-) -> anyhow::Result<Vec<MemberkitModule>> {
- let url = format!("{}/courses/{}", session.site_url, course_slug);
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_modules returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let mut modules = Vec::new();
-
- let section_re = regex::Regex::new(
- r#"(?s)<div[^>]+id="([^"]+)"[^>]*class="[^"]*section[^"]*"[^>]*>.*?<span[^>]*>([^<]+)</span>"#
- )?;
-
- let lesson_re = regex::Regex::new(
- r#"(?s)<li[^>]+data-id="(\d+)"[^>]*>.*?<a[^>]+class="[^"]*lesson__title[^"]*"[^>]+href="([^"]+)"[^>]*>([^<]+)"#
- )?;
-
- let sections: Vec<(String, String, usize)> = section_re
- .captures_iter(&body_text)
- .enumerate()
- .map(|(i, cap)| (cap[1].to_string(), cap[2].trim().to_string(), i))
- .collect();
-
- if sections.is_empty() {
- let mut lessons = Vec::new();
- for (i, cap) in lesson_re.captures_iter(&body_text).enumerate() {
- let lesson_id = cap[1].to_string();
- let lesson_url = cap[2].to_string();
- let lesson_name = cap[3].trim().to_string();
-
- if lessons.iter().any(|l: &MemberkitLesson| l.id == lesson_id) {
- continue;
- }
-
- let full_url = if lesson_url.starts_with("http") {
- lesson_url
- } else {
- format!("{}{}", session.site_url, lesson_url)
- };
-
- lessons.push(MemberkitLesson {
- id: lesson_id,
- name: lesson_name,
- url: full_url,
- order: i as i64,
- });
- }
-
- if !lessons.is_empty() {
- modules.push(MemberkitModule {
- id: "0".to_string(),
- name: "Content".to_string(),
- order: 0,
- lessons,
- });
- }
- } else {
- for (section_id, section_name, idx) in &sections {
- let section_start = body_text
- .find(&format!("id=\"{}\"", section_id))
- .unwrap_or(0);
-
- let section_end = if idx + 1 < sections.len() {
- body_text
- .find(&format!("id=\"{}\"", sections[idx + 1].0))
- .unwrap_or(body_text.len())
- } else {
- body_text.len()
- };
-
- let section_html = &body_text[section_start..section_end];
-
- let mut lessons = Vec::new();
- for (i, cap) in lesson_re.captures_iter(section_html).enumerate() {
- let lesson_id = cap[1].to_string();
- let lesson_url = cap[2].to_string();
- let lesson_name = cap[3].trim().to_string();
-
- if lessons.iter().any(|l: &MemberkitLesson| l.id == lesson_id) {
- continue;
- }
-
- let full_url = if lesson_url.starts_with("http") {
- lesson_url
- } else {
- format!("{}{}", session.site_url, lesson_url)
- };
-
- lessons.push(MemberkitLesson {
- id: lesson_id,
- name: lesson_name,
- url: full_url,
- order: i as i64,
- });
- }
-
- modules.push(MemberkitModule {
- id: section_id.clone(),
- name: section_name.clone(),
- order: *idx as i64,
- lessons,
- });
- }
- }
-
- Ok(modules)
-}
-
-pub async fn get_lesson_detail(
- session: &MemberkitSession,
- lesson_url: &str,
-) -> anyhow::Result<MemberkitLessonDetail> {
- let resp = session.client.get(lesson_url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lesson_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let title_re = regex::Regex::new(r#"<title>([^<]+)</title>"#)?;
- let name = title_re
- .captures(&body_text)
- .map(|c| c[1].trim().to_string())
- .unwrap_or_default();
-
- let id = lesson_url
- .rsplit('/')
- .next()
- .unwrap_or("")
- .to_string();
-
- let mut video_url: Option<String> = None;
-
- let yt_re = regex::Regex::new(r#"data-youtube-uid-value="([^"]+)""#)?;
- if let Some(cap) = yt_re.captures(&body_text) {
- video_url = Some(format!("https://www.youtube.com/watch?v={}", &cap[1]));
- }
-
- if video_url.is_none() {
- let vimeo_re = regex::Regex::new(r#"data-vimeo-uid-value="([^"]+)""#)?;
- if let Some(cap) = vimeo_re.captures(&body_text) {
- video_url = Some(format!("https://vimeo.com/{}", &cap[1]));
- }
- }
-
- if video_url.is_none() {
- let panda_re = regex::Regex::new(r#"data-panda-url-value="([^"]+)""#)?;
- if let Some(cap) = panda_re.captures(&body_text) {
- video_url = Some(cap[1].to_string());
- }
- }
-
- if video_url.is_none() {
- let iframe_re = regex::Regex::new(r#"<iframe[^>]+src="([^"]+)"[^>]*>"#)?;
- for cap in iframe_re.captures_iter(&body_text) {
- let src = &cap[1];
- if src.contains("scaleup")
- || src.contains("youtube")
- || src.contains("vimeo")
- || src.contains("pandavideo")
- || src.contains("player")
- {
- video_url = Some(src.to_string());
- break;
- }
- }
- }
-
- if video_url.is_none() {
- let video_re = regex::Regex::new(r#"<video[^>]+src="([^"]+)""#)?;
- if let Some(cap) = video_re.captures(&body_text) {
- video_url = Some(cap[1].to_string());
- }
- }
-
- let mut attachments = Vec::new();
-
- let dl_re = regex::Regex::new(
- r#"<a[^>]+href="([^"]*downloads/[^"]+)"[^>]*>([^<]+)"#
- )?;
-
- for cap in dl_re.captures_iter(&body_text) {
- let att_url = cap[1].to_string();
- let att_name = cap[2].trim().to_string();
-
- let full_url = if att_url.starts_with("http") {
- att_url
- } else {
- format!("{}{}", session.site_url, att_url)
- };
-
- attachments.push(MemberkitAttachment {
- name: att_name,
- url: full_url,
- });
- }
-
- let mut description: Option<String> = None;
- let body_re = regex::Regex::new(r#"(?s)class="[^"]*content__body[^"]*"[^>]*>(.*?)</div>"#)?;
- if let Some(cap) = body_re.captures(&body_text) {
- let text = cap[1].trim();
- if !text.is_empty() {
- description = Some(text.to_string());
- }
- }
- if description.is_none() {
- let lesson_re = regex::Regex::new(r#"(?s)class="[^"]*lesson__content[^"]*"[^>]*>(.*?)</div>"#)?;
- if let Some(cap) = lesson_re.captures(&body_text) {
- let text = cap[1].trim();
- if !text.is_empty() {
- description = Some(text.to_string());
- }
- }
- }
-
- Ok(MemberkitLessonDetail {
- id,
- name,
- video_url,
- attachments,
- description,
- })
-}
-
-fn extract_meta_csrf(html: &str) -> Option<String> {
- let re = regex::Regex::new(r#"<meta\s+name="csrf-token"\s+content="([^"]+)""#).ok()?;
- re.captures(html).map(|c| c[1].to_string())
-}
-
-fn extract_input_value(html: &str, name: &str) -> Option<String> {
- let pattern = format!(r#"name="{}"\s+value="([^"]*)""#, regex::escape(name));
- let re = regex::Regex::new(&pattern).ok()?;
- if let Some(cap) = re.captures(html) {
- return Some(cap[1].to_string());
- }
-
- let pattern2 = format!(r#"value="([^"]*)"\s+name="{}""#, regex::escape(name));
- let re2 = regex::Regex::new(&pattern2).ok()?;
- if let Some(cap) = re2.captures(html) {
- return Some(cap[1].to_string());
- }
-
- None
-}
-
-pub async fn save_session(session: &MemberkitSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- cookies: session.cookies.clone(),
- site_url: session.site_url.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[memberkit] session saved for {}", session.site_url);
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<MemberkitSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.cookies, &saved.site_url)?;
-
- tracing::info!("[memberkit] session loaded for {}", saved.site_url);
-
- Ok(Some(MemberkitSession {
- cookies: saved.cookies,
- site_url: saved.site_url,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/memberkit/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/memberkit/downloader.rs
deleted file mode 100644
index c1f8ea2b..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, MemberkitCourse, MemberkitSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct MemberkitCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &MemberkitSession,
- course: &MemberkitCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_modules(session, &course.slug).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[memberkit] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &MemberkitCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- let detail = match api::get_lesson_detail(session, &lesson.url).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[memberkit] Failed to get lesson detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MemberkitCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if let Some(ref desc) = detail.description {
- omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
- }
-
- if let Some(ref video_url) = detail.video_url {
- let video_path = format!(
- "{}/{}. {}.mp4",
- lesson_dir,
- li + 1,
- lesson_name,
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[memberkit] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MemberkitCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[memberkit] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[memberkit] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
-
- for attachment in &detail.attachments {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let att_name = filename::sanitize_path_component(&attachment.name);
- let att_path = format!("{}/{}", lesson_dir, att_name);
-
- if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&att_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match download_file_direct(&session.client, &attachment.url, &att_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[memberkit] Attachment download failed for '{}': {}",
- attachment.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &MemberkitCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- None,
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/memberkit/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/memberkit/mod.rs
deleted file mode 100644
index 9c1cdc15..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct MemberkitDownloader;
-
-impl Default for MemberkitDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl MemberkitDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for MemberkitDownloader {
- fn name(&self) -> &str {
- "memberkit"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "memberkit.com.br" || host.ends_with(".memberkit.com.br");
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Memberkit".to_string(),
- author: String::new(),
- platform: "memberkit".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "Original".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Memberkit"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/mod.rs
deleted file mode 100644
index 749f9627..00000000
--- a/src-tauri/omniget-plugin-courses/src/platforms/mod.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-pub use omniget_core::platforms::traits;
-
-pub mod hotmart;
-pub mod udemy;
-pub mod kiwify;
-pub mod gumroad;
-pub mod teachable;
-pub mod kajabi;
-pub mod skool;
-pub mod pluralsight;
-pub mod greatcourses;
-pub mod masterclass;
-pub mod thinkific;
-pub mod curseduca;
-pub mod cademi;
-pub mod cakto;
-pub mod kirvano;
-pub mod memberkit;
-pub mod rocketseat;
-pub mod grancursos;
-pub mod fluencyacademy;
-pub mod datascienceacademy;
-pub mod medcel;
-pub mod medcof;
-pub mod medway;
-pub mod afyainternato;
-pub mod alpaclass;
-pub mod areademembros;
-pub mod astronmembers;
-pub mod eduzznutror;
-pub mod entregadigital;
-pub mod greennclub;
-pub mod themembers;
-pub mod voompplay;
-pub mod estrategia_concursos;
-pub mod estrategia_ldi;
-pub mod estrategia_militares;
-pub mod matematicaprapassar;
-pub mod caktomembers;
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/api.rs
deleted file mode 100644
index 084f47f1..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("pluralsight_session.json"))
-}
-
-pub fn authenticate_cookies(cookies: &str) -> anyhow::Result<PluralsightSession> {
- let xsrf_token = extract_xsrf_token(cookies)
- .ok_or_else(|| anyhow!("XSRF-TOKEN not found in cookies. Make sure to include the full Cookie header from browser DevTools."))?;
-
- let client = build_client(cookies, &xsrf_token)?;
-
- Ok(PluralsightSession {
- cookies: cookies.to_string(),
- xsrf_token,
- client,
- })
-}
-
-pub async fn validate_token(session: &PluralsightSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://app.pluralsight.com/learner/user/user-content-history?dataSource=v2&limit=1")
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &PluralsightSession) -> anyhow::Result<Vec<PluralsightCourse>> {
- let resp = session
- .client
- .get("https://app.pluralsight.com/learner/user/user-content-history?dataSource=v2&limit=300")
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let mut courses = Vec::new();
-
- let items = body
- .get("data")
- .and_then(|v| v.as_array())
- .or_else(|| body.as_array())
- .cloned()
- .unwrap_or_default();
-
- for item in &items {
- let id = item
- .get("contentId")
- .or_else(|| item.get("id"))
- .or_else(|| item.get("courseId"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let name = item
- .get("title")
- .or_else(|| item.get("name"))
- .or_else(|| item.get("contentTitle"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if !id.is_empty() && !name.is_empty() {
- if !courses.iter().any(|c: &PluralsightCourse| c.id == id) {
- courses.push(PluralsightCourse { id, name });
- }
- }
- }
-
- Ok(courses)
-}
-
-pub async fn get_course_content(
- session: &PluralsightSession,
- course_id: &str,
-) -> anyhow::Result<Vec<PluralsightModule>> {
- let url = format!(
- "https://app.pluralsight.com/course-player/api/v1/table-of-contents/course/{}",
- course_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let modules_arr = body
- .get("modules")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for (mi, module_val) in modules_arr.iter().enumerate() {
- let module_id = module_val
- .get("id")
- .or_else(|| module_val.get("moduleId"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let module_name = module_val
- .get("title")
- .or_else(|| module_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let clips = module_val
- .get("contentItems")
- .or_else(|| module_val.get("clips"))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (ci, clip_val) in clips.iter().enumerate() {
- let clip_id = clip_val
- .get("id")
- .or_else(|| clip_val.get("clipId"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let clip_name = clip_val
- .get("title")
- .or_else(|| clip_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let version_id = clip_val
- .get("version")
- .or_else(|| clip_val.get("versionId"))
- .and_then(|v| match v {
- serde_json::Value::Number(n) => Some(n.to_string()),
- serde_json::Value::String(s) => Some(s.clone()),
- _ => None,
- })
- .unwrap_or_else(|| "1".to_string());
-
- if !clip_id.is_empty() {
- lessons.push(PluralsightLesson {
- id: format!("{}-{}", module_id, ci),
- name: clip_name,
- order: ci as i64,
- clip_id,
- version_id,
- });
- }
- }
-
- modules.push(PluralsightModule {
- id: if module_id.is_empty() {
- format!("{}", mi)
- } else {
- module_id
- },
- name: module_name,
- order: mi as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-pub async fn get_clip_url(
- session: &PluralsightSession,
- clip_id: &str,
- version_id: &str,
-) -> anyhow::Result<String> {
- let url = format!(
- "https://app.pluralsight.com/video/delivery/api/v1/clips/{}/versions/{}",
- clip_id, version_id
- );
-
- let resp = session
- .client
- .post(&url)
- .header("x-team", "video-services")
- .json(&serde_json::json!({
- "online": true,
- "boundedContext": "course",
- "preferredAudioLanguage": "en"
- }))
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_clip_url returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let m3u8_url = body
- .get("urls")
- .and_then(|u| u.as_array())
- .and_then(|arr| arr.first())
- .and_then(|v| v.get("url").or_else(|| v.get("src")))
- .and_then(|v| v.as_str())
- .or_else(|| body.get("url").and_then(|v| v.as_str()))
- .ok_or_else(|| anyhow!("No video URL found in clip response"))?
- .to_string();
-
- Ok(m3u8_url)
-}
-
-pub async fn save_session(session: &PluralsightSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- cookies: session.cookies.clone(),
- xsrf_token: session.xsrf_token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[pluralsight] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<PluralsightSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.cookies, &saved.xsrf_token)?;
-
- tracing::info!("[pluralsight] session loaded");
-
- Ok(Some(PluralsightSession {
- cookies: saved.cookies,
- xsrf_token: saved.xsrf_token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/downloader.rs
deleted file mode 100644
index 0e4995be..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, PluralsightCourse, PluralsightSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct PluralsightCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &PluralsightSession,
- course: &PluralsightCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, &course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[pluralsight] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &PluralsightCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let video_path = format!(
- "{}/{}. {}.mp4",
- mod_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[pluralsight] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &PluralsightCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- match api::get_clip_url(session, &lesson.clip_id, &lesson.version_id).await {
- Ok(clip_url) => {
- if clip_url.contains(".m3u8") {
- match download_hls_video(&clip_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[pluralsight] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(&clip_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[pluralsight] yt-dlp failed for '{}': {}, trying direct",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, &clip_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[pluralsight] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
- Err(e) => {
- tracing::error!(
- "[pluralsight] Failed to get clip URL for '{}': {}",
- lesson.name,
- e
- );
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &PluralsightCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://app.pluralsight.com/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://app.pluralsight.com/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/pluralsight/mod.rs
deleted file mode 100644
index 98f4b2c1..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct PluralsightDownloader;
-
-impl Default for PluralsightDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl PluralsightDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for PluralsightDownloader {
- fn name(&self) -> &str {
- "pluralsight"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "pluralsight.com" || host == "app.pluralsight.com";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Pluralsight Course".to_string(),
- author: String::new(),
- platform: "pluralsight".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Pluralsight courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/api.rs
deleted file mode 100644
index c6f31cd6..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("rocketseat_session.json"))
-}
-
-pub fn create_session(token: &str) -> anyhow::Result<RocketseatSession> {
- let client = build_client(token)?;
- Ok(RocketseatSession {
- token: token.to_string(),
- client,
- })
-}
-
-pub async fn validate_token(session: &RocketseatSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get(&format!("{}/v2/search/multi-search", API_URL))
- .query(&[("query", "test"), ("page", "1")])
- .header("Host", "skylab-api.rocketseat.com.br")
- .send()
- .await?;
-
- let status = resp.status();
- tracing::info!("[rocketseat] validate_token status={}", status);
-
- Ok(status.is_success())
-}
-
-pub async fn search_courses(
- session: &RocketseatSession,
- query: &str,
-) -> anyhow::Result<Vec<RocketseatCourse>> {
- let mut all_courses = Vec::new();
- let mut seen = std::collections::HashSet::new();
- let mut page = 1u32;
-
- loop {
- let url = format!("{}/v2/search/multi-search", API_URL);
- let resp = session
- .client
- .get(&url)
- .query(&[("query", query), ("page", &page.to_string())])
- .header("Host", "skylab-api.rocketseat.com.br")
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- if all_courses.is_empty() {
- return Err(anyhow!(
- "search_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
- break;
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let journeys = body
- .get("journeys")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- if journeys.is_empty() {
- break;
- }
-
- let mut new_count = 0;
- for item in &journeys {
- let id = item
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if id.is_empty() || seen.contains(&id) {
- continue;
- }
- seen.insert(id.clone());
- new_count += 1;
-
- let name = item
- .get("title")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let slug = item
- .get("slug")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let description = item
- .get("description")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- all_courses.push(RocketseatCourse {
- id,
- name,
- slug,
- description,
- });
- }
-
- if new_count == 0 {
- break;
- }
-
- let has_more = body
- .pointer("/meta/journeys/hasMore")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
-
- if !has_more || page > 50 {
- break;
- }
-
- page += 1;
- }
-
- Ok(all_courses)
-}
-
-pub async fn list_courses(
- session: &RocketseatSession,
-) -> anyhow::Result<Vec<RocketseatCourse>> {
- search_courses(session, "rocketseat").await
-}
-
-fn parse_rsc_response(text: &str) -> serde_json::Value {
- for line in text.lines() {
- if line.is_empty() {
- continue;
- }
- let parts: Vec<&str> = line.splitn(2, ':').collect();
- if parts.len() < 2 {
- continue;
- }
-
- if let Ok(data) = serde_json::from_str::<serde_json::Value>(parts[1]) {
- if let Some(arr) = data.as_array() {
- if arr.len() > 3 {
- if let Some(payload) = arr.get(3).and_then(|v| v.as_object()) {
- let payload_val = serde_json::Value::Object(payload.clone());
- if payload_val.get("journeyContents").is_some()
- || payload_val.get("lessonGroups").is_some()
- {
- return payload_val;
- }
- if let Some(inner) = payload_val.get("data").and_then(|v| v.as_object()) {
- let inner_val = serde_json::Value::Object(inner.clone());
- if inner_val.get("journeyContents").is_some()
- || inner_val.get("lessonGroups").is_some()
- {
- return inner_val;
- }
- }
- }
- }
- }
- }
- }
-
- serde_json::Value::Object(serde_json::Map::new())
-}
-
-pub async fn get_course_content(
- session: &RocketseatSession,
- course: &RocketseatCourse,
-) -> anyhow::Result<Vec<RocketseatModule>> {
- let url = format!("{}/jornada/{}/conteudos", BASE_URL, course.slug);
-
- let resp = session
- .client
- .get(&url)
- .query(&[("_rsc", "1")])
- .header("RSC", "1")
- .header("Accept", "*/*")
- .header("Host", "app.rocketseat.com.br")
- .send()
- .await?;
-
- if !resp.status().is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}",
- resp.status()
- ));
- }
-
- let text = resp.text().await?;
- let data = parse_rsc_response(&text);
-
- let nodes = data
- .pointer("/journeyContents/nodes")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
- let mut module_idx = 0i64;
-
- for node in &nodes {
- let sub_contents = node
- .get("contents")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_else(|| vec![node.clone()]);
-
- for sub in &sub_contents {
- let module_slug = sub
- .get("slug")
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- if module_slug.is_empty() {
- continue;
- }
-
- let module_title = sub
- .get("title")
- .and_then(|v| v.as_str())
- .unwrap_or(module_slug)
- .to_string();
-
- let lessons = fetch_module_lessons(session, &course.slug, module_slug).await?;
-
- if !lessons.is_empty() {
- module_idx += 1;
- modules.push(RocketseatModule {
- id: sub
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or(module_slug)
- .to_string(),
- name: module_title,
- order: module_idx,
- lessons,
- });
- }
- }
- }
-
- Ok(modules)
-}
-
-async fn fetch_module_lessons(
- session: &RocketseatSession,
- journey_slug: &str,
- module_slug: &str,
-) -> anyhow::Result<Vec<RocketseatLesson>> {
- let url = format!("{}/jornada/{}/sala/{}", BASE_URL, journey_slug, module_slug);
-
- let resp = session
- .client
- .get(&url)
- .query(&[("_rsc", "1")])
- .header("RSC", "1")
- .header("Accept", "*/*")
- .header("Host", "app.rocketseat.com.br")
- .send()
- .await?;
-
- if !resp.status().is_success() {
- return Ok(Vec::new());
- }
-
- let text = resp.text().await?;
- let data = parse_rsc_response(&text);
-
- let lesson_groups = data
- .get("lessonGroups")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
- let mut order = 0i64;
-
- for group in &lesson_groups {
- let group_lessons = group
- .get("lessons")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for lesson in &group_lessons {
- order += 1;
-
- let id = lesson
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let title = lesson
- .get("title")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let slug = lesson
- .get("slug")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_type = lesson
- .get("type")
- .and_then(|v| v.as_str())
- .unwrap_or("VIDEO")
- .to_string();
-
- let video_id = lesson
- .get("video")
- .and_then(|v| v.get("jupiterVideoId"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let duration = lesson
- .get("duration")
- .and_then(|v| v.as_i64());
-
- lessons.push(RocketseatLesson {
- id,
- name: title,
- order,
- slug,
- lesson_type,
- video_id,
- duration,
- });
- }
- }
-
- Ok(lessons)
-}
-
-pub fn get_video_embed_url(video_id: &str) -> String {
- format!(
- "https://iframe.mediadelivery.net/embed/{}/{}",
- BUNNY_LIBRARY_ID, video_id
- )
-}
-
-pub async fn save_session(session: &RocketseatSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[rocketseat] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<RocketseatSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[rocketseat] session loaded");
-
- Ok(Some(RocketseatSession {
- token: saved.token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/downloader.rs
deleted file mode 100644
index 5997506f..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, RocketseatCourse, RocketseatSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct RocketseatCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &RocketseatSession,
- course: &RocketseatCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, course).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[rocketseat] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &RocketseatCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let safe_name = format!("{}. {}", li + 1, lesson_name);
-
- if let Some(ref vid_id) = lesson.video_id {
- let video_path = format!("{}/{}.mp4", mod_dir, safe_name);
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[rocketseat] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &RocketseatCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- let embed_url = api::get_video_embed_url(vid_id);
-
- match download_with_ytdlp(&embed_url, &mod_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[rocketseat] yt-dlp download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &RocketseatCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://app.rocketseat.com.br/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/rocketseat/mod.rs
deleted file mode 100644
index aed53331..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct RocketseatDownloader;
-
-impl Default for RocketseatDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl RocketseatDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for RocketseatDownloader {
- fn name(&self) -> &str {
- "rocketseat"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "rocketseat.com.br"
- || host == "app.rocketseat.com.br";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Rocketseat".to_string(),
- author: String::new(),
- platform: "rocketseat".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "Original".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Rocketseat"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/skool/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/skool/api.rs
deleted file mode 100644
index d035a280..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("skool_session.json"))
-}
-
-async fn fetch_build_id(client: &reqwest::Client) -> anyhow::Result<String> {
- let resp = client
- .get("https://www.skool.com")
- .send()
- .await?;
-
- let html = resp.text().await?;
-
- let re = regex::Regex::new(r#""buildId"\s*:\s*"([^"]+)""#)?;
- let build_id = re
- .captures(&html)
- .and_then(|c| c.get(1))
- .map(|m| m.as_str().to_string())
- .ok_or_else(|| anyhow!("Could not extract buildId from Skool HTML"))?;
-
- Ok(build_id)
-}
-
-pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<SkoolSession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .cookie_store(true)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "email": email,
- "password": password,
- });
-
- let resp = temp_client
- .post("https://api2.skool.com/auth/login")
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
-
- let mut cookie_token = String::new();
- for cookie in resp.cookies() {
- if cookie.name() == "skooltok" {
- cookie_token = cookie.value().to_string();
- }
- }
-
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Authentication failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- if cookie_token.is_empty() {
- let body: serde_json::Value = serde_json::from_str(&body_text).unwrap_or_default();
- cookie_token = body
- .get("token")
- .or_else(|| body.get("skooltok"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
- }
-
- if cookie_token.is_empty() {
- return Err(anyhow!("No skooltok cookie or token in login response"));
- }
-
- let client = build_client(&cookie_token)?;
- let build_id = fetch_build_id(&client).await?;
-
- Ok(SkoolSession {
- cookie_token,
- build_id,
- client,
- })
-}
-
-pub async fn validate_token(session: &SkoolSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://api2.skool.com/self/groups?limit=1&prefs=false")
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_groups(session: &SkoolSession) -> anyhow::Result<Vec<SkoolGroup>> {
- let mut all_groups = Vec::new();
-
- let url = "https://api2.skool.com/self/groups?limit=50&prefs=false";
-
- let resp = session.client.get(url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_groups returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let groups_arr = body
- .get("groups")
- .or_else(|| body.as_array().map(|_| &body))
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- for item in &groups_arr {
- let metadata = item.get("metadata").unwrap_or(item);
-
- let id = item
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let slug = item
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let name = metadata
- .get("display_name")
- .and_then(|v| v.as_str())
- .or_else(|| item.get("display_name").and_then(|v| v.as_str()))
- .unwrap_or(&slug)
- .to_string();
-
- let image_url = metadata
- .get("cover_small_url")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let num_courses = metadata
- .get("num_courses")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- all_groups.push(SkoolGroup {
- id,
- slug,
- name,
- image_url,
- num_courses,
- });
- }
-
- Ok(all_groups)
-}
-
-pub async fn get_group_courses(
- session: &SkoolSession,
- group_slug: &str,
-) -> anyhow::Result<Vec<SkoolModule>> {
- let url = format!(
- "https://www.skool.com/_next/data/{}/{}/classroom.json?group={}",
- session.build_id, group_slug, group_slug
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_group_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let courses_arr = body
- .pointer("/pageProps/allCourses")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for (i, course) in courses_arr.iter().enumerate() {
- let course_id = course
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let course_slug = course
- .get("slug")
- .or_else(|| course.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let metadata = course.get("metadata").unwrap_or(course);
-
- let course_name = metadata
- .get("title")
- .or_else(|| metadata.get("display_name"))
- .and_then(|v| v.as_str())
- .unwrap_or(&course_slug)
- .to_string();
-
- let lessons = get_course_lessons(session, group_slug, &course_slug).await.unwrap_or_default();
-
- modules.push(SkoolModule {
- id: if course_id.is_empty() { course_slug } else { course_id },
- name: course_name,
- order: i as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-async fn get_course_lessons(
- session: &SkoolSession,
- group_slug: &str,
- course_slug: &str,
-) -> anyhow::Result<Vec<SkoolLesson>> {
- let url = format!(
- "https://www.skool.com/_next/data/{}/{}/classroom/{}.json?group={}&course={}",
- session.build_id, group_slug, course_slug, group_slug, course_slug
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_lessons returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let children = body
- .pointer("/pageProps/course/children")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (i, child) in children.iter().enumerate() {
- let metadata = child.get("metadata").unwrap_or(child);
-
- let lesson_id = child
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_name = metadata
- .get("title")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- lessons.push(SkoolLesson {
- id: if lesson_id.is_empty() { format!("{}", i) } else { lesson_id },
- name: lesson_name,
- order: i as i64,
- });
- }
-
- Ok(lessons)
-}
-
-pub async fn get_lesson_detail(
- _session: &SkoolSession,
- _group_slug: &str,
- _course_slug: &str,
- lesson_id: &str,
- children: &[serde_json::Value],
-) -> anyhow::Result<SkoolLessonDetail> {
- let child = children
- .iter()
- .find(|c| {
- c.get("id")
- .and_then(|v| v.as_str())
- .map(|id| id == lesson_id)
- .unwrap_or(false)
- })
- .cloned();
-
- let metadata = child
- .as_ref()
- .and_then(|c| c.get("metadata"))
- .unwrap_or(&serde_json::Value::Null);
-
- let name = metadata
- .get("title")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let description = metadata
- .get("description")
- .or_else(|| metadata.get("content"))
- .or_else(|| metadata.get("body"))
- .and_then(|v| {
- if v.is_string() {
- v.as_str().map(String::from)
- } else {
- Some(serde_json::to_string_pretty(v).unwrap_or_default())
- }
- })
- .filter(|s| !s.trim().is_empty());
-
- let video_url = metadata
- .get("videoLink")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let mut files = Vec::new();
-
- if let Some(attachments) = metadata.get("attachments").and_then(|v| v.as_array()) {
- for att in attachments {
- let file_id = att
- .get("id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let file_name = att
- .get("name")
- .or_else(|| att.get("filename"))
- .and_then(|v| v.as_str())
- .unwrap_or("file")
- .to_string();
-
- files.push(SkoolFile {
- id: file_id,
- name: file_name,
- url: None,
- });
- }
- }
-
- Ok(SkoolLessonDetail {
- id: lesson_id.to_string(),
- name,
- description,
- video_url,
- files,
- })
-}
-
-pub async fn get_file_download_url(
- session: &SkoolSession,
- file_id: &str,
-) -> anyhow::Result<String> {
- let url = format!(
- "https://api2.skool.com/files/{}/download-url?expire=28800",
- file_id
- );
-
- let resp = session.client.post(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_file_download_url returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let download_url = body
- .get("url")
- .or_else(|| body.get("download_url"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("No download URL in file response"))?
- .to_string();
-
- Ok(download_url)
-}
-
-pub async fn save_session(session: &SkoolSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- cookie_token: session.cookie_token.clone(),
- build_id: session.build_id.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[skool] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<SkoolSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.cookie_token)?;
-
- tracing::info!("[skool] session loaded");
-
- Ok(Some(SkoolSession {
- cookie_token: saved.cookie_token,
- build_id: saved.build_id,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/skool/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/skool/downloader.rs
deleted file mode 100644
index 69325cc2..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, SkoolGroup, SkoolSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct SkoolCourseDownloadProgress {
- pub group_id: String,
- pub group_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &SkoolSession,
- group: &SkoolGroup,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_group_courses(session, &group.slug).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- group.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&group.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &SkoolCourseDownloadProgress {
- group_id: group.id.clone(),
- group_name: group.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- let detail = match api::get_lesson_detail(session, &group.slug, &module.id, &lesson.id, &[]).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[skool] Failed to get lesson detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &SkoolCourseDownloadProgress {
- group_id: group.id.clone(),
- group_name: group.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if let Some(ref desc) = detail.description {
- omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
- }
-
- if let Some(ref video_url) = detail.video_url {
- let video_path = format!(
- "{}/{}. {}.mp4",
- lesson_dir,
- li + 1,
- lesson_name
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[skool] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &SkoolCourseDownloadProgress {
- group_id: group.id.clone(),
- group_name: group.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- match download_with_ytdlp(video_url, &lesson_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[skool] yt-dlp download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
-
- for file in &detail.files {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let file_name = filename::sanitize_path_component(&file.name);
- let file_path = format!("{}/{}", lesson_dir, file_name);
-
- if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&file_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- let download_url = if let Some(ref url) = file.url {
- url.clone()
- } else {
- match api::get_file_download_url(session, &file.id).await {
- Ok(url) => url,
- Err(e) => {
- tracing::error!(
- "[skool] Failed to get download URL for file '{}': {}",
- file.name,
- e
- );
- continue;
- }
- }
- };
-
- match download_file_direct(&session.client, &download_url, &file_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[skool] File download failed for '{}': {}",
- file.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &SkoolCourseDownloadProgress {
- group_id: group.id.clone(),
- group_name: group.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://www.skool.com/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/skool/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/skool/mod.rs
deleted file mode 100644
index fbe03741..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct SkoolDownloader;
-
-impl Default for SkoolDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl SkoolDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for SkoolDownloader {
- fn name(&self) -> &str {
- "skool"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "skool.com" || host == "www.skool.com";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Skool Course".to_string(),
- author: String::new(),
- platform: "skool".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Skool courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/teachable/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/teachable/api.rs
deleted file mode 100644
index 4589dd3c..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("teachable_session.json"))
-}
-
-pub async fn request_otp(email: &str) -> anyhow::Result<()> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "email": email,
- });
-
- let resp = temp_client
- .post("https://sso.teachable.com/api/v2/auth/otp/request")
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
-
- if !status.is_success() {
- let body_text = resp.text().await?;
- return Err(anyhow!(
- "OTP request failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- Ok(())
-}
-
-pub async fn verify_otp(email: &str, otp_code: &str) -> anyhow::Result<TeachableSession> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "email": email,
- "otp_code": otp_code,
- });
-
- let resp = temp_client
- .post("https://sso.teachable.com/api/v2/auth/otp/verify")
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "OTP verification failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let token = body
- .get("token")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("token not found in OTP verify response"))?
- .to_string();
-
- let client = build_client(&token)?;
-
- Ok(TeachableSession {
- token,
- school_id: None,
- client,
- })
-}
-
-pub async fn validate_token(session: &TeachableSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get(&format!("{}/schools", BASE_URL))
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_schools(session: &TeachableSession) -> anyhow::Result<Vec<TeachableSchool>> {
- let resp = session
- .client
- .get(&format!("{}/schools", BASE_URL))
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_schools returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let schools_arr = body
- .get("schools")
- .and_then(|v| v.as_array())
- .or_else(|| body.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut schools = Vec::new();
-
- for item in &schools_arr {
- let id = item
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let name = item
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let image_url = item
- .get("image_url")
- .or_else(|| item.get("logo_url"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- schools.push(TeachableSchool {
- id,
- name,
- image_url,
- });
- }
-
- Ok(schools)
-}
-
-pub async fn list_courses(
- session: &TeachableSession,
- school_id: &str,
-) -> anyhow::Result<Vec<TeachableCourse>> {
- let url = format!("{}/schools/{}/courses", BASE_URL, school_id);
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let courses_arr = body
- .get("courses")
- .and_then(|v| v.as_array())
- .or_else(|| body.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut courses = Vec::new();
-
- for item in &courses_arr {
- let id = item
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let name = item
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let image_url = item
- .get("image_url")
- .or_else(|| item.get("thumbnail_url"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- courses.push(TeachableCourse {
- id,
- name,
- image_url,
- school_id: school_id.to_string(),
- });
- }
-
- Ok(courses)
-}
-
-pub async fn get_syllabus(
- session: &TeachableSession,
- school_id: &str,
- course_id: &str,
-) -> anyhow::Result<Vec<TeachableModule>> {
- let url = format!(
- "{}/schools/{}/courses/{}/syllabus",
- BASE_URL, school_id, course_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_syllabus returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let sections_arr = body
- .get("sections")
- .and_then(|v| v.as_array())
- .or_else(|| body.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for (i, section) in sections_arr.iter().enumerate() {
- let section_id = section
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", i),
- })
- .unwrap_or_else(|| format!("{}", i));
-
- let section_name = section
- .get("name")
- .or_else(|| section.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lectures_arr = section
- .get("lectures")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for (j, lecture) in lectures_arr.iter().enumerate() {
- let lecture_id = lecture
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => format!("{}", j),
- })
- .unwrap_or_else(|| format!("{}", j));
-
- let lecture_name = lecture
- .get("name")
- .or_else(|| lecture.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- lessons.push(TeachableLesson {
- id: lecture_id,
- name: lecture_name,
- order: j as i64,
- });
- }
-
- modules.push(TeachableModule {
- id: section_id,
- name: section_name,
- order: i as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-pub async fn get_lecture_detail(
- session: &TeachableSession,
- school_id: &str,
- course_id: &str,
- lecture_id: &str,
-) -> anyhow::Result<TeachableLessonDetail> {
- let url = format!(
- "{}/schools/{}/courses/{}/lectures/{}",
- BASE_URL, school_id, course_id, lecture_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lecture_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let lecture = body.get("lecture").unwrap_or(&body);
-
- let id = lecture
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => lecture_id.to_string(),
- })
- .unwrap_or_else(|| lecture_id.to_string());
-
- let name = lecture
- .get("name")
- .or_else(|| lecture.get("title"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let attachments = lecture
- .get("attachments")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut video_url = None;
- let mut video_referer = None;
- let mut files = Vec::new();
-
- for att in &attachments {
- let kind = att
- .get("kind")
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- match kind {
- "video" => {
- let data = att.get("data").unwrap_or(att);
- video_url = data
- .get("url")
- .and_then(|v| v.as_str())
- .map(String::from);
- video_referer = data
- .get("referer")
- .and_then(|v| v.as_str())
- .map(String::from);
- }
- "pdf_embed" | "generic" => {
- let data = att.get("data").unwrap_or(att);
- let file_id = att
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let file_name = data
- .get("name")
- .or_else(|| data.get("filename"))
- .or_else(|| att.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("file")
- .to_string();
-
- let file_url = data
- .get("url")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- files.push(TeachableFile {
- id: file_id,
- name: file_name,
- url: file_url,
- });
- }
- _ => {}
- }
- }
-
- Ok(TeachableLessonDetail {
- id,
- name,
- video_url,
- video_referer,
- files,
- })
-}
-
-pub async fn save_session(session: &TeachableSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- school_id: session.school_id.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[teachable] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<TeachableSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[teachable] session loaded");
-
- Ok(Some(TeachableSession {
- token: saved.token,
- school_id: saved.school_id,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/teachable/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/teachable/downloader.rs
deleted file mode 100644
index b56dc8be..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, TeachableCourse, TeachableSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct TeachableCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &TeachableSession,
- course: &TeachableCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_syllabus(session, &course.school_id, &course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[teachable] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &TeachableCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- let detail = match api::get_lecture_detail(session, &course.school_id, &course.id, &lesson.id).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[teachable] Failed to get lecture detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &TeachableCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if let Some(ref video_url) = detail.video_url {
- let video_ext = if video_url.contains(".m3u8") {
- "mp4"
- } else {
- video_url
- .rsplit('.')
- .next()
- .and_then(|e| {
- let e = e.split('?').next().unwrap_or(e);
- if e.len() <= 4 {
- Some(e)
- } else {
- None
- }
- })
- .unwrap_or("mp4")
- };
-
- let video_path = format!(
- "{}/{}. {}.{}",
- lesson_dir,
- li + 1,
- lesson_name,
- video_ext
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[teachable] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &TeachableCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if video_url.contains(".m3u8") {
- let referer = detail.video_referer.as_deref().unwrap_or("https://teachable.com/");
- match download_hls_video(video_url, &video_path, referer, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[teachable] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- let referer = detail.video_referer.as_deref().unwrap_or("https://teachable.com/");
- match download_with_ytdlp(video_url, &lesson_dir, referer, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[teachable] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[teachable] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
-
- for file in &detail.files {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let file_name = filename::sanitize_path_component(&file.name);
- let file_path = format!("{}/{}", lesson_dir, file_name);
-
- if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&file_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- if let Some(ref url) = file.url {
- match download_file_direct(&session.client, url, &file_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[teachable] File download failed for '{}': {}",
- file.name,
- e
- );
- }
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &TeachableCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- referer: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- referer,
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- referer: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some(referer),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/teachable/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/teachable/mod.rs
deleted file mode 100644
index e4ddf56c..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct TeachableDownloader;
-
-impl Default for TeachableDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl TeachableDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for TeachableDownloader {
- fn name(&self) -> &str {
- "teachable"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "teachable.com"
- || host.ends_with(".teachable.com")
- || host == "sso.teachable.com";
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Teachable Course".to_string(),
- author: String::new(),
- platform: "teachable".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Teachable courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/themembers/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/themembers/api.rs
deleted file mode 100644
index f13855a7..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("themembers_session.json"))
-}
-
-pub async fn resolve_tenant(domain: &str) -> anyhow::Result<(String, String)> {
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let url = format!("{}/getTenant?domain={}", API_BASE, domain);
- let resp = temp_client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "resolve_tenant returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let tenant = body.get("tenant").unwrap_or(&body);
-
- let tenant_id = tenant
- .get("id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- let org_id = tenant
- .get("organization_id")
- .map(|v| match v {
- serde_json::Value::Number(n) => n.to_string(),
- serde_json::Value::String(s) => s.clone(),
- _ => String::new(),
- })
- .unwrap_or_default();
-
- if tenant_id.is_empty() {
- return Err(anyhow!("Could not resolve tenant_id for domain {}", domain));
- }
-
- Ok((tenant_id, org_id))
-}
-
-pub async fn authenticate(email: &str, password: &str, domain: &str) -> anyhow::Result<TheMembersSession> {
- let (tenant_id, org_id) = resolve_tenant(domain).await?;
-
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let payload = serde_json::json!({
- "email": email,
- "password": password,
- "tenant_id": tenant_id,
- });
-
- let resp = temp_client
- .post(format!("{}/auth/login", API_BASE))
- .json(&payload)
- .send()
- .await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "Authentication failed (status {}): {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let token = body
- .get("access_token")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("access_token not found in login response"))?
- .to_string();
-
- let client = build_client(&token, &tenant_id, &org_id, domain)?;
-
- Ok(TheMembersSession {
- token,
- tenant_id,
- org_id,
- domain: domain.to_string(),
- client,
- })
-}
-
-pub async fn authenticate_token(token: &str, domain: &str) -> anyhow::Result<TheMembersSession> {
- let (tenant_id, org_id) = resolve_tenant(domain).await?;
- let client = build_client(token, &tenant_id, &org_id, domain)?;
-
- let session = TheMembersSession {
- token: token.to_string(),
- tenant_id,
- org_id,
- domain: domain.to_string(),
- client,
- };
-
- let valid = validate_token(&session).await?;
- if !valid {
- return Err(anyhow!("Invalid token"));
- }
-
- Ok(session)
-}
-
-pub async fn validate_token(session: &TheMembersSession) -> anyhow::Result<bool> {
- let url = format!(
- "{}/auth/sideList/{}/courses",
- API_BASE, session.tenant_id
- );
-
- let resp = session.client.get(&url).send().await?;
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &TheMembersSession) -> anyhow::Result<Vec<TheMembersCourse>> {
- let url = format!(
- "{}/auth/sideList/{}/courses",
- API_BASE, session.tenant_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let data_arr = body
- .get("data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut courses = Vec::new();
- for item in &data_arr {
- let id = item.get("id").and_then(|v| v.as_i64()).unwrap_or(0);
- let name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if id != 0 {
- courses.push(TheMembersCourse { id, name });
- }
- }
-
- Ok(courses)
-}
-
-pub async fn get_course_content(
- session: &TheMembersSession,
- course_id: i64,
-) -> anyhow::Result<Vec<TheMembersModule>> {
- let modules_url = format!(
- "{}/auth/sideList/{}/modules",
- API_BASE, course_id
- );
-
- let resp = session.client.get(&modules_url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_course_content returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let modules_arr = body
- .get("data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for (mi, module_val) in modules_arr.iter().enumerate() {
- let module_id = module_val.get("id").and_then(|v| v.as_i64()).unwrap_or(0);
- let module_name = module_val
- .get("title")
- .or_else(|| module_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lessons_url = format!(
- "{}/auth/sideList/{}/lessons",
- API_BASE, module_id
- );
-
- let lessons = match session.client.get(&lessons_url).send().await {
- Ok(resp) if resp.status().is_success() => {
- let lessons_text = resp.text().await.unwrap_or_default();
- let lessons_body: serde_json::Value =
- serde_json::from_str(&lessons_text).unwrap_or(serde_json::Value::Null);
-
- let lessons_arr = lessons_body
- .get("data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- lessons_arr
- .iter()
- .enumerate()
- .map(|(li, lesson_val)| {
- let lesson_id = lesson_val
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let lesson_name = lesson_val
- .get("title")
- .or_else(|| lesson_val.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- TheMembersLesson {
- id: lesson_id,
- name: lesson_name,
- order: li as i64,
- }
- })
- .collect()
- }
- _ => vec![],
- };
-
- modules.push(TheMembersModule {
- id: module_id,
- name: module_name,
- order: mi as i64,
- lessons,
- });
- }
-
- Ok(modules)
-}
-
-pub async fn get_lesson_detail(
- session: &TheMembersSession,
- lesson_id: i64,
-) -> anyhow::Result<TheMembersLessonDetail> {
- let url = format!(
- "{}/auth/home/class/{}/{}",
- API_BASE, lesson_id, session.tenant_id
- );
-
- let resp = session.client.get(&url).send().await?;
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lesson_detail returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let class_obj = body.get("class").unwrap_or(&body);
-
- let name = class_obj
- .get("title")
- .or_else(|| class_obj.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let description = class_obj
- .get("description")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let url_pdf = class_obj
- .get("url_pdf")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty())
- .map(String::from);
-
- let host = class_obj
- .get("host")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let raw_video_url = class_obj
- .get("url_video")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let video_url = match (host.as_str(), &raw_video_url) {
- ("the-player-ai", Some(url)) => {
- resolve_the_player_ai_url(url).await.ok()
- }
- (_, Some(url)) if !url.is_empty() => Some(url.clone()),
- _ => None,
- };
-
- let materials_url = format!(
- "{}/auth/home/materials/{}",
- API_BASE, lesson_id
- );
-
- let files = match session.client.get(&materials_url).send().await {
- Ok(resp) if resp.status().is_success() => {
- let files_text = resp.text().await.unwrap_or_default();
- let files_body: serde_json::Value =
- serde_json::from_str(&files_text).unwrap_or(serde_json::Value::Array(vec![]));
-
- let files_arr = match &files_body {
- serde_json::Value::Array(arr) => arr.clone(),
- _ => files_body
- .get("data")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default(),
- };
-
- files_arr
- .iter()
- .filter_map(|f| {
- let file_name = f
- .get("title")
- .or_else(|| f.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("file")
- .to_string();
-
- let file_url = f
- .get("url")
- .or_else(|| f.get("file_url"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- file_url.map(|url| TheMembersFile {
- name: file_name,
- url,
- })
- })
- .collect()
- }
- _ => vec![],
- };
-
- Ok(TheMembersLessonDetail {
- id: lesson_id,
- name,
- description,
- video_url,
- url_pdf,
- host,
- files,
- })
-}
-
-async fn resolve_the_player_ai_url(video_url: &str) -> anyhow::Result<String> {
- let video_id = video_url
- .rsplit('/')
- .next()
- .unwrap_or(video_url)
- .split('?')
- .next()
- .unwrap_or(video_url);
-
- let temp_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(60))
- .build()?;
-
- let url = format!("https://player.themembers.com.br/api/video/{}", video_id);
- let resp = temp_client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "resolve_the_player_ai_url returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let hls_url = body
- .get("data")
- .and_then(|d| d.get("urls"))
- .and_then(|u| u.get("hls"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow!("No HLS URL found in the-player-ai response"))?
- .to_string();
-
- Ok(hls_url)
-}
-
-pub async fn save_session(session: &TheMembersSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- tenant_id: session.tenant_id.clone(),
- org_id: session.org_id.clone(),
- domain: session.domain.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[themembers] session saved for {}", session.domain);
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<TheMembersSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token, &saved.tenant_id, &saved.org_id, &saved.domain)?;
-
- tracing::info!("[themembers] session loaded for {}", saved.domain);
-
- Ok(Some(TheMembersSession {
- token: saved.token,
- tenant_id: saved.tenant_id,
- org_id: saved.org_id,
- domain: saved.domain,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/themembers/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/themembers/downloader.rs
deleted file mode 100644
index fa70f70d..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, TheMembersCourse, TheMembersSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct TheMembersCourseDownloadProgress {
- pub course_id: i64,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &TheMembersSession,
- course: &TheMembersCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &TheMembersCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- let detail = match api::get_lesson_detail(session, lesson.id).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[themembers] Failed to get lesson detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &TheMembersCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if let Some(ref desc) = detail.description {
- omniget_core::core::course_utils::save_description(&lesson_dir, desc, "html").await.ok();
- }
-
- if let Some(ref pdf_url) = detail.url_pdf {
- omniget_core::core::course_utils::download_attachment(
- &session.client,
- pdf_url,
- &lesson_dir,
- &format!("{}.pdf", lesson_name),
- &cancel_token,
- ).await.ok();
- }
-
- if let Some(ref video_url) = detail.video_url {
- let video_ext = if video_url.contains(".m3u8") {
- "mp4"
- } else {
- video_url
- .rsplit('.')
- .next()
- .and_then(|e| {
- let e = e.split('?').next().unwrap_or(e);
- if e.len() <= 4 {
- Some(e)
- } else {
- None
- }
- })
- .unwrap_or("mp4")
- };
-
- let video_path = format!(
- "{}/{}. {}.{}",
- lesson_dir,
- li + 1,
- lesson_name,
- video_ext
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[themembers] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &TheMembersCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- let referer = format!("https://{}/", session.domain);
-
- if video_url.contains(".m3u8") {
- match download_hls_video(video_url, &video_path, &referer, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[themembers] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(video_url, &lesson_dir, &referer, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[themembers] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, video_url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[themembers] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
-
- for file in &detail.files {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let file_name = filename::sanitize_path_component(&file.name);
- let file_path = format!("{}/{}", lesson_dir, file_name);
-
- if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&file_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match download_file_direct(&session.client, &file.url, &file_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[themembers] File download failed for '{}': {}",
- file.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &TheMembersCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- referer: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- referer,
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- referer: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some(referer),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/themembers/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/themembers/mod.rs
deleted file mode 100644
index 79ddf36b..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct TheMembersDownloader;
-
-impl TheMembersDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for TheMembersDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for TheMembersDownloader {
- fn name(&self) -> &str {
- "themembers"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "themembers.com.br"
- || host.ends_with(".themembers.com.br");
- }
- }
- false
- }
-
- async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "TheMembers".to_string(),
- author: String::new(),
- platform: "themembers".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from TheMembers"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/thinkific/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/thinkific/api.rs
deleted file mode 100644
index 9e0f27e9..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("thinkific_session.json"))
-}
-
-pub fn create_session(cookies: &str, site_url: &str) -> anyhow::Result<ThinkificSession> {
- let site_url = normalise_site_url(site_url);
- let client = build_client(cookies, &site_url)?;
- Ok(ThinkificSession {
- cookies: cookies.to_string(),
- site_url,
- client,
- })
-}
-
-pub async fn validate_session(session: &ThinkificSession) -> anyhow::Result<bool> {
- let url = format!(
- "{}/api/course_player/v2/enrollments",
- session.site_url
- );
- let resp = session.client.get(&url).send().await?;
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &ThinkificSession) -> anyhow::Result<Vec<ThinkificCourse>> {
- let mut courses = Vec::new();
-
- for endpoint in &[
- "/api/course_player/v2/enrollments",
- "/api/course_player/v2/courses",
- "/api/v0/enrollments",
- "/api/v0/courses",
- ] {
- let url = format!("{}{}", session.site_url, endpoint);
- let resp = match session.client.get(&url).send().await {
- Ok(r) if r.status().is_success() => r,
- _ => continue,
- };
-
- let body_text = resp.text().await.unwrap_or_default();
- let parsed = parse_enrollments(&body_text, session).await;
- if !parsed.is_empty() {
- courses = parsed;
- break;
- }
- }
-
- if courses.is_empty() {
- courses = scrape_enrollments(session).await.unwrap_or_default();
- }
-
- Ok(courses)
-}
-
-async fn parse_enrollments(
- body: &str,
- session: &ThinkificSession,
-) -> Vec<ThinkificCourse> {
- let raw: serde_json::Value = match serde_json::from_str(body) {
- Ok(v) => v,
- Err(_) => return Vec::new(),
- };
-
- let items = match &raw {
- serde_json::Value::Array(arr) => arr.clone(),
- serde_json::Value::Object(map) => {
- for key in &["items", "enrollments", "courses"] {
- if let Some(serde_json::Value::Array(arr)) = map.get(*key) {
- return parse_items_array(arr, session).await;
- }
- }
- return Vec::new();
- }
- _ => return Vec::new(),
- };
-
- parse_items_array(&items, session).await
-}
-
-async fn parse_items_array(
- items: &[serde_json::Value],
- session: &ThinkificSession,
-) -> Vec<ThinkificCourse> {
- let mut courses = Vec::new();
- let mut seen = std::collections::HashSet::new();
-
- for item in items {
- let slug = item
- .get("slug")
- .or_else(|| item.get("course_slug"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- if slug.is_empty() || seen.contains(&slug) {
- continue;
- }
- seen.insert(slug.clone());
-
- let mut name = item
- .get("name")
- .or_else(|| item.get("course_name"))
- .and_then(|v| v.as_str())
- .unwrap_or(&slug)
- .to_string();
-
- let mut image_url = extract_image(item);
-
- if name == slug || image_url.is_none() {
- if let Ok(detail) = fetch_course_detail(session, &slug).await {
- if let Some(co) = detail.get("course").and_then(|v| v.as_object()) {
- let co_val = serde_json::Value::Object(co.clone());
- if let Some(n) = co_val.get("name").and_then(|v| v.as_str()) {
- if !n.is_empty() {
- name = n.to_string();
- }
- }
- if image_url.is_none() {
- image_url = extract_image(&co_val);
- }
- } else {
- if let Some(n) = detail.get("name").and_then(|v| v.as_str()) {
- if !n.is_empty() && name == slug {
- name = n.to_string();
- }
- }
- if image_url.is_none() {
- image_url = extract_image(&detail);
- }
- }
- }
- }
-
- courses.push(ThinkificCourse {
- id: slug.clone(),
- name,
- slug,
- image_url,
- });
- }
-
- courses
-}
-
-fn extract_image(obj: &serde_json::Value) -> Option<String> {
- for field in &[
- "logo",
- "course_card_image_url",
- "card_image_url",
- "banner_image_url",
- "image_url",
- "thumbnail_url",
- "cover_image_url",
- "image",
- ] {
- if let Some(v) = obj.get(*field).and_then(|v| v.as_str()) {
- if !v.is_empty() {
- return Some(v.to_string());
- }
- }
- }
- None
-}
-
-async fn fetch_course_detail(
- session: &ThinkificSession,
- slug: &str,
-) -> anyhow::Result<serde_json::Value> {
- let url = format!(
- "{}/api/course_player/v2/courses/{}",
- session.site_url, slug
- );
- let resp = session.client.get(&url).send().await?;
- if !resp.status().is_success() {
- return Err(anyhow!("HTTP {}", resp.status()));
- }
- let body: serde_json::Value = resp.json().await?;
- Ok(body)
-}
-
-async fn scrape_enrollments(
- session: &ThinkificSession,
-) -> anyhow::Result<Vec<ThinkificCourse>> {
- let url = format!("{}/enrollments", session.site_url);
- let resp = session.client.get(&url).send().await?;
- if !resp.status().is_success() {
- return Ok(Vec::new());
- }
-
- let html = resp.text().await?;
- let slug_re = Regex::new(r#"href=["']/?courses/(?:take/|enrolled/|enroll/)?([a-zA-Z][a-zA-Z0-9_-]{2,})["']"#)?;
-
- let skip_set: std::collections::HashSet<&str> = [
- "take", "new", "edit", "enroll", "preview", "sign_in", "sign_up",
- "enrolled", "progress", "admin", "users", "bundle", "checkout",
- "cart", "payment",
- ]
- .into();
-
- let mut courses = Vec::new();
- let mut seen = std::collections::HashSet::new();
-
- for cap in slug_re.captures_iter(&html) {
- let slug = &cap[1];
- let lower = slug.to_lowercase();
- if seen.contains(&lower) || skip_set.contains(lower.as_str()) {
- continue;
- }
- seen.insert(lower);
-
- let mut name = slug.to_string();
- let mut image_url = None;
-
- if let Ok(detail) = fetch_course_detail(session, slug).await {
- if let Some(co) = detail.get("course").and_then(|v| v.as_object()) {
- let co_val = serde_json::Value::Object(co.clone());
- if let Some(n) = co_val.get("name").and_then(|v| v.as_str()) {
- if !n.is_empty() {
- name = n.to_string();
- }
- }
- image_url = extract_image(&co_val);
- } else {
- if let Some(n) = detail.get("name").and_then(|v| v.as_str()) {
- if !n.is_empty() {
- name = n.to_string();
- }
- }
- image_url = extract_image(&detail);
- }
- }
-
- courses.push(ThinkificCourse {
- id: slug.to_string(),
- name,
- slug: slug.to_string(),
- image_url,
- });
- }
-
- Ok(courses)
-}
-
-pub async fn get_course_content(
- session: &ThinkificSession,
- slug: &str,
-) -> anyhow::Result<Vec<ThinkificModule>> {
- let data = fetch_course_detail(session, slug).await?;
-
- let chapters = data
- .get("chapters")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let contents = data
- .get("contents")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut ch_map: std::collections::HashMap<i64, (String, i64)> = std::collections::HashMap::new();
- for (i, ch) in chapters.iter().enumerate() {
- let id = ch.get("id").and_then(|v| v.as_i64()).unwrap_or(0);
- let name = ch
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("Chapter")
- .to_string();
- let pos = ch
- .get("position")
- .and_then(|v| v.as_i64())
- .unwrap_or(i as i64 + 1);
- ch_map.insert(id, (name, pos));
- }
-
- let mut modules_map: std::collections::HashMap<i64, ThinkificModule> =
- std::collections::HashMap::new();
-
- for (i, content) in contents.iter().enumerate() {
- let ch_id = content.get("chapter_id").and_then(|v| v.as_i64()).unwrap_or(0);
- let (ch_name, ch_order) = ch_map
- .get(&ch_id)
- .cloned()
- .unwrap_or(("Extras".to_string(), 999));
-
- let contentable_id = content
- .get("contentable_id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let contentable_type = content
- .get("contentable_type")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson_name = content
- .get("name")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lesson = ThinkificLesson {
- id: format!("{}", contentable_id),
- name: if lesson_name.is_empty() {
- format!("Lesson {}", i + 1)
- } else {
- lesson_name
- },
- order: i as i64,
- contentable_type,
- contentable_id,
- };
-
- modules_map
- .entry(ch_id)
- .or_insert_with(|| ThinkificModule {
- id: format!("{}", ch_id),
- name: ch_name,
- order: ch_order,
- lessons: Vec::new(),
- })
- .lessons
- .push(lesson);
- }
-
- let mut modules: Vec<ThinkificModule> = modules_map.into_values().collect();
- modules.sort_by_key(|m| m.order);
- for m in &mut modules {
- m.lessons.sort_by_key(|l| l.order);
- }
-
- Ok(modules)
-}
-
-pub async fn get_lesson_detail(
- session: &ThinkificSession,
- lesson: &ThinkificLesson,
-) -> anyhow::Result<ThinkificLessonDetail> {
- let lesson_id = lesson.contentable_id;
-
- match lesson.contentable_type.as_str() {
- "Download" => {
- let files = fetch_download_files(session, lesson_id).await?;
- Ok(ThinkificLessonDetail {
- id: lesson.id.clone(),
- name: lesson.name.clone(),
- video_url: None,
- html_text: None,
- files,
- })
- }
- "HtmlItem" => {
- let html = fetch_html_item(session, lesson_id).await?;
- Ok(ThinkificLessonDetail {
- id: lesson.id.clone(),
- name: lesson.name.clone(),
- video_url: None,
- html_text: Some(html),
- files: Vec::new(),
- })
- }
- _ => {
- let url = format!(
- "{}/api/course_player/v2/lessons/{}",
- session.site_url, lesson_id
- );
- let resp = session.client.get(&url).send().await?;
- if !resp.status().is_success() {
- return Ok(ThinkificLessonDetail {
- id: lesson.id.clone(),
- name: lesson.name.clone(),
- video_url: None,
- html_text: None,
- files: Vec::new(),
- });
- }
-
- let body: serde_json::Value = resp.json().await?;
- let lesson_obj = body.get("lesson").unwrap_or(&body);
-
- let video_url = lesson_obj
- .get("video_url")
- .or_else(|| lesson_obj.get("video_embed_url"))
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let html_text = lesson_obj
- .get("html_text")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let files = body
- .get("download_files")
- .and_then(|v| v.as_array())
- .map(|arr| {
- arr.iter()
- .filter_map(|f| {
- let dl_url = f.get("download_url").and_then(|v| v.as_str())?;
- let fname = f
- .get("file_name")
- .or_else(|| f.get("label"))
- .and_then(|v| v.as_str())
- .unwrap_or("attachment")
- .to_string();
- Some(ThinkificFile {
- name: fname,
- url: dl_url.to_string(),
- })
- })
- .collect()
- })
- .unwrap_or_default();
-
- Ok(ThinkificLessonDetail {
- id: lesson.id.clone(),
- name: lesson.name.clone(),
- video_url,
- html_text,
- files,
- })
- }
- }
-}
-
-async fn fetch_download_files(
- session: &ThinkificSession,
- lesson_id: i64,
-) -> anyhow::Result<Vec<ThinkificFile>> {
- let url = format!(
- "{}/api/course_player/v2/downloads/{}",
- session.site_url, lesson_id
- );
-
- let resp = session.client.get(&url).send().await;
- let body: serde_json::Value = match resp {
- Ok(r) if r.status().is_success() => r.json().await?,
- _ => {
- let fallback = format!(
- "{}/api/course_player/v2/lessons/{}",
- session.site_url, lesson_id
- );
- let r = session.client.get(&fallback).send().await?;
- if !r.status().is_success() {
- return Ok(Vec::new());
- }
- r.json().await?
- }
- };
-
- let files = body
- .get("download_files")
- .and_then(|v| v.as_array())
- .map(|arr| {
- arr.iter()
- .filter_map(|f| {
- let dl_url = f.get("download_url").and_then(|v| v.as_str())?;
- let fname = f
- .get("file_name")
- .or_else(|| f.get("label"))
- .and_then(|v| v.as_str())
- .unwrap_or("file")
- .to_string();
- Some(ThinkificFile {
- name: fname,
- url: dl_url.to_string(),
- })
- })
- .collect()
- })
- .unwrap_or_default();
-
- Ok(files)
-}
-
-async fn fetch_html_item(
- session: &ThinkificSession,
- lesson_id: i64,
-) -> anyhow::Result<String> {
- let url = format!(
- "{}/api/course_player/v2/html_items/{}",
- session.site_url, lesson_id
- );
-
- let resp = session.client.get(&url).send().await?;
- if !resp.status().is_success() {
- return Ok(String::new());
- }
-
- let body: serde_json::Value = resp.json().await?;
- let item = body.get("html_item").unwrap_or(&body);
-
- let content = item
- .get("html_text")
- .or_else(|| item.get("body"))
- .or_else(|| item.get("content"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- Ok(content)
-}
-
-pub fn resolve_video_url(page_html: &str, fallback_url: &str) -> String {
- let player_re = Regex::new(r"player\.thinkific\.com/embed/([a-f0-9-]+)").ok();
- let mp4_re = Regex::new(r#"https?://[^\s"']+\.mp4"#).ok();
- let wistia_re = Regex::new(r#"(?i)(?:wistia_async_|fast\.wistia\.com/embed/(?:medias|iframe)/|hashedId["']?\s*[:=]\s*["'])([a-z0-9]+)"#).ok();
- let cdn_re = Regex::new(r#"(https://(?:d2p6ecj15pyavq|d1fto35gcfffzn)\.cloudfront\.net/[^\s"']+\.(?:mp4|m3u8)|https://player-api\.thinkific\.com/(?:hls|api/video)/[^\s"']+)"#).ok();
-
- if let Some(re) = wistia_re {
- if let Some(cap) = re.captures(page_html) {
- return format!("https://fast.wistia.com/embed/iframe/{}", &cap[1]);
- }
- }
-
- if let Some(re) = cdn_re {
- if let Some(cap) = re.captures(page_html) {
- return cap[1].to_string();
- }
- }
-
- if let Some(re) = player_re {
- if let Some(cap) = re.captures(page_html) {
- return format!("https://player.thinkific.com/embed/{}", &cap[1]);
- }
- }
-
- if let Some(re) = mp4_re {
- if let Some(m) = re.find(page_html) {
- return m.as_str().to_string();
- }
- }
-
- fallback_url.to_string()
-}
-
-pub async fn save_session(session: &ThinkificSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- cookies: session.cookies.clone(),
- site_url: session.site_url.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[thinkific] session saved for {}", session.site_url);
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<ThinkificSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.cookies, &saved.site_url)?;
-
- tracing::info!("[thinkific] session loaded for {}", saved.site_url);
-
- Ok(Some(ThinkificSession {
- cookies: saved.cookies,
- site_url: saved.site_url,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/thinkific/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/thinkific/downloader.rs
deleted file mode 100644
index 5aa0297f..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::filename;
-
-use super::api::{self, ThinkificCourse, ThinkificSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct ThinkificCourseDownloadProgress {
- pub course_id: String,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &ThinkificSession,
- course: &ThinkificCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let modules = api::get_course_content(session, &course.slug).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- tracing::info!("[thinkific] course already complete, skipping");
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &ThinkificCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let safe_name = format!("{}. {}", li + 1, lesson_name);
-
- let detail = match api::get_lesson_detail(session, lesson).await {
- Ok(d) => d,
- Err(e) => {
- tracing::error!(
- "[thinkific] Failed to get lesson detail '{}': {}. Continuing...",
- lesson.name,
- e
- );
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &ThinkificCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- };
-
- if let Some(ref video_url) = detail.video_url {
- if !video_url.is_empty() {
- let video_path = format!("{}/{}.mp4", mod_dir, safe_name);
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[thinkific] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &ThinkificCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- let resolved_url = resolve_video_url_with_fetch(session, video_url).await;
-
- match download_with_ytdlp(&resolved_url, &mod_dir, &session.cookies, &session.site_url, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[thinkific] yt-dlp download failed for '{}': {}",
- lesson.name,
- e
- );
- }
- }
- }
- }
-
- if let Some(ref html) = detail.html_text {
- if !html.trim().is_empty() {
- let html_path = format!("{}/{}.html", mod_dir, safe_name);
- if !tokio::fs::try_exists(&html_path).await.unwrap_or(false) {
- let doc = format!(
- "<!DOCTYPE html>\n<html><head><meta charset=\"UTF-8\"><title>{}</title>\n<style>body {{ font-family: system-ui, sans-serif; max-width: 800px; margin: 40px auto; padding: 0 20px; line-height: 1.6; }} img {{ max-width: 100%; }}</style>\n</head><body>\n<h1>{}</h1>\n{}\n</body></html>",
- lesson.name, lesson.name, html
- );
- let _ = tokio::fs::write(&html_path, doc).await;
- }
- }
- }
-
- for file in &detail.files {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let file_name = filename::sanitize_path_component(&file.name);
- let file_path = format!("{}/{}", mod_dir, file_name);
-
- if tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&file_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match download_file_direct(&session.client, &file.url, &file_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[thinkific] File download failed for '{}': {}",
- file.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &ThinkificCourseDownloadProgress {
- course_id: course.id.clone(),
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn resolve_video_url_with_fetch(session: &ThinkificSession, video_url: &str) -> String {
- let page_resp = session
- .client
- .get(video_url)
- .header("Accept", "text/html,*/*")
- .send()
- .await;
-
- if let Ok(resp) = page_resp {
- if let Ok(text) = resp.text().await {
- return api::resolve_video_url(&text, video_url);
- }
- }
-
- video_url.to_string()
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cookies: &str,
- site_url: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let cookie_header = format!("Cookie:{}", cookies);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some(&format!("{}/", site_url)),
- cancel_token.clone(),
- None,
- 8,
- false,
- &["--add-headers".to_string(), cookie_header],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/thinkific/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/thinkific/mod.rs
deleted file mode 100644
index 218b9370..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct ThinkificDownloader;
-
-impl Default for ThinkificDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl ThinkificDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for ThinkificDownloader {
- fn name(&self) -> &str {
- "thinkific"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "thinkific.com" || host.ends_with(".thinkific.com");
- }
- }
- false
- }
-
- async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Thinkific Course".to_string(),
- author: String::new(),
- platform: "thinkific".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![VideoQuality {
- label: "course".to_string(),
- width: 0,
- height: 0,
- url: url.to_string(),
- format: "course".to_string(),
- }],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download Thinkific courses"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/udemy/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/udemy/api.rs
deleted file mode 100644
index a022ff5b..00000000
--- a/src-tauri/omniget-plugin-courses/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/omniget-plugin-courses/src/platforms/udemy/auth.rs b/src-tauri/omniget-plugin-courses/src/platforms/udemy/auth.rs
deleted file mode 100644
index 7bfebb29..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent("okhttp/4.12.0 UdemyAndroid 9.51.2(594) (phone)")
- .default_headers(default_headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(300))
- .build()?;
-
- Ok(client)
-}
-
-fn build_enterprise_client(saved: &SavedSession) -> anyhow::Result<reqwest::Client> {
- let mut default_headers = HeaderMap::new();
-
- let cookie_header = saved
- .cookies
- .iter()
- .map(|(name, value)| format!("{}={}", name, value))
- .collect::<Vec<_>>()
- .join("; ");
-
- if !cookie_header.is_empty() {
- default_headers.insert("Cookie", HeaderValue::from_str(&cookie_header)?);
- }
-
- if let Some(csrf) = saved.cookies.iter().find(|(n, _)| n == "csrftoken") {
- default_headers.insert("X-CSRFToken", HeaderValue::from_str(&csrf.1)?);
- }
-
- let origin = format!("https://{}.udemy.com", saved.portal_name);
- default_headers.insert("Referer", HeaderValue::from_str(&format!("{}/", origin))?);
- default_headers.insert("Origin", HeaderValue::from_str(&origin)?);
- default_headers.insert(
- "x-requested-with",
- HeaderValue::from_static("XMLHttpRequest"),
- );
- default_headers.insert(
- "Accept",
- HeaderValue::from_static("application/json, text/plain, */*"),
- );
- default_headers.insert(
- "accept-language",
- HeaderValue::from_static("en_US"),
- );
-
- let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
- .default_headers(default_headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(300))
- .build()?;
-
- Ok(client)
-}
-
-pub async fn save_session(session: &UdemySession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- access_token: session.access_token.clone(),
- email: session.email.clone(),
- cookies: session.cookies.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- portal_name: session.portal_name.clone(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[udemy] session saved for {}, {} cookies", session.email, session.cookies.len());
- Ok(())
-}
-
-pub async fn load_saved_session() -> anyhow::Result<UdemySession> {
- let path = session_file_path()?;
- let json = tokio::fs::read_to_string(&path).await?;
- let saved: SavedSession = serde_json::from_str(&json)?;
-
- tracing::info!("[udemy] session loaded for {}, {} cookies", saved.email, saved.cookies.len());
-
- let client = build_client_from_saved(&saved)?;
-
- Ok(UdemySession {
- access_token: saved.access_token,
- email: saved.email,
- cookies: saved.cookies,
- client,
- portal_name: saved.portal_name,
- })
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if path.exists() {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
-
-#[cfg(windows)]
-const COOKIE_URIS: &[&str] = &[
- "https://www.udemy.com",
- "https://udemy.com",
-];
-
-#[cfg(windows)]
-async fn extract_webview_cookies_for_uri(
- window: &tauri::WebviewWindow,
- uri: &str,
-) -> anyhow::Result<Vec<(String, String)>> {
- use webview2_com::GetCookiesCompletedHandler;
- use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2_2;
- use windows_core::{Interface, HSTRING, PCWSTR, PWSTR};
-
- let (tx, rx) = tokio::sync::oneshot::channel::<Vec<(String, String)>>();
- let uri_owned = uri.to_string();
-
- window
- .with_webview(move |webview| {
- unsafe {
- let core = webview.controller().CoreWebView2().unwrap();
- let core2: ICoreWebView2_2 = core.cast().unwrap();
- let manager = core2.CookieManager().unwrap();
- let uri_hstring = HSTRING::from(uri_owned);
-
- let _ = manager.GetCookies(
- PCWSTR::from_raw(uri_hstring.as_ptr()),
- &GetCookiesCompletedHandler::create(Box::new(
- move |error_code, cookie_list| {
- let mut result = Vec::new();
- if error_code.is_ok() {
- if let Some(list) = cookie_list {
- let mut count = 0u32;
- list.Count(&mut count)?;
- for i in 0..count {
- let cookie = list.GetValueAtIndex(i)?;
- let mut name = PWSTR::null();
- let mut value = PWSTR::null();
- cookie.Name(&mut name)?;
- cookie.Value(&mut value)?;
- result.push((
- webview2_com::take_pwstr(name),
- webview2_com::take_pwstr(value),
- ));
- }
- }
- }
- let _ = tx.send(result);
- Ok(())
- },
- )),
- );
- }
- })
- .map_err(|e| anyhow!("{}", e))?;
-
- let cookies = tokio::time::timeout(Duration::from_secs(10), rx)
- .await
- .map_err(|_| anyhow!("Timeout getting cookies from WebView"))?
- .map_err(|_| anyhow!("Cookie channel closed"))?;
-
- Ok(cookies)
-}
-
-#[cfg(windows)]
-async fn extract_webview_cookies(
- window: &tauri::WebviewWindow,
-) -> anyhow::Result<Vec<(String, String)>> {
- let mut seen = HashMap::<String, String>::new();
-
- for uri in COOKIE_URIS {
- match extract_webview_cookies_for_uri(window, uri).await {
- Ok(cookies) => {
- let names: Vec<&str> = cookies.iter().map(|(n, _)| n.as_str()).collect();
- tracing::info!("[udemy] cookies {} → {} cookies: {:?}", uri, cookies.len(), names);
- for (name, value) in cookies {
- seen.insert(name, value);
- }
- }
- Err(e) => {
- tracing::warn!("[udemy] cookies {} → error: {}", uri, e);
- }
- }
- }
-
- let cookies: Vec<(String, String)> = seen.into_iter().collect();
- tracing::info!("[udemy] total unique cookies: {}", cookies.len());
-
- Ok(cookies)
-}
-
-#[allow(dead_code)]
-fn parse_document_cookie(s: &str) -> Vec<(String, String)> {
- s.split(';')
- .filter_map(|pair| {
- let pair = pair.trim();
- if pair.is_empty() {
- return None;
- }
- let (name, value) = pair.split_once('=')?;
- Some((name.trim().to_string(), value.trim().to_string()))
- })
- .collect()
-}
-
-#[cfg(not(windows))]
-async fn extract_webview_cookies_js(
- window: &tauri::WebviewWindow,
- cookie_data: &Arc<std::sync::Mutex<Option<String>>>,
-) -> anyhow::Result<Vec<(String, String)>> {
- *cookie_data.lock().unwrap() = None;
-
- window
- .eval(
- "window.location.href = 'https://omniget-udemy-cookie-extract.local/?cookies=' + encodeURIComponent(document.cookie)",
- )
- .map_err(|e| anyhow!("JS eval failed: {}", e))?;
-
- let start = std::time::Instant::now();
- let timeout = Duration::from_secs(5);
- loop {
- if let Some(cookie_str) = cookie_data.lock().unwrap().take() {
- let cookies = parse_document_cookie(&cookie_str);
- let names: Vec<&str> = cookies.iter().map(|(n, _)| n.as_str()).collect();
- tracing::info!("[udemy] document.cookie → {} cookies: {:?}", cookies.len(), names);
- return Ok(cookies);
- }
- if start.elapsed() > timeout {
- tracing::warn!("[udemy] timeout waiting for document.cookie response");
- return Ok(Vec::new());
- }
- tokio::time::sleep(Duration::from_millis(50)).await;
- }
-}
-
-fn strip_cookie_quotes(value: &str) -> &str {
- let v = value.trim();
- if v.starts_with('"') && v.ends_with('"') && v.len() >= 2 {
- &v[1..v.len() - 1]
- } else {
- v
- }
-}
-
-pub async fn authenticate(
- app: &tauri::AppHandle,
- email: &str,
-) -> anyhow::Result<UdemySession> {
- use tauri::Emitter;
-
- let post_login_detected = Arc::new(std::sync::atomic::AtomicBool::new(false));
- let post_login_flag = post_login_detected.clone();
-
- #[cfg(not(windows))]
- let cookie_data = Arc::new(std::sync::Mutex::new(Option::<String>::None));
- #[cfg(not(windows))]
- let cookie_data_nav = cookie_data.clone();
-
- let email_json = serde_json::to_string(email)?;
-
- let init_script = format!(
- r#"(function() {{
- if (window.location.hostname !== 'www.udemy.com') return;
- var filled = false;
- function fillEmail() {{
- if (filled) return;
- var input = document.querySelector('input[name="email"], input[name="Email"], input[type="email"]');
- if (!input) return;
- filled = true;
- var s = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
- s.call(input, {email_json});
- input.dispatchEvent(new Event('input', {{ bubbles: true }}));
- input.dispatchEvent(new Event('change', {{ bubbles: true }}));
- setTimeout(function() {{
- var btn = document.querySelector('button[type="submit"], form button');
- if (btn) btn.click();
- }}, 500);
- }}
- setTimeout(fillEmail, 1500);
- setInterval(fillEmail, 500);
- }})()"#
- );
-
- if let Some(existing) = app.get_webview_window("udemy-login") {
- let _ = existing.close();
- tokio::time::sleep(Duration::from_millis(500)).await;
- }
-
- let login_url = "https://www.udemy.com/join/passwordless-auth/?locale=en_US&next=https%3A%2F%2Fwww.udemy.com%2F&response_type=html&action=login";
-
- let login_window = tauri::WebviewWindowBuilder::new(
- app,
- "udemy-login",
- tauri::WebviewUrl::External(login_url.parse().unwrap()),
- )
- .title("Udemy Login")
- .inner_size(500.0, 700.0)
- .initialization_script(&init_script)
- .on_navigation(move |url| {
- let host = url.host_str().unwrap_or("");
- let url_str = url.as_str();
-
- tracing::info!("[udemy] navigation → {} (host={})", url_str, host);
-
- if (host == "www.udemy.com" || host == "udemy.com")
- && !url_str.contains("/join/")
- && !url_str.contains("/passwordless-auth/")
- {
- post_login_flag.store(true, std::sync::atomic::Ordering::Relaxed);
- }
-
- #[cfg(not(windows))]
- {
- if host == "omniget-udemy-cookie-extract.local" {
- for (key, value) in url.query_pairs() {
- if key == "cookies" {
- *cookie_data_nav.lock().unwrap() = Some(value.to_string());
- break;
- }
- }
- return false;
- }
- }
-
- true
- })
- .build()
- .map_err(|e| anyhow!("Failed to create login window: {}", e))?;
-
- let _ = app.emit("udemy-auth-waiting-code", ());
-
- let start = std::time::Instant::now();
- let timeout = Duration::from_secs(180);
- let poll_start_delay = Duration::from_secs(5);
- let mut last_log_secs: u64 = 0;
-
- loop {
- if start.elapsed() > timeout {
- let _ = login_window.close();
- return Err(anyhow!("Timeout waiting for login. Check your email for the verification code."));
- }
-
- let nav_detected = post_login_detected.load(std::sync::atomic::Ordering::Relaxed);
- let should_poll = nav_detected || start.elapsed() > poll_start_delay;
-
- if should_poll {
- #[cfg(windows)]
- let cookies = extract_webview_cookies(&login_window).await?;
- #[cfg(not(windows))]
- let cookies = extract_webview_cookies_js(&login_window, &cookie_data).await?;
-
- let has_access_token = cookies.iter().any(|(name, _)| name == "access_token");
- let has_logged_in = cookies
- .iter()
- .any(|(name, value)| name == "ud_cache_logged_in" && value == "1");
-
- if has_access_token || has_logged_in {
- tracing::info!(
- "[udemy] login detected after {:.1}s (access_token={}, ud_cache_logged_in={}, nav_detected={})",
- start.elapsed().as_secs_f64(),
- has_access_token,
- has_logged_in,
- nav_detected
- );
- let _ = login_window.close();
-
- let access_token = cookies
- .iter()
- .find(|(name, _)| name == "access_token")
- .map(|(_, value)| strip_cookie_quotes(value).to_string())
- .unwrap_or_default();
-
- let saved = SavedSession {
- access_token: access_token.clone(),
- email: email.to_string(),
- cookies: cookies.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- portal_name: "www".into(),
- };
-
- let client = build_client_from_saved(&saved)?;
-
- return Ok(UdemySession {
- access_token,
- email: email.to_string(),
- client,
- cookies,
- portal_name: "www".into(),
- });
- }
-
- let elapsed_secs = start.elapsed().as_secs();
- if elapsed_secs >= last_log_secs + 5 {
- last_log_secs = elapsed_secs;
- let cookie_names: Vec<&str> =
- cookies.iter().map(|(n, _)| n.as_str()).collect();
- tracing::info!(
- "[udemy] polling at {}s, {} cookies: {:?}",
- elapsed_secs,
- cookies.len(),
- cookie_names
- );
- }
- }
-
- let sleep_ms = if nav_detected { 500 } else { 2000 };
- tokio::time::sleep(Duration::from_millis(sleep_ms)).await;
- }
-}
-
-pub async fn authenticate_with_cookie_json(cookie_json_str: &str) -> anyhow::Result<UdemySession> {
- #[derive(Deserialize)]
- struct CookieEntry {
- name: String,
- value: String,
- #[allow(dead_code)]
- domain: Option<String>,
- }
-
- #[derive(Deserialize)]
- struct CookieExport {
- url: Option<String>,
- cookies: Vec<CookieEntry>,
- }
-
- #[derive(Deserialize)]
- #[serde(untagged)]
- enum CookieInput {
- Export(CookieExport),
- CookieArray(Vec<CookieEntry>),
- }
-
- let input: CookieInput = serde_json::from_str(cookie_json_str).map_err(|e| anyhow!("Invalid cookie JSON: {}", e))?;
-
- let export = match input {
- CookieInput::Export(export) => export,
- CookieInput::CookieArray(cookies) => CookieExport { url: None, cookies },
- };
-
- if export.cookies.is_empty() {
- return Err(anyhow!("No cookies provided"));
- }
-
- // Detect portal from URL or cookie domains
- let portal_name = if let Some(ref url) = export.url {
- detect_portal_from_url(url)
- } else {
- export
- .cookies
- .iter()
- .filter_map(|c| c.domain.as_deref())
- .find_map(|d| {
- let d = d.trim_start_matches('.');
- d.strip_suffix(".udemy.com")
- .map(|sub| sub.to_string())
- })
- .unwrap_or_else(|| "www".into())
- };
-
- let cookies: Vec<(String, String)> = export
- .cookies
- .iter()
- .map(|c| (c.name.clone(), c.value.clone()))
- .collect();
-
- let access_token = cookies
- .iter()
- .find(|(name, _)| name == "access_token")
- .map(|(_, value)| strip_cookie_quotes(value).to_string())
- .unwrap_or_default();
-
- // Try to extract email from ud_user_jwt cookie (base64url-encoded JWT)
- let email = cookies
- .iter()
- .find(|(name, _)| name == "ud_user_jwt")
- .and_then(|(_, value)| decode_jwt_email(value))
- .unwrap_or_else(|| format!("enterprise@{}.udemy.com", portal_name));
-
- let saved = SavedSession {
- access_token: access_token.clone(),
- email: email.clone(),
- cookies: cookies.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- portal_name: portal_name.clone(),
- };
-
- let client = build_client_from_saved(&saved)?;
-
- tracing::info!(
- "[udemy] cookie login for portal={}, email={}, {} cookies",
- portal_name,
- email,
- cookies.len()
- );
-
- Ok(UdemySession {
- access_token,
- email,
- client,
- cookies,
- portal_name,
- })
-}
-
-fn detect_portal_from_url(url: &str) -> String {
- url::Url::parse(url)
- .ok()
- .and_then(|u| u.host_str().map(|h| h.to_string()))
- .and_then(|host| {
- host.strip_suffix(".udemy.com")
- .map(|sub| sub.to_string())
- })
- .unwrap_or_else(|| "www".into())
-}
-
-fn decode_jwt_email(jwt: &str) -> Option<String> {
- use base64::Engine;
-
- // JWT has 3 parts: header.payload.signature
- let parts: Vec<&str> = jwt.split('.').collect();
- if parts.len() < 2 {
- return None;
- }
-
- let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
- .decode(parts[1])
- .or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(parts[1]))
- .ok()?;
-
- let claims: serde_json::Value = serde_json::from_slice(&payload).ok()?;
- claims
- .get("email")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/udemy/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/udemy/downloader.rs
deleted file mode 100644
index 709909e6..00000000
--- a/src-tauri/omniget-plugin-courses/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 omniget_core::core::media_processor::MediaProcessor;
-
-use super::api::{self, UdemyCourse};
-use super::auth::UdemySession;
-
-const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0";
-const MAX_FILENAME_BYTES: usize = 200;
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct UdemyCourseDownloadProgress {
- pub course_id: u64,
- pub course_name: String,
- pub percent: f64,
- pub current_chapter: String,
- pub current_lecture: String,
- pub downloaded_bytes: u64,
- pub total_lectures: u32,
- pub completed_lectures: u32,
-}
-
-pub struct UdemyDownloader {
- session: Arc<Mutex<Option<UdemySession>>>,
- hls_client: reqwest::Client,
- max_concurrent_segments: u32,
- max_retries: u32,
-}
-
-fn safe_filename(name: &str) -> String {
- let sanitized = sanitize_filename::sanitize(name);
- if sanitized.len() <= MAX_FILENAME_BYTES {
- return sanitized;
- }
- let mut end = MAX_FILENAME_BYTES;
- while !sanitized.is_char_boundary(end) && end > 0 {
- end -= 1;
- }
- sanitized[..end].to_string()
-}
-
-impl UdemyDownloader {
- pub fn new(
- session: Arc<Mutex<Option<UdemySession>>>,
- max_concurrent_segments: u32,
- max_retries: u32,
- ) -> Self {
- let hls_client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(300))
- .build()
- .unwrap_or_default();
-
- Self {
- session,
- hls_client,
- max_concurrent_segments,
- max_retries,
- }
- }
-
- pub async fn download_full_course(
- &self,
- course: &UdemyCourse,
- output_dir: &str,
- curriculum: api::UdemyCurriculum,
- progress_tx: mpsc::Sender<UdemyCourseDownloadProgress>,
- cancel_token: CancellationToken,
- ) -> anyhow::Result<u32> {
- let session = {
- let guard = self.session.lock().await;
- guard.clone().ok_or_else(|| anyhow!("Not authenticated"))?
- };
-
- let _ = progress_tx.send(UdemyCourseDownloadProgress {
- course_id: course.id,
- course_name: course.title.clone(),
- percent: 0.0,
- current_chapter: String::new(),
- current_lecture: String::new(),
- downloaded_bytes: 0,
- total_lectures: curriculum.total_lectures,
- completed_lectures: 0,
- }).await;
-
- let course_dir_name = safe_filename(&course.title);
- let course_dir = PathBuf::from(output_dir).join(&course_dir_name);
- tokio::fs::create_dir_all(&course_dir).await?;
-
- let total_lectures = curriculum.total_lectures;
- let mut completed_lectures: u32 = 0;
- let mut downloaded_bytes: u64 = 0;
- let mut drm_skipped: u32 = 0;
-
- for (ch_idx, chapter) in curriculum.chapters.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled"));
- }
-
- let chapter_dir_name = format!(
- "{:02} - {}",
- ch_idx + 1,
- safe_filename(&chapter.title)
- );
- let chapter_dir = course_dir.join(&chapter_dir_name);
- tokio::fs::create_dir_all(&chapter_dir).await?;
-
- for (lec_idx, lecture) in chapter.lectures.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled"));
- }
-
- let lecture_num = (lec_idx + 1) as u32;
-
- let _ = progress_tx.send(UdemyCourseDownloadProgress {
- course_id: course.id,
- course_name: course.title.clone(),
- percent: if total_lectures > 0 {
- (completed_lectures as f64 / total_lectures as f64) * 100.0
- } else {
- 0.0
- },
- current_chapter: chapter.title.clone(),
- current_lecture: format!("{}/{} - {}", lecture_num, chapter.lectures.len(), lecture.title),
- downloaded_bytes,
- total_lectures,
- completed_lectures,
- }).await;
-
- let result = self.download_lecture(
- &session,
- lecture,
- &chapter_dir,
- &cancel_token,
- lecture_num,
- ).await;
-
- match result {
- Ok((b, drm)) => {
- downloaded_bytes += b;
- drm_skipped += drm;
- }
- Err(e) => {
- tracing::error!(
- "[udemy] failed to download lecture '{}': {}",
- lecture.title, e
- );
- }
- }
-
- if lecture.lecture_class == "lecture" {
- completed_lectures += 1;
- }
- }
- }
-
- let _ = progress_tx.send(UdemyCourseDownloadProgress {
- course_id: course.id,
- course_name: course.title.clone(),
- percent: 100.0,
- current_chapter: String::new(),
- current_lecture: String::new(),
- downloaded_bytes,
- total_lectures,
- completed_lectures,
- }).await;
-
- tracing::info!(
- "[udemy] course '{}' download complete: {} lectures, {} bytes, {} drm-skipped",
- course.title, completed_lectures, downloaded_bytes, drm_skipped
- );
-
- Ok(drm_skipped)
- }
-
- async fn download_lecture(
- &self,
- session: &UdemySession,
- lecture: &api::UdemyLecture,
- chapter_dir: &Path,
- cancel_token: &CancellationToken,
- lecture_num: u32,
- ) -> anyhow::Result<(u64, u32)> {
- if lecture.lecture_class == "quiz" || lecture.lecture_class == "practice" {
- tracing::info!("[udemy] skipping {}: {}", lecture.lecture_class, lecture.title);
- return Ok((0, 0));
- }
-
- let asset = match &lecture.asset {
- Some(a) => a,
- None => return Ok((0, 0)),
- };
-
- let asset_type = asset.get("asset_type")
- .or_else(|| asset.get("assetType"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_lowercase();
-
- let mut total_bytes: u64 = 0;
- let mut drm_skipped: u32 = 0;
-
- match asset_type.as_str() {
- "video" => {
- let (bytes, drm) = self.download_video_asset(
- session, asset, &lecture.title, chapter_dir, cancel_token, lecture_num
- ).await?;
- total_bytes += bytes;
- drm_skipped += drm;
- }
- "article" => {
- let body = asset.get("body").and_then(|v| v.as_str()).unwrap_or("");
- if !body.is_empty() {
- let file_name = format!(
- "{:02} - {}.html",
- lecture_num,
- safe_filename(&lecture.title)
- );
- let file_path = chapter_dir.join(&file_name);
- if !file_exists_with_content(&file_path).await {
- tokio::fs::write(&file_path, body.as_bytes()).await?;
- tracing::info!("[udemy] saved article: {}", file_name);
- }
- }
- }
- "file" | "e-book" | "presentation" | "audio" => {
- total_bytes += self.download_downloadable_asset(
- session, asset, &lecture.title, chapter_dir, lecture_num
- ).await?;
- }
- _ => {
- if !asset_type.is_empty() {
- tracing::warn!("[udemy] unknown asset type '{}' for '{}'", asset_type, lecture.title);
- }
- }
- }
-
- let captions = asset.get("captions").and_then(|v| v.as_array());
- if let Some(tracks) = captions {
- for track in tracks {
- let class = track.get("_class").and_then(|v| v.as_str()).unwrap_or("");
- if class != "caption" {
- continue;
- }
- let url = match track.get("url").and_then(|v| v.as_str()) {
- Some(u) => u,
- None => continue,
- };
- let lang = track.get("language")
- .or_else(|| track.get("srclang"))
- .or_else(|| track.get("label"))
- .and_then(|v| v.as_str())
- .unwrap_or("unknown");
-
- let ext = if url.contains(".vtt") { "vtt" } else { "srt" };
- let caption_name = format!(
- "{:02} - {}_{}.{}",
- lecture_num,
- safe_filename(&lecture.title),
- lang,
- ext
- );
- let caption_path = chapter_dir.join(&caption_name);
-
- if !file_exists_with_content(&caption_path).await {
- match download_file_simple(&session.client, url, &caption_path).await {
- Ok(b) => {
- total_bytes += b;
- tracing::info!("[udemy] saved caption: {}", caption_name);
- }
- Err(e) => {
- tracing::warn!("[udemy] failed to download caption '{}': {}", caption_name, e);
- }
- }
- }
- }
- }
-
- let supp_assets = asset.get("supplementary_assets").and_then(|v| v.as_array());
- if let Some(assets) = supp_assets {
- for supp in assets {
- total_bytes += self.download_supplementary_asset(
- session, supp, chapter_dir, lecture_num
- ).await.unwrap_or(0);
- }
- }
-
- Ok((total_bytes, drm_skipped))
- }
-
- async fn download_video_asset(
- &self,
- session: &UdemySession,
- asset: &serde_json::Value,
- title: &str,
- chapter_dir: &Path,
- cancel_token: &CancellationToken,
- lecture_num: u32,
- ) -> anyhow::Result<(u64, u32)> {
- let file_name = format!("{:02} - {}.mp4", lecture_num, safe_filename(title));
- let file_path = chapter_dir.join(&file_name);
-
- if file_exists_with_content(&file_path).await {
- tracing::info!("[udemy] skipping existing video: {}", file_name);
- return Ok((0, 0));
- }
-
- let stream_urls = asset.get("stream_urls");
- if let Some(streams) = stream_urls {
- if let Some(videos) = streams.get("Video").and_then(|v| v.as_array()) {
- match self.download_from_stream_urls(
- session, videos, &file_path, title, cancel_token
- ).await {
- Ok(bytes) => return Ok((bytes, 0)),
- Err(e) if e.to_string().contains("SAMPLE-AES") => {
- tracing::warn!("[udemy] DRM-protected (SAMPLE-AES) via stream_urls: '{}'", title);
- return Ok((0, 1));
- }
- Err(e) => return Err(e),
- }
- }
- }
-
- if let Some(sources) = asset.get("media_sources").and_then(|v| v.as_array()) {
- let result = self.download_from_media_sources(
- session, sources, &file_path, title, cancel_token
- ).await;
-
- match result {
- Ok(bytes) if bytes > 0 => return Ok((bytes, 0)),
- Ok(_) => {}
- Err(e) => {
- let is_drm = asset.get("course_is_drmed")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
- if is_drm || e.to_string().contains("SAMPLE-AES") {
- tracing::warn!("[udemy] DRM-protected video skipped: '{}'", title);
- return Ok((0, 1));
- }
- tracing::warn!("[udemy] media_sources download failed for '{}': {}", title, e);
- return Err(e);
- }
- }
-
- let is_drm = asset.get("course_is_drmed")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
-
- if is_drm {
- tracing::warn!(
- "[udemy] DRM-protected video skipped: '{}' (no downloadable sources available)",
- title
- );
- return Ok((0, 1));
- }
-
- tracing::warn!(
- "[udemy] no usable video sources in media_sources for '{}' (types: {})",
- title,
- sources.iter()
- .filter_map(|s| s.get("type").and_then(|t| t.as_str()))
- .collect::<Vec<_>>()
- .join(", ")
- );
- return Ok((0, 0));
- }
-
- tracing::warn!("[udemy] no video sources found for '{}'", title);
- Ok((0, 0))
- }
-
- async fn download_from_stream_urls(
- &self,
- session: &UdemySession,
- videos: &[serde_json::Value],
- file_path: &Path,
- title: &str,
- cancel_token: &CancellationToken,
- ) -> anyhow::Result<u64> {
- let mut sources: Vec<(&str, u32)> = Vec::new();
- for v in videos {
- let label = v.get("label").and_then(|l| l.as_str()).unwrap_or("0");
- let url = match v.get("file").and_then(|f| f.as_str()) {
- Some(u) => u,
- None => continue,
- };
- if label.to_lowercase() == "audio" {
- continue;
- }
- let height: u32 = label.parse().unwrap_or(0);
- sources.push((url, height));
- }
-
- if sources.is_empty() {
- tracing::warn!("[udemy] no valid video sources for '{}'", title);
- return Ok(0);
- }
-
- sources.sort_by(|a, b| b.1.cmp(&a.1));
- let (best_url, best_height) = sources[0];
-
- tracing::info!("[udemy] downloading '{}' at {}p", title, best_height);
-
- let url_str = best_url.to_string();
- let is_hls = url_str.contains(".m3u8");
-
- if is_hls {
- self.download_hls_and_remux(&url_str, file_path, title, cancel_token).await
- } else {
- let bytes = download_file_simple(&session.client, &url_str, file_path).await?;
- tracing::info!("[udemy] direct download complete: {} ({}p, {} bytes)", title, best_height, bytes);
- Ok(bytes)
- }
- }
-
- async fn download_from_media_sources(
- &self,
- session: &UdemySession,
- sources: &[serde_json::Value],
- file_path: &Path,
- title: &str,
- cancel_token: &CancellationToken,
- ) -> anyhow::Result<u64> {
- let mut mp4_sources: Vec<(&str, u32)> = Vec::new();
- let mut hls_source: Option<&str> = None;
-
- for source in sources {
- let src = match source.get("src").and_then(|v| v.as_str()) {
- Some(s) => s,
- None => continue,
- };
- let media_type = source.get("type").and_then(|v| v.as_str()).unwrap_or("");
-
- match media_type {
- "video/mp4" => {
- let label = source.get("label").and_then(|v| v.as_str()).unwrap_or("0");
- let height: u32 = label.parse().unwrap_or(0);
- mp4_sources.push((src, height));
- }
- "application/x-mpegURL" => {
- if hls_source.is_none() {
- hls_source = Some(src);
- }
- }
- _ => {}
- }
- }
-
- if !mp4_sources.is_empty() {
- mp4_sources.sort_by(|a, b| b.1.cmp(&a.1));
- let (best_url, best_height) = mp4_sources[0];
-
- tracing::info!("[udemy] downloading '{}' at {}p (via media_sources mp4)", title, best_height);
-
- let bytes = download_file_simple(&session.client, best_url, file_path).await?;
- tracing::info!("[udemy] direct download complete: {} ({}p, {} bytes)", title, best_height, bytes);
- return Ok(bytes);
- }
-
- if let Some(hls_url) = hls_source {
- tracing::info!("[udemy] downloading '{}' via HLS (media_sources)", title);
- return self.download_hls_and_remux(hls_url, file_path, title, cancel_token).await;
- }
-
- Ok(0)
- }
-
- async fn download_hls_and_remux(
- &self,
- hls_url: &str,
- file_path: &Path,
- title: &str,
- cancel_token: &CancellationToken,
- ) -> anyhow::Result<u64> {
- let temp_ts_path = file_path.with_extension("ts");
- let output_str_ts = temp_ts_path.to_string_lossy().to_string();
- let output_str_mp4 = file_path.to_string_lossy().to_string();
-
- let result = MediaProcessor::download_hls(
- hls_url,
- &output_str_ts,
- "https://www.udemy.com/",
- None,
- cancel_token.clone(),
- self.max_concurrent_segments,
- self.max_retries,
- Some(self.hls_client.clone()),
- ).await;
-
- match result {
- Ok(r) => {
- tracing::info!("[udemy] HLS download complete ({} bytes), remuxing...", r.file_size);
- if let Err(e) = MediaProcessor::remux(&output_str_ts, &output_str_mp4).await {
- tracing::error!("[udemy] Remuxing failed: {}", e);
- let _ = tokio::fs::remove_file(&temp_ts_path).await;
- return Err(e);
- }
- let _ = tokio::fs::remove_file(&temp_ts_path).await;
- let final_size = tokio::fs::metadata(file_path).await?.len();
- tracing::info!("[udemy] Remux complete: {}", title);
- Ok(final_size)
- }
- Err(e) => {
- let _ = tokio::fs::remove_file(&temp_ts_path).await;
- Err(e)
- }
- }
- }
-
- async fn download_downloadable_asset(
- &self,
- session: &UdemySession,
- asset: &serde_json::Value,
- title: &str,
- chapter_dir: &Path,
- lecture_num: u32,
- ) -> anyhow::Result<u64> {
- let filename = asset.get("filename")
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- let download_url = asset.get("download_urls")
- .and_then(|d| {
- if let Some(obj) = d.as_object() {
- for (_key, val) in obj {
- if let Some(arr) = val.as_array() {
- if let Some(first) = arr.first() {
- if let Some(url) = first.get("file").and_then(|f| f.as_str()) {
- return Some(url.to_string());
- }
- }
- }
- }
- }
- None
- });
-
- let url = match download_url {
- Some(u) => u,
- None => {
- tracing::warn!("[udemy] no download URL for asset '{}'", title);
- return Ok(0);
- }
- };
-
- let safe_name = if filename.is_empty() {
- format!("{:02} - {}.bin", lecture_num, safe_filename(title))
- } else {
- format!("{:02} - {}", lecture_num, safe_filename(filename))
- };
-
- let file_path = chapter_dir.join(&safe_name);
-
- if file_exists_with_content(&file_path).await {
- tracing::info!("[udemy] skipping existing file: {}", safe_name);
- return Ok(0);
- }
-
- match download_file_simple(&session.client, &url, &file_path).await {
- Ok(b) => {
- tracing::info!("[udemy] downloaded asset: {}", safe_name);
- Ok(b)
- }
- Err(e) => {
- tracing::error!("[udemy] failed to download '{}': {}", safe_name, e);
- Ok(0)
- }
- }
- }
-
- async fn download_supplementary_asset(
- &self,
- session: &UdemySession,
- supp: &serde_json::Value,
- chapter_dir: &Path,
- lecture_num: u32,
- ) -> anyhow::Result<u64> {
- let asset_type = supp.get("asset_type")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_lowercase();
- let filename = supp.get("filename")
- .and_then(|v| v.as_str())
- .unwrap_or("");
- let title = supp.get("title")
- .and_then(|v| v.as_str())
- .unwrap_or("");
-
- match asset_type.as_str() {
- "file" | "sourcecode" => {
- let download_url = supp.get("download_urls")
- .and_then(|d| {
- if let Some(obj) = d.as_object() {
- for (_key, val) in obj {
- if let Some(arr) = val.as_array() {
- if let Some(first) = arr.first() {
- return first.get("file").and_then(|f| f.as_str()).map(|s| s.to_string());
- }
- }
- }
- }
- None
- });
-
- let url = match download_url {
- Some(u) => u,
- None => return Ok(0),
- };
-
- let base = if filename.is_empty() {
- safe_filename(title)
- } else {
- safe_filename(filename)
- };
- let safe_name = format!("{:02} - {}", lecture_num, base);
- let file_path = chapter_dir.join(&safe_name);
-
- if file_exists_with_content(&file_path).await {
- return Ok(0);
- }
-
- download_file_simple(&session.client, &url, &file_path).await.ok();
- }
- "externallink" => {
- let external_url = supp.get("external_url")
- .and_then(|v| v.as_str())
- .unwrap_or("");
- if !external_url.is_empty() {
- let base = if filename.is_empty() {
- safe_filename(title)
- } else {
- safe_filename(filename)
- };
- let safe_name = format!("{:02} - {}.url", lecture_num, base);
- let file_path = chapter_dir.join(&safe_name);
- if !file_exists_with_content(&file_path).await {
- let content = format!("[InternetShortcut]\nURL={}", external_url);
- tokio::fs::write(&file_path, content.as_bytes()).await?;
- }
- }
- }
- _ => {}
- }
-
- Ok(0)
- }
-}
-
-async fn file_exists_with_content(path: &Path) -> bool {
- match tokio::fs::metadata(path).await {
- Ok(m) => m.len() > 0,
- Err(_) => false,
- }
-}
-
-async fn download_file_simple(
- client: &reqwest::Client,
- url: &str,
- output_path: &Path,
-) -> anyhow::Result<u64> {
- let part_path = output_path.with_extension(
- format!(
- "{}.part",
- output_path.extension().unwrap_or_default().to_string_lossy()
- )
- );
-
- let result = download_file_inner(client, url, output_path, &part_path).await;
- if result.is_err() {
- let _ = tokio::fs::remove_file(&part_path).await;
- }
- result
-}
-
-async fn download_file_inner(
- client: &reqwest::Client,
- url: &str,
- output_path: &Path,
- part_path: &Path,
-) -> anyhow::Result<u64> {
- let resp = client.get(url)
- .timeout(Duration::from_secs(600))
- .send()
- .await
- .map_err(|e| anyhow!("Download request failed: {}", e))?;
-
- let status = resp.status();
- if !status.is_success() {
- if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
- return Err(anyhow!("Auth error ({}), session may have expired", status));
- }
- return Err(anyhow!("Download returned status {}", status));
- }
-
- let mut total: u64 = 0;
- let mut stream = resp.bytes_stream();
- let mut file = tokio::fs::File::create(part_path).await?;
-
- while let Some(chunk) = stream.next().await {
- let chunk = chunk.map_err(|e| anyhow!("Stream error: {}", e))?;
- tokio::io::AsyncWriteExt::write_all(&mut file, &chunk).await?;
- total += chunk.len() as u64;
- }
-
- tokio::io::AsyncWriteExt::flush(&mut file).await?;
- drop(file);
-
- tokio::fs::rename(part_path, output_path).await?;
-
- Ok(total)
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/udemy/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/udemy/mod.rs
deleted file mode 100644
index 40571cdd..00000000
--- a/src-tauri/omniget-plugin-courses/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/omniget-plugin-courses/src/platforms/udemy/webview_api.rs b/src-tauri/omniget-plugin-courses/src/platforms/udemy/webview_api.rs
deleted file mode 100644
index c8261c35..00000000
--- a/src-tauri/omniget-plugin-courses/src/platforms/udemy/webview_api.rs
+++ /dev/null
@@ -1,103 +0,0 @@
-use std::sync::Arc;
-use std::time::Duration;
-
-use anyhow::anyhow;
-use tauri::Manager;
-
-pub async fn ensure_api_webview(
- app: &tauri::AppHandle,
- result_store: &Arc<std::sync::Mutex<Option<String>>>,
- portal_name: &str,
-) -> anyhow::Result<tauri::WebviewWindow> {
- if let Some(existing) = app.get_webview_window("udemy-api") {
- return Ok(existing);
- }
-
- let store = result_store.clone();
- let base_url = format!("https://{}.udemy.com/", portal_name);
-
- let window = tauri::WebviewWindowBuilder::new(
- app,
- "udemy-api",
- tauri::WebviewUrl::External(base_url.parse().unwrap()),
- )
- .visible(false)
- .inner_size(100.0, 100.0)
- .initialization_script(
- r#"window.__omniget_fetch = function(url) {
- fetch(url, {
- credentials: 'include',
- headers: {
- 'Accept': 'application/json, text/plain, */*',
- 'X-Requested-With': 'XMLHttpRequest'
- }
- })
- .then(function(r) { return r.text() })
- .then(function(text) {
- window.location.href = 'https://omniget-api-result.local/?data=' + encodeURIComponent(text);
- })
- .catch(function(err) {
- window.location.href = 'https://omniget-api-result.local/?error=' + encodeURIComponent(err.message);
- });
- };"#,
- )
- .on_navigation(move |url| {
- if url.host_str() == Some("omniget-api-result.local") {
- for (key, value) in url.query_pairs() {
- if key == "data" {
- *store.lock().unwrap() = Some(value.to_string());
- return false;
- }
- if key == "error" {
- *store.lock().unwrap() =
- Some(format!("{{\"__fetch_error\":\"{}\"}}", value));
- return false;
- }
- }
- return false;
- }
- true
- })
- .build()
- .map_err(|e| anyhow!("Failed to create API webview: {}", e))?;
-
- tokio::time::sleep(Duration::from_secs(3)).await;
-
- Ok(window)
-}
-
-pub async fn webview_get(
- window: &tauri::WebviewWindow,
- url: &str,
- result_store: &Arc<std::sync::Mutex<Option<String>>>,
-) -> anyhow::Result<String> {
- *result_store.lock().unwrap() = None;
-
- let js = format!("window.__omniget_fetch('{}')", url);
- window
- .eval(&js)
- .map_err(|e| anyhow!("eval failed: {}", e))?;
-
- let start = std::time::Instant::now();
- let timeout = Duration::from_secs(90);
- let mut poll_interval = 100u64;
- loop {
- if let Some(data) = result_store.lock().unwrap().take() {
- if let Some(err_msg) = data.strip_prefix("{\"__fetch_error\":\"") {
- let err_msg = err_msg.trim_end_matches("\"}");
- return Err(anyhow!("Fetch error: {}", err_msg));
- }
- return Ok(data);
- }
- if start.elapsed() > timeout {
- return Err(anyhow!(
- "Timeout waiting for API response ({}s). The page may be blocked by Cloudflare or the server is slow.",
- timeout.as_secs()
- ));
- }
- tokio::time::sleep(Duration::from_millis(poll_interval)).await;
- if poll_interval < 500 {
- poll_interval = (poll_interval * 3 / 2).min(500);
- }
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/voompplay/api.rs b/src-tauri/omniget-plugin-courses/src/platforms/voompplay/api.rs
deleted file mode 100644
index 8ff9fa8e..00000000
--- a/src-tauri/omniget-plugin-courses/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 = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())
- .user_agent(USER_AGENT)
- .default_headers(headers)
- .redirect(reqwest::redirect::Policy::limited(10))
- .connect_timeout(Duration::from_secs(30))
- .timeout(Duration::from_secs(120))
- .build()?;
-
- Ok(client)
-}
-
-fn session_file_path() -> anyhow::Result<PathBuf> {
- let data_dir =
- dirs::data_dir().ok_or_else(|| anyhow!("Could not find app data directory"))?;
- Ok(data_dir.join("omniget").join("voomp_session.json"))
-}
-
-pub async fn validate_token(session: &VoompSession) -> anyhow::Result<bool> {
- let resp = session
- .client
- .get("https://api.voompplay.com.br/member/me")
- .send()
- .await?;
-
- Ok(resp.status().is_success())
-}
-
-pub async fn list_courses(session: &VoompSession) -> anyhow::Result<Vec<VoompCourse>> {
- let mut all_courses = Vec::new();
- let mut page = 1u32;
-
- loop {
- let url = format!(
- "https://api.voompplay.com.br/member/me/all-courses?page={}",
- page
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "list_courses returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let last_page = body
- .get("meta")
- .and_then(|m| m.get("last_page"))
- .and_then(|v| v.as_u64())
- .unwrap_or(1) as u32;
-
- let courses_obj = body
- .get("courses")
- .and_then(|v| v.as_object());
-
- if let Some(sites) = courses_obj {
- for (_site_name, courses_val) in sites {
- let courses_arr = match courses_val.as_array() {
- Some(arr) => arr,
- None => continue,
- };
-
- for item in courses_arr {
- let has_access = item
- .get("has_access")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
-
- if !has_access {
- continue;
- }
-
- let id = item
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let lessons_count = item
- .get("lessons_count")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- all_courses.push(VoompCourse {
- id,
- name,
- lessons_count,
- });
- }
- }
- }
-
- if page >= last_page {
- break;
- }
-
- page += 1;
- }
-
- Ok(all_courses)
-}
-
-pub async fn get_modules(
- session: &VoompSession,
- course_id: i64,
-) -> anyhow::Result<Vec<VoompModule>> {
- let url = format!(
- "https://api.voompplay.com.br/course/{}/watch?data[]=course&data[]=modules",
- course_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_modules returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let modules_arr = body
- .get("modules")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut modules = Vec::new();
-
- for item in &modules_arr {
- let id = item
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let order = item
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- modules.push(VoompModule {
- id,
- name,
- order,
- lessons: Vec::new(),
- });
- }
-
- modules.sort_by_key(|m| m.order);
-
- Ok(modules)
-}
-
-pub async fn get_lessons(
- session: &VoompSession,
- course_id: i64,
- module_id: i64,
-) -> anyhow::Result<Vec<VoompLesson>> {
- let url = format!(
- "https://api.voompplay.com.br/course/{}/watch?data[]=currentModuleLessons&current_module_id={}",
- course_id, module_id
- );
-
- let resp = session.client.get(&url).send().await?;
-
- let status = resp.status();
- let body_text = resp.text().await?;
-
- if !status.is_success() {
- return Err(anyhow!(
- "get_lessons returned status {}: {}",
- status,
- &body_text[..body_text.len().min(300)]
- ));
- }
-
- let body: serde_json::Value = serde_json::from_str(&body_text)?;
-
- let lessons_arr = body
- .get("currentModuleLessons")
- .and_then(|v| v.as_array())
- .cloned()
- .unwrap_or_default();
-
- let mut lessons = Vec::new();
-
- for item in &lessons_arr {
- let id = item
- .get("id")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let name = item
- .get("title")
- .or_else(|| item.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
-
- let order = item
- .get("order")
- .and_then(|v| v.as_i64())
- .unwrap_or(0);
-
- let media_type = item
- .get("mediaType")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let source = item
- .get("source")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let content = item
- .get("content")
- .and_then(|v| v.as_str())
- .map(String::from);
-
- let duration = item
- .get("duration")
- .and_then(|v| v.as_f64());
-
- let attachments = item
- .get("attachments")
- .and_then(|v| v.as_array())
- .map(|arr| {
- arr.iter()
- .filter_map(|a| {
- let url = a
- .get("cdn_url")
- .or_else(|| a.get("path"))
- .and_then(|v| v.as_str())?
- .to_string();
-
- let att_name = a
- .get("title")
- .or_else(|| a.get("name"))
- .and_then(|v| v.as_str())
- .unwrap_or("attachment")
- .to_string();
-
- let size = a
- .get("size")
- .and_then(|v| v.as_u64());
-
- Some(VoompAttachment {
- url,
- name: att_name,
- size,
- })
- })
- .collect()
- })
- .unwrap_or_default();
-
- lessons.push(VoompLesson {
- id,
- name,
- order,
- media_type,
- source,
- content,
- duration,
- attachments,
- });
- }
-
- lessons.sort_by_key(|l| l.order);
-
- Ok(lessons)
-}
-
-pub fn extract_panda_video_id(source: &str) -> Option<String> {
- let re = regex::Regex::new(r"[?&]v=([a-f0-9-]+)").ok()?;
- re.captures(source).map(|c| c[1].to_string())
-}
-
-pub async fn save_session(session: &VoompSession) -> anyhow::Result<()> {
- let path = session_file_path()?;
- if let Some(parent) = path.parent() {
- tokio::fs::create_dir_all(parent).await?;
- }
-
- let saved = SavedSession {
- token: session.token.clone(),
- saved_at: std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs(),
- };
-
- let json = serde_json::to_string_pretty(&saved)?;
- tokio::fs::write(&path, json).await?;
- tracing::info!("[voomp] session saved");
- Ok(())
-}
-
-pub async fn load_session() -> anyhow::Result<Option<VoompSession>> {
- let path = session_file_path()?;
- let json = match tokio::fs::read_to_string(&path).await {
- Ok(j) => j,
- Err(_) => return Ok(None),
- };
-
- let saved: SavedSession = serde_json::from_str(&json)?;
- let client = build_client(&saved.token)?;
-
- tracing::info!("[voomp] session loaded");
-
- Ok(Some(VoompSession {
- token: saved.token,
- client,
- }))
-}
-
-pub async fn delete_saved_session() -> anyhow::Result<()> {
- let path = session_file_path()?;
- if tokio::fs::try_exists(&path).await.unwrap_or(false) {
- tokio::fs::remove_file(&path).await?;
- }
- Ok(())
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/voompplay/downloader.rs b/src-tauri/omniget-plugin-courses/src/platforms/voompplay/downloader.rs
deleted file mode 100644
index 7612f42c..00000000
--- a/src-tauri/omniget-plugin-courses/src/platforms/voompplay/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 omniget_core::core::filename;
-
-use super::api::{self, VoompCourse, VoompSession};
-
-#[derive(Debug, Clone, serde::Serialize)]
-pub struct VoompCourseDownloadProgress {
- pub course_id: i64,
- pub course_name: String,
- pub percent: f64,
- pub current_module: String,
- #[serde(rename = "current_page")]
- pub current_lesson: String,
- pub downloaded_bytes: u64,
- #[serde(rename = "total_pages")]
- pub total_lessons: u32,
- #[serde(rename = "completed_pages")]
- pub completed_lessons: u32,
- pub total_modules: u32,
- pub current_module_index: u32,
-}
-
-pub async fn download_full_course(
- app: &tauri::AppHandle,
- session: &VoompSession,
- course: &VoompCourse,
- output_dir: &str,
- cancel_token: CancellationToken,
-) -> anyhow::Result<()> {
- let mut modules = api::get_modules(session, course.id).await?;
-
- if modules.is_empty() {
- return Err(anyhow!(
- "'{}' has no modules available for download",
- course.name
- ));
- }
-
- for module in &mut modules {
- let lessons = api::get_lessons(session, course.id, module.id).await?;
- module.lessons = lessons;
- }
-
- let course_dir = format!(
- "{}/{}",
- output_dir,
- filename::sanitize_path_component(&course.name)
- );
- tokio::fs::create_dir_all(&course_dir).await?;
-
- if omniget_core::core::course_utils::is_course_complete(&course_dir) {
- return Ok(());
- }
-
- let total_lessons: usize = modules.iter().map(|m| m.lessons.len()).sum();
- let total_modules = modules.len();
- let total_bytes = Arc::new(AtomicU64::new(0));
- let completed = Arc::new(AtomicUsize::new(0));
-
- let _ = app.emit(
- "download-progress",
- &VoompCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: 0.0,
- current_module: "Starting...".to_string(),
- current_lesson: String::new(),
- downloaded_bytes: 0,
- total_lessons: total_lessons as u32,
- completed_lessons: 0,
- total_modules: total_modules as u32,
- current_module_index: 0,
- },
- );
-
- for (mi, module) in modules.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let mod_name = filename::sanitize_path_component(&module.name);
- let mod_dir = format!("{}/{}. {}", course_dir, mi + 1, mod_name);
- tokio::fs::create_dir_all(&mod_dir).await?;
-
- for (li, lesson) in module.lessons.iter().enumerate() {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let lesson_name = filename::sanitize_path_component(&lesson.name);
- let lesson_dir = format!("{}/{}. {}", mod_dir, li + 1, lesson_name);
- tokio::fs::create_dir_all(&lesson_dir).await?;
-
- if let Some(ref content) = lesson.content {
- omniget_core::core::course_utils::save_description(&lesson_dir, content, "html").await.ok();
- }
-
- let mut video_url: Option<String> = None;
-
- if let Some(ref source) = lesson.source {
- if let Some(ref mt) = lesson.media_type {
- if mt.contains("panda") {
- if let Some(_vid) = api::extract_panda_video_id(source) {
- video_url = Some(source.clone());
- }
- }
- }
-
- if video_url.is_none()
- && (source.contains("http://") || source.contains("https://"))
- {
- video_url = Some(source.clone());
- }
- }
-
- if let Some(ref url) = video_url {
- let video_ext = if url.contains(".m3u8") {
- "mp4"
- } else {
- url.rsplit('.')
- .next()
- .and_then(|e| {
- let e = e.split('?').next().unwrap_or(e);
- if e.len() <= 4 {
- Some(e)
- } else {
- None
- }
- })
- .unwrap_or("mp4")
- };
-
- let video_path = format!(
- "{}/{}. {}.{}",
- lesson_dir,
- li + 1,
- lesson_name,
- video_ext
- );
-
- if tokio::fs::try_exists(&video_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&video_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- tracing::info!("[voomp] Skipping existing: {}", video_path);
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &VoompCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- continue;
- }
- }
-
- if url.contains(".m3u8") {
- match download_hls_video(url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[voomp] HLS download failed for '{}': {}",
- lesson.name,
- e
- );
- let _ = tokio::fs::remove_file(&video_path).await;
- }
- }
- } else {
- match download_with_ytdlp(url, &lesson_dir, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[voomp] yt-dlp download failed for '{}': {}, trying direct download",
- lesson.name,
- e
- );
- match download_file_direct(&session.client, url, &video_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e2) => {
- tracing::error!(
- "[voomp] Direct download also failed for '{}': {}",
- lesson.name,
- e2
- );
- }
- }
- }
- }
- }
- }
-
- for attachment in &lesson.attachments {
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- let att_name = filename::sanitize_path_component(&attachment.name);
- let att_path = format!("{}/{}", lesson_dir, att_name);
-
- if tokio::fs::try_exists(&att_path).await.unwrap_or(false) {
- let meta = tokio::fs::metadata(&att_path).await;
- if meta.map(|m| m.len() > 0).unwrap_or(false) {
- continue;
- }
- }
-
- match download_file_direct(&session.client, &attachment.url, &att_path, &cancel_token).await {
- Ok(size) => {
- total_bytes.fetch_add(size, Ordering::Relaxed);
- }
- Err(e) => {
- tracing::error!(
- "[voomp] Attachment download failed for '{}': {}",
- attachment.name,
- e
- );
- }
- }
- }
-
- let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
- let _ = app.emit(
- "download-progress",
- &VoompCourseDownloadProgress {
- course_id: course.id,
- course_name: course.name.clone(),
- percent: done as f64 / total_lessons as f64 * 100.0,
- current_module: module.name.clone(),
- current_lesson: lesson.name.clone(),
- downloaded_bytes: total_bytes.load(Ordering::Relaxed),
- total_lessons: total_lessons as u32,
- completed_lessons: done as u32,
- total_modules: total_modules as u32,
- current_module_index: (mi + 1) as u32,
- },
- );
- }
- }
-
- if cancel_token.is_cancelled() {
- return Err(anyhow!("Download cancelled by user"));
- }
-
- omniget_core::core::course_utils::mark_course_complete(&course_dir).await.ok();
-
- Ok(())
-}
-
-async fn download_hls_video(
- m3u8_url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- use omniget_core::core::media_processor::MediaProcessor;
-
- let _result = MediaProcessor::download_hls(
- m3u8_url,
- output_path,
- "https://voompplay.com.br/",
- None,
- cancel_token.clone(),
- 20,
- 3,
- None,
- )
- .await?;
-
- let meta = tokio::fs::metadata(output_path).await?;
- Ok(meta.len())
-}
-
-async fn download_with_ytdlp(
- url: &str,
- output_dir: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let ytdlp_path = omniget_core::core::ytdlp::ensure_ytdlp().await?;
- let out_dir = Path::new(output_dir);
- let (tx, _rx) = mpsc::channel(8);
-
- let result = omniget_core::core::ytdlp::download_video(
- &ytdlp_path,
- url,
- out_dir,
- None,
- tx,
- None,
- None,
- None,
- Some("https://voompplay.com.br/"),
- cancel_token.clone(),
- None,
- 8,
- false,
- &[],
- )
- .await?;
-
- Ok(result.file_size_bytes)
-}
-
-async fn download_file_direct(
- client: &reqwest::Client,
- url: &str,
- output_path: &str,
- cancel_token: &CancellationToken,
-) -> anyhow::Result<u64> {
- let out = Path::new(output_path);
- let (tx, _rx) = mpsc::channel(8);
-
- omniget_core::core::direct_downloader::download_direct(
- client,
- url,
- out,
- tx,
- Some(cancel_token),
- )
- .await
-}
diff --git a/src-tauri/omniget-plugin-courses/src/platforms/voompplay/mod.rs b/src-tauri/omniget-plugin-courses/src/platforms/voompplay/mod.rs
deleted file mode 100644
index 950bcd99..00000000
--- a/src-tauri/omniget-plugin-courses/src/platforms/voompplay/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
-use crate::platforms::traits::PlatformDownloader;
-
-pub struct VoompPlayDownloader;
-
-impl VoompPlayDownloader {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for VoompPlayDownloader {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl PlatformDownloader for VoompPlayDownloader {
- fn name(&self) -> &str {
- "voompplay"
- }
-
- fn can_handle(&self, url: &str) -> bool {
- if let Ok(parsed) = url::Url::parse(url) {
- if let Some(host) = parsed.host_str() {
- let host = host.to_lowercase();
- return host == "voompplay.com.br"
- || host.ends_with(".voompplay.com.br");
- }
- }
- false
- }
-
- async fn get_media_info(&self, _url: &str) -> anyhow::Result<MediaInfo> {
- Ok(MediaInfo {
- title: "Voomp Play".to_string(),
- author: String::new(),
- platform: "voompplay".to_string(),
- duration_seconds: None,
- thumbnail_url: None,
- available_qualities: vec![],
- media_type: MediaType::Course,
- file_size_bytes: None,
- })
- }
-
- async fn download(
- &self,
- _info: &MediaInfo,
- _opts: &DownloadOptions,
- _progress: mpsc::Sender<f64>,
- ) -> anyhow::Result<DownloadResult> {
- Err(anyhow!("Use the courses interface to download from Voomp Play"))
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/settings_helper.rs b/src-tauri/omniget-plugin-courses/src/settings_helper.rs
deleted file mode 100644
index cac1e593..00000000
--- a/src-tauri/omniget-plugin-courses/src/settings_helper.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-use tauri::AppHandle;
-use tauri_plugin_store::StoreExt;
-use omniget_core::models::settings::AppSettings;
-
-const STORE_PATH: &str = "settings.json";
-const STORE_KEY: &str = "app_settings";
-
-pub fn load_settings(app: &AppHandle) -> AppSettings {
- let store = match app.store(STORE_PATH) {
- Ok(s) => s,
- Err(_) => return AppSettings::default(),
- };
-
- match store.get(STORE_KEY) {
- Some(val) => serde_json::from_value::<AppSettings>(val.clone()).unwrap_or_default(),
- None => AppSettings::default(),
- }
-}
diff --git a/src-tauri/omniget-plugin-courses/src/state.rs b/src-tauri/omniget-plugin-courses/src/state.rs
deleted file mode 100644
index 0459182f..00000000
--- a/src-tauri/omniget-plugin-courses/src/state.rs
+++ /dev/null
@@ -1,454 +0,0 @@
-use std::collections::HashMap;
-use std::sync::Arc;
-use tokio_util::sync::CancellationToken;
-use crate::platforms::hotmart::auth::HotmartSession;
-use crate::platforms::hotmart::api::Course;
-use crate::platforms::udemy::auth::UdemySession;
-use crate::platforms::udemy::api::UdemyCourse;
-use crate::platforms::gumroad::api::GumroadProduct;
-use crate::platforms::skool::api::SkoolGroup;
-use crate::platforms::kiwify::api::KiwifyCourse;
-use crate::platforms::greennclub::api::GreennCourse;
-use crate::platforms::voompplay::api::VoompCourse;
-use crate::platforms::entregadigital::api::EntregaDigitalCourse;
-use crate::platforms::alpaclass::api::AlpaclassCourse;
-use crate::platforms::themembers::api::TheMembersCourse;
-use crate::platforms::kirvano::api::KirvanoCourse;
-use crate::platforms::datascienceacademy::api::DsaCourse;
-use crate::platforms::medcel::api::MedcelCourse;
-use crate::platforms::afyainternato::api::AfyaCourse;
-use crate::platforms::medway::api::MedwayCourse;
-use crate::platforms::estrategia_concursos::api::EstrategiaConcursosCourse;
-use crate::platforms::estrategia_ldi::api::EstrategiaLdiCourse;
-use crate::platforms::estrategia_militares::api::EstrategiaMilitaresCourse;
-use crate::platforms::grancursos::api::GranCursosCourse;
-use crate::platforms::teachable::api::TeachableCourse;
-use crate::platforms::kajabi::api::KajabiCourse;
-use crate::platforms::fluencyacademy::api::FluencyCourse;
-use crate::platforms::eduzznutror::api::NutrorCourse;
-use crate::platforms::cademi::api::CademiCourse;
-use crate::platforms::memberkit::api::MemberkitCourse;
-use crate::platforms::areademembros::api::AreaDeMembrosApiCourse;
-use crate::platforms::astronmembers::api::AstronCourse;
-use crate::platforms::cakto::api::CaktoCourse;
-use crate::platforms::caktomembers::api::CaktoMembersCourse;
-use crate::platforms::curseduca::api::CurseducaCourse;
-use crate::platforms::medcof::api::MedcofCourse;
-use crate::platforms::pluralsight::api::PluralsightCourse;
-use crate::platforms::greatcourses::api::WondriumCourse;
-use crate::platforms::masterclass::api::MasterClassCourse;
-use crate::platforms::thinkific::api::ThinkificCourse;
-use crate::platforms::rocketseat::api::RocketseatCourse;
-
-
-pub struct CoursesCache {
- pub courses: Vec<Course>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct UdemyCoursesCache {
- pub courses: Vec<UdemyCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct KiwifyCoursesCache {
- pub courses: Vec<KiwifyCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct GreennCoursesCache {
- pub courses: Vec<GreennCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct VoompCoursesCache {
- pub courses: Vec<VoompCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct EntregaDigitalCoursesCache {
- pub courses: Vec<EntregaDigitalCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct AlpaclassCoursesCache {
- pub courses: Vec<AlpaclassCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct TheMembersCoursesCache {
- pub courses: Vec<TheMembersCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct GumroadCoursesCache {
- pub products: Vec<GumroadProduct>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct KirvanoCoursesCache {
- pub courses: Vec<KirvanoCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct DsaCoursesCache {
- pub courses: Vec<DsaCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct MedcelCoursesCache {
- pub courses: Vec<MedcelCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct AfyaCoursesCache {
- pub courses: Vec<AfyaCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct MedwayCoursesCache {
- pub courses: Vec<MedwayCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct EstrategiaConcursosCoursesCache {
- pub courses: Vec<EstrategiaConcursosCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct EstrategiaLdiCoursesCache {
- pub courses: Vec<EstrategiaLdiCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct EstrategiaMilitaresCoursesCache {
- pub courses: Vec<EstrategiaMilitaresCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct GranCursosCoursesCache {
- pub courses: Vec<GranCursosCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct SkoolCoursesCache {
- pub groups: Vec<SkoolGroup>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct TeachableCoursesCache {
- pub courses: Vec<TeachableCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct KajabiCoursesCache {
- pub courses: Vec<KajabiCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct FluencyCoursesCache {
- pub courses: Vec<FluencyCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct NutrorCoursesCache {
- pub courses: Vec<NutrorCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct CademiCoursesCache {
- pub courses: Vec<CademiCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct MemberkitCoursesCache {
- pub courses: Vec<MemberkitCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct AreaDeMembrosCoursesCache {
- pub courses: Vec<AreaDeMembrosApiCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct AstronCoursesCache {
- pub courses: Vec<AstronCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct CaktoCoursesCache {
- pub courses: Vec<CaktoCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct CaktoMembersCoursesCache {
- pub courses: Vec<CaktoMembersCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct CurseducaCoursesCache {
- pub courses: Vec<CurseducaCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct MedcofCoursesCache {
- pub courses: Vec<MedcofCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct PluralsightCoursesCache {
- pub courses: Vec<PluralsightCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct WondriumCoursesCache {
- pub courses: Vec<WondriumCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct MasterClassCoursesCache {
- pub courses: Vec<MasterClassCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct ThinkificCoursesCache {
- pub courses: Vec<ThinkificCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct RocketseatCoursesCache {
- pub courses: Vec<RocketseatCourse>,
- pub fetched_at: std::time::Instant,
-}
-
-pub struct CoursesState {
- pub hotmart_session: Arc<tokio::sync::Mutex<Option<HotmartSession>>>,
- pub active_downloads: Arc<tokio::sync::Mutex<HashMap<u64, CancellationToken>>>,
- pub courses_cache: Arc<tokio::sync::Mutex<Option<CoursesCache>>>,
- pub session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub udemy_session: Arc<tokio::sync::Mutex<Option<UdemySession>>>,
- pub udemy_courses_cache: Arc<tokio::sync::Mutex<Option<UdemyCoursesCache>>>,
- pub udemy_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub udemy_api_webview: Arc<tokio::sync::Mutex<Option<tauri::WebviewWindow>>>,
- pub udemy_api_result: Arc<std::sync::Mutex<Option<String>>>,
- pub kiwify_session: Arc<tokio::sync::Mutex<Option<crate::platforms::kiwify::api::KiwifySession>>>,
- pub kiwify_courses_cache: Arc<tokio::sync::Mutex<Option<KiwifyCoursesCache>>>,
- pub kiwify_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub greenn_session: Arc<tokio::sync::Mutex<Option<crate::platforms::greennclub::api::GreennSession>>>,
- pub greenn_courses_cache: Arc<tokio::sync::Mutex<Option<GreennCoursesCache>>>,
- pub greenn_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub voomp_session: Arc<tokio::sync::Mutex<Option<crate::platforms::voompplay::api::VoompSession>>>,
- pub voomp_courses_cache: Arc<tokio::sync::Mutex<Option<VoompCoursesCache>>>,
- pub voomp_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub entregadigital_session: Arc<tokio::sync::Mutex<Option<crate::platforms::entregadigital::api::EntregaDigitalSession>>>,
- pub entregadigital_courses_cache: Arc<tokio::sync::Mutex<Option<EntregaDigitalCoursesCache>>>,
- pub entregadigital_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub alpaclass_session: Arc<tokio::sync::Mutex<Option<crate::platforms::alpaclass::api::AlpaclassSession>>>,
- pub alpaclass_courses_cache: Arc<tokio::sync::Mutex<Option<AlpaclassCoursesCache>>>,
- pub alpaclass_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub themembers_session: Arc<tokio::sync::Mutex<Option<crate::platforms::themembers::api::TheMembersSession>>>,
- pub themembers_courses_cache: Arc<tokio::sync::Mutex<Option<TheMembersCoursesCache>>>,
- pub themembers_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub gumroad_session: Arc<tokio::sync::Mutex<Option<crate::platforms::gumroad::api::GumroadSession>>>,
- pub gumroad_courses_cache: Arc<tokio::sync::Mutex<Option<GumroadCoursesCache>>>,
- pub gumroad_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub kirvano_session: Arc<tokio::sync::Mutex<Option<crate::platforms::kirvano::api::KirvanoSession>>>,
- pub kirvano_courses_cache: Arc<tokio::sync::Mutex<Option<KirvanoCoursesCache>>>,
- pub kirvano_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub dsa_session: Arc<tokio::sync::Mutex<Option<crate::platforms::datascienceacademy::api::DsaSession>>>,
- pub dsa_courses_cache: Arc<tokio::sync::Mutex<Option<DsaCoursesCache>>>,
- pub dsa_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub medcel_session: Arc<tokio::sync::Mutex<Option<crate::platforms::medcel::api::MedcelSession>>>,
- pub medcel_courses_cache: Arc<tokio::sync::Mutex<Option<MedcelCoursesCache>>>,
- pub medcel_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub afya_session: Arc<tokio::sync::Mutex<Option<crate::platforms::afyainternato::api::AfyaSession>>>,
- pub afya_courses_cache: Arc<tokio::sync::Mutex<Option<AfyaCoursesCache>>>,
- pub afya_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub medway_session: Arc<tokio::sync::Mutex<Option<crate::platforms::medway::api::MedwaySession>>>,
- pub medway_courses_cache: Arc<tokio::sync::Mutex<Option<MedwayCoursesCache>>>,
- pub medway_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub estrategia_concursos_session: Arc<tokio::sync::Mutex<Option<crate::platforms::estrategia_concursos::api::EstrategiaConcursosSession>>>,
- pub estrategia_concursos_courses_cache: Arc<tokio::sync::Mutex<Option<EstrategiaConcursosCoursesCache>>>,
- pub estrategia_concursos_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub estrategia_ldi_session: Arc<tokio::sync::Mutex<Option<crate::platforms::estrategia_ldi::api::EstrategiaLdiSession>>>,
- pub estrategia_ldi_courses_cache: Arc<tokio::sync::Mutex<Option<EstrategiaLdiCoursesCache>>>,
- pub estrategia_ldi_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub estrategia_militares_session: Arc<tokio::sync::Mutex<Option<crate::platforms::estrategia_militares::api::EstrategiaMilitaresSession>>>,
- pub estrategia_militares_courses_cache: Arc<tokio::sync::Mutex<Option<EstrategiaMilitaresCoursesCache>>>,
- pub estrategia_militares_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub grancursos_session: Arc<tokio::sync::Mutex<Option<crate::platforms::grancursos::api::GranCursosSession>>>,
- pub grancursos_courses_cache: Arc<tokio::sync::Mutex<Option<GranCursosCoursesCache>>>,
- pub grancursos_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub skool_session: Arc<tokio::sync::Mutex<Option<crate::platforms::skool::api::SkoolSession>>>,
- pub skool_courses_cache: Arc<tokio::sync::Mutex<Option<SkoolCoursesCache>>>,
- pub skool_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub teachable_session: Arc<tokio::sync::Mutex<Option<crate::platforms::teachable::api::TeachableSession>>>,
- pub teachable_courses_cache: Arc<tokio::sync::Mutex<Option<TeachableCoursesCache>>>,
- pub teachable_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub kajabi_session: Arc<tokio::sync::Mutex<Option<crate::platforms::kajabi::api::KajabiSession>>>,
- pub kajabi_courses_cache: Arc<tokio::sync::Mutex<Option<KajabiCoursesCache>>>,
- pub kajabi_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub fluency_session: Arc<tokio::sync::Mutex<Option<crate::platforms::fluencyacademy::api::FluencySession>>>,
- pub fluency_courses_cache: Arc<tokio::sync::Mutex<Option<FluencyCoursesCache>>>,
- pub fluency_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub nutror_session: Arc<tokio::sync::Mutex<Option<crate::platforms::eduzznutror::api::NutrorSession>>>,
- pub nutror_courses_cache: Arc<tokio::sync::Mutex<Option<NutrorCoursesCache>>>,
- pub nutror_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub cademi_session: Arc<tokio::sync::Mutex<Option<crate::platforms::cademi::api::CademiSession>>>,
- pub cademi_courses_cache: Arc<tokio::sync::Mutex<Option<CademiCoursesCache>>>,
- pub cademi_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub memberkit_session: Arc<tokio::sync::Mutex<Option<crate::platforms::memberkit::api::MemberkitSession>>>,
- pub memberkit_courses_cache: Arc<tokio::sync::Mutex<Option<MemberkitCoursesCache>>>,
- pub memberkit_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub areademembros_session: Arc<tokio::sync::Mutex<Option<crate::platforms::areademembros::api::AreaDeMembrosSession>>>,
- pub areademembros_courses_cache: Arc<tokio::sync::Mutex<Option<AreaDeMembrosCoursesCache>>>,
- pub areademembros_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub astron_session: Arc<tokio::sync::Mutex<Option<crate::platforms::astronmembers::api::AstronSession>>>,
- pub astron_courses_cache: Arc<tokio::sync::Mutex<Option<AstronCoursesCache>>>,
- pub astron_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub cakto_session: Arc<tokio::sync::Mutex<Option<crate::platforms::cakto::api::CaktoSession>>>,
- pub cakto_courses_cache: Arc<tokio::sync::Mutex<Option<CaktoCoursesCache>>>,
- pub cakto_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub caktomembers_session: Arc<tokio::sync::Mutex<Option<crate::platforms::caktomembers::api::CaktoMembersSession>>>,
- pub caktomembers_courses_cache: Arc<tokio::sync::Mutex<Option<CaktoMembersCoursesCache>>>,
- pub caktomembers_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub curseduca_session: Arc<tokio::sync::Mutex<Option<crate::platforms::curseduca::api::CurseducaSession>>>,
- pub curseduca_courses_cache: Arc<tokio::sync::Mutex<Option<CurseducaCoursesCache>>>,
- pub curseduca_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub medcof_session: Arc<tokio::sync::Mutex<Option<crate::platforms::medcof::api::MedcofSession>>>,
- pub medcof_courses_cache: Arc<tokio::sync::Mutex<Option<MedcofCoursesCache>>>,
- pub medcof_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub thinkific_session: Arc<tokio::sync::Mutex<Option<crate::platforms::thinkific::api::ThinkificSession>>>,
- pub thinkific_courses_cache: Arc<tokio::sync::Mutex<Option<ThinkificCoursesCache>>>,
- pub thinkific_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub rocketseat_session: Arc<tokio::sync::Mutex<Option<crate::platforms::rocketseat::api::RocketseatSession>>>,
- pub rocketseat_courses_cache: Arc<tokio::sync::Mutex<Option<RocketseatCoursesCache>>>,
- pub rocketseat_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub pluralsight_session: Arc<tokio::sync::Mutex<Option<crate::platforms::pluralsight::api::PluralsightSession>>>,
- pub pluralsight_courses_cache: Arc<tokio::sync::Mutex<Option<PluralsightCoursesCache>>>,
- pub pluralsight_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub wondrium_session: Arc<tokio::sync::Mutex<Option<crate::platforms::greatcourses::api::WondriumSession>>>,
- pub wondrium_courses_cache: Arc<tokio::sync::Mutex<Option<WondriumCoursesCache>>>,
- pub wondrium_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
- pub masterclass_session: Arc<tokio::sync::Mutex<Option<crate::platforms::masterclass::api::MasterClassSession>>>,
- pub masterclass_courses_cache: Arc<tokio::sync::Mutex<Option<MasterClassCoursesCache>>>,
- pub masterclass_session_validated_at: Arc<tokio::sync::Mutex<Option<std::time::Instant>>>,
-}
-
-impl Default for CoursesState {
- fn default() -> Self {
- Self {
- hotmart_session: Arc::new(tokio::sync::Mutex::new(None)),
- active_downloads: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
- courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- udemy_session: Arc::new(tokio::sync::Mutex::new(None)),
- udemy_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- udemy_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- udemy_api_webview: Arc::new(tokio::sync::Mutex::new(None)),
- udemy_api_result: Arc::new(std::sync::Mutex::new(None)),
- kiwify_session: Arc::new(tokio::sync::Mutex::new(None)),
- kiwify_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- kiwify_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- greenn_session: Arc::new(tokio::sync::Mutex::new(None)),
- greenn_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- greenn_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- voomp_session: Arc::new(tokio::sync::Mutex::new(None)),
- voomp_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- voomp_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- entregadigital_session: Arc::new(tokio::sync::Mutex::new(None)),
- entregadigital_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- entregadigital_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- alpaclass_session: Arc::new(tokio::sync::Mutex::new(None)),
- alpaclass_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- alpaclass_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- themembers_session: Arc::new(tokio::sync::Mutex::new(None)),
- themembers_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- themembers_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- gumroad_session: Arc::new(tokio::sync::Mutex::new(None)),
- gumroad_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- gumroad_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- kirvano_session: Arc::new(tokio::sync::Mutex::new(None)),
- kirvano_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- kirvano_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- dsa_session: Arc::new(tokio::sync::Mutex::new(None)),
- dsa_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- dsa_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- medcel_session: Arc::new(tokio::sync::Mutex::new(None)),
- medcel_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- medcel_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- afya_session: Arc::new(tokio::sync::Mutex::new(None)),
- afya_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- afya_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- medway_session: Arc::new(tokio::sync::Mutex::new(None)),
- medway_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- medway_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- estrategia_concursos_session: Arc::new(tokio::sync::Mutex::new(None)),
- estrategia_concursos_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- estrategia_concursos_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- estrategia_ldi_session: Arc::new(tokio::sync::Mutex::new(None)),
- estrategia_ldi_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- estrategia_ldi_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- estrategia_militares_session: Arc::new(tokio::sync::Mutex::new(None)),
- estrategia_militares_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- estrategia_militares_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- grancursos_session: Arc::new(tokio::sync::Mutex::new(None)),
- grancursos_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- grancursos_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- skool_session: Arc::new(tokio::sync::Mutex::new(None)),
- skool_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- skool_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- teachable_session: Arc::new(tokio::sync::Mutex::new(None)),
- teachable_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- teachable_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- kajabi_session: Arc::new(tokio::sync::Mutex::new(None)),
- kajabi_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- kajabi_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- fluency_session: Arc::new(tokio::sync::Mutex::new(None)),
- fluency_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- fluency_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- nutror_session: Arc::new(tokio::sync::Mutex::new(None)),
- nutror_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- nutror_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- cademi_session: Arc::new(tokio::sync::Mutex::new(None)),
- cademi_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- cademi_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- memberkit_session: Arc::new(tokio::sync::Mutex::new(None)),
- memberkit_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- memberkit_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- areademembros_session: Arc::new(tokio::sync::Mutex::new(None)),
- areademembros_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- areademembros_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- astron_session: Arc::new(tokio::sync::Mutex::new(None)),
- astron_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- astron_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- cakto_session: Arc::new(tokio::sync::Mutex::new(None)),
- cakto_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- cakto_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- caktomembers_session: Arc::new(tokio::sync::Mutex::new(None)),
- caktomembers_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- caktomembers_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- curseduca_session: Arc::new(tokio::sync::Mutex::new(None)),
- curseduca_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- curseduca_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- medcof_session: Arc::new(tokio::sync::Mutex::new(None)),
- medcof_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- medcof_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- thinkific_session: Arc::new(tokio::sync::Mutex::new(None)),
- thinkific_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- thinkific_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- rocketseat_session: Arc::new(tokio::sync::Mutex::new(None)),
- rocketseat_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- rocketseat_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- pluralsight_session: Arc::new(tokio::sync::Mutex::new(None)),
- pluralsight_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- pluralsight_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- wondrium_session: Arc::new(tokio::sync::Mutex::new(None)),
- wondrium_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- wondrium_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- masterclass_session: Arc::new(tokio::sync::Mutex::new(None)),
- masterclass_courses_cache: Arc::new(tokio::sync::Mutex::new(None)),
- masterclass_session_validated_at: Arc::new(tokio::sync::Mutex::new(None)),
- }
- }
-}
diff --git a/src-tauri/omniget-plugin-telegram/.github/workflows/release.yml b/src-tauri/omniget-plugin-telegram/.github/workflows/release.yml
deleted file mode 100644
index ac8752f5..00000000
--- a/src-tauri/omniget-plugin-telegram/.github/workflows/release.yml
+++ /dev/null
@@ -1,58 +0,0 @@
-name: Release
-on:
- push:
- tags: ['v*']
-
-jobs:
- build:
- strategy:
- matrix:
- include:
- - os: windows-latest
- target: x86_64-pc-windows-msvc
- artifact: windows-x86_64
- - os: ubuntu-22.04
- target: x86_64-unknown-linux-gnu
- artifact: linux-x86_64
- - os: macos-latest
- target: aarch64-apple-darwin
- artifact: macos-aarch64
- - os: macos-13
- target: x86_64-apple-darwin
- artifact: macos-x86_64
-
- runs-on: ${{ matrix.os }}
- permissions:
- contents: write
-
- steps:
- - uses: actions/checkout@v4
-
- - uses: dtolnay/rust-toolchain@stable
- with:
- targets: ${{ matrix.target }}
-
- - name: Install Linux deps
- if: runner.os == 'Linux'
- run: |
- sudo apt-get update
- sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libssl-dev libayatana-appindicator3-dev librsvg2-dev
-
- - name: Build
- run: cargo build --release --target ${{ matrix.target }}
-
- - name: Package
- shell: bash
- run: |
- mkdir -p dist
- cp plugin.json dist/
- cp target/${{ matrix.target }}/release/*.dll dist/ 2>/dev/null || true
- cp target/${{ matrix.target }}/release/*.so dist/ 2>/dev/null || true
- cp target/${{ matrix.target }}/release/*.dylib dist/ 2>/dev/null || true
- if [ -d frontend ]; then cp -r frontend dist/frontend; fi
- if [ -d assets ]; then cp -r assets dist/assets; fi
- cd dist && zip -r ../omniget-plugin-telegram-${{ github.ref_name }}-${{ matrix.artifact }}.zip .
-
- - uses: softprops/action-gh-release@v2
- with:
- files: omniget-plugin-telegram-*.zip
diff --git a/src-tauri/omniget-plugin-telegram/Cargo.toml b/src-tauri/omniget-plugin-telegram/Cargo.toml
deleted file mode 100644
index 985e142c..00000000
--- a/src-tauri/omniget-plugin-telegram/Cargo.toml
+++ /dev/null
@@ -1,30 +0,0 @@
-[package]
-name = "omniget-plugin-telegram"
-version = "0.1.0"
-edition = "2021"
-
-[lib]
-crate-type = ["cdylib", "rlib"]
-
-[dependencies]
-tokio = { version = "1", features = ["full"] }
-serde = { version = "1", features = ["derive"] }
-serde_json = "1"
-async-trait = "0.1"
-anyhow = "1"
-tracing = "0.1"
-tokio-util = { version = "0.7", features = ["rt"] }
-base64 = "0.22.1"
-grammers-client = "0.8"
-grammers-session = "0.8"
-grammers-tl-types = "0.8"
-grammers-mtsender = "0.8"
-qrcode = { version = "0.14", default-features = false, features = ["svg"] }
-dirs = "6"
-sanitize-filename = "0.6"
-url = "2"
-filetime = "0.2.27"
-os_info = "3"
-sys-locale = "0.3"
-omniget-core = { path = "../omniget-core", features = ["desktop"] }
-omniget-plugin-sdk = { path = "../omniget-plugin-sdk" }
diff --git a/src-tauri/omniget-plugin-telegram/README.md b/src-tauri/omniget-plugin-telegram/README.md
deleted file mode 100644
index 19b0481d..00000000
--- a/src-tauri/omniget-plugin-telegram/README.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# OmniGet Telegram Plugin
-
-Download media from Telegram channels and groups.
-
-## Features
-
-- QR code login (scan from Telegram app)
-- Phone number + verification code login
-- Two-factor authentication support
-- Browse channels and groups
-- Download photos, videos, files, and audio
-- Batch download with progress tracking
-- Thumbnail cache for fast browsing
-- Search within chats
-
-## Install
-
-This plugin is bundled with OmniGet. It can also be installed from the in-app Marketplace.
-
-## Development
-
-```bash
-cargo check -p omniget-plugin-telegram
-```
diff --git a/src-tauri/omniget-plugin-telegram/plugin.json b/src-tauri/omniget-plugin-telegram/plugin.json
deleted file mode 100644
index 7c7b1b30..00000000
--- a/src-tauri/omniget-plugin-telegram/plugin.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "id": "telegram",
- "name": "Telegram Downloader",
- "version": "0.1.0",
- "min_omniget_version": "0.4.0",
- "description": "Download photos, videos, files, and audio from Telegram channels and groups with QR code or phone login.",
- "author": "tonhowtf",
- "license": "GPL-3.0",
- "homepage": "https://github.com/tonhowtf/omniget-plugin-telegram",
- "icon": "assets/icon.png",
- "nav": [
- {
- "route": "/telegram",
- "label": { "en": "Telegram", "pt": "Telegram", "zh": "Telegram", "ja": "Telegram", "fr": "Telegram", "it": "Telegram", "el": "Telegram" },
- "icon_svg": "M21 5L2 12.5l7 1M21 5l-5.5 15-4.5-7.5M21 5L9 13.5",
- "group": "secondary",
- "order": 35
- }
- ],
- "events": {
- "progress": ["telegram-batch-file-status"],
- "complete": []
- },
- "capabilities": [
- "core:events",
- "core:toast",
- "core:settings",
- "core:filesystem"
- ]
-}
diff --git a/src-tauri/omniget-plugin-telegram/src/lib.rs b/src-tauri/omniget-plugin-telegram/src/lib.rs
deleted file mode 100644
index 653c0f38..00000000
--- a/src-tauri/omniget-plugin-telegram/src/lib.rs
+++ /dev/null
@@ -1,323 +0,0 @@
-pub mod platforms;
-
-use std::collections::HashMap;
-use std::sync::Arc;
-use serde::Serialize;
-use tokio::sync::{mpsc, Semaphore};
-use tokio_util::sync::CancellationToken;
-use base64::Engine;
-use omniget_plugin_sdk::{OmnigetPlugin, PluginHost};
-use platforms::telegram::api::{self, TelegramChat, TelegramMediaItem};
-use platforms::telegram::auth::{self, TelegramSessionHandle, TelegramState, QrPollStatus, VerifyError};
-use platforms::telegram::thumbnail_cache;
-
-pub struct TelegramPlugin {
- host: Option<Arc<dyn PluginHost>>,
- telegram_session: TelegramSessionHandle,
- active_downloads: Arc<tokio::sync::Mutex<HashMap<u64, (String, CancellationToken)>>>,
-}
-
-impl TelegramPlugin {
- pub fn new() -> Self {
- Self {
- host: None,
- telegram_session: Arc::new(tokio::sync::Mutex::new(TelegramState::new())),
- active_downloads: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
- }
- }
-
- fn get_setting(&self, key: &str) -> serde_json::Value {
- self.host.as_ref()
- .map(|h| h.get_settings("telegram"))
- .and_then(|s| s.get(key).cloned())
- .unwrap_or(serde_json::Value::Null)
- }
-
- fn fix_file_extensions(&self) -> bool {
- self.get_setting("fix_file_extensions").as_bool().unwrap_or(false)
- }
-
- fn concurrent_downloads(&self) -> usize {
- self.get_setting("concurrent_downloads").as_u64().unwrap_or(3) as usize
- }
-}
-
-#[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)]
-struct BatchFileStatus { batch_id: u64, message_id: i32, status: String, percent: f64, error: Option<String> }
-
-#[derive(Clone, serde::Deserialize)]
-struct BatchItem { message_id: i32, file_name: String, file_size: u64 }
-
-impl OmnigetPlugin for TelegramPlugin {
- fn id(&self) -> &str { "telegram" }
- fn name(&self) -> &str { "Telegram Downloader" }
- fn version(&self) -> &str { env!("CARGO_PKG_VERSION") }
-
- fn initialize(&mut self, host: Arc<dyn PluginHost>) -> anyhow::Result<()> {
- self.host = Some(host);
- Ok(())
- }
-
- fn handle_command(
- &self,
- command: String,
- args: serde_json::Value,
- ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<serde_json::Value, String>> + Send + 'static>> {
- let host = self.host.clone();
- let session = self.telegram_session.clone();
- let active = self.active_downloads.clone();
- let fix_ext = self.fix_file_extensions();
- let concurrent = self.concurrent_downloads().clamp(1, 10);
-
- Box::pin(async move {
- match command.as_str() {
- "telegram_check_session" => {
- let r = auth::check_session(&session).await.map_err(|e| e.to_string())?;
- Ok(serde_json::to_value(r).map_err(|e| e.to_string())?)
- }
-
- "telegram_qr_start" => {
- let r = auth::qr_login_start(&session).await.map_err(|e| e.to_string())?;
- Ok(serde_json::json!({ "svg": r.qr_svg, "expires": r.expires }))
- }
-
- "telegram_qr_poll" => {
- match auth::qr_login_poll(&session).await {
- Ok(QrPollStatus::Waiting) => Ok(serde_json::json!("waiting")),
- Ok(QrPollStatus::Success { phone }) => Ok(serde_json::json!(format!("success:{}", phone))),
- Ok(QrPollStatus::PasswordRequired { hint }) => {
- if hint.is_empty() { Ok(serde_json::json!("password_required")) }
- else { Ok(serde_json::json!(format!("password_required:{}", hint))) }
- }
- Err(e) => Err(e.to_string()),
- }
- }
-
- "telegram_send_code" => {
- let phone: String = serde_json::from_value(args.get("phone").cloned().ok_or("missing 'phone'")?).map_err(|e| e.to_string())?;
- auth::send_code(&session, &phone).await.map_err(|e| e.to_string())?;
- Ok(serde_json::json!(null))
- }
-
- "telegram_verify_code" => {
- let code: String = serde_json::from_value(args.get("code").cloned().ok_or("missing 'code'")?).map_err(|e| e.to_string())?;
- match auth::verify_code(&session, &code).await {
- Ok(phone) => Ok(serde_json::json!(phone)),
- Err(VerifyError::InvalidCode) => Err("invalid_code".into()),
- Err(VerifyError::PasswordRequired { hint }) => Err(format!("password_required:{}", hint)),
- Err(VerifyError::NoSession) => Err("no_session".into()),
- Err(VerifyError::Other(msg)) => Err(msg),
- }
- }
-
- "telegram_verify_2fa" => {
- let password: String = serde_json::from_value(args.get("password").cloned().ok_or("missing 'password'")?).map_err(|e| e.to_string())?;
- let r = auth::verify_password(&session, &password).await.map_err(|e| e.to_string())?;
- Ok(serde_json::json!(r))
- }
-
- "telegram_logout" => {
- thumbnail_cache::clear_cache().await;
- auth::logout(&session).await.map_err(|e| e.to_string())?;
- Ok(serde_json::json!(null))
- }
-
- "telegram_list_chats" => {
- let r = api::list_chats(&session).await.map_err(|e| e.to_string())?;
- serde_json::to_value(r).map_err(|e| e.to_string())
- }
-
- "telegram_list_media" => {
- let chat_id: i64 = serde_json::from_value(args.get("chat_id").or(args.get("chatId")).cloned().ok_or("missing 'chatId'")?).map_err(|e| e.to_string())?;
- let chat_type: String = serde_json::from_value(args.get("chat_type").or(args.get("chatType")).cloned().ok_or("missing 'chatType'")?).map_err(|e| e.to_string())?;
- let media_type: Option<String> = args.get("media_type").or(args.get("mediaType")).cloned().and_then(|v| serde_json::from_value(v).ok());
- let offset: i32 = serde_json::from_value(args.get("offset").cloned().unwrap_or(serde_json::json!(0))).map_err(|e| e.to_string())?;
- let limit: u32 = serde_json::from_value(args.get("limit").cloned().unwrap_or(serde_json::json!(50))).map_err(|e| e.to_string())?;
- let r = api::list_media(&session, chat_id, &chat_type, media_type.as_deref(), offset, limit, fix_ext).await.map_err(|e| e.to_string())?;
- serde_json::to_value(r).map_err(|e| e.to_string())
- }
-
- "telegram_download_media" => {
- let chat_id: i64 = serde_json::from_value(args.get("chat_id").or(args.get("chatId")).cloned().ok_or("missing 'chatId'")?).map_err(|e| e.to_string())?;
- let chat_type: String = serde_json::from_value(args.get("chat_type").or(args.get("chatType")).cloned().ok_or("missing 'chatType'")?).map_err(|e| e.to_string())?;
- let message_id: i32 = serde_json::from_value(args.get("message_id").or(args.get("messageId")).cloned().ok_or("missing 'messageId'")?).map_err(|e| e.to_string())?;
- let file_name: String = serde_json::from_value(args.get("file_name").or(args.get("fileName")).cloned().ok_or("missing 'fileName'")?).map_err(|e| e.to_string())?;
- let output_dir: String = serde_json::from_value(args.get("output_dir").or(args.get("outputDir")).cloned().ok_or("missing 'outputDir'")?).map_err(|e| e.to_string())?;
-
- 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 a = active.lock().await;
- let key = format!("tg:{}:{}", chat_id, message_id);
- if a.values().any(|(u, _)| u == &key) { return Err("Download already in progress".into()); }
- a.insert(download_id, (key, cancel_token.clone()));
- }
-
- let host = host.ok_or("Plugin not initialized")?;
- let active = active.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 _ = host.emit_event("generic-download-progress", serde_json::to_value(&GenericDownloadProgress { id: download_id, title: file_name_clone.clone(), platform: "telegram".into(), percent: 0.0 }).unwrap_or_default());
- let (tx, mut rx) = mpsc::channel::<f64>(32);
- let host_p = host.clone();
- let fn_p = file_name_clone.clone();
- let pf = tokio::spawn(async move { while let Some(p) = rx.recv().await { let _ = host_p.emit_event("generic-download-progress", serde_json::to_value(&GenericDownloadProgress { id: download_id, title: fn_p.clone(), platform: "telegram".into(), percent: p }).unwrap_or_default()); } });
- let result = api::download_media_with_retry(&session, chat_id, &chat_type, message_id, &output_path, tx, &cancel_token).await;
- let _ = pf.await;
- active.lock().await.remove(&download_id);
- match result {
- Ok(size) => { let _ = host.emit_event("generic-download-complete", serde_json::to_value(&GenericDownloadComplete { id: download_id, title: file_name_clone, platform: "telegram".into(), success: true, error: None, file_path: Some(output_path.to_string_lossy().into()), file_size_bytes: Some(size), file_count: Some(1) }).unwrap_or_default()); }
- Err(e) => { let _ = host.emit_event("generic-download-complete", serde_json::to_value(&GenericDownloadComplete { id: download_id, title: file_name_clone, platform: "telegram".into(), success: false, error: Some(e.to_string()), file_path: None, file_size_bytes: None, file_count: None }).unwrap_or_default()); }
- }
- });
- Ok(serde_json::json!({ "id": download_id, "file_name": file_name }))
- }
-
- "telegram_download_batch" => {
- let chat_id: i64 = serde_json::from_value(args.get("chat_id").or(args.get("chatId")).cloned().ok_or("missing 'chatId'")?).map_err(|e| e.to_string())?;
- let chat_type: String = serde_json::from_value(args.get("chat_type").or(args.get("chatType")).cloned().ok_or("missing 'chatType'")?).map_err(|e| e.to_string())?;
- let chat_title: String = serde_json::from_value(args.get("chat_title").or(args.get("chatTitle")).cloned().ok_or("missing 'chatTitle'")?).map_err(|e| e.to_string())?;
- let items: Vec<BatchItem> = serde_json::from_value(args.get("items").cloned().ok_or("missing 'items'")?).map_err(|e| e.to_string())?;
- let output_dir: String = serde_json::from_value(args.get("output_dir").or(args.get("outputDir")).cloned().ok_or("missing 'outputDir'")?).map_err(|e| e.to_string())?;
-
- 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 a = active.lock().await; a.insert(batch_id, (format!("tg-batch:{}", batch_id), cancel_token.clone())); }
-
- let host = host.ok_or("Plugin not initialized")?;
- let active = active.clone();
- let total_files = items.len() as u32;
-
- let _ = host.emit_event("generic-download-progress", serde_json::to_value(&GenericDownloadProgress { id: batch_id, title: chat_title.clone(), platform: "telegram".into(), percent: 0.0 }).unwrap_or_default());
-
- tokio::spawn(async move {
- let sem = 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 = sem.clone(); let session = session.clone(); let host = host.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();
-
- handles.push(tokio::spawn(async move {
- if cancel.is_cancelled() { return; }
- let output_path = std::path::PathBuf::from(&output_dir).join(&item.file_name);
-
- 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 _ = host.emit_event("telegram-batch-file-status", serde_json::to_value(&BatchFileStatus { batch_id, message_id: item.message_id, status: "skipped".into(), percent: 100.0, error: None }).unwrap_or_default());
- let _ = host.emit_event("generic-download-progress", serde_json::to_value(&GenericDownloadProgress { id: batch_id, title: chat_title, platform: "telegram".into(), percent: (done as f64 / total_files as f64) * 100.0 }).unwrap_or_default());
- return;
- }
- }
- }
-
- let _permit = tokio::select! { p = sem.acquire() => match p { Ok(p) => p, Err(_) => return }, _ = cancel.cancelled() => return };
- if cancel.is_cancelled() { return; }
-
- let _ = host.emit_event("telegram-batch-file-status", serde_json::to_value(&BatchFileStatus { batch_id, message_id: item.message_id, status: "downloading".into(), percent: 0.0, error: None }).unwrap_or_default());
- let (tx, mut rx) = mpsc::channel::<f64>(32);
- let host_p = host.clone();
- let mid = item.message_id;
- let pf = tokio::spawn(async move { while let Some(p) = rx.recv().await { let _ = host_p.emit_event("telegram-batch-file-status", serde_json::to_value(&BatchFileStatus { batch_id, message_id: mid, status: "downloading".into(), percent: p, error: None }).unwrap_or_default()); } });
-
- let result = api::download_media_with_retry(&session, chat_id, &chat_type, item.message_id, &output_path, tx, &cancel).await;
- let _ = pf.await;
-
- match result {
- Ok(_) => { completed.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let _ = host.emit_event("telegram-batch-file-status", serde_json::to_value(&BatchFileStatus { batch_id, message_id: item.message_id, status: "done".into(), percent: 100.0, error: None }).unwrap_or_default()); }
- Err(e) => { if e.to_string().contains("cancelled") { return; } failed.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let _ = host.emit_event("telegram-batch-file-status", serde_json::to_value(&BatchFileStatus { batch_id, message_id: item.message_id, status: "error".into(), percent: 0.0, error: Some(e.to_string()) }).unwrap_or_default()); }
- }
-
- let done = completed.load(std::sync::atomic::Ordering::Relaxed) + failed.load(std::sync::atomic::Ordering::Relaxed) + skipped.load(std::sync::atomic::Ordering::Relaxed);
- let _ = host.emit_event("generic-download-progress", serde_json::to_value(&GenericDownloadProgress { id: batch_id, title: chat_title, platform: "telegram".into(), percent: (done as f64 / total_files as f64) * 100.0 }).unwrap_or_default());
- }));
- }
-
- for h in handles { let _ = h.await; }
- active.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 _ = host.emit_event("generic-download-complete", serde_json::to_value(&GenericDownloadComplete {
- id: batch_id, title: chat_title, platform: "telegram".into(),
- success: fail_count == 0 && !cancel_token.is_cancelled(),
- error: if cancel_token.is_cancelled() { Some("Batch cancelled".into()) } 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),
- }).unwrap_or_default());
- });
- Ok(serde_json::json!(batch_id))
- }
-
- "telegram_cancel_batch" => {
- let batch_id: u64 = serde_json::from_value(args.get("batch_id").or(args.get("batchId")).cloned().ok_or("missing 'batchId'")?).map_err(|e| e.to_string())?;
- let a = active.lock().await;
- if let Some((key, token)) = a.get(&batch_id) {
- if key.starts_with("tg-batch:") { token.cancel(); return Ok(serde_json::json!(null)); }
- }
- Err("Batch not found".into())
- }
-
- "telegram_get_thumbnail" => {
- let chat_id: i64 = serde_json::from_value(args.get("chat_id").or(args.get("chatId")).cloned().ok_or("missing 'chatId'")?).map_err(|e| e.to_string())?;
- let chat_type: String = serde_json::from_value(args.get("chat_type").or(args.get("chatType")).cloned().ok_or("missing 'chatType'")?).map_err(|e| e.to_string())?;
- let message_id: i32 = serde_json::from_value(args.get("message_id").or(args.get("messageId")).cloned().ok_or("missing 'messageId'")?).map_err(|e| e.to_string())?;
- let data = thumbnail_cache::get_thumbnail(&session, chat_id, &chat_type, message_id).await.map_err(|e| e.to_string())?;
- Ok(serde_json::json!(base64::engine::general_purpose::STANDARD.encode(&data)))
- }
-
- "telegram_search_media" => {
- let chat_id: i64 = serde_json::from_value(args.get("chat_id").or(args.get("chatId")).cloned().ok_or("missing 'chatId'")?).map_err(|e| e.to_string())?;
- let chat_type: String = serde_json::from_value(args.get("chat_type").or(args.get("chatType")).cloned().ok_or("missing 'chatType'")?).map_err(|e| e.to_string())?;
- let query: String = serde_json::from_value(args.get("query").cloned().ok_or("missing 'query'")?).map_err(|e| e.to_string())?;
- let media_type: Option<String> = args.get("media_type").or(args.get("mediaType")).cloned().and_then(|v| serde_json::from_value(v).ok());
- let limit: u32 = serde_json::from_value(args.get("limit").cloned().unwrap_or(serde_json::json!(50))).map_err(|e| e.to_string())?;
- let r = api::search_media(&session, chat_id, &chat_type, &query, media_type.as_deref(), limit, fix_ext).await.map_err(|e| e.to_string())?;
- serde_json::to_value(r).map_err(|e| e.to_string())
- }
-
- "telegram_get_chat_photo" => {
- let chat_id: i64 = serde_json::from_value(args.get("chat_id").or(args.get("chatId")).cloned().ok_or("missing 'chatId'")?).map_err(|e| e.to_string())?;
- let chat_type: String = serde_json::from_value(args.get("chat_type").or(args.get("chatType")).cloned().ok_or("missing 'chatType'")?).map_err(|e| e.to_string())?;
- let data = thumbnail_cache::get_chat_photo(&session, chat_id, &chat_type).await.map_err(|e| e.to_string())?;
- Ok(serde_json::json!(base64::engine::general_purpose::STANDARD.encode(&data)))
- }
-
- "telegram_clear_thumbnail_cache" => {
- thumbnail_cache::clear_cache().await;
- Ok(serde_json::json!(null))
- }
-
- _ => Err(format!("Unknown command: {}", command)),
- }
- })
- }
-
- fn commands(&self) -> Vec<String> {
- vec![
- "telegram_check_session".into(), "telegram_qr_start".into(), "telegram_qr_poll".into(),
- "telegram_send_code".into(), "telegram_verify_code".into(), "telegram_verify_2fa".into(),
- "telegram_logout".into(), "telegram_list_chats".into(), "telegram_list_media".into(),
- "telegram_download_media".into(), "telegram_download_batch".into(), "telegram_cancel_batch".into(),
- "telegram_get_thumbnail".into(), "telegram_search_media".into(), "telegram_get_chat_photo".into(),
- "telegram_clear_thumbnail_cache".into(),
- ]
- }
-}
-
-omniget_plugin_sdk::export_plugin!(TelegramPlugin::new());
diff --git a/src-tauri/omniget-plugin-telegram/src/platforms/mod.rs b/src-tauri/omniget-plugin-telegram/src/platforms/mod.rs
deleted file mode 100644
index 57ac8013..00000000
--- a/src-tauri/omniget-plugin-telegram/src/platforms/mod.rs
+++ /dev/null
@@ -1,3 +0,0 @@
-pub use omniget_core::platforms::traits;
-
-pub mod telegram;
diff --git a/src-tauri/omniget-plugin-telegram/src/platforms/telegram/api.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/api.rs
deleted file mode 100644
index 01101889..00000000
--- a/src-tauri/omniget-plugin-telegram/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/omniget-plugin-telegram/src/platforms/telegram/auth.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/auth.rs
deleted file mode 100644
index f46f0712..00000000
--- a/src-tauri/omniget-plugin-telegram/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/omniget-plugin-telegram/src/platforms/telegram/downloader.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/downloader.rs
deleted file mode 100644
index 3c9c806f..00000000
--- a/src-tauri/omniget-plugin-telegram/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use omniget_core::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/omniget-plugin-telegram/src/platforms/telegram/mod.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/mod.rs
deleted file mode 100644
index 3050460c..00000000
--- a/src-tauri/omniget-plugin-telegram/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/omniget-plugin-telegram/src/platforms/telegram/parallel_download.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/parallel_download.rs
deleted file mode 100644
index 70b243cb..00000000
--- a/src-tauri/omniget-plugin-telegram/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/omniget-plugin-telegram/src/platforms/telegram/telegram/api.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/telegram/api.rs
deleted file mode 100644
index 01101889..00000000
--- a/src-tauri/omniget-plugin-telegram/src/platforms/telegram/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/omniget-plugin-telegram/src/platforms/telegram/telegram/auth.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/telegram/auth.rs
deleted file mode 100644
index f46f0712..00000000
--- a/src-tauri/omniget-plugin-telegram/src/platforms/telegram/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/omniget-plugin-telegram/src/platforms/telegram/telegram/downloader.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/telegram/downloader.rs
deleted file mode 100644
index 3c9c806f..00000000
--- a/src-tauri/omniget-plugin-telegram/src/platforms/telegram/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 omniget_core::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
-use omniget_core::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/omniget-plugin-telegram/src/platforms/telegram/telegram/mod.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/telegram/mod.rs
deleted file mode 100644
index 3050460c..00000000
--- a/src-tauri/omniget-plugin-telegram/src/platforms/telegram/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/omniget-plugin-telegram/src/platforms/telegram/telegram/parallel_download.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/telegram/parallel_download.rs
deleted file mode 100644
index 70b243cb..00000000
--- a/src-tauri/omniget-plugin-telegram/src/platforms/telegram/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/omniget-plugin-telegram/src/platforms/telegram/telegram/thumbnail_cache.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/telegram/thumbnail_cache.rs
deleted file mode 100644
index be275a01..00000000
--- a/src-tauri/omniget-plugin-telegram/src/platforms/telegram/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/omniget-plugin-telegram/src/platforms/telegram/thumbnail_cache.rs b/src-tauri/omniget-plugin-telegram/src/platforms/telegram/thumbnail_cache.rs
deleted file mode 100644
index be275a01..00000000
--- a/src-tauri/omniget-plugin-telegram/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/lib.rs b/src-tauri/src/lib.rs
index 47683640..f54b298d 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -277,7 +277,6 @@ pub fn run() {
.build(),
)
.plugin(tauri_plugin_clipboard_manager::init())
- .plugin(omniget_plugin_courses::init())
.setup(|app| {
let settings = storage::config::load_settings(app.handle());
core::http_client::init_proxy(settings.proxy.clone());
@@ -371,252 +370,6 @@ pub fn run() {
commands::p2p::p2p_resume_send,
commands::p2p::p2p_get_active_sends,
commands::p2p::p2p_validate_code,
- omniget_plugin_courses::commands::auth::hotmart_login,
- omniget_plugin_courses::commands::auth::hotmart_check_session,
- omniget_plugin_courses::commands::auth::hotmart_logout,
- omniget_plugin_courses::commands::courses::hotmart_list_courses,
- omniget_plugin_courses::commands::courses::hotmart_refresh_courses,
- omniget_plugin_courses::commands::courses::hotmart_get_modules,
- omniget_plugin_courses::commands::downloads::start_course_download,
- omniget_plugin_courses::commands::downloads::cancel_course_download,
- omniget_plugin_courses::commands::downloads::get_active_downloads,
- omniget_plugin_courses::commands::kiwify::kiwify_login,
- omniget_plugin_courses::commands::kiwify::kiwify_login_token,
- omniget_plugin_courses::commands::kiwify::kiwify_check_session,
- omniget_plugin_courses::commands::kiwify::kiwify_logout,
- omniget_plugin_courses::commands::kiwify::kiwify_list_courses,
- omniget_plugin_courses::commands::kiwify::kiwify_refresh_courses,
- omniget_plugin_courses::commands::kiwify::start_kiwify_course_download,
- omniget_plugin_courses::commands::skool::skool_login,
- omniget_plugin_courses::commands::skool::skool_login_token,
- omniget_plugin_courses::commands::skool::skool_check_session,
- omniget_plugin_courses::commands::skool::skool_logout,
- omniget_plugin_courses::commands::skool::skool_list_groups,
- omniget_plugin_courses::commands::skool::skool_refresh_groups,
- omniget_plugin_courses::commands::skool::start_skool_course_download,
- omniget_plugin_courses::commands::udemy_auth::udemy_login,
- omniget_plugin_courses::commands::udemy_auth::udemy_login_cookies,
- omniget_plugin_courses::commands::udemy_auth::udemy_check_session,
- omniget_plugin_courses::commands::udemy_auth::udemy_get_portal,
- omniget_plugin_courses::commands::udemy_auth::udemy_logout,
- omniget_plugin_courses::commands::udemy_courses::udemy_list_courses,
- omniget_plugin_courses::commands::udemy_courses::udemy_refresh_courses,
- omniget_plugin_courses::commands::udemy_downloads::start_udemy_course_download,
- omniget_plugin_courses::commands::udemy_downloads::cancel_udemy_course_download,
- omniget_plugin_courses::commands::afya::afya_login,
- omniget_plugin_courses::commands::afya::afya_login_token,
- omniget_plugin_courses::commands::afya::afya_check_session,
- omniget_plugin_courses::commands::afya::afya_logout,
- omniget_plugin_courses::commands::afya::afya_list_courses,
- omniget_plugin_courses::commands::afya::afya_refresh_courses,
- omniget_plugin_courses::commands::afya::start_afya_course_download,
- omniget_plugin_courses::commands::alpaclass::alpaclass_login,
- omniget_plugin_courses::commands::alpaclass::alpaclass_check_session,
- omniget_plugin_courses::commands::alpaclass::alpaclass_logout,
- omniget_plugin_courses::commands::alpaclass::alpaclass_list_courses,
- omniget_plugin_courses::commands::alpaclass::alpaclass_refresh_courses,
- omniget_plugin_courses::commands::alpaclass::start_alpaclass_course_download,
- omniget_plugin_courses::commands::areademembros::areademembros_login_token,
- omniget_plugin_courses::commands::areademembros::areademembros_check_session,
- omniget_plugin_courses::commands::areademembros::areademembros_logout,
- omniget_plugin_courses::commands::areademembros::areademembros_list_courses,
- omniget_plugin_courses::commands::areademembros::areademembros_refresh_courses,
- omniget_plugin_courses::commands::areademembros::start_areademembros_course_download,
- omniget_plugin_courses::commands::astronmembers::astron_login,
- omniget_plugin_courses::commands::astronmembers::astron_login_token,
- omniget_plugin_courses::commands::astronmembers::astron_check_session,
- omniget_plugin_courses::commands::astronmembers::astron_logout,
- omniget_plugin_courses::commands::astronmembers::astron_list_courses,
- omniget_plugin_courses::commands::astronmembers::astron_refresh_courses,
- omniget_plugin_courses::commands::astronmembers::start_astron_course_download,
- omniget_plugin_courses::commands::cademi_cmd::cademi_login,
- omniget_plugin_courses::commands::cademi_cmd::cademi_login_cookie,
- omniget_plugin_courses::commands::cademi_cmd::cademi_check_session,
- omniget_plugin_courses::commands::cademi_cmd::cademi_logout,
- omniget_plugin_courses::commands::cademi_cmd::cademi_list_courses,
- omniget_plugin_courses::commands::cademi_cmd::cademi_refresh_courses,
- omniget_plugin_courses::commands::cademi_cmd::start_cademi_course_download,
- omniget_plugin_courses::commands::cakto::cakto_login,
- omniget_plugin_courses::commands::cakto::cakto_login_token,
- omniget_plugin_courses::commands::cakto::cakto_check_session,
- omniget_plugin_courses::commands::cakto::cakto_logout,
- omniget_plugin_courses::commands::cakto::cakto_list_courses,
- omniget_plugin_courses::commands::cakto::cakto_refresh_courses,
- omniget_plugin_courses::commands::cakto::start_cakto_course_download,
- omniget_plugin_courses::commands::caktomembers::caktomembers_login_token,
- omniget_plugin_courses::commands::caktomembers::caktomembers_check_session,
- omniget_plugin_courses::commands::caktomembers::caktomembers_logout,
- omniget_plugin_courses::commands::caktomembers::caktomembers_list_courses,
- omniget_plugin_courses::commands::caktomembers::caktomembers_refresh_courses,
- omniget_plugin_courses::commands::caktomembers::start_caktomembers_course_download,
- omniget_plugin_courses::commands::curseduca::curseduca_login,
- omniget_plugin_courses::commands::curseduca::curseduca_login_token,
- omniget_plugin_courses::commands::curseduca::curseduca_check_session,
- omniget_plugin_courses::commands::curseduca::curseduca_logout,
- omniget_plugin_courses::commands::curseduca::curseduca_list_courses,
- omniget_plugin_courses::commands::curseduca::curseduca_refresh_courses,
- omniget_plugin_courses::commands::curseduca::start_curseduca_course_download,
- omniget_plugin_courses::commands::dsa::dsa_login_token,
- omniget_plugin_courses::commands::dsa::dsa_check_session,
- omniget_plugin_courses::commands::dsa::dsa_logout,
- omniget_plugin_courses::commands::dsa::dsa_list_courses,
- omniget_plugin_courses::commands::dsa::dsa_refresh_courses,
- omniget_plugin_courses::commands::dsa::start_dsa_course_download,
- omniget_plugin_courses::commands::entregadigital::entregadigital_login_token,
- omniget_plugin_courses::commands::entregadigital::entregadigital_check_session,
- omniget_plugin_courses::commands::entregadigital::entregadigital_logout,
- omniget_plugin_courses::commands::entregadigital::entregadigital_list_courses,
- omniget_plugin_courses::commands::entregadigital::entregadigital_refresh_courses,
- omniget_plugin_courses::commands::entregadigital::start_entregadigital_course_download,
- omniget_plugin_courses::commands::estrategia_concursos::estrategia_concursos_login_token,
- omniget_plugin_courses::commands::estrategia_concursos::estrategia_concursos_check_session,
- omniget_plugin_courses::commands::estrategia_concursos::estrategia_concursos_logout,
- omniget_plugin_courses::commands::estrategia_concursos::estrategia_concursos_list_courses,
- omniget_plugin_courses::commands::estrategia_concursos::estrategia_concursos_refresh_courses,
- omniget_plugin_courses::commands::estrategia_concursos::start_estrategia_concursos_course_download,
- omniget_plugin_courses::commands::estrategia_ldi::estrategia_ldi_login_token,
- omniget_plugin_courses::commands::estrategia_ldi::estrategia_ldi_check_session,
- omniget_plugin_courses::commands::estrategia_ldi::estrategia_ldi_logout,
- omniget_plugin_courses::commands::estrategia_ldi::estrategia_ldi_list_courses,
- omniget_plugin_courses::commands::estrategia_ldi::estrategia_ldi_refresh_courses,
- omniget_plugin_courses::commands::estrategia_ldi::start_estrategia_ldi_course_download,
- omniget_plugin_courses::commands::estrategia_militares::estrategia_militares_login_token,
- omniget_plugin_courses::commands::estrategia_militares::estrategia_militares_check_session,
- omniget_plugin_courses::commands::estrategia_militares::estrategia_militares_logout,
- omniget_plugin_courses::commands::estrategia_militares::estrategia_militares_list_courses,
- omniget_plugin_courses::commands::estrategia_militares::estrategia_militares_search_courses,
- omniget_plugin_courses::commands::estrategia_militares::estrategia_militares_refresh_courses,
- omniget_plugin_courses::commands::estrategia_militares::start_estrategia_militares_course_download,
- omniget_plugin_courses::commands::fluencyacademy::fluency_login,
- omniget_plugin_courses::commands::fluencyacademy::fluency_login_token,
- omniget_plugin_courses::commands::fluencyacademy::fluency_check_session,
- omniget_plugin_courses::commands::fluencyacademy::fluency_logout,
- omniget_plugin_courses::commands::fluencyacademy::fluency_list_courses,
- omniget_plugin_courses::commands::fluencyacademy::fluency_refresh_courses,
- omniget_plugin_courses::commands::fluencyacademy::start_fluency_course_download,
- omniget_plugin_courses::commands::grancursos::grancursos_login_cookies,
- omniget_plugin_courses::commands::grancursos::grancursos_check_session,
- omniget_plugin_courses::commands::grancursos::grancursos_logout,
- omniget_plugin_courses::commands::grancursos::grancursos_list_courses,
- omniget_plugin_courses::commands::grancursos::grancursos_refresh_courses,
- omniget_plugin_courses::commands::grancursos::start_grancursos_course_download,
- omniget_plugin_courses::commands::greatcourses::wondrium_login,
- omniget_plugin_courses::commands::greatcourses::wondrium_login_token,
- omniget_plugin_courses::commands::greatcourses::wondrium_check_session,
- omniget_plugin_courses::commands::greatcourses::wondrium_logout,
- omniget_plugin_courses::commands::greatcourses::wondrium_list_courses,
- omniget_plugin_courses::commands::greatcourses::wondrium_refresh_courses,
- omniget_plugin_courses::commands::greatcourses::start_wondrium_course_download,
- omniget_plugin_courses::commands::greenn::greenn_login_token,
- omniget_plugin_courses::commands::greenn::greenn_check_session,
- omniget_plugin_courses::commands::greenn::greenn_logout,
- omniget_plugin_courses::commands::greenn::greenn_list_courses,
- omniget_plugin_courses::commands::greenn::greenn_refresh_courses,
- omniget_plugin_courses::commands::greenn::start_greenn_course_download,
- omniget_plugin_courses::commands::gumroad::gumroad_login,
- omniget_plugin_courses::commands::gumroad::gumroad_login_token,
- omniget_plugin_courses::commands::gumroad::gumroad_check_session,
- omniget_plugin_courses::commands::gumroad::gumroad_logout,
- omniget_plugin_courses::commands::gumroad::gumroad_list_products,
- omniget_plugin_courses::commands::gumroad::gumroad_refresh_products,
- omniget_plugin_courses::commands::gumroad::start_gumroad_download,
- omniget_plugin_courses::commands::kajabi::kajabi_request_login_link,
- omniget_plugin_courses::commands::kajabi::kajabi_verify_login,
- omniget_plugin_courses::commands::kajabi::kajabi_login_token,
- omniget_plugin_courses::commands::kajabi::kajabi_check_session,
- omniget_plugin_courses::commands::kajabi::kajabi_logout,
- omniget_plugin_courses::commands::kajabi::kajabi_list_sites,
- omniget_plugin_courses::commands::kajabi::kajabi_set_site,
- omniget_plugin_courses::commands::kajabi::kajabi_list_courses,
- omniget_plugin_courses::commands::kajabi::kajabi_refresh_courses,
- omniget_plugin_courses::commands::kajabi::start_kajabi_course_download,
- omniget_plugin_courses::commands::kirvano::kirvano_login,
- omniget_plugin_courses::commands::kirvano::kirvano_login_token,
- omniget_plugin_courses::commands::kirvano::kirvano_check_session,
- omniget_plugin_courses::commands::kirvano::kirvano_logout,
- omniget_plugin_courses::commands::kirvano::kirvano_list_courses,
- omniget_plugin_courses::commands::kirvano::kirvano_refresh_courses,
- omniget_plugin_courses::commands::kirvano::start_kirvano_course_download,
- omniget_plugin_courses::commands::masterclass::masterclass_login_cookies,
- omniget_plugin_courses::commands::masterclass::masterclass_check_session,
- omniget_plugin_courses::commands::masterclass::masterclass_logout,
- omniget_plugin_courses::commands::masterclass::masterclass_list_courses,
- omniget_plugin_courses::commands::masterclass::masterclass_refresh_courses,
- omniget_plugin_courses::commands::masterclass::start_masterclass_course_download,
- omniget_plugin_courses::commands::medcel::medcel_login,
- omniget_plugin_courses::commands::medcel::medcel_login_token,
- omniget_plugin_courses::commands::medcel::medcel_check_session,
- omniget_plugin_courses::commands::medcel::medcel_logout,
- omniget_plugin_courses::commands::medcel::medcel_list_courses,
- omniget_plugin_courses::commands::medcel::medcel_refresh_courses,
- omniget_plugin_courses::commands::medcel::start_medcel_course_download,
- omniget_plugin_courses::commands::medcof::medcof_login_token,
- omniget_plugin_courses::commands::medcof::medcof_check_session,
- omniget_plugin_courses::commands::medcof::medcof_logout,
- omniget_plugin_courses::commands::medcof::medcof_list_courses,
- omniget_plugin_courses::commands::medcof::medcof_refresh_courses,
- omniget_plugin_courses::commands::medcof::start_medcof_course_download,
- omniget_plugin_courses::commands::medway::medway_login_token,
- omniget_plugin_courses::commands::medway::medway_check_session,
- omniget_plugin_courses::commands::medway::medway_logout,
- omniget_plugin_courses::commands::medway::medway_list_courses,
- omniget_plugin_courses::commands::medway::medway_refresh_courses,
- omniget_plugin_courses::commands::medway::start_medway_course_download,
- omniget_plugin_courses::commands::memberkit_cmd::memberkit_login,
- omniget_plugin_courses::commands::memberkit_cmd::memberkit_login_cookie,
- omniget_plugin_courses::commands::memberkit_cmd::memberkit_check_session,
- omniget_plugin_courses::commands::memberkit_cmd::memberkit_logout,
- omniget_plugin_courses::commands::memberkit_cmd::memberkit_list_courses,
- omniget_plugin_courses::commands::memberkit_cmd::memberkit_refresh_courses,
- omniget_plugin_courses::commands::memberkit_cmd::start_memberkit_course_download,
- omniget_plugin_courses::commands::nutror::nutror_login_token,
- omniget_plugin_courses::commands::nutror::nutror_check_session,
- omniget_plugin_courses::commands::nutror::nutror_logout,
- omniget_plugin_courses::commands::nutror::nutror_list_courses,
- omniget_plugin_courses::commands::nutror::nutror_refresh_courses,
- omniget_plugin_courses::commands::nutror::start_nutror_course_download,
- omniget_plugin_courses::commands::pluralsight::pluralsight_login_cookies,
- omniget_plugin_courses::commands::pluralsight::pluralsight_check_session,
- omniget_plugin_courses::commands::pluralsight::pluralsight_logout,
- omniget_plugin_courses::commands::pluralsight::pluralsight_list_courses,
- omniget_plugin_courses::commands::pluralsight::pluralsight_refresh_courses,
- omniget_plugin_courses::commands::pluralsight::start_pluralsight_course_download,
- omniget_plugin_courses::commands::rocketseat::rocketseat_login_token,
- omniget_plugin_courses::commands::rocketseat::rocketseat_check_session,
- omniget_plugin_courses::commands::rocketseat::rocketseat_logout,
- omniget_plugin_courses::commands::rocketseat::rocketseat_list_courses,
- omniget_plugin_courses::commands::rocketseat::rocketseat_search_courses,
- omniget_plugin_courses::commands::rocketseat::rocketseat_refresh_courses,
- omniget_plugin_courses::commands::rocketseat::start_rocketseat_course_download,
- omniget_plugin_courses::commands::teachable::teachable_request_otp,
- omniget_plugin_courses::commands::teachable::teachable_verify_otp,
- omniget_plugin_courses::commands::teachable::teachable_login_token,
- omniget_plugin_courses::commands::teachable::teachable_check_session,
- omniget_plugin_courses::commands::teachable::teachable_logout,
- omniget_plugin_courses::commands::teachable::teachable_set_school,
- omniget_plugin_courses::commands::teachable::teachable_list_schools,
- omniget_plugin_courses::commands::teachable::teachable_list_courses,
- omniget_plugin_courses::commands::teachable::teachable_refresh_courses,
- omniget_plugin_courses::commands::teachable::start_teachable_course_download,
- omniget_plugin_courses::commands::themembers::themembers_login,
- omniget_plugin_courses::commands::themembers::themembers_login_token,
- omniget_plugin_courses::commands::themembers::themembers_check_session,
- omniget_plugin_courses::commands::themembers::themembers_logout,
- omniget_plugin_courses::commands::themembers::themembers_list_courses,
- omniget_plugin_courses::commands::themembers::themembers_refresh_courses,
- omniget_plugin_courses::commands::themembers::start_themembers_course_download,
- omniget_plugin_courses::commands::thinkific::thinkific_login,
- omniget_plugin_courses::commands::thinkific::thinkific_check_session,
- omniget_plugin_courses::commands::thinkific::thinkific_logout,
- omniget_plugin_courses::commands::thinkific::thinkific_list_courses,
- omniget_plugin_courses::commands::thinkific::thinkific_refresh_courses,
- omniget_plugin_courses::commands::thinkific::start_thinkific_course_download,
- omniget_plugin_courses::commands::voomp::voomp_login_token,
- omniget_plugin_courses::commands::voomp::voomp_check_session,
- omniget_plugin_courses::commands::voomp::voomp_logout,
- omniget_plugin_courses::commands::voomp::voomp_list_courses,
- omniget_plugin_courses::commands::voomp::voomp_refresh_courses,
- omniget_plugin_courses::commands::voomp::start_voomp_course_download,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");