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(courses): resolve Udemy empty courses list and 0-byte download failures (fixes #72)
IGECT25ba825096c2
diff --git a/src-tauri/plugins/courses/src/commands/udemy_courses.rs b/src-tauri/plugins/courses/src/commands/udemy_courses.rsindex 2800f60f..5921501a 100644--- a/src-tauri/plugins/courses/src/commands/udemy_courses.rs+++ b/src-tauri/plugins/courses/src/commands/udemy_courses.rs@@ -88,13 +88,17 @@ pub async fn fetch_courses_via_api(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 results = match data.get("results").and_then(|r| r.as_array()) {+ Some(arr) => arr,+ None => {+ if let Some(detail) = data.get("detail").and_then(|d| d.as_str()) {+ return Err(format!("Udemy API authorization error: {}", detail));+ }+ return Err("Invalid API response: missing 'results' array".to_string());+ }+ };- let mut courses = parse_courses_from_results(&results);+ 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",@@ -169,13 +173,17 @@ async fn fetch_courses_via_webview(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 results = match data.get("results").and_then(|r| r.as_array()) {+ Some(arr) => arr,+ None => {+ if let Some(detail) = data.get("detail").and_then(|d| d.as_str()) {+ return Err(format!("Udemy API authorization error: {}", detail));+ }+ return Err("Invalid API response: missing 'results' array".to_string());+ }+ };- let mut courses = parse_courses_from_results(&results);+ 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",diff --git a/src-tauri/plugins/courses/src/commands/udemy_downloads.rs b/src-tauri/plugins/courses/src/commands/udemy_downloads.rsindex ab23207b..dc71e304 100644--- a/src-tauri/plugins/courses/src/commands/udemy_downloads.rs+++ b/src-tauri/plugins/courses/src/commands/udemy_downloads.rs@@ -57,11 +57,15 @@ async fn fetch_curriculum_via_webview(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();+ let mut all_results = match data.get("results").and_then(|r| r.as_array()) {+ Some(arr) => arr.clone(),+ None => {+ if let Some(detail) = data.get("detail").and_then(|d| d.as_str()) {+ return Err(format!("Udemy authorization error: {}", detail));+ }+ return Err("Invalid API response: missing 'results' array".to_string());+ }+ };loop {let next_url = data@@ -137,11 +141,15 @@ async fn fetch_curriculum_via_api(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();+ let mut all_results = match data.get("results").and_then(|r| r.as_array()) {+ Some(arr) => arr.clone(),+ None => {+ if let Some(detail) = data.get("detail").and_then(|d| d.as_str()) {+ return Err(format!("Udemy authorization error: {}", detail));+ }+ return Err("Invalid API response: missing 'results' array".to_string());+ }+ };loop {let next_url = data@@ -222,40 +230,33 @@ pub async fn start_udemy_course_download(.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)+ let curriculum = 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(e) => {- active.lock().await.remove(&course_id);- return Err(format!("Failed to fetch curriculum: {}", e));+ {+ Ok(c) => c,+ Err(e2) => {+ active.lock().await.remove(&course_id);+ return Err(format!(+ "Failed to fetch curriculum: {} (direct API error: {})",+ e2, e+ ));+ }}}};diff --git a/src-tauri/plugins/courses/src/platforms/udemy/auth.rs b/src-tauri/plugins/courses/src/platforms/udemy/auth.rsindex 58e634b9..b57aea21 100644--- a/src-tauri/plugins/courses/src/platforms/udemy/auth.rs+++ b/src-tauri/plugins/courses/src/platforms/udemy/auth.rs@@ -9,6 +9,8 @@ use reqwest::header::{HeaderMap, HeaderValue};use serde::{Deserialize, Serialize};use tauri::Manager;+pub const UDEMY_API_USER_AGENT: &str = "okhttp/4.9.2 UdemyAndroid 9.7.0(515) (phone)";+#[derive(Clone)]pub struct UdemySession {pub access_token: String,@@ -102,14 +104,8 @@ pub fn build_client_from_saved(saved: &SavedSession) -> anyhow::Result<reqwest::}default_headers.insert("accept-language", HeaderValue::from_static("en_US"));- let user_agent = if !saved.cookies.is_empty() {- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"- } else {- "okhttp/4.12.0 UdemyAndroid 9.51.2(594) (phone)"- };-let client = omniget_core::core::http_client::apply_global_proxy(reqwest::Client::builder())- .user_agent(user_agent)+ .user_agent(UDEMY_API_USER_AGENT).default_headers(default_headers).redirect(reqwest::redirect::Policy::limited(10)).connect_timeout(Duration::from_secs(30))@@ -160,7 +156,7 @@ fn build_enterprise_client(saved: &SavedSession) -> anyhow::Result<reqwest::Cliedefault_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")+ .user_agent(UDEMY_API_USER_AGENT).default_headers(default_headers).redirect(reqwest::redirect::Policy::limited(10)).connect_timeout(Duration::from_secs(30))@@ -584,17 +580,34 @@ pub async fn authenticate_with_cookie_json(cookie_json_str: &str) -> anyhow::Resreturn Err(anyhow!("No cookies provided"));}- // Detect portal from URL or cookie domains+ // Detect portal from URL or cookie domains (prioritizing auth cookies over tracking 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| {+ .find(|c| c.name == "access_token" || c.name == "dj_session_id" || c.name == "ud_user_jwt")+ .and_then(|c| c.domain.as_deref())+ .and_then(|d| {let d = d.trim_start_matches('.');- d.strip_suffix(".udemy.com").map(|sub| sub.to_string())+ d.strip_suffix(".udemy.com").map(sanitize_portal_name)+ })+ .or_else(|| {+ export+ .cookies+ .iter()+ .filter_map(|c| c.domain.as_deref())+ .find_map(|d| {+ let d = d.trim_start_matches('.');+ let sub = d.strip_suffix(".udemy.com")?;+ let sanitized = sanitize_portal_name(sub);+ if sanitized != "www" {+ Some(sanitized)+ } else {+ None+ }+ })}).unwrap_or_else(|| "www".into())};@@ -647,11 +660,22 @@ pub async fn authenticate_with_cookie_json(cookie_json_str: &str) -> anyhow::Res})}+pub fn sanitize_portal_name(sub: &str) -> String {+ let clean = sub.trim().trim_start_matches('.').to_ascii_lowercase();+ match clean.as_str() {+ "" | "www" | "trk" | "support" | "about" | "blog" | "img-c" | "s" => "www".to_string(),+ enterprise => enterprise.to_string(),+ }+}+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()))+ .and_then(|host| {+ let h = host.trim_start_matches('.');+ h.strip_suffix(".udemy.com").map(sanitize_portal_name)+ }).unwrap_or_else(|| "www".into())}@@ -696,4 +720,53 @@ mod tests {assert!(!id.is_empty());assert!(!secret.is_empty());}++ #[test]+ fn test_udemy_user_agent_is_valid_mobile_string() {+ assert_eq!(UDEMY_API_USER_AGENT, "okhttp/4.9.2 UdemyAndroid 9.7.0(515) (phone)");+ }++ #[test]+ fn test_sanitize_portal_name() {+ assert_eq!(sanitize_portal_name(""), "www");+ assert_eq!(sanitize_portal_name("www"), "www");+ assert_eq!(sanitize_portal_name("trk"), "www");+ assert_eq!(sanitize_portal_name(".trk"), "www");+ assert_eq!(sanitize_portal_name("support"), "www");+ assert_eq!(sanitize_portal_name("about"), "www");+ assert_eq!(sanitize_portal_name("blog"), "www");+ assert_eq!(sanitize_portal_name("img-c"), "www");+ assert_eq!(sanitize_portal_name("s"), "www");+ assert_eq!(sanitize_portal_name("acmewidgets"), "acmewidgets");+ assert_eq!(sanitize_portal_name(".acmewidgets"), "acmewidgets");+ }++ #[test]+ fn test_detect_portal_from_url() {+ assert_eq!(detect_portal_from_url("https://www.udemy.com/home/my-courses/"), "www");+ assert_eq!(detect_portal_from_url("https://trk.udemy.com/api-2.0/"), "www");+ assert_eq!(detect_portal_from_url("https://acme.udemy.com/organization/home/"), "acme");+ assert_eq!(detect_portal_from_url("invalid-url"), "www");+ }++ #[tokio::test]+ async fn test_cookie_import_prioritizes_auth_cookie_and_filters_tracking_domain() {+ let json_with_trk_first = r#"[+ {"name": "irld", "value": "xyz", "domain": ".trk.udemy.com"},+ {"name": "access_token", "value": "token123", "domain": ".udemy.com"},+ {"name": "client_id", "value": "cid123", "domain": ".udemy.com"}+ ]"#;++ let session = authenticate_with_cookie_json(json_with_trk_first).await.expect("Session parse failed");+ assert_eq!(session.portal_name, "www");+ assert_eq!(session.access_token, "token123");++ let enterprise_json = r#"[+ {"name": "irld", "value": "xyz", "domain": ".trk.udemy.com"},+ {"name": "access_token", "value": "token456", "domain": ".enterprise-corp.udemy.com"}+ ]"#;++ let ent_session = authenticate_with_cookie_json(enterprise_json).await.expect("Enterprise parse failed");+ assert_eq!(ent_session.portal_name, "enterprise-corp");+ }}diff --git a/src/lib/courses/security-logic.test.ts b/src/lib/courses/security-logic.test.tsindex 78389250..cb3b5ba2 100644--- a/src/lib/courses/security-logic.test.ts+++ b/src/lib/courses/security-logic.test.ts@@ -4,6 +4,8 @@ import {shouldFallbackToWebview,formatTokenIdentity,resolveClientCredentials,+ sanitizePortalName,+ parseUdemyResults,} from "./security-logic";describe("Course Security & Platform Logic", () => {@@ -61,4 +63,43 @@ describe("Course Security & Platform Logic", () => {expect(creds.clientSecret).toBeTruthy();});});++ describe("Udemy Portal Sanitization & Error Handling (Issue 72)", () => {+ it("should sanitize tracking and non-portal subdomains to www", () => {+ expect(sanitizePortalName("")).toBe("www");+ expect(sanitizePortalName("www")).toBe("www");+ expect(sanitizePortalName("trk")).toBe("www");+ expect(sanitizePortalName(".trk")).toBe("www");+ expect(sanitizePortalName("support")).toBe("www");+ expect(sanitizePortalName("blog")).toBe("www");+ expect(sanitizePortalName("img-c")).toBe("www");+ expect(sanitizePortalName("s")).toBe("www");+ });++ it("should preserve enterprise subdomains", () => {+ expect(sanitizePortalName("acmewidgets")).toBe("acmewidgets");+ expect(sanitizePortalName(".enterprise-corp")).toBe("enterprise-corp");+ });++ it("should successfully extract results array when present", () => {+ const payload = { results: [{ id: 101, title: "Rust Mastery" }] };+ const parsed = parseUdemyResults(payload);+ expect(parsed).toHaveLength(1);+ expect(parsed[0]).toEqual({ id: 101, title: "Rust Mastery" });+ });++ it("should throw error with details when authorization fails", () => {+ const unauthorizedPayload = { detail: "You do not have permission to perform this action." };+ expect(() => parseUdemyResults(unauthorizedPayload)).toThrow(+ "Udemy authorization error: You do not have permission to perform this action."+ );+ });++ it("should throw error when results key is missing from payload", () => {+ const invalidPayload = { unexpected: true };+ expect(() => parseUdemyResults(invalidPayload)).toThrow(+ "Invalid API response: missing 'results' array"+ );+ });+ });});diff --git a/src/lib/courses/security-logic.ts b/src/lib/courses/security-logic.tsindex 3068f6c3..8efdcae5 100644--- a/src/lib/courses/security-logic.ts+++ b/src/lib/courses/security-logic.ts@@ -37,3 +37,37 @@ export function resolveClientCredentials(): { clientId: string; clientSecret: stconst clientSecret = process.env.UDEMY_CLIENT_SECRET || "f2lgDUDxjFiOlVHUpwQNFUfCQPyMO0tJQMaud53PF01UKueW8enYjeEYoyVeP0bb2XVEDkJ5GLJaVTfM5QgMVz6yyXyydZdA5QhzgvG9UmCPUYaCrIVf7VpmiilfbLJc";return { clientId, clientSecret };}++/**+ * Sanitizes portal name from cookie subdomains, ignoring non-portal subdomains like 'trk'.+ */+export function sanitizePortalName(sub: string): string {+ const clean = sub.trim().replace(/^\.+/, "").toLowerCase();+ switch (clean) {+ case "":+ case "www":+ case "trk":+ case "support":+ case "about":+ case "blog":+ case "img-c":+ case "s":+ return "www";+ default:+ return clean;+ }+}++/**+ * Validates Udemy API response to guarantee an error is thrown instead of swallowing+ * authorization/challenge failures into an empty list.+ */+export function parseUdemyResults(data: Record<string, any>): unknown[] {+ if (Array.isArray(data.results)) {+ return data.results;+ }+ if (typeof data.detail === "string") {+ throw new Error(`Udemy authorization error: ${data.detail}`);+ }+ throw new Error("Invalid API response: missing 'results' array");+}