use crate::core::EpubReader;
use crate::core::Reader;
use crate::progress::{BookProgress, ProgressStore};
use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};
pub fn scan_directory(dir: &Path, profile_dir: Option<PathBuf>) -> Result<(), Box<dyn Error>> {
let progress_path = profile_dir.map(|mut p| {
p.push("progress.json");
p
});
let mut store = ProgressStore::load(progress_path);
let mut count = 0;
fn visit_dirs(
dir: &Path,
store: &mut ProgressStore,
count: &mut usize,
) -> Result<(), Box<dyn Error>> {
if dir.is_dir() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
visit_dirs(&path, store, count)?;
} else if path.extension().and_then(|s| s.to_str()) == Some("epub") {
let path_str = path.to_string_lossy().to_string();
if let Ok(reader) = EpubReader::new(&path_str) {
let book_id = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path_str.clone());
if !store.books.contains_key(&book_id) {
store.set_book(
book_id,
BookProgress {
title: reader.title().to_string(),
author: reader.author().to_string(),
path: path_str,
current_chapter: 0,
..Default::default()
},
);
*count += 1;
}
}
}
}
}
Ok(())
}
visit_dirs(dir, &mut store, &mut count)?;
if count > 0 {
store.save()?;
println!("Added {} new books to the library.", count);
} else {
println!("No new EPUB files found.");
}
Ok(())
}