Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.
Rust downloadmanagerguihacktoberfesthomebrewlightweightlinuxlinux-distributionlocal-firstmacosmacos-packagemedia-toolboxopen-sourcerustsveltetauritrendingtrending-repositorieswindowswindows-desktopytdlp
fix: refactor authentication process to use Tauri's Webview for cookie extraction
Tonho24f13bcbd26b
diff --git a/src-tauri/src/platforms/hotmart/auth.rs b/src-tauri/src/platforms/hotmart/auth.rsindex 0dceb39e..0f2462e0 100644--- a/src-tauri/src/platforms/hotmart/auth.rs+++ b/src-tauri/src/platforms/hotmart/auth.rs@@ -1,13 +1,12 @@use std::path::PathBuf;use std::sync::Arc;-use std::time::{Duration, Instant};+use std::time::Duration;use anyhow::anyhow;-use chromiumoxide::browser::{Browser, BrowserConfig};-use futures::StreamExt;use reqwest::cookie::Jar;use reqwest::header::{HeaderMap, HeaderValue};use serde::{Deserialize, Serialize};+use tauri::Manager;#[derive(Clone)]pub struct HotmartSession {@@ -122,187 +121,176 @@ pub async fn delete_saved_session() -> anyhow::Result<()> {Ok(())}-fn is_post_login_url(url: &str) -> bool {- url.contains("consumer.hotmart.com")- || url.contains("hotmart.com/buyer")- || url.contains("club.hotmart.com")-}--fn build_session_from_cookies(- email: &str,- token: &str,- cookies: &[chromiumoxide::cdp::browser_protocol::network::Cookie],-) -> anyhow::Result<HotmartSession> {- 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 c in cookies {- 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());- }- }-- 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"));+#[cfg(windows)]+async fn extract_webview_cookies(+ window: &tauri::WebviewWindow,+) -> 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)>>();++ 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::from("https://hotmart.com");++ let _ = manager.GetCookies(+ PCWSTR::from_raw(uri.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 client = 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))- .build()?;+ 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(HotmartSession {- token: token.to_string(),- email: email.to_string(),- client,- cookies: cookies- .iter()- .map(|c| (c.name.clone(), c.value.clone()))- .collect(),- })+ Ok(cookies)}-pub async fn authenticate(email: &str, password: &str) -> anyhow::Result<HotmartSession> {- let temp_profile = std::env::temp_dir().join(format!(- "omniget_chrome_{}",- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_millis()- ));-- let (browser, mut handler) = Browser::launch(- BrowserConfig::builder()- .with_head()- .arg(format!("--user-data-dir={}", temp_profile.display()))- .arg("--disable-gpu")- .arg("--no-sandbox")- .arg("--disable-extensions")- .arg("--no-first-run")- .arg("--no-default-browser-check")- .arg("--disable-background-networking")- .build()- .map_err(|e| anyhow!("Falha ao configurar browser: {}", e))?,- )- .await?;- tokio::spawn(async move {- while handler.next().await.is_some() {}- });-- let page = browser.new_page("https://sso.hotmart.com/login").await?;- tokio::time::sleep(Duration::from_secs(3)).await;-- let url = page.url().await?.unwrap_or_default();-- if is_post_login_url(&url) {- } else if url.contains("sso.hotmart.com") {- page.evaluate(- r#"- const el = document.querySelector('#hotmart-cookie-policy');- if (el && el.shadowRoot) {- const btn = el.shadowRoot.querySelector('button.cookie-policy-accept-all');- if (btn) btn.click();- }- "#,- )- .await- .ok();- tokio::time::sleep(Duration::from_secs(1)).await;-- let email_json = serde_json::to_string(email)?;- let password_json = serde_json::to_string(password)?;- page.evaluate(format!(- r#"(function() {{- var s = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;+pub async fn authenticate(+ app: &tauri::AppHandle,+ email: &str,+ password: &str,+) -> anyhow::Result<HotmartSession> {+ let post_login_detected = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let post_login_flag = post_login_detected.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');- s.call(u, {});+ 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, {});+ s.call(p, {password_json});p.dispatchEvent(new Event('input', {{ bubbles: true }}));p.dispatchEvent(new Event('change', {{ bubbles: true }}));- }})()"#,- email_json, password_json,- ))- .await?;- tokio::time::sleep(Duration::from_millis(300)).await;-- page.find_element("[name=submit]").await?.click().await?;-- let start = Instant::now();- loop {- tokio::time::sleep(Duration::from_millis(500)).await;- let current = page.url().await?.unwrap_or_default();- if is_post_login_url(¤t) {- break;- }- if current.contains("captcha") {- let _ = tokio::fs::remove_dir_all(&temp_profile).await;- return Err(anyhow!("Captcha detectado. Tente novamente."));- }- if start.elapsed() > Duration::from_secs(30) {- let page_html = page- .evaluate("document.body ? document.body.innerText : ''")- .await- .ok()- .and_then(|v| v.into_value::<String>().ok())- .unwrap_or_default()- .to_lowercase();+ 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 _ = tokio::fs::remove_dir_all(&temp_profile).await;+ let login_window = tauri::WebviewWindowBuilder::new(+ app,+ "hotmart-login",+ tauri::WebviewUrl::External("https://sso.hotmart.com/login".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("");+ if host == "consumer.hotmart.com" {+ post_login_flag.store(true, std::sync::atomic::Ordering::Relaxed);+ }+ true+ })+ .build()+ .map_err(|e| anyhow!("Falha ao criar janela de login: {}", e))?;- if page_html.contains("incorrect username or password")- || page_html.contains("senha incorreta")- || page_html.contains("credenciais inválidas")- {- return Err(anyhow!("Credenciais inválidas."));- }+ let start = std::time::Instant::now();+ let timeout = Duration::from_secs(120);- return Err(anyhow!(- "Timeout esperando login. Verifique credenciais."- ));- }+ loop {+ if start.elapsed() > timeout {+ let _ = login_window.close();+ return Err(anyhow!("Timeout esperando login. Verifique credenciais."));}- } else {- page.goto("https://consumer.hotmart.com").await?;- tokio::time::sleep(Duration::from_secs(3)).await;- }- page.goto("https://consumer.hotmart.com").await?;- tokio::time::sleep(Duration::from_secs(3)).await;-- let mut cookies = page.get_cookies().await?;- let mut token = cookies- .iter()- .find(|c| c.name == "hmVlcIntegration")- .map(|c| c.value.clone());-- if token.is_none() {- tokio::time::sleep(Duration::from_secs(4)).await;- cookies = page.get_cookies().await?;- token = cookies- .iter()- .find(|c| c.name == "hmVlcIntegration")- .map(|c| c.value.clone());- }+ if post_login_detected.load(std::sync::atomic::Ordering::Relaxed) {+ tokio::time::sleep(Duration::from_secs(5)).await;++ let cookies = extract_webview_cookies(&login_window).await?;+ let _ = login_window.close();- let _ = tokio::fs::remove_dir_all(&temp_profile).await;+ let token = cookies+ .iter()+ .find(|(name, _)| name == "hmVlcIntegration")+ .map(|(_, value)| value.clone())+ .ok_or_else(|| anyhow!("Cookie hmVlcIntegration não encontrado."))?;++ 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 token = token.ok_or_else(|| anyhow!("Cookie hmVlcIntegration não encontrado após tentativas"))?;+ let client = build_client_from_saved(&saved)?;- build_session_from_cookies(email, &token, &cookies)+ return Ok(HotmartSession {+ token,+ email: email.to_string(),+ client,+ cookies,+ });+ }++ tokio::time::sleep(Duration::from_millis(500)).await;+ }}