Pour tout problème contactez-nous par mail : support@froggit.fr | La FAQ :grey_question: | Rejoignez-nous sur le Chat :speech_balloon:

Skip to content
Snippets Groups Projects
Commit f39608b5 authored by Pierre Jarriges's avatar Pierre Jarriges
Browse files

fix assets dir & WebSite impl Serialize

parent 0b53d2f6
No related branches found
No related tags found
No related merge requests found
...@@ -11,7 +11,7 @@ readme = "README.md" ...@@ -11,7 +11,7 @@ readme = "README.md"
actix-web = { version = "4.1.0", features = ["rustls", "secure-cookies"] } actix-web = { version = "4.1.0", features = ["rustls", "secure-cookies"] }
rustls = "0.20.6" rustls = "0.20.6"
rustls-pemfile = "1.0.1" rustls-pemfile = "1.0.1"
serde = { version = "1.0.144", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1.0.83" serde_json = "1.0.83"
regex = "1.6" regex = "1.6"
fs_extra = "1.2" fs_extra = "1.2"
......
...@@ -26,14 +26,16 @@ async fn main() -> std::io::Result<()> { ...@@ -26,14 +26,16 @@ async fn main() -> std::io::Result<()> {
) )
.init(); .init();
let website = { let website = WebSiteBuilder::load(&app_state.config)
let mut wb = WebSiteBuilder::load(&app_state.config); .with_static_files_manager(
let static_manager = StaticFilesManager::new(&app_state).unwrap().build(); StaticFilesManager::new(&app_state)
wb.save(&app_state.config).unwrap(); .unwrap()
wb.with_static_files_manager(static_manager) .build_assets_index(),
.build() )
.unwrap() .build()
}; .unwrap();
website.save(&app_state.config).unwrap();
let host = app_state.config.host.clone(); let host = app_state.config.host.clone();
let port = app_state.config.port; let port = app_state.config.port;
......
...@@ -48,7 +48,7 @@ async fn write_uploaded_file( ...@@ -48,7 +48,7 @@ async fn write_uploaded_file(
filename: &String, filename: &String,
upload_type: UploadFileType, upload_type: UploadFileType,
) -> Result<String, String> { ) -> Result<String, String> {
let root = &website.static_files_manager.dir.join("assets"); let root = &website.static_files_manager.assets_dir();
let sub_dir = dirname_from_type(&upload_type); let sub_dir = dirname_from_type(&upload_type);
let filepath = root.join(sub_dir).join(&filename); let filepath = root.join(sub_dir).join(&filename);
...@@ -100,7 +100,7 @@ pub async fn post_files(website: Data<RwLock<WebSite>>, mut payload: Multipart) ...@@ -100,7 +100,7 @@ pub async fn post_files(website: Data<RwLock<WebSite>>, mut payload: Multipart)
Ok(filepath) => uploaded_filepathes.extend( Ok(filepath) => uploaded_filepathes.extend(
website website
.static_files_manager .static_files_manager
.push_path(std::path::Path::new(&filepath)), .push_asset_path(std::path::Path::new(&filepath)),
), ),
} }
} }
...@@ -115,7 +115,13 @@ pub async fn post_files(website: Data<RwLock<WebSite>>, mut payload: Multipart) ...@@ -115,7 +115,13 @@ pub async fn post_files(website: Data<RwLock<WebSite>>, mut payload: Multipart)
#[get("/static-files-index")] #[get("/static-files-index")]
async fn get_static_files_index(website: Data<RwLock<WebSite>>) -> impl Responder { async fn get_static_files_index(website: Data<RwLock<WebSite>>) -> impl Responder {
HttpResponse::Ok().json(website.read().unwrap().static_files_manager.get_index()) HttpResponse::Ok().json(
website
.read()
.unwrap()
.static_files_manager
.get_assets_index(),
)
} }
#[delete("/delete-file/{category}/{filename}")] #[delete("/delete-file/{category}/{filename}")]
......
...@@ -103,7 +103,7 @@ impl StaticFilesManager { ...@@ -103,7 +103,7 @@ impl StaticFilesManager {
if entry.path().is_dir() { if entry.path().is_dir() {
self.rec_read_dir(&entry.path(), strip_from); self.rec_read_dir(&entry.path(), strip_from);
} else { } else {
self.push_path(&entry.path().strip_prefix(strip_from).unwrap()); self.push_asset_path(&entry.path().strip_prefix(strip_from).unwrap());
} }
} }
} }
...@@ -120,7 +120,7 @@ impl StaticFilesManager { ...@@ -120,7 +120,7 @@ impl StaticFilesManager {
} }
} }
pub fn push_path(&mut self, path: &Path) -> Vec<PathBuf> { pub fn push_asset_path(&mut self, path: &Path) -> Vec<PathBuf> {
if self.validate_path(path) { if self.validate_path(path) {
self.index self.index
.push(self.clean_relative_path(path).to_str().unwrap().to_owned()); .push(self.clean_relative_path(path).to_str().unwrap().to_owned());
...@@ -134,18 +134,18 @@ impl StaticFilesManager { ...@@ -134,18 +134,18 @@ impl StaticFilesManager {
} }
} }
pub fn add_pathes(&mut self, pathes: &Vec<String>) -> Vec<PathBuf> { pub fn add_assets_pathes(&mut self, pathes: &Vec<String>) -> Vec<PathBuf> {
let mut added: Vec<PathBuf> = Vec::new(); let mut added: Vec<PathBuf> = Vec::new();
for pth in pathes.iter() { for pth in pathes.iter() {
let p = self.push_path(Path::new(pth)); let p = self.push_asset_path(Path::new(pth));
added.extend(p.iter().map(|pb| pb.clone())); added.extend(p.iter().map(|pb| pb.clone()));
} }
added added
} }
pub fn build(&mut self) -> Self { pub fn build_assets_index(&mut self) -> Self {
self.index = Vec::new(); self.index = Vec::new();
self.rec_read_dir(&self.dir.clone(), &self.dir.clone()); self.rec_read_dir(&self.assets_dir(), &self.dir.clone());
self.clone() self.clone()
} }
...@@ -158,10 +158,14 @@ impl StaticFilesManager { ...@@ -158,10 +158,14 @@ impl StaticFilesManager {
.collect(); .collect();
} }
pub fn get_index(&self) -> Vec<String> { pub fn get_assets_index(&self) -> Vec<String> {
self.index.clone() self.index.clone()
} }
pub fn assets_dir(&self) -> PathBuf {
self.dir.join("assets")
}
pub fn write_html_page(&self, url: &PathBuf, page: &Page) -> std::io::Result<()> { pub fn write_html_page(&self, url: &PathBuf, page: &Page) -> std::io::Result<()> {
let dir = self.dir.join(self.clean_relative_path(url)); let dir = self.dir.join(self.clean_relative_path(url));
...@@ -221,7 +225,7 @@ mod test_static_files_manager { ...@@ -221,7 +225,7 @@ mod test_static_files_manager {
let mut manager = StaticFilesManager::testing_new(&test_dir).unwrap(); let mut manager = StaticFilesManager::testing_new(&test_dir).unwrap();
let file_pth = test_dir.join("assets").join("docs").join("testing.txt"); let file_pth = test_dir.join("assets").join("docs").join("testing.txt");
std::fs::File::create(&file_pth).unwrap(); std::fs::File::create(&file_pth).unwrap();
manager = manager.build(); manager = manager.build_assets_index();
assert!( assert!(
manager manager
...@@ -237,11 +241,13 @@ mod test_static_files_manager { ...@@ -237,11 +241,13 @@ mod test_static_files_manager {
#[test] #[test]
fn test_push_and_remove_path() { fn test_push_and_remove_path() {
let test_dir = create_test_dir(); let test_dir = create_test_dir();
let mut manager = StaticFilesManager::testing_new(&test_dir).unwrap().build(); let mut manager = StaticFilesManager::testing_new(&test_dir)
.unwrap()
.build_assets_index();
let file_pth = test_dir.join("assets").join("docs").join("testing.txt"); let file_pth = test_dir.join("assets").join("docs").join("testing.txt");
std::fs::File::create(&file_pth).unwrap(); std::fs::File::create(&file_pth).unwrap();
let indexed_path = Path::new("assets/docs/testing.txt"); let indexed_path = Path::new("assets/docs/testing.txt");
let added = manager.push_path(&indexed_path); let added = manager.push_asset_path(&indexed_path);
assert_eq!( assert_eq!(
added, added,
...@@ -274,9 +280,11 @@ mod test_static_files_manager { ...@@ -274,9 +280,11 @@ mod test_static_files_manager {
#[test] #[test]
fn test_push_unexisting_path() { fn test_push_unexisting_path() {
let test_dir = create_test_dir(); let test_dir = create_test_dir();
let mut manager = StaticFilesManager::testing_new(&test_dir).unwrap().build(); let mut manager = StaticFilesManager::testing_new(&test_dir)
.unwrap()
.build_assets_index();
let indexed_path = Path::new("assets/images/unexisting.png"); let indexed_path = Path::new("assets/images/unexisting.png");
let added = manager.push_path(&indexed_path); let added = manager.push_asset_path(&indexed_path);
assert_eq!( assert_eq!(
added.len(), added.len(),
......
use super::page::{Page, PageTemplate}; use super::page::{Page, PageTemplate};
use crate::app::AppConfig; use crate::app::AppConfig;
use crate::static_files::StaticFilesManager; use crate::static_files::StaticFilesManager;
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::io::prelude::*; use std::io::prelude::*;
use std::path::PathBuf; use std::path::PathBuf;
...@@ -20,6 +21,19 @@ pub struct WebSite { ...@@ -20,6 +21,19 @@ pub struct WebSite {
templates: Vec<PageTemplate>, templates: Vec<PageTemplate>,
} }
impl Serialize for WebSite {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("WebSite", 3)?;
state.serialize_field("root_page", &self.root_page)?;
state.serialize_field("templates", &self.templates)?;
state.serialize_field("assets_index", &self.static_files_manager.index)?;
state.end()
}
}
impl WebSiteBuilder { impl WebSiteBuilder {
pub fn from_json(json: &str) -> Self { pub fn from_json(json: &str) -> Self {
serde_json::from_str(json).unwrap() serde_json::from_str(json).unwrap()
...@@ -33,7 +47,7 @@ impl WebSiteBuilder { ...@@ -33,7 +47,7 @@ impl WebSiteBuilder {
root_page: self.root_page.clone(), root_page: self.root_page.clone(),
static_files_manager: { static_files_manager: {
let mut static_files_manager = static_files_manager; let mut static_files_manager = static_files_manager;
static_files_manager.add_pathes(&self.assets_index); static_files_manager.add_assets_pathes(&self.assets_index);
static_files_manager static_files_manager
}, },
templates: self.templates.clone(), templates: self.templates.clone(),
...@@ -79,20 +93,6 @@ impl WebSiteBuilder { ...@@ -79,20 +93,6 @@ impl WebSiteBuilder {
None None
} }
pub fn save(&self, config: &AppConfig) -> std::io::Result<()> {
let save_json = serde_json::to_string(self).unwrap();
let json_path = config.storage_dir.join("website.json");
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&json_path)?;
f.write_all(save_json.as_bytes())?;
f.flush()?;
Ok(())
}
} }
impl WebSite { impl WebSite {
...@@ -107,4 +107,19 @@ impl WebSite { ...@@ -107,4 +107,19 @@ impl WebSite {
Ok(self.clone()) Ok(self.clone())
} }
pub fn save(&self, config: &AppConfig) -> std::io::Result<()> {
let save_json = serde_json::to_string(self).unwrap();
let json_path = config.storage_dir.join("website.json");
let mut f = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(&json_path)?;
f.write_all(save_json.as_bytes())?;
f.flush()?;
Ok(())
}
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment