summaryrefslogtreecommitdiff
path: root/src/db
diff options
context:
space:
mode:
authorWriterV2 <primary-v2@protonmail.com>2024-11-05 16:33:19 +0100
committerWriterV2 <primary-v2@protonmail.com>2024-11-05 16:33:19 +0100
commitdab09c4e4d1e4b21216b630bb44e57f597dfe85b (patch)
tree5c01c51c49ba4b64b03ffe9ca65c1d0ac5cd1eef /src/db
parent56233352feb78ec6da39d8ab7734102abae1e4ed (diff)
Feat: auto file (pdf + epub) creation and synchronization for story
Diffstat (limited to 'src/db')
-rw-r--r--src/db/story.rs28
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>