Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Zwiterrion committed Dec 3, 2024
1 parent f6874c8 commit d758256
Show file tree
Hide file tree
Showing 37 changed files with 198 additions and 1,860 deletions.
17 changes: 17 additions & 0 deletions cli/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ testcontainers = "0.23.1"
slug = "0.1.5"
regex = "1.11.1"
zip = "2.2.1"
mime_guess = "2.0.5"

[dependencies.uuid]
version = "1.7.0"
Expand Down
25 changes: 15 additions & 10 deletions cli/src/commands/assets.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{
fs::{self, File},
io::Read,
path::PathBuf,
path::{Path, PathBuf},
str::FromStr,
};

Expand All @@ -18,6 +18,7 @@ use crate::{
use bytes::Bytes;

use hyper::header;
use mime_guess::mime;
use serde::{Deserialize, Serialize};
use walkdir::WalkDir;

Expand Down Expand Up @@ -126,21 +127,24 @@ async fn add(

let project = get_default_project()?;

let mut file = File::open(
PathBuf::from_str(&project.path)
.unwrap()
.join("assets")
.join(path.unwrap_or("".to_string()))
.join(filename),
)
.map_err(|err| DaikokuCliError::FileSystem(err.to_string()))?;
let filepath = PathBuf::from_str(&project.path)
.unwrap()
.join("assets")
.join(path.unwrap_or("".to_string()))
.join(filename);
let mut file =
File::open(filepath.clone()).map_err(|err| DaikokuCliError::FileSystem(err.to_string()))?;

let mut contents = Vec::new();
let _ = file
.read_to_end(&mut contents)
.map_err(|err| DaikokuCliError::FileSystem(err.to_string()));

let _ = daikoku_cms_api_post(&url, Bytes::from(contents), false).await?;
let content_type = mime_guess::from_path(filepath.to_string_lossy().into_owned())
.first()
.unwrap_or(mime::APPLICATION_OCTET_STREAM);

let _ = daikoku_cms_api_post(&url, Bytes::from(contents), false, Some(content_type)).await?;

logger::success("New asset has been pushed".to_string());

Expand Down Expand Up @@ -327,6 +331,7 @@ async fn sync() -> DaikokuResult<()> {
DaikokuCliError::ParsingError("failed to convert assets to json array".to_string())
})?),
false,
None
)
.await?;

Expand Down
31 changes: 0 additions & 31 deletions cli/src/commands/cms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -472,12 +472,6 @@ async fn migrate(name: String, path: String, server: String, apikey: String) ->

let sources_path = project_path.join("src");

let root_mail_tenant = bytes_to_struct::<TenantMailBody>(
raw_daikoku_cms_api_get("/tenants/default", &server, &apikey)
.await?
.response,
)?;

