diff options
Diffstat (limited to 'src/db/story.rs')
| -rw-r--r-- | src/db/story.rs | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/src/db/story.rs b/src/db/story.rs index 686c33f..0680e94 100644 --- a/src/db/story.rs +++ b/src/db/story.rs @@ -1,3 +1,7 @@ +use std::ffi::OsStr; +use std::fs::{read_dir, remove_file}; +use std::io::{BufWriter, Write}; + use axum::async_trait; use maud::html; use sqlx::SqlitePool; @@ -25,6 +29,30 @@ impl ProductMarker for Story { } } +pub async fn synchronize_story_files(pool: &SqlitePool) -> Result<(), anyhow::Error> { + for entry in read_dir("static")? { + let path = entry?.path(); + if path.extension().is_some_and(|ext| ext == OsStr::new("pdf") || ext == OsStr::new("epub")) { + remove_file(path)?; + } + } + let results = sqlx::query!("SELECT p.name, s.pdf, s.epub FROM story s INNER JOIN product p ON s.pid = p.id").fetch_all(pool).await?; + for result in results.iter() { + let mut pdf_filename = format!("{}.pdf", result.name).to_lowercase(); + pdf_filename.retain(|c| !c.is_whitespace()); + + let file = std::fs::File::create_new(format!("static/{}", pdf_filename))?; + BufWriter::new(file).write_all(&result.pdf.to_vec())?; + + let mut epub_filename = format!("{}.epub", result.name).to_lowercase(); + epub_filename.retain(|c| !c.is_whitespace()); + + let file = std::fs::File::create_new(format!("static/{}", epub_filename))?; + BufWriter::new(file).write_all(&result.epub.to_vec())?; + } + Ok(()) +} + #[async_trait] impl ProductDatabaseHandler for Story { async fn get_all(pool: &SqlitePool) -> Result<Vec<Self>, AppError> |
