Skip to content

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

feat: implement session management for Hotmart with save, load, and delete functionality

Tonhocdef1bfac70b
diff --git a/src-tauri/src/platforms/hotmart/auth.rs b/src-tauri/src/platforms/hotmart/auth.rs
index a6f3370e..00d16128 100644
--- a/src-tauri/src/platforms/hotmart/auth.rs
+++ b/src-tauri/src/platforms/hotmart/auth.rs
@@ -1,3 +1,4 @@
+use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -6,6 +7,7 @@ use chromiumoxide::browser::{Browser, BrowserConfig};
use futures::StreamExt;
use reqwest::cookie::Jar;
use reqwest::header::{HeaderMap, HeaderValue};
+use serde::{Deserialize, Serialize};
pub struct HotmartSession {
pub token: String,
@@ -14,6 +16,117 @@ pub struct HotmartSession {
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!("Não foi possível encontrar diretório de dados do app"))?;
+ 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.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 = reqwest::Client::builder()
+ .cookie_provider(Arc::new(jar))
+ .default_headers(default_headers)
+ .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!("Sessão salva em {:?}", path);
+ 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!(
+ "Sessão restaurada do disco para {} (salva em {})",
+ saved.email,
+ saved.saved_at
+ );
+
+ 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?;
+ tracing::info!("Sessão removida do disco: {:?}", path);
+ }
+ Ok(())
+}
+
pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<HotmartSession> {
tracing::info!("Iniciando autenticação Hotmart para {}", email);
@@ -106,12 +219,9 @@ pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<Hotmart
.ok_or_else(|| anyhow!("Cookie hmVlcIntegration não encontrado"))?;
tracing::info!("Token extraído: {}...", &token[..20.min(token.len())]);
- // Log all cookie names for debugging
let cookie_names: Vec<&str> = cookies.iter().map(|c| c.name.as_str()).collect();
tracing::info!("Cookies extraídos do browser: {:?}", cookie_names);
- // Build cookie jar with ALL browser cookies for all hotmart domains
- // Replicate Python requests.Session() behavior: cookies available for all subdomains
let jar = Jar::default();
let domains = [
"https://hotmart.com",
@@ -129,7 +239,6 @@ pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<Hotmart
}
tracing::info!("Cookies adicionados ao jar para {} domínios", domains.len());
- // Set global default headers matching the Python session
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 {}", token))?);