let root_mail_user_translations = bytes_to_struct::<IntlTranslationBody>(
raw_daikoku_cms_api_get(
"/translations/_mail?domain=tenant.mail.template",
Expand Down Expand Up @@ -507,7 +501,6 @@ async fn migrate(name: String, path: String, server: String, apikey: String) ->
.filter(|api| !EXCLUDE_API.contains(&api._id.as_str()))
.collect();

create_mail_tenant(root_mail_tenant, sources_path.clone())?;
create_mail_folder(root_mail_user_translations, sources_path.clone(), true)?;
create_mail_folder(mail_user_template, sources_path.clone(), false)?;

Expand Down Expand Up @@ -616,30 +609,6 @@ pub(crate) fn create_api_folder(
Ok(created)
}

pub(crate) fn create_mail_tenant(
mail_settings: TenantMailBody,
project_path: PathBuf,
) -> DaikokuResult<()> {
let filename = "page.html".to_string();

let file_path = project_path
.clone()
.join(get_mail_page_path(&filename, true).unwrap());

let _ = create_path_and_file(
file_path,
mail_settings
.mailer_settings
.map(|mailer| mailer.template.unwrap_or("".to_string()))
.unwrap_or("".to_string()),
filename,
HashMap::new(),
SourceExtension::HTML,
);

Ok(())
}

pub(crate) fn create_mail_folder(
intl_translation: IntlTranslationBody,
project_path: PathBuf,
Expand Down
20 changes: 8 additions & 12 deletions cli/src/commands/pull.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use crate::{

use super::{
cms::{
self, create_api_folder, create_mail_folder, create_mail_tenant, Api, CmsPage,
IntlTranslationBody, TenantMailBody, EXCLUDE_API,
self, create_api_folder, create_mail_folder, Api, CmsPage, IntlTranslationBody,
TenantMailBody, EXCLUDE_API,
},
environments::{get_default_environment, read_apikey_from_secrets},
};
Expand Down Expand Up @@ -81,10 +81,6 @@ async fn mails_synchronization(project: &cms::Project) -> DaikokuResult<()> {
.collect::<Vec<&CmsPage>>();

if existing_emails_pages.is_empty() {
let root_mail_tenant = bytes_to_struct::<TenantMailBody>(
daikoku_cms_api_get("/tenants/default").await?.response,
)?;

let root_mail_user_translations = bytes_to_struct::<IntlTranslationBody>(
daikoku_cms_api_get("/translations/_mail?domain=tenant.mail.template")
.await?
Expand All @@ -97,7 +93,6 @@ async fn mails_synchronization(project: &cms::Project) -> DaikokuResult<()> {
.response,
)?;

create_mail_tenant(root_mail_tenant, sources_path.clone())?;
create_mail_folder(root_mail_user_translations, sources_path.clone(), true)?;
create_mail_folder(mail_user_template, sources_path.clone(), false)?;
} else {
Expand All @@ -107,15 +102,16 @@ async fn mails_synchronization(project: &cms::Project) -> DaikokuResult<()> {
.join(item.path.clone().unwrap().replacen("/", "", 1))
.join("page.html");

let mut file = std::fs::OpenOptions::new()
let file = std::fs::OpenOptions::new()
.write(true)
.truncate(true)
.open(file_path)
.unwrap();
.open(file_path);

let _ = file.write_all(item.content.clone().as_bytes());
if let Ok(mut email) = file {
let _ = email.write_all(item.content.clone().as_bytes());

let _ = file.flush();
let _ = email.flush();
}
});
}

Expand Down
2 changes: 1 addition & 1 deletion cli/src/commands/push.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ async fn synchronization(body: &mut Vec<CmsFile>, dry_run: bool) -> DaikokuResul
);

if !dry_run {
daikoku_cms_api_post("/sync", body, true).await?;
daikoku_cms_api_post("/sync", body, true, None).await?;
}

Ok(())
Expand Down
33 changes: 24 additions & 9 deletions cli/src/commands/watch.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use hyper::header::{HeaderValue, LOCATION};
use regex::Regex;
use std::collections::HashMap;
use std::io::Read;
Expand All @@ -8,7 +9,7 @@ use http_body_util::{BodyExt, Empty, Full};
use hyper::body::Bytes;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{header, Method};
use hyper::{header, Method, StatusCode};
use hyper::{Request, Response};

use hyper_util::rt::TokioIo;
Expand Down Expand Up @@ -110,8 +111,18 @@ async fn watcher(
) -> Result<Response<Full<Bytes>>, DaikokuCliError> {
let uri = req.uri().path().to_string();

if uri.starts_with("/api/") || uri.starts_with("/tenant-assets/") {
logger::println("forward to api or /tenant-assets".to_string());
if uri.starts_with("/tenant-assets/") {
let redirect_url = "http://localhost:5173/tenant-assets/api3.jpeg";

let mut response = Response::new(Full::<Bytes>::new(Bytes::from("")));
*response.status_mut() = StatusCode::FOUND; // 302 status
response
.headers_mut()
.insert(LOCATION, HeaderValue::from_str(redirect_url).unwrap());

Ok(response)
} else if uri.starts_with("/api/") {
logger::println("forward to api".to_string());
forward_api_call(uri, req, environment).await
} else {
let path = uri.replace("_/", "");
Expand Down Expand Up @@ -242,13 +253,12 @@ async fn forward_api_call(

let url: String = format!("{}{}", environment.server, uri);

let cookie = read_cookie_from_environment(true)?;

let raw_req = Request::builder()
.method(Method::from_str(&method).unwrap())
.uri(&url)
.header(header::HOST, &host)
.header(header::COOKIE, cookie);
.header("Accept", "*/*")
.header(header::COOKIE, read_cookie_from_environment(true)?);

let req = if method == "GET" {
raw_req.body(Empty::<Bytes>::new().boxed()).unwrap()
Expand Down Expand Up @@ -292,7 +302,9 @@ async fn forward_api_call(

let (
hyper::http::response::Parts {
headers: _, status, ..
headers: _headers,
status,
..
},
body,
) = upstream_resp.into_parts();
Expand All @@ -301,6 +313,8 @@ async fn forward_api_call(

let status = status.as_u16();

println!("{:?}", _headers);

if status >= 300 && status < 400 {
Ok(Response::new(Full::new(Bytes::from(
"Authentication needed! Refresh this page once done",
Expand Down Expand Up @@ -340,7 +354,9 @@ async fn render_page(
fields.insert(param.key, param.value);
}

if watch_path.starts_with("/mails") {
if watch_path.starts_with("/mails")
&& !watch_path.starts_with("/mails/root/tenant-mail-template")
{
let language = if watch_path.contains("/fr") {
"fr"
} else {
Expand Down Expand Up @@ -449,7 +465,6 @@ async fn render_page(

let source = src.replace('"', "&quot;");


let children: String = if SourceExtension::from_str(&page.content_type()).unwrap()
== SourceExtension::HTML
{
Expand Down
22 changes: 15 additions & 7 deletions cli/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::any::type_name;

use bytes::Buf;
use hyper::header;
use mime_guess::Mime;
use serde::Deserialize;

use crate::{
Expand Down Expand Up @@ -45,6 +46,7 @@ pub(crate) async fn daikoku_cms_api_post<T: Buf + std::marker::Send + 'static>(
path: &str,
body: T,
is_json_content: bool,
content_type: Option<Mime>,
) -> DaikokuResult<Vec<u8>>
where
reqwest::Body: From<T>,
Expand All @@ -60,18 +62,24 @@ where

let url: String = format!("{}/cms-api{}", environment.server, &path);

let builder = reqwest::Client::new().post(url).header(header::HOST, host);
let mut builder = reqwest::Client::new().post(url).header(header::HOST, host);

let resp = if is_json_content {
builder = if is_json_content {
builder.header(header::CONTENT_TYPE, "application/json")
} else {
builder
}
.header(header::AUTHORIZATION, format!("Basic {}", apikey))
.body(body)
.send()
.await
.map_err(|err| DaikokuCliError::DaikokuStrError(err.to_string()))?;
.header(header::AUTHORIZATION, format!("Basic {}", apikey));

if let Some(content) = content_type {
builder = builder.header("Asset-Content-Type", content.to_string());
}

let resp = builder
.body(body)
.send()
.await
.map_err(|err| DaikokuCliError::DaikokuStrError(err.to_string()))?;

let status = resp.status().as_u16();

Expand Down
2 changes: 0 additions & 2 deletions daikoku/app/controllers/HomeController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -284,8 +284,6 @@ class HomeController(
true
)

// println(strictPage)

val (page, urlSearchParams) =
if (strictPage._1.nonEmpty)
strictPage
Expand Down
Loading

0 comments on commit d758256

Please sign in to comment.