Skip to content

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

feat: add hotmart_debug_auth command for debugging authentication and session management

Tonhob13a10d46c91
diff --git a/src-tauri/src/commands/auth.rs b/src-tauri/src/commands/auth.rs
index 6d2d7596..7d11abf7 100644
--- a/src-tauri/src/commands/auth.rs
+++ b/src-tauri/src/commands/auth.rs
@@ -1,3 +1,4 @@
+use crate::platforms::hotmart::api;
use crate::platforms::hotmart::auth::authenticate;
use crate::AppState;
@@ -43,7 +44,6 @@ pub async fn hotmart_check_session(
"https://api-sec-vlc.hotmart.com/security/oauth/check_token?token={}",
token
))
- .header("Authorization", format!("Bearer {}", token))
.send()
.await
.map_err(|e| format!("Erro na validação: {}", e))?;
@@ -66,3 +66,103 @@ pub async fn hotmart_logout(
tracing::info!("Sessão Hotmart removida");
Ok(())
}
+
+#[tauri::command]
+pub async fn hotmart_debug_auth(
+ state: tauri::State<'_, AppState>,
+) -> Result<String, String> {
+ tracing::info!("=== DEBUG AUTH INICIADO ===");
+
+ // Step 1: Check if session exists, if not login with test account
+ let guard = state.hotmart_session.lock().await;
+ let has_session = guard.is_some();
+ drop(guard);
+
+ if !has_session {
+ tracing::info!("[DEBUG] Nenhuma sessão ativa, fazendo login...");
+ match authenticate("[email protected]", "Cecilinda2019").await {
+ Ok(session) => {
+ tracing::info!("[DEBUG] Login bem-sucedido!");
+ let mut guard = state.hotmart_session.lock().await;
+ *guard = Some(session);
+ }
+ Err(e) => {
+ let msg = format!("[DEBUG] FALHA no login: {}", e);
+ tracing::error!("{}", msg);
+ return Err(msg);
+ }
+ }
+ }
+
+ let guard = state.hotmart_session.lock().await;
+ let session = guard.as_ref().unwrap();
+
+ // Step 2: Log token
+ tracing::info!("[DEBUG] Token extraído: {}...", &session.token[..20.min(session.token.len())]);
+
+ // Log all cookies
+ let cookie_names: Vec<&str> = session.cookies.iter().map(|(name, _)| name.as_str()).collect();
+ tracing::info!("[DEBUG] Cookies na sessão: {:?}", cookie_names);
+
+ let has_vlc = session.cookies.iter().any(|(name, _)| name == "hmVlcIntegration");
+ tracing::info!("[DEBUG] hmVlcIntegration presente: {}", has_vlc);
+
+ // Step 3: check_token
+ tracing::info!("[DEBUG] Chamando check_token...");
+ match api::get_subdomains(session).await {
+ Ok(subdomains) => {
+ tracing::info!("[DEBUG] Subdomínios encontrados: {}", subdomains.len());
+ for s in &subdomains {
+ tracing::info!("[DEBUG] productId: {} → subdomain: {}", s.product_id, s.subdomain);
+ }
+ }
+ Err(e) => {
+ tracing::error!("[DEBUG] FALHA check_token: {}", e);
+ return Err(format!("check_token falhou: {}", e));
+ }
+ }
+
+ // Step 4: list courses
+ tracing::info!("[DEBUG] Chamando list_courses...");
+ let mut courses = match api::list_courses(session).await {
+ Ok(c) => {
+ tracing::info!("[DEBUG] Cursos encontrados: {}", c.len());
+ c
+ }
+ Err(e) => {
+ tracing::error!("[DEBUG] FALHA list_courses: {}", e);
+ return Err(format!("list_courses falhou: {}", e));
+ }
+ };
+
+ // Merge subdomains
+ if let Ok(subdomains) = api::get_subdomains(session).await {
+ api::merge_subdomains(&mut courses, &subdomains);
+ }
+
+ // Step 5: Get price for each course
+ let mut output_lines = Vec::new();
+ for course in &mut courses {
+ let price = match api::get_course_price(session, course.id).await {
+ Ok(p) => {
+ course.price = Some(p);
+ format!("R${:.2}", p)
+ }
+ Err(_) => "N/A".to_string(),
+ };
+ let line = format!(
+ "- {} (ID: {}, slug: {:?}, preço: {})",
+ course.name, course.id, course.slug, price
+ );
+ tracing::info!("[DEBUG] {}", line);
+ output_lines.push(line);
+ }
+
+ tracing::info!("=== DEBUG AUTH CONCLUÍDO: {} cursos ===", courses.len());
+
+ Ok(format!(
+ "Debug concluído: {} cursos encontrados\n{}",
+ courses.len(),
+ output_lines.join("\n")
+ ))
+}
diff --git a/src-tauri/src/commands/courses.rs b/src-tauri/src/commands/courses.rs
index 1ef2b43e..01c8d02f 100644
--- a/src-tauri/src/commands/courses.rs
+++ b/src-tauri/src/commands/courses.rs
@@ -10,11 +10,35 @@ pub async fn hotmart_list_courses(
.as_ref()
.ok_or_else(|| "Não autenticado. Faça login primeiro.".to_string())?;
+ // Step 1: get subdomains via check_token
+ let subdomains = match api::get_subdomains(session).await {
+ Ok(s) => {
+ tracing::info!("Subdomínios carregados: {}", s.len());
+ s
+ }
+ Err(e) => {
+ tracing::warn!("Falha ao buscar subdomínios: {}. Continuando sem eles.", e);
+ vec![]
+ }
+ };
+
+ // Step 2: list courses
let mut courses = api::list_courses(session).await.map_err(|e| e.to_string())?;
- match api::get_subdomains(session).await {
- Ok(subdomains) => api::merge_subdomains(&mut courses, &subdomains),
- Err(e) => tracing::warn!("Falha ao buscar subdomínios: {}. Continuando sem eles.", e),
+ // Step 3: merge subdomains
+ api::merge_subdomains(&mut courses, &subdomains);
+
+ // Step 4: fetch prices for each course
+ for course in &mut courses {
+ match api::get_course_price(session, course.id).await {
+ Ok(price) => {
+ course.price = Some(price);
+ tracing::info!("- {} (ID: {}, slug: {:?}, preço: R${:.2})", course.name, course.id, course.slug, price);
+ }
+ Err(e) => {
+ tracing::warn!("Preço não disponível para {} (ID: {}): {}", course.name, course.id, e);
+ }
+ }
}
Ok(courses)
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 7572626d..62579698 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -37,6 +37,7 @@ pub fn run() {
commands::auth::hotmart_login,
commands::auth::hotmart_check_session,
commands::auth::hotmart_logout,
+ commands::auth::hotmart_debug_auth,
commands::courses::hotmart_list_courses,
commands::courses::hotmart_get_modules,
])
diff --git a/src-tauri/src/platforms/hotmart/api.rs b/src-tauri/src/platforms/hotmart/api.rs
index 7b878232..7b6016ea 100644
--- a/src-tauri/src/platforms/hotmart/api.rs
+++ b/src-tauri/src/platforms/hotmart/api.rs
@@ -2,6 +2,7 @@ use anyhow::anyhow;
use serde::{Deserialize, Serialize};
use super::auth::HotmartSession;
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Course {
pub id: u64,
@@ -10,6 +11,9 @@ pub struct Course {
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>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -66,28 +70,99 @@ pub struct SubdomainInfo {
pub subdomain: String,
}
+/// CHAMADA 1: check_token — get subdomains mapping (productId → subdomain)
+pub async fn get_subdomains(session: &HotmartSession) -> anyhow::Result<Vec<SubdomainInfo>> {
+ tracing::info!("Buscando subdomínios via check_token...");
+
+ let url = format!(
+ "https://api-sec-vlc.hotmart.com/security/oauth/check_token?token={}",
+ session.token
+ );
+
+ let resp = session
+ .client
+ .get(&url)
+ .send()
+ .await?;
+
+ let status = resp.status();
+ let body_text = resp.text().await?;
+ tracing::info!("check_token status: {} | body (200 chars): {}", status, &body_text[..200.min(body_text.len())]);
+
+ 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!("Campo 'resources' não encontrado em 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,
+ });
+ }
+ }
+
+ tracing::info!("{} subdomínios encontrados", subdomains.len());
+ Ok(subdomains)
+}
+
+/// CHAMADA 2: list purchases — get all courses
pub async fn list_courses(session: &HotmartSession) -> anyhow::Result<Vec<Course>> {
tracing::info!("Listando cursos Hotmart...");
let resp = session
.client
.get("https://api-hub.cb.hotmart.com/club-drive-api/rest/v2/purchase/?archived=UNARCHIVED")
- .header("Authorization", format!("Bearer {}", session.token))
- .header("Origin", "https://consumer.hotmart.com")
+ .header("Host", "api-hub.cb.hotmart.com")
.send()
- .await?
- .error_for_status()?;
+ .await?;
- let body: serde_json::Value = resp.json().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+ tracing::info!("list_courses status: {} | body (200 chars): {}", status, &body_text[..200.min(body_text.len())]);
+
+ 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)?;
+
+ // The API returns { "data": [...] } where each item has a nested "product" object
+ // Fallback: try root array, then "purchases", then "data"
let purchases = body
- .as_array()
+ .get("data")
+ .and_then(|d| d.as_array())
.or_else(|| body.get("purchases").and_then(|p| p.as_array()))
- .ok_or_else(|| anyhow!("Formato inesperado na resposta de cursos"))?;
+ .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 {
+ // data[].product.id, data[].product.name, etc.
let product = p.get("product").unwrap_or(p);
+
let id = product
.get("id")
.and_then(|v| v.as_u64())
@@ -97,25 +172,55 @@ pub async fn list_courses(session: &HotmartSession) -> anyhow::Result<Vec<Course
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
- let seller = p
- .get("producer")
- .or_else(|| p.get("seller"))
+
+ // data[].product.seller.name
+ 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 is_hotmart_club = p
- .get("accessRights")
- .and_then(|a| a.get("hasClubAccess"))
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
+
+ // data[].product.hotmartClub.slug
+ 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);
+
+ // data[].product.category
+ let category = product
+ .get("category")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ // Try to get image from logo or image fields
+ let image_url = product
+ .get("logo")
+ .and_then(|v| v.as_str())
+ .or_else(|| product.get("image").and_then(|v| v.as_str()))
+ .or_else(|| product.get("imageUrl").and_then(|v| v.as_str()))
+ .map(String::from);
courses.push(Course {
id,
name,
- slug: None,
+ slug,
seller,
subdomain: None,
is_hotmart_club,
+ price: None,
+ image_url,
+ category,
});
}
@@ -123,65 +228,55 @@ pub async fn list_courses(session: &HotmartSession) -> anyhow::Result<Vec<Course
Ok(courses)
}
-pub async fn get_subdomains(session: &HotmartSession) -> anyhow::Result<Vec<SubdomainInfo>> {
- tracing::info!("Buscando subdomínios...");
-
+/// CHAMADA 3: get price for a single course
+pub async fn get_course_price(session: &HotmartSession, product_id: u64) -> anyhow::Result<f64> {
let url = format!(
- "https://api-sec-vlc.hotmart.com/security/oauth/check_token?token={}",
- session.token
+ "https://api-hub.cb.hotmart.com/club-drive-api/rest/v2/purchase/products/{}",
+ product_id
);
+
let resp = session
.client
.get(&url)
- .header("Authorization", format!("Bearer {}", session.token))
+ .header("Host", "api-hub.cb.hotmart.com")
.send()
- .await?
- .error_for_status()?;
-
- let body: serde_json::Value = resp.json().await?;
-
- let resources = body
- .get("resources")
- .and_then(|r| r.as_array())
- .ok_or_else(|| anyhow!("Campo 'resources' não encontrado em 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();
+ .await?;
- if product_id > 0 && !subdomain.is_empty() {
- subdomains.push(SubdomainInfo {
- product_id,
- subdomain,
- });
- }
+ let status = resp.status();
+ if !status.is_success() {
+ let body_text = resp.text().await.unwrap_or_default();
+ tracing::warn!("get_course_price({}) status {}: {}", product_id, status, &body_text[..200.min(body_text.len())]);
+ return Err(anyhow!("Preço não disponível (status {})", status));
}
- tracing::info!("{} subdomínios encontrados", subdomains.len());
- Ok(subdomains)
+ let body: serde_json::Value = resp.json().await?;
+
+ // purchases[0].value
+ 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());
- course.slug = Some(info.subdomain.clone());
+ // If slug wasn't set from the purchase API, use subdomain
+ if course.slug.is_none() {
+ course.slug = Some(info.subdomain.clone());
+ }
}
}
}
+/// Navigation API — requires different headers (Origin/Referer = https://hotmart.com)
pub async fn get_modules(
session: &HotmartSession,
slug: &str,
@@ -189,23 +284,33 @@ pub async fn get_modules(
) -> anyhow::Result<Vec<Module>> {
tracing::info!("Buscando módulos do curso {} (slug={})", product_id, slug);
+ // Navigation API needs different headers than the default session headers
let resp = session
.client
.get("https://api-club-course-consumption-gateway.hotmart.com/v1/navigation")
.header("Authorization", format!("Bearer {}", session.token))
- .header("Origin", "https://consumer.hotmart.com")
.header("Host", "api-club-course-consumption-gateway.hotmart.com")
+ .header("Origin", "https://hotmart.com")
+ .header("Referer", "https://hotmart.com")
.header("slug", slug)
.header("x-product-id", product_id.to_string())
.send()
- .await?
- .error_for_status()?;
+ .await?;
- let body: serde_json::Value = resp.json().await?;
+ let status = resp.status();
+ let body_text = resp.text().await?;
+ tracing::info!("get_modules status: {} | body (200 chars): {}", status, &body_text[..200.min(body_text.len())]);
+
+ 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
- .as_array()
- .or_else(|| body.get("modules").and_then(|m| m.as_array()))
+ .get("modules")
+ .and_then(|m| m.as_array())
+ .or_else(|| body.as_array())
.ok_or_else(|| anyhow!("Formato inesperado na resposta de módulos"))?;
let mut modules = Vec::new();
@@ -275,8 +380,9 @@ pub async fn get_lesson(
.client
.get(&url)
.header("Authorization", format!("Bearer {}", session.token))
- .header("Origin", "https://consumer.hotmart.com")
.header("Host", "api-club-course-consumption-gateway.hotmart.com")
+ .header("Origin", "https://hotmart.com")
+ .header("Referer", "https://hotmart.com")
.header("slug", slug)
.header("x-product-id", product_id.to_string())
.send()
@@ -382,8 +488,6 @@ pub async fn get_attachment_url(
let resp = session
.client
.get(&url)
- .header("Authorization", format!("Bearer {}", session.token))
- .header("Origin", "https://consumer.hotmart.com")
.send()
.await?
.error_for_status()?;
diff --git a/src-tauri/src/platforms/hotmart/auth.rs b/src-tauri/src/platforms/hotmart/auth.rs
index 3319fc1a..a6f3370e 100644
--- a/src-tauri/src/platforms/hotmart/auth.rs
+++ b/src-tauri/src/platforms/hotmart/auth.rs
@@ -5,6 +5,7 @@ use anyhow::anyhow;
use chromiumoxide::browser::{Browser, BrowserConfig};
use futures::StreamExt;
use reqwest::cookie::Jar;
+use reqwest::header::{HeaderMap, HeaderValue};
pub struct HotmartSession {
pub token: String,
@@ -105,18 +106,44 @@ 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",
+ "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 c in &cookies {
- jar.add_cookie_str(
- &format!("{}={}", c.name, c.value),
- &"https://hotmart.com".parse().unwrap(),
- );
+ let cookie_str = format!("{}={}; Domain=.hotmart.com; Path=/", c.name, c.value);
+ for domain in &domains {
+ jar.add_cookie_str(&cookie_str, &domain.parse().unwrap());
+ }
}
+ 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))?);
+ 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()?;
- tracing::info!("Login Hotmart concluído com sucesso");
+ tracing::info!("Login Hotmart concluído com sucesso (client com headers globais)");
Ok(HotmartSession {
token,
diff --git a/src/components/hotmart/CourseCard.svelte b/src/components/hotmart/CourseCard.svelte
index 1e464844..e363a144 100644
--- a/src/components/hotmart/CourseCard.svelte
+++ b/src/components/hotmart/CourseCard.svelte
@@ -1,261 +1,134 @@
<script lang="ts">
- import { invoke } from "@tauri-apps/api/core";
- import ModuleList from "./ModuleList.svelte";
-
- type Course = {
- id: number;
+ type CourseCardProps = {
name: string;
- slug: string | null;
- seller: string;
- subdomain: string | null;
- is_hotmart_club: boolean;
+ price: string;
+ imageUrl?: string;
+ onDownload: () => void;
};
- type Module = {
- id: string;
- name: string;
- pages: { hash: string; name: string; page_type: string }[];
- };
-
- let { course }: { course: Course } = $props();
-
- let expanded = $state(false);
- let modules: Module[] = $state([]);
- let loadingModules = $state(false);
- let modulesLoaded = $state(false);
- let modulesError = $state("");
-
- let totalLessons = $derived(
- modules.reduce((sum, m) => sum + m.pages.length, 0)
- );
-
- async function toggle() {
- expanded = !expanded;
- if (expanded && !modulesLoaded) {
- await loadModules();
- }
- }
-
- async function loadModules() {
- if (!course.subdomain) {
- modulesError = "Subdomain indisponivel para este curso.";
- return;
- }
- loadingModules = true;
- modulesError = "";
- try {
- modules = await invoke("hotmart_get_modules", {
- courseId: course.id,
- slug: course.subdomain,
- });
- modulesLoaded = true;
- } catch (e: any) {
- modulesError = typeof e === "string" ? e : e.message ?? "Erro ao carregar modulos";
- } finally {
- loadingModules = false;
- }
- }
+ let { name, price, imageUrl, onDownload }: CourseCardProps = $props();
</script>
-<div class="course-card" class:expanded>
- <button class="card-header" onclick={toggle}>
- <div class="header-left">
- <span class="course-name">{course.name}</span>
- <span class="course-seller">{course.seller}</span>
- </div>
- <div class="header-right">
- {#if course.is_hotmart_club}
- <span class="badge">Club</span>
- {/if}
- <span class="chevron" class:rotated={expanded}>&#9662;</span>
- </div>
- </button>
-
- {#if expanded}
- <div class="card-body">
- <div class="body-top">
- {#if modulesLoaded}
- <span class="summary">{modules.length} modulos &middot; {totalLessons} aulas</span>
- {/if}
- <button class="button" disabled>Baixar Curso</button>
+<div class="course-card">
+ <div class="card-image">
+ {#if imageUrl}
+ <img src={imageUrl} alt={name} />
+ {:else}
+ <div class="placeholder">
+ <svg
+ width="32"
+ height="32"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.5"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ >
+ <path d="M22 9l-10 -4l-10 4l10 4l10 -4v6" />
+ <path d="M6 10.6v5.4a6 3 0 0 0 12 0v-5.4" />
+ </svg>
</div>
-
- {#if loadingModules}
- <div class="spinner-wrap">
- <span class="spinner"></span>
- </div>
- {:else if modulesError}
- <p class="error-msg">{modulesError}</p>
- {:else if modules.length > 0}
- <ModuleList {modules} />
- {:else if modulesLoaded}
- <p class="empty-msg">Nenhum modulo encontrado.</p>
- {/if}
- </div>
- {/if}
+ {/if}
+ </div>
+
+ <div class="card-body">
+ <h4 class="card-title" title={name}>{name}</h4>
+ <span class="card-price">{price}</span>
+ <button class="button elevated card-download" onclick={onDownload}>
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ >
+ <path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2" />
+ <polyline points="7 11 12 16 17 11" />
+ <line x1="12" y1="4" x2="12" y2="16" />
+ </svg>
+ Baixar
+ </button>
+ </div>
</div>
<style>
.course-card {
- background: var(--button-elevated);
- box-shadow: var(--button-box-shadow);
+ background: var(--button);
border-radius: var(--border-radius);
+ box-shadow: var(--button-box-shadow);
overflow: hidden;
- }
-
- .course-card.expanded {
- box-shadow: 0 0 0 1px var(--blue) inset;
- }
-
- .card-header {
- width: 100%;
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: calc(var(--padding) + 2px) calc(var(--padding) + 4px);
- background: transparent;
- border: none;
- cursor: pointer;
- text-align: left;
- color: var(--secondary);
- gap: var(--padding);
- }
-
- @media (hover: hover) {
- .card-header:hover {
- background: var(--button-stroke);
- }
- }
-
- .card-header:active {
- background: var(--button-stroke);
- }
-
- .card-header:focus-visible {
- outline: var(--focus-ring);
- outline-offset: var(--focus-ring-offset);
- }
-
- .header-left {
display: flex;
flex-direction: column;
- gap: 4px;
- min-width: 0;
}
- .course-name {
- font-weight: 500;
- font-size: 14.5px;
- white-space: nowrap;
+ .card-image {
+ aspect-ratio: 16 / 9;
+ background: var(--button-elevated);
overflow: hidden;
- text-overflow: ellipsis;
}
- .course-seller {
- font-size: 12.5px;
- font-weight: 500;
- color: var(--gray);
+ .card-image img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ pointer-events: none;
}
- .header-right {
+ .placeholder {
+ width: 100%;
+ height: 100%;
display: flex;
align-items: center;
- gap: calc(var(--padding) / 1.5);
- flex-shrink: 0;
- }
-
- .badge {
- font-size: 11px;
- font-weight: 500;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- background: var(--blue);
- color: var(--primary);
- padding: 2px calc(var(--padding) / 2);
- border-radius: calc(var(--border-radius) / 2);
- }
-
- .chevron {
- font-size: 12px;
+ justify-content: center;
color: var(--gray);
- transition: transform 0.15s;
}
- .chevron.rotated {
- transform: rotate(180deg);
+ .placeholder svg {
+ pointer-events: none;
}
.card-body {
- padding: 0 calc(var(--padding) + 4px) calc(var(--padding) + 2px);
+ padding: var(--padding);
display: flex;
flex-direction: column;
- gap: var(--padding);
- animation: slideDown 0.15s ease-out;
- }
-
- @keyframes slideDown {
- from {
- opacity: 0;
- transform: translateY(-8px);
- }
- to {
- opacity: 1;
- transform: translateY(0);
- }
+ gap: calc(var(--padding) / 2);
}
- .body-top {
- display: flex;
- align-items: center;
- justify-content: space-between;
- border-top: 1px solid var(--content-border);
- padding-top: var(--padding);
+ .card-title {
+ font-size: 14.5px;
+ font-weight: 500;
+ margin-block: 0;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ line-height: 1.3;
+ color: var(--secondary);
+ user-select: text;
}
- .summary {
+ .card-price {
font-size: 12.5px;
font-weight: 500;
color: var(--gray);
}
- .body-top .button {
- padding: calc(var(--padding) / 2) var(--padding);
- font-size: 12.5px;
- opacity: 0.5;
- }
-
- .spinner-wrap {
+ .card-download {
+ width: 100%;
display: flex;
+ align-items: center;
justify-content: center;
- padding: calc(var(--padding) * 1.5) 0;
- }
-
- .spinner {
- width: 20px;
- height: 20px;
- border: 2px solid var(--input-border);
- border-top-color: var(--blue);
- border-radius: 50%;
- animation: spin 0.6s linear infinite;
+ gap: calc(var(--padding) / 2);
+ margin-top: calc(var(--padding) / 2);
}
- @keyframes spin {
- to {
- transform: rotate(360deg);
- }
- }
-
- .error-msg {
- color: var(--red);
- font-size: 12.5px;
- font-weight: 500;
- }
-
- .empty-msg {
- color: var(--gray);
- font-size: 12.5px;
- font-weight: 500;
- text-align: center;
- padding: var(--padding) 0;
+ .card-download svg {
+ pointer-events: none;
}
</style>
diff --git a/src/routes/hotmart/+page.svelte b/src/routes/hotmart/+page.svelte
index f0a39671..4cbda855 100644
--- a/src/routes/hotmart/+page.svelte
+++ b/src/routes/hotmart/+page.svelte
@@ -9,6 +9,9 @@
seller: string;
subdomain: string | null;
is_hotmart_club: boolean;
+ price: number | null;
+ image_url: string | null;
+ category: string | null;
};
let email = $state("");
@@ -24,6 +27,47 @@
let loadingCourses = $state(false);
let coursesError = $state("");
+ let debugOutput = $state("");
+ let debugLoading = $state(false);
+
+ // Pagination
+ const ITEMS_PER_PAGE = 12;
+ let currentPage = $state(1);
+
+ let totalPages = $derived(Math.max(1, Math.ceil(courses.length / ITEMS_PER_PAGE)));
+ let paginatedCourses = $derived(
+ courses.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE)
+ );
+
+ // Generate page numbers for pagination display
+ let pageNumbers = $derived((): number[] => {
+ const pages: number[] = [];
+ if (totalPages <= 7) {
+ for (let i = 1; i <= totalPages; i++) pages.push(i);
+ } else {
+ pages.push(1);
+ if (currentPage > 3) pages.push(-1); // ellipsis
+ const start = Math.max(2, currentPage - 1);
+ const end = Math.min(totalPages - 1, currentPage + 1);
+ for (let i = start; i <= end; i++) pages.push(i);
+ if (currentPage < totalPages - 2) pages.push(-1); // ellipsis
+ pages.push(totalPages);
+ }
+ return pages;
+ });
+
+ function formatPrice(price: number | null): string {
+ if (price === null || price === undefined) return "—";
+ if (price === 0) return "Gratuito";
+ return `R$ ${price.toFixed(2).replace(".", ",")}`;
+ }
+
+ function goToPage(page: number) {
+ if (page >= 1 && page <= totalPages) {
+ currentPage = page;
+ }
+ }
+
$effect(() => {
checkSession();
});
@@ -66,6 +110,8 @@
sessionEmail = "";
courses = [];
coursesError = "";
+ currentPage = 1;
+ debugOutput = "";
}
async function loadCourses() {
@@ -73,28 +119,59 @@
coursesError = "";
try {
courses = await invoke("hotmart_list_courses");
+ currentPage = 1;
} catch (e: any) {
coursesError = typeof e === "string" ? e : e.message ?? "Erro ao carregar cursos";
} finally {
loadingCourses = false;
}
}
+
+ async function handleDebugAuth() {
+ debugLoading = true;
+ debugOutput = "";
+ try {
+ const result = await invoke<string>("hotmart_debug_auth");
+ debugOutput = result;
+ } catch (e: any) {
+ debugOutput = `ERRO: ${typeof e === "string" ? e : e.message ?? "Erro desconhecido"}`;
+ } finally {
+ debugLoading = false;
+ }
+ }
</script>
{#if checking}
+ <!-- Estado 1: Verificando sessão -->
<div class="page-center">
<span class="spinner"></span>
+ <span class="spinner-text">Verificando sessão...</span>
</div>
{:else if loggedIn}
- <div class="page-scroll">
+ <!-- Estado 3/4: Logado -->
+ <div class="page-logged">
<div class="session-bar">
<span class="session-info">
- {sessionEmail ? `Logado como ${sessionEmail}` : "Logado"}
+ Logado como {sessionEmail || "—"}
</span>
- <button class="button" onclick={handleLogout}>Sair</button>
+ <div class="session-actions">
+ <button
+ class="button"
+ onclick={handleDebugAuth}
+ disabled={debugLoading}
+ >
+ {debugLoading ? "Debugando..." : "Debug Auth"}
+ </button>
+ <button class="button" onclick={handleLogout}>Sair</button>
+ </div>
</div>
+ {#if debugOutput}
+ <pre class="debug-output">{debugOutput}</pre>
+ {/if}
+
{#if loadingCourses}
+ <!-- Estado 3: Carregando cursos -->
<div class="spinner-section">
<span class="spinner"></span>
<span class="spinner-text">Carregando cursos...</span>
@@ -105,20 +182,73 @@
<button class="button" onclick={loadCourses}>Tentar novamente</button>
</div>
{:else if courses.length === 0}
- <p class="empty-text">Nenhum curso encontrado.</p>
+ <p class="empty-text">Nenhum curso encontrado nesta conta.</p>
{:else}
- <p class="courses-count">{courses.length} {courses.length === 1 ? 'curso' : 'cursos'}</p>
- <div class="courses-list">
- {#each courses as course (course.id)}
- <CourseCard {course} />
+ <!-- Estado 4: Cursos carregados -->
+ <div class="courses-header">
+ <h2>Seus Cursos</h2>
+ <span class="subtext">{courses.length} {courses.length === 1 ? "curso" : "cursos"}</span>
+ </div>
+
+ <div class="courses-grid">
+ {#each paginatedCourses as course (course.id)}
+ <CourseCard
+ name={course.name}
+ price={formatPrice(course.price)}
+ imageUrl={course.image_url ?? undefined}
+ onDownload={() => {
+ /* TODO: download logic */
+ }}
+ />
{/each}
</div>
+
+ <!-- Pagination -->
+ {#if totalPages > 1}
+ <div class="pagination">
+ <span class="pagination-info">
+ Página {currentPage} de {totalPages} &middot; {courses.length} cursos
+ </span>
+ <div class="pagination-controls">
+ <button
+ class="button pagination-btn"
+ disabled={currentPage <= 1}
+ onclick={() => goToPage(currentPage - 1)}
+ >
+ &lt;
+ </button>
+
+ {#each pageNumbers() as page}
+ {#if page === -1}
+ <span class="pagination-ellipsis">&hellip;</span>
+ {:else}
+ <button
+ class="button pagination-btn"
+ class:active={page === currentPage}
+ onclick={() => goToPage(page)}
+ >
+ {page}
+ </button>
+ {/if}
+ {/each}
+
+ <button
+ class="button pagination-btn"
+ disabled={currentPage >= totalPages}
+ onclick={() => goToPage(currentPage + 1)}
+ >
+ &gt;
+ </button>
+ </div>
+ </div>
+ {/if}
{/if}
</div>
{:else}
+ <!-- Estado 2: Não logado -->
<div class="page-center">
<div class="login-card">
- <h2>Login</h2>
+ <h2>Hotmart</h2>
<form class="form" onsubmit={(e) => { e.preventDefault(); handleLogin(); }}>
<label class="field">
<span class="field-label">Email</span>
@@ -132,10 +262,10 @@
/>
</label>
<label class="field">
- <span class="field-label">Password</span>
+ <span class="field-label">Senha</span>
<input
type="password"
- placeholder="Your password"
+ placeholder="Sua senha"
bind:value={password}
class="input"
disabled={loading}
@@ -151,7 +281,7 @@
{#if loading}
Autenticando...
{:else}
- Sign in
+ Entrar
{/if}
</button>
</form>
@@ -160,27 +290,32 @@
{/if}
<style>
+ /* === State 1: Checking / Center layout === */
.page-center {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: calc(100vh - var(--padding) * 4);
+ gap: var(--padding);
}
- .page-scroll {
+ /* === State 3/4: Logged in layout === */
+ .page-logged {
display: flex;
flex-direction: column;
align-items: center;
- gap: var(--padding);
- padding-top: var(--padding);
+ gap: calc(var(--padding) * 1.5);
+ padding: calc(var(--padding) * 1.5);
+ width: 100%;
}
- .page-scroll > :global(*) {
+ .page-logged > :global(*) {
width: 100%;
- max-width: 580px;
+ max-width: 1200px;
}
+ /* === Session bar === */
.session-bar {
display: flex;
align-items: center;
@@ -193,11 +328,112 @@
color: var(--gray);
}
- .session-bar .button {
+ .session-actions {
+ display: flex;
+ gap: calc(var(--padding) / 2);
+ }
+
+ .session-bar :global(.button) {
padding: calc(var(--padding) / 2) var(--padding);
font-size: 12.5px;
}
+ /* === Debug output === */
+ .debug-output {
+ background: var(--button);
+ border-radius: var(--border-radius);
+ padding: var(--padding);
+ font-size: 11px;
+ color: var(--secondary);
+ white-space: pre-wrap;
+ word-break: break-all;
+ user-select: text;
+ max-height: 200px;
+ overflow-y: auto;
+ box-shadow: var(--button-box-shadow);
+ }
+
+ /* === Courses header === */
+ .courses-header {
+ display: flex;
+ align-items: baseline;
+ gap: var(--padding);
+ }
+
+ .courses-header h2 {
+ margin-block: 0;
+ }
+
+ .subtext {
+ font-size: 12.5px;
+ font-weight: 500;
+ color: var(--gray);
+ }
+
+ /* === Courses grid (responsive) === */
+ .courses-grid {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: var(--padding);
+ }
+
+ @media (max-width: 1000px) {
+ .courses-grid {
+ grid-template-columns: repeat(3, 1fr);
+ }
+ }
+
+ @media (max-width: 750px) {
+ .courses-grid {
+ grid-template-columns: repeat(2, 1fr);
+ }
+ }
+
+ @media (max-width: 535px) {
+ .courses-grid {
+ grid-template-columns: 1fr;
+ }
+ }
+
+ /* === Pagination === */
+ .pagination {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: var(--padding);
+ padding-top: var(--padding);
+ }
+
+ .pagination-info {
+ font-size: 12.5px;
+ font-weight: 500;
+ color: var(--gray);
+ }
+
+ .pagination-controls {
+ display: flex;
+ align-items: center;
+ gap: calc(var(--padding) / 3);
+ }
+
+ .pagination-btn {
+ min-width: 36px;
+ height: 36px;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 14.5px;
+ }
+
+ .pagination-ellipsis {
+ min-width: 36px;
+ text-align: center;
+ color: var(--gray);
+ font-size: 14.5px;
+ }
+
+ /* === Login card === */
.login-card {
width: 100%;
max-width: 400px;
@@ -209,6 +445,10 @@
gap: calc(var(--padding) * 1.5);
}
+ .login-card h2 {
+ margin-block: 0;
+ }
+
.form {
display: flex;
flex-direction: column;
@@ -251,24 +491,13 @@
cursor: default;
}
+ /* === Shared === */
.error-msg {
color: var(--red);
font-size: 12.5px;
font-weight: 500;
}
- .courses-count {
- font-size: 12.5px;
- font-weight: 500;
- color: var(--gray);
- }
-
- .courses-list {
- display: flex;
- flex-direction: column;
- gap: calc(var(--padding) / 1.5);
- }
-
.spinner-section {
display: flex;
flex-direction: column;