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(thinkific): implement course download functionality with progress tracking

Tonhod1c18dbcb4f6
diff --git a/src-tauri/src/platforms/thinkific/downloader.rs b/src-tauri/src/platforms/thinkific/downloader.rs
new file mode 100644
index 00000000..3c96cfa7
--- /dev/null
+++ b/src-tauri/src/platforms/thinkific/downloader.rs
@@ -0,0 +1,298 @@
+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 crate::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,
+ pub current_lesson: String,
+ pub downloaded_bytes: u64,
+ pub total_lessons: u32,
+ 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?;
+
+ 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(
+ "thinkific-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(
+ "thinkific-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(
+ "thinkific-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(
+ "thinkific-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"));
+ }
+
+ 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 = crate::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 = crate::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);
+
+ crate::core::direct_downloader::download_direct(
+ client,
+ url,
+ out,
+ tx,
+ Some(cancel_token),
+ )
+ .await
+}