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(study): implement course discovery scanner and player progress commands (Ticket 03)

IGECT7ac2dd49dc0d
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 395d821a..529942bd 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -7148,11 +7148,13 @@ version = "0.13.0"
dependencies = [
"anyhow",
"chrono",
+ "dirs 6.0.0",
"omniget-core",
"omniget-plugin-sdk",
"rusqlite",
"serde",
"serde_json",
+ "tempfile",
"tokio",
"tracing",
"walkdir",
diff --git a/src-tauri/plugins/study/Cargo.toml b/src-tauri/plugins/study/Cargo.toml
index 22de93ca..22f558b0 100644
--- a/src-tauri/plugins/study/Cargo.toml
+++ b/src-tauri/plugins/study/Cargo.toml
@@ -11,6 +11,10 @@ anyhow = "1"
tracing = "0.1"
rusqlite = { version = "0.32", features = ["bundled"] }
chrono = { version = "0.4", features = ["serde"] }
+dirs = "6"
walkdir = "2"
omniget-core = { path = "../../omniget-core", features = ["desktop"] }
omniget-plugin-sdk = { path = "../../omniget-plugin-sdk" }
+
+[dev-dependencies]
+tempfile = "3"
diff --git a/src-tauri/plugins/study/src/commands.rs b/src-tauri/plugins/study/src/commands.rs
new file mode 100644
index 00000000..1a055c62
--- /dev/null
+++ b/src-tauri/plugins/study/src/commands.rs
@@ -0,0 +1,354 @@
+use serde_json::Value;
+use std::path::PathBuf;
+
+use crate::db::StudyDb;
+use crate::scanner;
+
+fn extract_id(args: &Value, keys: &[&str]) -> Option<i64> {
+ for &k in keys {
+ if let Some(v) = args.get(k) {
+ if let Some(n) = v.as_i64() {
+ return Some(n);
+ }
+ if let Some(s) = v.as_str() {
+ if let Ok(n) = s.parse::<i64>() {
+ return Some(n);
+ }
+ }
+ }
+ }
+ None
+}
+
+pub async fn dispatch(db: &StudyDb, command: &str, args: Value) -> Result<Value, String> {
+ match command {
+ "study:courses:list" => {
+ let courses = db.list_courses().map_err(|e| e.to_string())?;
+ // If empty, attempt a scan of default download roots
+ if courses.is_empty() {
+ for root in scanner::default_courses_roots() {
+ let _ = scanner::scan_root_dir(&root, db);
+ }
+ let res = db.list_courses().map_err(|e| e.to_string())?;
+ return serde_json::to_value(res).map_err(|e| e.to_string());
+ }
+ Ok(serde_json::to_value(courses).map_err(|e| e.to_string())?)
+ }
+
+ "study:courses:get" => {
+ let course_id = extract_id(&args, &["courseId", "id", "course_id"])
+ .ok_or_else(|| "missing courseId".to_string())?;
+ let detail = db.get_course_detail(course_id).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_value(detail).map_err(|e| e.to_string())?)
+ }
+
+ "study:lesson:get" => {
+ let lesson_id = extract_id(&args, &["lessonId", "id", "lesson_id"])
+ .ok_or_else(|| "missing lessonId".to_string())?;
+ let lesson = db.get_lesson(lesson_id).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_value(lesson).map_err(|e| e.to_string())?)
+ }
+
+ "study:player:time_changed" => {
+ let lesson_id = extract_id(&args, &["lessonId", "id", "lesson_id"])
+ .ok_or_else(|| "missing lessonId".to_string())?;
+ let time_ms = args.get("timeMs").and_then(|v| v.as_f64()).unwrap_or(0.0);
+ let duration_ms = args.get("durationMs").and_then(|v| v.as_f64());
+ let course_id = extract_id(&args, &["courseId", "course_id"]);
+
+ let pos_secs = time_ms / 1000.0;
+ let dur_secs = duration_ms.map(|d| d / 1000.0);
+
+ db.save_progress(lesson_id, course_id, pos_secs, dur_secs, None)
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+
+ "study:player:seek" => {
+ let lesson_id = extract_id(&args, &["lessonId", "id", "lesson_id"])
+ .ok_or_else(|| "missing lessonId".to_string())?;
+ let to_ms = args.get("toMs").and_then(|v| v.as_f64()).unwrap_or(0.0);
+ db.save_progress(lesson_id, None, to_ms / 1000.0, None, None)
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+
+ "study:progress:mark_lesson" => {
+ let lesson_id = extract_id(&args, &["lessonId", "id", "lesson_id"])
+ .ok_or_else(|| "missing lessonId".to_string())?;
+ let seconds = args.get("seconds").and_then(|v| v.as_f64()).unwrap_or(0.0);
+ let completed = args
+ .get("completed")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(true);
+
+ db.mark_lesson_completed(lesson_id, seconds, completed)
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+
+ "study:progress:mark_lessons_bulk" => {
+ let completed = args
+ .get("completed")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(true);
+ let mut ids = Vec::new();
+ if let Some(arr) = args.get("lessonIds").and_then(|v| v.as_array()) {
+ for item in arr {
+ if let Some(n) = item.as_i64() {
+ ids.push(n);
+ }
+ }
+ }
+ db.mark_lessons_bulk(&ids, completed)
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true, "count": ids.len() }))
+ }
+
+ "study:player:speed:get" => {
+ let course_id = extract_id(&args, &["courseId", "id", "course_id"])
+ .ok_or_else(|| "missing courseId".to_string())?;
+ let speed = db
+ .get_playback_speed(course_id)
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({
+ "course_id": course_id,
+ "playback_speed": speed
+ }))
+ }
+
+ "study:player:speed:set" => {
+ let course_id = extract_id(&args, &["courseId", "id", "course_id"])
+ .ok_or_else(|| "missing courseId".to_string())?;
+ let speed = args.get("speed").and_then(|v| v.as_f64());
+ db.set_playback_speed(course_id, speed)
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({
+ "course_id": course_id,
+ "playback_speed": speed
+ }))
+ }
+
+ "study:courses:recents:touch" => {
+ let course_id = extract_id(&args, &["courseId", "id", "course_id"])
+ .ok_or_else(|| "missing courseId".to_string())?;
+ db.touch_course_recent(course_id)
+ .map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({ "ok": true }))
+ }
+
+ "study:courses:recents:list" => {
+ let limit = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(10) as usize;
+ let recents = db.list_recents(limit).map_err(|e| e.to_string())?;
+ Ok(serde_json::to_value(recents).map_err(|e| e.to_string())?)
+ }
+
+ "study:courses:toggle_favorite" => {
+ let course_id = extract_id(&args, &["courseId", "id", "course_id"])
+ .ok_or_else(|| "missing courseId".to_string())?;
+ let favorite = db.toggle_favorite(course_id).map_err(|e| e.to_string())?;
+ Ok(serde_json::json!({
+ "id": course_id,
+ "favorite": favorite
+ }))
+ }
+
+ "study:courses:scan" | "study:rescan" => {
+ let mut total_scanned = 0;
+ for root in scanner::default_courses_roots() {
+ if let Ok(c) = scanner::scan_root_dir(&root, db) {
+ total_scanned += c;
+ }
+ }
+ Ok(serde_json::json!({ "ok": true, "scanned": total_scanned }))
+ }
+
+ "study:library:telegram:default_output_dir" => {
+ let dir = dirs::download_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .to_string_lossy()
+ .to_string();
+ Ok(serde_json::json!({ "path": dir }))
+ }
+
+ "study:settings:get" => Ok(serde_json::json!({
+ "player": {
+ "default_rate": 1.0
+ }
+ })),
+
+ "study:settings:save" => Ok(args
+ .get("settings")
+ .cloned()
+ .unwrap_or_else(|| serde_json::json!({}))),
+
+ "study:gamification:state" => Ok(serde_json::json!({
+ "xp": 0,
+ "level": 1,
+ "streak_days": 0
+ })),
+
+ "study:player:context" => Ok(serde_json::json!({
+ "thumbnails": [],
+ "audio_tracks": []
+ })),
+
+ "study:player:detect_skip_gaps" | "study:player:skip_gaps:get" => {
+ Ok(serde_json::json!(null))
+ }
+
+ "study:player:next_lesson" => Ok(serde_json::json!(null)),
+
+ "study:lesson:thumbnails" => Ok(serde_json::json!([])),
+
+ // Safe catch-all fallback
+ other => {
+ tracing::debug!(
+ "[study] unhandled command fallback: '{}' with args: {:?}",
+ other,
+ args
+ );
+ Ok(serde_json::json!({}))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn test_commands_dispatch_lifecycle() {
+ let db = StudyDb::open_in_memory().expect("in-memory db");
+ let cid = db
+ .upsert_course("Test Course", "/courses/test", None)
+ .expect("course upsert");
+ let lid = db
+ .upsert_lesson(
+ cid,
+ None,
+ 1,
+ "01 Video",
+ "/courses/test/01.mp4",
+ None,
+ Some(60_000),
+ )
+ .expect("lesson upsert");
+
+ // 1. Test study:courses:list
+ let list_res = dispatch(&db, "study:courses:list", serde_json::json!({}))
+ .await
+ .expect("study:courses:list");
+ assert!(!list_res.as_array().unwrap().is_empty());
+
+ // 2. Test study:courses:get
+ let get_res = dispatch(
+ &db,
+ "study:courses:get",
+ serde_json::json!({ "courseId": cid }),
+ )
+ .await
+ .expect("study:courses:get");
+ assert_eq!(get_res["course"]["title"], "Test Course");
+
+ // 3. Test study:lesson:get
+ let lesson_res = dispatch(
+ &db,
+ "study:lesson:get",
+ serde_json::json!({ "lessonId": lid }),
+ )
+ .await
+ .expect("study:lesson:get");
+ assert_eq!(lesson_res["title"], "01 Video");
+
+ // 4. Test study:player:time_changed
+ let time_res = dispatch(
+ &db,
+ "study:player:time_changed",
+ serde_json::json!({
+ "lessonId": lid,
+ "timeMs": 25000.0,
+ "durationMs": 60000.0
+ }),
+ )
+ .await
+ .expect("time_changed");
+ assert_eq!(time_res["ok"], true);
+
+ let p = db.get_progress(lid).unwrap().unwrap();
+ assert_eq!(p.position_secs, 25.0);
+
+ // 5. Test study:progress:mark_lesson
+ let mark_res = dispatch(
+ &db,
+ "study:progress:mark_lesson",
+ serde_json::json!({
+ "lessonId": lid,
+ "seconds": 60.0,
+ "completed": true
+ }),
+ )
+ .await
+ .expect("mark_lesson");
+ assert_eq!(mark_res["ok"], true);
+
+ let p_after = db.get_progress(lid).unwrap().unwrap();
+ assert!(p_after.completed);
+
+ // 6. Test playback speed get/set
+ dispatch(
+ &db,
+ "study:player:speed:set",
+ serde_json::json!({ "courseId": cid, "speed": 1.75 }),
+ )
+ .await
+ .expect("speed:set");
+
+ let speed_res = dispatch(
+ &db,
+ "study:player:speed:get",
+ serde_json::json!({ "courseId": cid }),
+ )
+ .await
+ .expect("speed:get");
+ assert_eq!(speed_res["playback_speed"], 1.75);
+
+ // 7. Test toggle favorite
+ let fav_res = dispatch(
+ &db,
+ "study:courses:toggle_favorite",
+ serde_json::json!({ "courseId": cid }),
+ )
+ .await
+ .expect("toggle_favorite");
+ assert_eq!(fav_res["favorite"], true);
+
+ // 8. Test recents
+ dispatch(
+ &db,
+ "study:courses:recents:touch",
+ serde_json::json!({ "courseId": cid }),
+ )
+ .await
+ .expect("recents:touch");
+
+ let recents_res = dispatch(
+ &db,
+ "study:courses:recents:list",
+ serde_json::json!({ "limit": 5 }),
+ )
+ .await
+ .expect("recents:list");
+ assert_eq!(recents_res.as_array().unwrap().len(), 1);
+
+ // 9. Test default output dir
+ let dir_res = dispatch(
+ &db,
+ "study:library:telegram:default_output_dir",
+ serde_json::json!({}),
+ )
+ .await
+ .expect("default_output_dir");
+ assert!(dir_res["path"].as_str().is_some());
+ }
+}
diff --git a/src-tauri/plugins/study/src/db.rs b/src-tauri/plugins/study/src/db.rs
index b6206285..5a68ab8e 100644
--- a/src-tauri/plugins/study/src/db.rs
+++ b/src-tauri/plugins/study/src/db.rs
@@ -251,6 +251,7 @@ impl StudyDb {
}
}
+ #[allow(clippy::too_many_arguments)]
pub fn upsert_lesson(
&self,
course_id: i64,
diff --git a/src-tauri/plugins/study/src/lib.rs b/src-tauri/plugins/study/src/lib.rs
index a2f56485..6e2b2ed8 100644
--- a/src-tauri/plugins/study/src/lib.rs
+++ b/src-tauri/plugins/study/src/lib.rs
@@ -1,4 +1,6 @@
+pub mod commands;
pub mod db;
+pub mod scanner;
use omniget_plugin_sdk::{OmnigetPlugin, PluginHost, PluginManifest};
use std::sync::Arc;
@@ -65,23 +67,28 @@ impl OmnigetPlugin for StudyPlugin {
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = Result<serde_json::Value, String>> + Send + 'static>,
> {
- Box::pin(async move {
- match command.as_str() {
- // Catch-all safety dispatcher: prevents UI unhandled exception crashes
- other => {
- tracing::debug!(
- "[study] unhandled command fallback: '{}' with args: {:?}",
- other,
- args
- );
- Ok(serde_json::json!({}))
- }
- }
- })
+ let db = self.db.clone();
+ Box::pin(async move { commands::dispatch(&db, &command, args).await })
}
fn commands(&self) -> Vec<String> {
- vec![]
+ vec![
+ "study:courses:list".to_string(),
+ "study:courses:get".to_string(),
+ "study:courses:scan".to_string(),
+ "study:rescan".to_string(),
+ "study:courses:toggle_favorite".to_string(),
+ "study:courses:recents:touch".to_string(),
+ "study:courses:recents:list".to_string(),
+ "study:lesson:get".to_string(),
+ "study:player:time_changed".to_string(),
+ "study:player:seek".to_string(),
+ "study:player:speed:get".to_string(),
+ "study:player:speed:set".to_string(),
+ "study:progress:mark_lesson".to_string(),
+ "study:progress:mark_lessons_bulk".to_string(),
+ "study:library:telegram:default_output_dir".to_string(),
+ ]
}
}
@@ -98,4 +105,17 @@ mod tests {
assert!(res.is_ok());
assert_eq!(res.unwrap(), serde_json::json!({}));
}
+
+ #[tokio::test]
+ async fn test_study_plugin_course_flow() {
+ let db = db::StudyDb::open_in_memory().expect("in-memory db");
+ let plugin = StudyPlugin::with_db(db);
+
+ // List initial (empty)
+ let list = plugin
+ .handle_command("study:courses:list".to_string(), serde_json::json!({}))
+ .await
+ .expect("courses:list");
+ assert_eq!(list, serde_json::json!([]));
+ }
}
diff --git a/src-tauri/plugins/study/src/scanner.rs b/src-tauri/plugins/study/src/scanner.rs
new file mode 100644
index 00000000..ebc81409
--- /dev/null
+++ b/src-tauri/plugins/study/src/scanner.rs
@@ -0,0 +1,319 @@
+use std::path::{Path, PathBuf};
+use walkdir::WalkDir;
+
+use crate::db::StudyDb;
+
+const VIDEO_EXTENSIONS: &[&str] = &["mp4", "mkv", "webm", "mov", "avi", "m4v"];
+const SUBTITLE_EXTENSIONS: &[&str] = &["vtt", "srt"];
+const IMAGE_EXTENSIONS: &[&str] = &["jpg", "jpeg", "png", "webp"];
+
+pub fn is_video_file(path: &Path) -> bool {
+ path.extension()
+ .and_then(|e| e.to_str())
+ .map(|e| {
+ VIDEO_EXTENSIONS
+ .iter()
+ .any(|&ext| ext.eq_ignore_ascii_case(e))
+ })
+ .unwrap_or(false)
+}
+
+pub fn is_subtitle_file(path: &Path) -> bool {
+ path.extension()
+ .and_then(|e| e.to_str())
+ .map(|e| {
+ SUBTITLE_EXTENSIONS
+ .iter()
+ .any(|&ext| ext.eq_ignore_ascii_case(e))
+ })
+ .unwrap_or(false)
+}
+
+pub fn is_image_file(path: &Path) -> bool {
+ path.extension()
+ .and_then(|e| e.to_str())
+ .map(|e| {
+ IMAGE_EXTENSIONS
+ .iter()
+ .any(|&ext| ext.eq_ignore_ascii_case(e))
+ })
+ .unwrap_or(false)
+}
+
+pub fn extract_position_and_title(filename: &str, fallback_pos: i64) -> (i64, String) {
+ let stem = Path::new(filename)
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or(filename);
+
+ let trimmed = stem.trim().trim_start_matches('[');
+ let mut num_str = String::new();
+ for c in trimmed.chars() {
+ if c.is_ascii_digit() {
+ num_str.push(c);
+ } else {
+ break;
+ }
+ }
+
+ if !num_str.is_empty() {
+ if let Ok(pos) = num_str.parse::<i64>() {
+ let remainder = &trimmed[num_str.len()..];
+ let clean_title = remainder
+ .trim_start_matches(|c: char| {
+ c == '.' || c == '-' || c == '_' || c == ']' || c == ' '
+ })
+ .trim();
+ if !clean_title.is_empty() {
+ return (pos, clean_title.to_string());
+ }
+ }
+ }
+
+ (fallback_pos, stem.to_string())
+}
+
+pub fn find_subtitle_for_video(video_path: &Path) -> Option<PathBuf> {
+ let parent = video_path.parent()?;
+ let stem = video_path.file_stem()?.to_str()?;
+
+ for ext in SUBTITLE_EXTENSIONS {
+ let sub = parent.join(format!("{}.{}", stem, ext));
+ if sub.exists() {
+ return Some(sub);
+ }
+ }
+ None
+}
+
+pub fn find_course_thumbnail(course_dir: &Path) -> Option<PathBuf> {
+ for name in &["cover", "folder", "thumbnail", "poster"] {
+ for ext in IMAGE_EXTENSIONS {
+ let p = course_dir.join(format!("{}.{}", name, ext));
+ if p.exists() {
+ return Some(p);
+ }
+ }
+ }
+
+ if let Ok(entries) = std::fs::read_dir(course_dir) {
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_file() && is_image_file(&path) {
+ return Some(path);
+ }
+ }
+ }
+
+ None
+}
+
+pub fn scan_course_dir(course_dir: &Path, db: &StudyDb) -> anyhow::Result<i64> {
+ if !course_dir.is_dir() {
+ anyhow::bail!("Path is not a directory: {:?}", course_dir);
+ }
+
+ let course_title = course_dir
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("Untitled Course");
+
+ let thumbnail_path =
+ find_course_thumbnail(course_dir).and_then(|p| p.to_str().map(|s| s.to_string()));
+
+ let source_path = course_dir
+ .to_str()
+ .ok_or_else(|| anyhow::anyhow!("Invalid course path encoding"))?;
+
+ let course_id = db.upsert_course(course_title, source_path, thumbnail_path.as_deref())?;
+
+ let mut direct_videos = Vec::new();
+ let mut module_dirs = Vec::new();
+
+ if let Ok(entries) = std::fs::read_dir(course_dir) {
+ for entry in entries.flatten() {
+ let p = entry.path();
+ if p.is_dir() {
+ // Check if this subdirectory contains video files
+ let has_videos = WalkDir::new(&p)
+ .max_depth(3)
+ .into_iter()
+ .filter_map(|e| e.ok())
+ .any(|e| is_video_file(e.path()));
+
+ if has_videos {
+ module_dirs.push(p);
+ }
+ } else if p.is_file() && is_video_file(&p) {
+ direct_videos.push(p);
+ }
+ }
+ }
+
+ // Sort direct videos naturally
+ direct_videos.sort_by(|a, b| a.file_name().cmp(&b.file_name()));
+ for (idx, video) in direct_videos.iter().enumerate() {
+ let filename = video.file_name().and_then(|n| n.to_str()).unwrap_or("");
+ let (pos, title) = extract_position_and_title(filename, (idx + 1) as i64);
+ let video_str = video.to_str().unwrap_or("");
+ let sub_str =
+ find_subtitle_for_video(video).and_then(|p| p.to_str().map(|s| s.to_string()));
+
+ let _ = db.upsert_lesson(
+ course_id,
+ None,
+ pos,
+ &title,
+ video_str,
+ sub_str.as_deref(),
+ None,
+ );
+ }
+
+ // Process module subdirectories
+ module_dirs.sort_by(|a, b| a.file_name().cmp(&b.file_name()));
+ for (m_idx, m_dir) in module_dirs.iter().enumerate() {
+ let m_name = m_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
+ let (m_pos, m_title) = extract_position_and_title(m_name, (m_idx + 1) as i64);
+ let m_str = m_dir.to_str().unwrap_or("");
+
+ let mod_id = db.upsert_module(course_id, m_pos, &m_title, m_str)?;
+
+ let mut mod_videos = Vec::new();
+ if let Ok(entries) = std::fs::read_dir(m_dir) {
+ for entry in entries.flatten() {
+ let p = entry.path();
+ if p.is_file() && is_video_file(&p) {
+ mod_videos.push(p);
+ }
+ }
+ }
+
+ mod_videos.sort_by(|a, b| a.file_name().cmp(&b.file_name()));
+ for (l_idx, video) in mod_videos.iter().enumerate() {
+ let filename = video.file_name().and_then(|n| n.to_str()).unwrap_or("");
+ let (pos, title) = extract_position_and_title(filename, (l_idx + 1) as i64);
+ let video_str = video.to_str().unwrap_or("");
+ let sub_str =
+ find_subtitle_for_video(video).and_then(|p| p.to_str().map(|s| s.to_string()));
+
+ let _ = db.upsert_lesson(
+ course_id,
+ Some(mod_id),
+ pos,
+ &title,
+ video_str,
+ sub_str.as_deref(),
+ None,
+ );
+ }
+ }
+
+ Ok(course_id)
+}
+
+pub fn scan_root_dir(root: &Path, db: &StudyDb) -> anyhow::Result<usize> {
+ if !root.is_dir() {
+ return Ok(0);
+ }
+
+ let mut scanned = 0;
+ if let Ok(entries) = std::fs::read_dir(root) {
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ // Check if directory has any video files anywhere inside
+ let has_videos = WalkDir::new(&path)
+ .max_depth(4)
+ .into_iter()
+ .filter_map(|e| e.ok())
+ .any(|e| is_video_file(e.path()));
+
+ if has_videos && scan_course_dir(&path, db).is_ok() {
+ scanned += 1;
+ }
+ }
+ }
+ }
+
+ Ok(scanned)
+}
+
+pub fn default_courses_roots() -> Vec<PathBuf> {
+ let mut roots = Vec::new();
+ if let Some(dl) = dirs::download_dir() {
+ roots.push(dl.join("OmniGet").join("Courses"));
+ roots.push(dl.join("courses"));
+ roots.push(dl);
+ }
+ roots
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::tempdir;
+
+ #[test]
+ fn test_extract_position_and_title() {
+ assert_eq!(
+ extract_position_and_title("01 - Welcome.mp4", 99),
+ (1, "Welcome".to_string())
+ );
+ assert_eq!(
+ extract_position_and_title("02. Setup Environment.mkv", 99),
+ (2, "Setup Environment".to_string())
+ );
+ assert_eq!(
+ extract_position_and_title("[05] Functions and Closures.webm", 99),
+ (5, "Functions and Closures".to_string())
+ );
+ assert_eq!(
+ extract_position_and_title("Unnumbered Lesson.mp4", 7),
+ (7, "Unnumbered Lesson".to_string())
+ );
+ }
+
+ #[test]
+ fn test_scan_course_directory_structure() {
+ let dir = tempdir().expect("tempdir");
+ let course_dir = dir.path().join("Complete Rust Course");
+ let mod_dir = course_dir.join("01 - Getting Started");
+ std::fs::create_dir_all(&mod_dir).expect("create_dir_all");
+
+ // Create loose lesson and thumbnail in course root
+ std::fs::write(course_dir.join("00 - Course Overview.mp4"), b"video").unwrap();
+ std::fs::write(course_dir.join("cover.jpg"), b"cover").unwrap();
+
+ // Create module lessons and subtitle
+ std::fs::write(mod_dir.join("01 - Installation.mp4"), b"video").unwrap();
+ std::fs::write(mod_dir.join("01 - Installation.vtt"), b"subtitle").unwrap();
+ std::fs::write(mod_dir.join("02 - Hello World.mp4"), b"video").unwrap();
+
+ let db = StudyDb::open_in_memory().expect("in-memory db");
+ let cid = scan_course_dir(&course_dir, &db).expect("scan course");
+ assert!(cid > 0);
+
+ let detail = db
+ .get_course_detail(cid)
+ .expect("course detail")
+ .expect("exists");
+
+ assert_eq!(detail.course.title, "Complete Rust Course");
+ assert!(detail.course.thumbnail_path.is_some());
+ assert_eq!(detail.loose_lessons.len(), 1);
+ assert_eq!(detail.loose_lessons[0].title, "Course Overview");
+
+ assert_eq!(detail.modules.len(), 1);
+ assert_eq!(detail.modules[0].title, "Getting Started");
+ assert_eq!(detail.modules[0].lessons.len(), 2);
+ assert_eq!(detail.modules[0].lessons[0].title, "Installation");
+ assert!(detail.modules[0].lessons[0].subtitle_path.is_some());
+ assert_eq!(detail.modules[0].lessons[1].title, "Hello World");
+
+ let courses = db.list_courses().expect("list courses");
+ assert_eq!(courses.len(), 1);
+ assert_eq!(courses[0].total_lessons, 3);
+ assert_eq!(courses[0].completed_lessons, 0);
+ }
+}