initial commit
This commit is contained in:
commit
be696df5c4
1
.dockerignore
Normal file
1
.dockerignore
Normal file
@ -0,0 +1 @@
|
||||
/target
|
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
/target
|
||||
debug.log
|
||||
frontend/dist/
|
2799
Cargo.lock
generated
Normal file
2799
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
5
Cargo.toml
Normal file
5
Cargo.toml
Normal file
@ -0,0 +1,5 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"backend", "frontend",
|
||||
]
|
2350
backend/Cargo.lock
generated
Normal file
2350
backend/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
9
backend/Cargo.toml
Normal file
9
backend/Cargo.toml
Normal file
@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "peazyweb-backend"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
rocket = { version = "0.5.1", features = ["json", "serde_json"] }
|
||||
rocket_cors = "0.6.0"
|
||||
tokio = { version = "1.44.1", features = ["fs", "process"] }
|
153
backend/openapi.json
Normal file
153
backend/openapi.json
Normal file
@ -0,0 +1,153 @@
|
||||
{
|
||||
"openapi": "3.0.4",
|
||||
"info": {
|
||||
"title": "Peazyrsa generator",
|
||||
"description": "service to generate ovpn configs",
|
||||
"contact": {
|
||||
"email": "mail@b4tman.ru"
|
||||
},
|
||||
"license": {
|
||||
"name": "MIT"
|
||||
},
|
||||
"version": "0.0.1"
|
||||
},
|
||||
"tags": [
|
||||
{
|
||||
"name": "OpenVPN",
|
||||
"description": "OpenVPN related"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/get": {
|
||||
"get": {
|
||||
"summary": "get directories",
|
||||
"description": "",
|
||||
"operationId": "",
|
||||
"responses": {
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"content": {
|
||||
"text/plain; charset=utf-8": {
|
||||
"examples": {
|
||||
"error": {
|
||||
"value": "Failed to read directory"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"description": "Default sample response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"examples": {
|
||||
"example": {
|
||||
"value": [
|
||||
"dir1",
|
||||
"dir2"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"OpenVPN"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/get/<directory>": {
|
||||
"get": {
|
||||
"summary": "get directory file",
|
||||
"description": "",
|
||||
"operationId": "",
|
||||
"responses": {
|
||||
"default": {
|
||||
"description": "Default sample response",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"examples": {
|
||||
"example": {
|
||||
"value": [
|
||||
"file1",
|
||||
"file2"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"OpenVPN"
|
||||
]
|
||||
}
|
||||
},
|
||||
"/generate": {
|
||||
"summary": "generate config",
|
||||
"post": {
|
||||
"summary": "generate config",
|
||||
"description": "",
|
||||
"operationId": "",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"directory": {
|
||||
"type": "string",
|
||||
"example": "dir1"
|
||||
},
|
||||
"common_name": {
|
||||
"type": "string",
|
||||
"example": "computer2"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"404": {
|
||||
"description": "dir not found",
|
||||
"content": {
|
||||
"text/plain; charset=utf-8": {
|
||||
"examples": {
|
||||
"error": {
|
||||
"value": "Directory not found"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"content": {
|
||||
"text/plain; charset=utf-8": {
|
||||
"examples": {
|
||||
"error": {
|
||||
"value": "Failed create config"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"default": {
|
||||
"description": "Default sample response",
|
||||
"content": {
|
||||
"text/plain; charset=utf-8": {
|
||||
"example": "client\nproto udp\ndev tun\n...\n"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"OpenVPN"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
223
backend/src/main.rs
Normal file
223
backend/src/main.rs
Normal file
@ -0,0 +1,223 @@
|
||||
use rocket::fs::NamedFile;
|
||||
use rocket::http::Status;
|
||||
use rocket::response::{Responder, status};
|
||||
use rocket::serde::{Deserialize, json::Json};
|
||||
use rocket::{self, get, launch, post, routes};
|
||||
use rocket::http::Method;
|
||||
use rocket_cors::{AllowedOrigins, CorsOptions};
|
||||
use std::env;
|
||||
use std::path::Path;
|
||||
|
||||
#[get("/")]
|
||||
fn index() -> &'static str {
|
||||
"Hello, world!"
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(crate = "rocket::serde")]
|
||||
struct GenerationRequest<'r> {
|
||||
directory: &'r str,
|
||||
common_name: &'r str,
|
||||
}
|
||||
|
||||
#[derive(Responder)]
|
||||
enum GenerationError {
|
||||
#[response(status = 500, content_type = "json")]
|
||||
InternalError(String),
|
||||
#[response(status = 404, content_type = "json")]
|
||||
DirectoryNotFoundError(String),
|
||||
}
|
||||
|
||||
fn get_base_directory() -> String {
|
||||
match env::var("GENERATION_BASE_DIRECTORY") {
|
||||
Ok(directory) => directory,
|
||||
Err(_) => "base/".into(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_is_valid_directory(
|
||||
directory: impl AsRef<Path> + Clone,
|
||||
) -> Result<(), GenerationError> {
|
||||
match tokio::fs::metadata(directory.clone()).await {
|
||||
Ok(metadata) => {
|
||||
if !metadata.is_dir() {
|
||||
return Err(GenerationError::DirectoryNotFoundError(
|
||||
"The specified directory is not valid".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(GenerationError::DirectoryNotFoundError(
|
||||
"The specified directory is not exists".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
// Check if the directory contains a 'vars.bat' and 'template.ovpn' files
|
||||
const REQUIRED_FILES: [&str; 2] = ["vars.bat", "template.ovpn"];
|
||||
for file_name in REQUIRED_FILES.iter() {
|
||||
let file_path = directory.as_ref().join(file_name);
|
||||
match tokio::fs::metadata(&file_path).await {
|
||||
Ok(metadata) => {
|
||||
if !metadata.is_file() {
|
||||
return Err(GenerationError::DirectoryNotFoundError(format!(
|
||||
"The specified directory is not valid, invalid file: {}",
|
||||
file_name
|
||||
)));
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
return Err(GenerationError::DirectoryNotFoundError(format!(
|
||||
"The specified directory is not valid, missing file: {}",
|
||||
file_name
|
||||
)));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[get("/get")]
|
||||
async fn list_directories() -> Result<Json<Vec<String>>, status::Custom<String>> {
|
||||
let mut reader = tokio::fs::read_dir(get_base_directory())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
status::Custom(
|
||||
Status::InternalServerError,
|
||||
format!("Failed to read directory: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut directories = Vec::new();
|
||||
while let Ok(Some(entry)) = reader.next_entry().await {
|
||||
let path = entry.path();
|
||||
if check_is_valid_directory(&path).await.is_ok() {
|
||||
if let Some(name) = path.file_name() {
|
||||
directories.push(name.to_str().unwrap().to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(directories))
|
||||
}
|
||||
|
||||
#[get("/get/<directory>")]
|
||||
async fn list_directory(directory: &str) -> Result<Json<Vec<String>>, status::Custom<String>> {
|
||||
let base = get_base_directory();
|
||||
let dir = Path::new(&base).join(directory);
|
||||
if check_is_valid_directory(&dir).await.is_err() {
|
||||
return Err(status::Custom(
|
||||
Status::BadRequest,
|
||||
"The specified directory is not valid".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let dir = dir.join("config");
|
||||
let mut reader = tokio::fs::read_dir(dir).await.map_err(|e| {
|
||||
status::Custom(
|
||||
Status::InternalServerError,
|
||||
format!("Failed to read directory: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
let mut files = Vec::new();
|
||||
while let Ok(Some(entry)) = reader.next_entry().await {
|
||||
let path = entry.path();
|
||||
if let Ok(meta) = path.metadata() {
|
||||
if !meta.is_file() {
|
||||
continue;
|
||||
}
|
||||
if let Some(ext) = path.extension() {
|
||||
if ext.to_str().unwrap() != "ovpn" {
|
||||
continue;
|
||||
};
|
||||
if let Some(name) = path.file_name() {
|
||||
files.push(name.to_str().unwrap().to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(files))
|
||||
}
|
||||
|
||||
#[get("/get/<directory>/<file>")]
|
||||
async fn get_file(directory: &str, file: &str) -> Result<NamedFile, status::NotFound<String>> {
|
||||
let dir = Path::new(&get_base_directory()).join(directory);
|
||||
if check_is_valid_directory(&dir).await.is_err() {
|
||||
return Err(status::NotFound(
|
||||
"The specified directory is not valid".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let dir = dir.join("config");
|
||||
let path = dir.join(file);
|
||||
NamedFile::open(&path)
|
||||
.await
|
||||
.map_err(|e| status::NotFound(e.to_string()))
|
||||
}
|
||||
|
||||
#[post("/generate", data = "<request>")]
|
||||
async fn generate(request: Json<GenerationRequest<'_>>) -> Result<NamedFile, GenerationError> {
|
||||
let dir = Path::new(&get_base_directory()).join(request.directory);
|
||||
check_is_valid_directory(dir.clone()).await?;
|
||||
|
||||
let generator_bin = env::var("GENERATOR_BIN").unwrap_or("peazyrsa".into());
|
||||
let mut cmd = tokio::process::Command::new(generator_bin);
|
||||
if env::var("USE_OPENSSL").unwrap_or("no".into()) == "yes" {
|
||||
let openssl_bin = env::var("OPENSSL_BIN").unwrap_or("openssl".into());
|
||||
cmd.arg("--with-openssl").arg(openssl_bin);
|
||||
}
|
||||
cmd.arg("-d").arg(&dir).arg(request.common_name);
|
||||
|
||||
// execute the command and check error code
|
||||
let status = cmd
|
||||
.status()
|
||||
.await
|
||||
.map_err(|e| GenerationError::InternalError(format!("Failed to execute command: {}", e)))?;
|
||||
if !status.success() {
|
||||
return Err(GenerationError::InternalError(format!(
|
||||
"Command failed with status: {}",
|
||||
status
|
||||
)));
|
||||
}
|
||||
|
||||
// check output file exists
|
||||
let output_file = dir
|
||||
.join("config")
|
||||
.join(format!("{}.ovpn", request.common_name));
|
||||
if !output_file.exists() {
|
||||
return Err(GenerationError::InternalError(
|
||||
"Output file not found".into(),
|
||||
));
|
||||
}
|
||||
|
||||
match NamedFile::open(output_file).await {
|
||||
Err(e) => {
|
||||
return Err(GenerationError::InternalError(format!(
|
||||
"Failed to open output file: {}",
|
||||
e
|
||||
)));
|
||||
}
|
||||
Ok(f) => Ok(f),
|
||||
}
|
||||
}
|
||||
|
||||
#[launch]
|
||||
fn rocket() -> _ {
|
||||
let cors = CorsOptions::default()
|
||||
.allowed_origins(AllowedOrigins::all())
|
||||
.allowed_methods(
|
||||
vec![Method::Get, Method::Post]
|
||||
.into_iter()
|
||||
.map(From::from)
|
||||
.collect(),
|
||||
)
|
||||
.allow_credentials(true);
|
||||
|
||||
rocket::build().mount(
|
||||
"/api/v1",
|
||||
routes![index, list_directories, list_directory, get_file, generate],
|
||||
).attach(cors.to_cors().unwrap())
|
||||
}
|
14
frontend/Cargo.toml
Normal file
14
frontend/Cargo.toml
Normal file
@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "peazyweb-frontend"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
gloo = "0.11.0"
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
serde_json = "1.0.140"
|
||||
wasm-bindgen = "0.2.100"
|
||||
wasm-bindgen-futures = "0.4.50"
|
||||
web-sys = { version = "0.3.77", features = ["console"] }
|
||||
yew = { version = "0.21.0", features = ["csr"] }
|
||||
yew-router = "0.18.0"
|
16
frontend/index.html
Normal file
16
frontend/index.html
Normal file
@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Peazyweb - OpenVPN config creator</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module">
|
||||
import init from './pkg/frontend.js';
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
326
frontend/src/main.rs
Normal file
326
frontend/src/main.rs
Normal file
@ -0,0 +1,326 @@
|
||||
use gloo::net::http::Request;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use wasm_bindgen_futures::spawn_local;
|
||||
use yew::Properties;
|
||||
use yew::prelude::*;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
struct GenerationRequest {
|
||||
directory: String,
|
||||
common_name: String,
|
||||
}
|
||||
|
||||
use yew_router::prelude::*;
|
||||
|
||||
#[derive(Clone, Routable, PartialEq)]
|
||||
pub enum Route {
|
||||
#[at("/")]
|
||||
Home,
|
||||
#[at("/dir")]
|
||||
Directories,
|
||||
#[at("/dir/:dir_name")]
|
||||
Configs { dir_name: String },
|
||||
#[at("/dir/:dir_name/:file_name")]
|
||||
Config { dir_name: String, file_name: String },
|
||||
#[at("/gen/:dir_name")]
|
||||
Generate { dir_name: String },
|
||||
#[not_found]
|
||||
#[at("/404")]
|
||||
NotFound,
|
||||
}
|
||||
|
||||
#[derive(Properties, PartialEq)]
|
||||
pub struct NavProps {
|
||||
#[prop_or("".into())]
|
||||
pub currrent_dir: AttrValue,
|
||||
#[prop_or(Route::Home)]
|
||||
pub currrent_route: Route,
|
||||
}
|
||||
|
||||
// component to show the navbar
|
||||
#[function_component(Navbar)]
|
||||
fn navbar(props: &NavProps) -> Html {
|
||||
let classes_active = "block py-2 px-3 text-white bg-blue-700 rounded-sm md:bg-transparent md:text-blue-700 md:p-0 dark:text-white md:dark:text-blue-500";
|
||||
let classes_inactive = "block py-2 px-3 text-gray-900 rounded-sm hover:bg-gray-100 md:hover:bg-transparent md:border-0 md:hover:text-blue-700 md:p-0 dark:text-white md:dark:hover:text-blue-500 dark:hover:bg-gray-700 dark:hover:text-white md:dark:hover:bg-transparent";
|
||||
let has_dir = props.currrent_dir.len() > 0;
|
||||
let is_current_home = props.currrent_route == Route::Home;
|
||||
|
||||
html! {
|
||||
<nav class="bg-white border-gray-200 dark:bg-gray-900">
|
||||
<div class="max-w-screen-xl flex flex-wrap items-center justify-between mx-auto p-4">
|
||||
<a href="/" class="flex items-center space-x-3 rtl:space-x-reverse">
|
||||
<span class="self-center text-2xl font-semibold whitespace-nowrap dark:text-white">{"Home"}</span>
|
||||
</a>
|
||||
<button data-collapse-toggle="navbar-default" type="button" class="inline-flex items-center p-2 w-10 h-10 justify-center text-sm text-gray-500 rounded-lg md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600" aria-controls="navbar-default" aria-expanded="false">
|
||||
<span class="sr-only">{"Open main menu"}</span>
|
||||
<svg class="w-5 h-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 17 14">
|
||||
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M1 1h15M1 7h15M1 13h15"/>
|
||||
</svg>
|
||||
</button>
|
||||
<div class="hidden w-full md:block md:w-auto" id="navbar-default">
|
||||
<ul class="font-medium flex flex-col p-4 md:p-0 mt-4 border border-gray-100 rounded-lg bg-gray-50 md:flex-row md:space-x-8 rtl:space-x-reverse md:mt-0 md:border-0 md:bg-white dark:bg-gray-800 md:dark:bg-gray-900 dark:border-gray-700">
|
||||
<li class={if is_current_home {classes_active} else {classes_inactive}}><Link<Route> to={Route::Home}>{ "Home" }</Link<Route>></li>
|
||||
if has_dir {
|
||||
<li class={
|
||||
match props.currrent_route.clone() {
|
||||
Route::Configs{dir_name} if dir_name == props.currrent_dir.to_string() => classes_active,
|
||||
_ => classes_inactive,
|
||||
}
|
||||
}><Link<Route> to={Route::Configs{dir_name: props.currrent_dir.to_string()}}>{ props.currrent_dir.clone() }</Link<Route>></li>
|
||||
}
|
||||
<li class={if !is_current_home {classes_active} else {classes_inactive}}><Link<Route> to={Route::Directories}>{ "Directories" }</Link<Route>></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
}
|
||||
}
|
||||
|
||||
// component to show the directories
|
||||
#[function_component(Directories)]
|
||||
fn directories() -> Html {
|
||||
let dirs = use_state(Vec::new);
|
||||
let message = use_state(|| "".to_string());
|
||||
|
||||
let get_dirs = {
|
||||
let dirs = dirs.clone();
|
||||
let message = message.clone();
|
||||
Callback::from(move |_| {
|
||||
let url = "http://127.0.0.1:8000/api/v1/get/";
|
||||
let dirs = dirs.clone();
|
||||
let message = message.clone();
|
||||
spawn_local(async move {
|
||||
match Request::get(url).send().await {
|
||||
Ok(response) if response.ok() => match response.json::<Vec<String>>().await {
|
||||
Ok(json) => {
|
||||
dirs.set(json);
|
||||
}
|
||||
_ => message.set("Failed to fetch directories".into()),
|
||||
},
|
||||
_ => message.set("Failed to fetch directories".into()),
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
// Добавляем use_effect с пустым вектором зависимостей
|
||||
{
|
||||
let get_dirs = get_dirs.clone();
|
||||
use_effect_with((),
|
||||
move |_| {
|
||||
get_dirs.emit(());
|
||||
()
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
html! {
|
||||
<div>
|
||||
<p><button
|
||||
onclick={get_dirs.reform(|_| ())}
|
||||
class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded mb-4">
|
||||
{ "Refresh" }
|
||||
</button></p>
|
||||
<h1>{"Directories"}</h1>
|
||||
<h2 class="text-2xl font-bold text-gray-700 mb-2">{ "Directory List" }</h2>
|
||||
<ul class="list-disc pl-5">
|
||||
{ for (*dirs).iter().map(|dir| {
|
||||
html! {
|
||||
<li class="mb-2">
|
||||
<Link<Route> to={Route::Configs { dir_name: dir.to_string() }}>{dir}</Link<Route>>
|
||||
</li>
|
||||
}
|
||||
}) }
|
||||
</ul>
|
||||
|
||||
if !message.is_empty() {
|
||||
<p class="text-green-500 mt-2">{ &*message }</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Properties, PartialEq)]
|
||||
pub struct ConfigsProps {
|
||||
pub dir: AttrValue,
|
||||
}
|
||||
|
||||
#[function_component(Configs)]
|
||||
fn configs(props: &ConfigsProps) -> Html {
|
||||
let configs = use_state(Vec::new);
|
||||
let message = use_state(|| "".to_string());
|
||||
let dir_name = props.dir.clone();
|
||||
|
||||
let get_configs = {
|
||||
let configs = configs.clone();
|
||||
let message = message.clone();
|
||||
Callback::from(move |_| {
|
||||
let url = format!("http://127.0.0.1:8000/api/v1/get/{}", dir_name.clone());
|
||||
let configs = configs.clone();
|
||||
let message = message.clone();
|
||||
spawn_local(async move {
|
||||
match Request::get(&url).send().await {
|
||||
Ok(response) if response.ok() => match response.json::<Vec<String>>().await {
|
||||
Ok(json) => {
|
||||
configs.set(json);
|
||||
}
|
||||
_ => message.set("Failed to fetch configs".into()),
|
||||
},
|
||||
_ => message.set("Failed to fetch configs".into()),
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
{
|
||||
let get_configs_clone = get_configs.clone();
|
||||
use_effect_with((), move |_| {
|
||||
get_configs_clone.emit(());
|
||||
()
|
||||
});
|
||||
}
|
||||
|
||||
html! {
|
||||
<div>
|
||||
<p><button
|
||||
onclick={get_configs.reform(|_| ())}
|
||||
class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded mb-4">
|
||||
{ "Refresh" }
|
||||
</button></p>
|
||||
<h1>{ "Configs" }</h1>
|
||||
<h2 class="text-2xl font-bold text-gray-700 mb-2">{format!("Configs for {}:", props.dir.clone())}</h2>
|
||||
<ul class="list-disc pl-5">
|
||||
{ for (*configs).iter().map(|file_name| {
|
||||
html! {
|
||||
<li class="mb-2">
|
||||
<Link<Route> to={Route::Config { dir_name: props.dir.clone().to_string(), file_name: file_name.clone() }}>{file_name}</Link<Route>>
|
||||
</li>
|
||||
}
|
||||
}) }
|
||||
</ul>
|
||||
|
||||
if !message.is_empty() {
|
||||
<p class="text-green-500 mt-2">{ &*message }</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Properties, PartialEq)]
|
||||
pub struct ConfigProps {
|
||||
pub dir: AttrValue,
|
||||
pub file_name: AttrValue,
|
||||
}
|
||||
|
||||
#[function_component(Config)]
|
||||
fn config(props: &ConfigProps) -> Html {
|
||||
let dir_name = props.dir.clone();
|
||||
let file_name = props.file_name.clone();
|
||||
let contents = use_state(|| "".to_string());
|
||||
|
||||
let get_contents = {
|
||||
let contents = contents.clone();
|
||||
Callback::from(move |_| {
|
||||
let url = format!(
|
||||
"http://127.0.0.1:8000/api/v1/get/{}/{}",
|
||||
dir_name.clone(),
|
||||
file_name.clone()
|
||||
);
|
||||
let contents = contents.clone();
|
||||
spawn_local(async move {
|
||||
match Request::get(&url).send().await {
|
||||
Ok(response) if response.ok() => {
|
||||
if let Ok(text) = response.text().await {
|
||||
contents.set(text);
|
||||
}
|
||||
}
|
||||
_ => contents.set("Failed to fetch contents".into()),
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
{
|
||||
let get_contents_clone = get_contents.clone();
|
||||
use_effect_with((), move |_| {
|
||||
get_contents_clone.emit(());
|
||||
()
|
||||
});
|
||||
}
|
||||
|
||||
html! {
|
||||
<div class="w-full">
|
||||
<p><button
|
||||
onclick={get_contents.reform(|_| ())}
|
||||
class="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded mb-4">
|
||||
{ "Refresh" }
|
||||
</button></p>
|
||||
<p>{"Config "}<b>{props.file_name.clone()}</b>{" for "}<b>{props.dir.clone()}</b>{":"}</p>
|
||||
<div class="mb-2 flex justify-between items-center">
|
||||
<p class="text-sm font-medium text-gray-900 dark:text-white">{"Config "}<b>{props.file_name.clone()}</b>{" for "}<b>{props.dir.clone()}</b>{":"}</p>
|
||||
</div>
|
||||
<div class="relative bg-gray-50 rounded-lg dark:bg-gray-700 p-4">
|
||||
<div class="overflow-scroll max-h-full">
|
||||
<pre><code id="code-block" class="text-sm text-gray-500 dark:text-gray-400 whitespace-pre">{&*contents}</code></pre>
|
||||
</div>
|
||||
<div class="absolute top-2 end-2 bg-gray-50 dark:bg-gray-700">
|
||||
<a href={format!("http://127.0.0.1:8000/api/v1/get/{}/{}", props.dir.clone(), props.file_name.clone())} download={props.file_name.clone()}><button type="button" class="text-white bg-gradient-to-br from-purple-600 to-blue-500 hover:bg-gradient-to-bl focus:ring-4 focus:outline-none focus:ring-blue-300 dark:focus:ring-blue-800 font-medium rounded-lg text-sm px-5 py-2.5 text-center me-2 mb-2">
|
||||
<svg class="w-6 h-6 text-gray-800 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path fill-rule="evenodd" d="M13 11.15V4a1 1 0 1 0-2 0v7.15L8.78 8.374a1 1 0 1 0-1.56 1.25l4 5a1 1 0 0 0 1.56 0l4-5a1 1 0 1 0-1.56-1.25L13 11.15Z" clip-rule="evenodd"/>
|
||||
<path fill-rule="evenodd" d="M9.657 15.874 7.358 13H5a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-2.358l-2.3 2.874a3 3 0 0 1-4.685 0ZM17 16a1 1 0 1 0 0 2h.01a1 1 0 1 0 0-2H17Z" clip-rule="evenodd"/>
|
||||
</svg>{"Download"}</button></a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
fn switch(routes: Route) -> Html {
|
||||
match routes.clone() {
|
||||
Route::Home => html! {
|
||||
<div>
|
||||
<Navbar currrent_route={routes.clone()} />
|
||||
<h1>{ "Home" }</h1> <Link<Route> to={Route::Directories}>{ "Directories" }</Link<Route>>
|
||||
</div> },
|
||||
Route::Directories => html! {
|
||||
<div>
|
||||
<Navbar currrent_route={routes.clone()} />
|
||||
<Directories />
|
||||
</div>
|
||||
},
|
||||
Route::Configs { dir_name } => html! {
|
||||
<div>
|
||||
<Navbar currrent_route={routes.clone()} currrent_dir={dir_name.clone()} />
|
||||
<Configs dir={dir_name.clone()} />
|
||||
</div>
|
||||
},
|
||||
Route::Config {
|
||||
dir_name,
|
||||
file_name,
|
||||
} => html! {
|
||||
<div>
|
||||
<Navbar currrent_route={routes.clone()} currrent_dir={dir_name.clone()} />
|
||||
<Config dir={dir_name.clone()} file_name={file_name.clone()} />
|
||||
</div>
|
||||
},
|
||||
_ => html! {
|
||||
<div>
|
||||
<Navbar />
|
||||
<h1>{ "todo" }</h1>
|
||||
</div>
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[function_component]
|
||||
fn App() -> Html {
|
||||
html! {
|
||||
<BrowserRouter>
|
||||
<Switch<Route> render={switch} />
|
||||
</BrowserRouter>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
yew::Renderer::<App>::new().render();
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user