Skip to content
This repository has been archived by the owner on Jul 22, 2023. It is now read-only.

Commit

Permalink
added code from webapp repo
Browse files Browse the repository at this point in the history
  • Loading branch information
crapStone committed Jul 25, 2021
1 parent 92345b0 commit 491083d
Show file tree
Hide file tree
Showing 16 changed files with 1,011 additions and 36 deletions.
429 changes: 424 additions & 5 deletions src-tauri/Cargo.lock

Large diffs are not rendered by default.

14 changes: 12 additions & 2 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ cabr2_logger = { path = "./cabr2_logger/", optional = true }
cabr2_search = { path = "./cabr2_search/" }
log = "0.4.14"
tauri = { version = "1.0.0-beta.4", features = ["api-all"], optional = true }
tokio = { version = "1.8.1", features = ["macros", "rt-multi-thread"], optional = true }
warp = { version = "0.3.1", optional = true }

[features]
default = [
Expand All @@ -32,17 +34,25 @@ default = [
"pdf",
"gestis",
"tauri_app",
# "webserver",
]
portable = [ "cabr2_config/portable" ]
custom-protocol = [ "tauri/custom-protocol" ] # needed for tauri release builds
tauri_app = [
"tauri",
"cabr2_logger",
"cabr2_logger/tauri_plugin",
"cabr2_config/tauri_plugin",
"cabr2_load_save/tauri_plugin",
"cabr2_search/tauri_plugin",
]
webserver = [ ]
webserver = [
"warp",
"tokio",
"cabr2_logger",
"cabr2_config/webserver",
"cabr2_load_save/webserver",
"cabr2_search/webserver",
]

# cabr2_load_save file types
beryllium = [ "cabr2_load_save/beryllium" ]
Expand Down
2 changes: 2 additions & 0 deletions src-tauri/cabr2_config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ tauri = { version = "1.0.0-beta.4", default-features = false, optional = true }
thiserror = "1.0.26"
tokio = { version = "1.9.0", features = ["fs", "io-util"] }
toml = { version = "0.5.8", features = ["preserve_order"] }
warp = { version = "0.3.1", optional = true }

[features]
portable = []
tauri_plugin = ["tauri"]
webserver = ["warp"]
default = []
2 changes: 2 additions & 0 deletions src-tauri/cabr2_config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ mod types;

#[cfg(feature = "tauri_plugin")]
pub mod plugin;
#[cfg(feature = "webserver")]
pub mod webserver;

pub use handler::{get_hazard_symbols, read_config, DATA_DIR, TMP_DIR};
pub use types::{BackendConfig, GHSSymbols};
66 changes: 66 additions & 0 deletions src-tauri/cabr2_config/src/webserver.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use std::convert::Infallible;

use serde::Deserialize;
use serde_json::Value;
use warp::{hyper::StatusCode, Reply};

use crate::handler;

pub async fn handle_hazard_symbols() -> Result<impl Reply, Infallible> {
match handler::get_hazard_symbols() {
Ok(res) => Ok(warp::reply::with_status(warp::reply::json(&res), StatusCode::OK)),
Err(err) => Ok(warp::reply::with_status(
warp::reply::json(&Value::String(err.to_string())),
StatusCode::BAD_REQUEST,
)),
}
}

pub async fn handle_program_version() -> Result<impl Reply, Infallible> {
Ok(warp::reply::with_status(
warp::reply::json(&env!("CARGO_PKG_VERSION")),
StatusCode::OK,
))
}

pub async fn handle_prompt_html(body: PromptHtmlBody) -> Result<impl Reply, Infallible> {
match handler::get_prompt_html(body.name) {
Ok(res) => Ok(warp::reply::with_status(warp::reply::json(&res), StatusCode::OK)),
Err(err) => Ok(warp::reply::with_status(
warp::reply::json(&Value::String(err.to_string())),
StatusCode::BAD_REQUEST,
)),
}
}

pub async fn handle_available_languages() -> Result<impl Reply, Infallible> {
match handler::get_available_languages() {
Ok(res) => Ok(warp::reply::with_status(warp::reply::json(&res), StatusCode::OK)),
Err(err) => Ok(warp::reply::with_status(
warp::reply::json(&Value::String(err.to_string())),
StatusCode::BAD_REQUEST,
)),
}
}

pub async fn handle_localized_strings(body: LocalizedStringsBody) -> Result<impl Reply, Infallible> {
match handler::get_localized_strings(body.language) {
Ok(res) => Ok(warp::reply::with_status(warp::reply::json(&res), StatusCode::OK)),
Err(err) => Ok(warp::reply::with_status(
warp::reply::json(&Value::String(err.to_string())),
StatusCode::BAD_REQUEST,
)),
}
}

// Body definitions

#[derive(Debug, Deserialize)]
pub struct PromptHtmlBody {
name: String,
}

#[derive(Debug, Deserialize)]
pub struct LocalizedStringsBody {
language: String,
}
7 changes: 5 additions & 2 deletions src-tauri/cabr2_load_save/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,15 @@ serde = { version = "1.0.126", features = ["derive"] }
serde_json = { version = "1.0.64", optional = true }
tauri = { version = "1.0.0-beta.4", default-features = false, optional = true }
thiserror = "1.0.26"
tokio = { version = "1.9.0", features = ["fs", "rt-multi-thread", "sync"] }
tokio = { version = "1.9.0", features = ["fs"], optional = true }
uuid = { version = "0.8.2", features = ["serde", "v4"], optional = true }
warp = { version = "0.3.1", features = [], optional = true }
wkhtmltopdf = { version = "0.4.0", optional = true }

[features]
beryllium = ["chrono", "quick-xml", "regex"]
cabr2 = ["serde_json"]
pdf = ["chrono", "handlebars", "lopdf", "serde_json", "wkhtmltopdf"]
tauri_plugin = ["tauri", "serde_json"]
tauri_plugin = ["serde_json", "tauri"]
webserver = ["tokio", "uuid", "warp"]
default = []
2 changes: 2 additions & 0 deletions src-tauri/cabr2_load_save/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ mod types;

#[cfg(feature = "tauri_plugin")]
pub mod plugin;
#[cfg(feature = "webserver")]
pub mod webserver;

#[cfg(feature = "beryllium")]
mod beryllium;
Expand Down
194 changes: 194 additions & 0 deletions src-tauri/cabr2_load_save/src/webserver.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
use std::{convert::Infallible, path::PathBuf, time::Duration};

use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::fs;
use uuid::Uuid;
use warp::{hyper::StatusCode, Reply};

use cabr2_types::ProviderMapping;

use crate::{handler, types::CaBr2Document};

pub const DOWNLOAD_FOLDER: &str = "/tmp/cabr2_server/created";
pub const CACHE_FOLDER: &str = "/tmp/cabr2_server/cache";

pub struct LoadSave;

impl LoadSave {
pub fn new(provider_mapping: ProviderMapping) -> Self {
handler::init_handlers(provider_mapping);
LoadSave
}
}

pub async fn handle_available_document_types() -> Result<impl Reply, Infallible> {
match handler::get_available_document_types() {
Ok(res) => Ok(warp::reply::with_status(warp::reply::json(&res), StatusCode::OK)),
Err(err) => Ok(warp::reply::with_status(
warp::reply::json(&Value::String(err.to_string())),
StatusCode::BAD_REQUEST,
)),
}
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LoadDocumentBody {
file_type: String,
document: String,
}

pub async fn handle_load_document(body: LoadDocumentBody) -> Result<impl Reply, Infallible> {
lazy_static! {
static ref TMP: PathBuf = PathBuf::from(CACHE_FOLDER);
}

let mut path;
loop {
path = TMP.clone();
path.push(&serde_json::to_string(&Uuid::new_v4()).unwrap().replace('"', ""));
let path = path.with_extension(&body.file_type);

if !path.exists() {
break;
}
}

let contents = fs::read(&path).await;

if contents.is_err() {
return Ok(warp::reply::with_status(
warp::reply::json(&Value::String(contents.err().unwrap().to_string())),
StatusCode::INTERNAL_SERVER_ERROR,
));
}

let reply = match fs::write(&path, body.document).await {
Ok(_) => match handler::load_document(
path.extension().unwrap_or_default().to_str().unwrap_or_default(),
contents.unwrap(),
) {
Ok(res) => Ok(warp::reply::with_status(warp::reply::json(&res), StatusCode::OK)),
Err(err) => Ok(warp::reply::with_status(
warp::reply::json(&Value::String(err.to_string())),
StatusCode::BAD_REQUEST,
)),
},
Err(err) => Ok(warp::reply::with_status(
warp::reply::json(&Value::String(err.to_string())),
StatusCode::INTERNAL_SERVER_ERROR,
)),
};

fs::remove_file(&path)
.await
.unwrap_or_else(|err| log::error!("removing file '{:?}' failed: {}", path, err.to_string()));

reply
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SaveDocumentBody {
file_type: String,
document: CaBr2Document,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct SaveDocumentResponse {
download_url: String,
}

pub async fn handle_save_document(body: SaveDocumentBody) -> Result<impl Reply, Infallible> {
lazy_static! {
static ref TMP: PathBuf = PathBuf::from(DOWNLOAD_FOLDER);
}

let mut path;
let mut uuid_str;
loop {
path = TMP.clone();
uuid_str = serde_json::to_string(&Uuid::new_v4()).unwrap().replace('"', "");
path.push(&uuid_str);
let path = path.with_extension(&body.file_type);

if !path.exists() {
break;
}
}

let contents = match handler::save_document(body.file_type.as_str(), body.document) {
Ok(contents) => contents,
Err(err) => {
return Ok(warp::reply::with_status(
warp::reply::json(&Value::String(err.to_string())),
StatusCode::INTERNAL_SERVER_ERROR,
))
}
};

let res = fs::write(&path, contents).await;

match res {
Ok(_) => Ok(warp::reply::with_status(
warp::reply::json(&SaveDocumentResponse {
#[cfg(not(debug_assertions))]
download_url: format!("https://api.cabr2.de/download/{}.{}", uuid_str, body.file_type),
#[cfg(debug_assertions)]
download_url: format!("http://localhost:3030/download/{}.{}", uuid_str, body.file_type),
}),
StatusCode::CREATED,
)),
Err(err) => Ok(warp::reply::with_status(
warp::reply::json(&Value::String(err.to_string())),
StatusCode::BAD_REQUEST,
)),
}
}

pub async fn cleanup_thread() {
// I'm sorry for the number of match statements.
// This logic should ignore every error and continue working on the next file
// but we want to know what went wrong.

loop {
let mut res = match fs::read_dir(DOWNLOAD_FOLDER).await {
Ok(iter) => iter,
Err(err) => {
log::error!("{:?}", err);
break;
}
};

// go through all generated files and remove all that are older than 24 hours
loop {
let path = res.next_entry().await.unwrap_or_default();
match path {
Some(path) => match path.metadata().await {
Ok(data) => match data.modified() {
Ok(c_time) => match c_time.elapsed() {
Ok(dur) => {
if dur.as_secs() > 86400 {
match fs::remove_file(path.path()).await {
Ok(_) => log::debug!("deleted file: {:?}", path.path()),
Err(e) => log::error!("{:?}", e),
};
}
}
Err(e) => log::error!("{:?}", e),
},
Err(e) => log::error!("{:?}", e),
},
Err(e) => log::error!("{:?}", e),
},
None => break,
}
}

// check every 15 minutes
tokio::time::sleep(Duration::from_secs(900)).await;
}
}
10 changes: 7 additions & 3 deletions src-tauri/cabr2_logger/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ cabr2_types = { path = "../cabr2_types/" }
chrono = "0.4.19"
fern = "0.6.0"
log = "0.4.14"
serde = { version = "1.0.126", features = ["derive"] }
serde_json = "1.0.64"
tauri = { version = "1.0.0-beta.4", default-features = false }
serde = { version = "1.0.126", features = ["derive"], optional = true }
serde_json = { version = "1.0.64", optional = true }
tauri = { version = "1.0.0-beta.4", default-features = false, optional = true }
tokio = "1.9.0"

[features]
tauri_plugin = ["serde", "serde_json", "tauri"]
default = []
1 change: 1 addition & 0 deletions src-tauri/cabr2_logger/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![allow(clippy::new_without_default)]

#[cfg(feature = "tauri_plugin")]
pub mod plugin;

use std::fs;
Expand Down
2 changes: 2 additions & 0 deletions src-tauri/cabr2_search/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ tauri = { version = "1.0.0-beta.4", default-features = false, optional = true }
thiserror = "1.0.26"
tokio = { version = "1.9.0", features = ["sync"] }
ureq = { version = "2.1.0", features = ["tls", "json"], optional = true }
warp = { version = "0.3.1", optional = true }

[features]
gestis = [ "roxmltree", "ureq" ]
tauri_plugin = [ "tauri" ]
webserver = ["warp"]
default = []

[[bin]]
Expand Down
2 changes: 2 additions & 0 deletions src-tauri/cabr2_search/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ mod gestis;

#[cfg(feature = "tauri_plugin")]
pub mod plugin;
#[cfg(feature = "webserver")]
pub mod webserver;
Loading

0 comments on commit 491083d

Please sign in to comment.