Skip to content

Commit

Permalink
remake checkbox to be able to be restyle everywhere
Browse files Browse the repository at this point in the history
  • Loading branch information
Sir-Thom committed Sep 21, 2023
1 parent 3904802 commit 3bc4d6b
Show file tree
Hide file tree
Showing 11 changed files with 239 additions and 16 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"dependencies": {
"@tabler/icons-react": "^2.8.0",
"@tauri-apps/api": "^1.4.0",
"axios": "^1.5.0",
"framer-motion": "^10.8.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
Expand Down
4 changes: 3 additions & 1 deletion src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use axum::http::{HeaderValue, Method};
use axum::Router;
use log::{debug, trace};
use magic_eye::server::server_config::{
__cmd__get_server_config_options, get_server_config_options,
__cmd__get_server_config_options, __cmd__post_server_config_options, get_server_config_options,
post_server_config_options,
};
use magic_eye::utils;
use magic_eye::utils::browser::{__cmd__open_web_browser, open_web_browser};
Expand Down Expand Up @@ -97,6 +98,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
get_config_file_content,
update_settings_file,
get_server_config_options,
post_server_config_options
])
.run(context)
.expect("error while running tauri application");
Expand Down
19 changes: 14 additions & 5 deletions src-tauri/src/server/server_config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use log::{debug, error, info, warn};

use reqwest;
use serde_json::Value;

#[tauri::command]
pub async fn get_server_config_options(url: &str) -> Result<String, String> {
Expand Down Expand Up @@ -38,19 +38,28 @@ pub async fn get_server_config_options(url: &str) -> Result<String, String> {
}

#[tauri::command]
pub async fn post_server_config_options(url: &str) -> Result<String, String> {
pub async fn post_server_config_options(config_data: Value, url: &str) -> Result<String, String> {
let client = reqwest::Client::new();
println!("config_data: {:?}", config_data);

// Serialize the JSON data to a string
let data = config_data.to_string();

// Make the POST request with the serialized data
let response = client
.post(url)
.header("Content-Type", "application/json") // Set the content type
.body(data)
.send()
.await
.map_err(|err| err.to_string())?;

debug!("Response: {:?}", response);

if response.status().is_redirection() {
warn!("Redirection: {:?}", response);
}

if response.status().is_success() {
// Deserialize the JSON response into a Value
let body_json: serde_json::Value = response.json().await.map_err(|err| err.to_string())?;
Expand All @@ -60,9 +69,9 @@ pub async fn post_server_config_options(url: &str) -> Result<String, String> {
info!("Response body: {}", body_json_string);
Ok(body_json_string.into())
} else if response.status().is_server_error() {
error!(" error: {:?}", response.status());
// if is unable to connect to the
return Err(format!("Error:{:?}", response.status()).into());
error!("Error: {:?}", response.status());
// If unable to connect to the server or other server error
return Err(format!("Error: {:?}", response.status()).into());
} else {
error!("Request was not successful: {:?}", response.status());

Expand Down
55 changes: 51 additions & 4 deletions src-tauri/src/utils/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,59 @@ pub fn create_configuartion_file_setting() {
}
}
"windows" => {
warn!("No implementation for Windows for now");
println!("No implementation for Windows for now");
let app_data_dir = match var("APPDATA") {
Ok(appdata) => appdata,
Err(_) => {
error!("Failed to retrieve APPDATA environment variable");
return;
}
};

debug!("APPDATA directory: {}", app_data_dir);
let conf_dir = PathBuf::from(&app_data_dir).join(APP_NAME);
let path_config_file = conf_dir.join(SETTINGS_FILE_NAME);
info!("Path to config file: {:?}", path_config_file);

// Create the directory if it doesn't exist
if !Path::new(&conf_dir).exists() {
create_dir_all(&conf_dir).expect("Failed to create config directory");
error!(
"Failed to create config directory for Windows: {:?}",
conf_dir
);
}

let asset_dir_path = tauri::api::path::app_data_dir(&tauri::Config::default())
.unwrap()
.to_str()
.unwrap()
.to_string()
+ APP_NAME
+ "/asset";
trace!("Asset directory path: {}", asset_dir_path);
if !Path::new(&asset_dir_path).exists() {
create_dir_all(&asset_dir_path).expect("Failed to create config directory");
error!(
"Failed to create config directory for Windows: {:?}",
asset_dir_path
);
}

if !Path::new(&path_config_file).exists() {
// Create the file if it doesn't exist
// Get all values from setting
let json_data = serde_json::to_string_pretty(&Setting::new()).unwrap();
trace!("JSON data for config file: {}", json_data);

let mut file = File::create(&path_config_file).unwrap();
file.write_all(json_data.as_bytes()).unwrap();

info!("Config file created");
}
}

_ => {
warn!("no file created for this OS");
error!("Unsupported OS");
println!("Unsupported OS");
}
Expand Down Expand Up @@ -192,7 +241,6 @@ pub fn get_config_file_content() -> String {
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
debug!("content: {}", contents);
// println!("content: {}", contents);
contents
}

Expand All @@ -207,7 +255,6 @@ pub fn update_settings_file(new_settings: String) -> Result<String, String> {
trace!("config file location: {:?}", path_config_file);
let json_data = serde_json::to_string_pretty(&new_settings).map_err(|err| err.to_string())?;
trace!("json data: {}", json_data);
//println!("json data: {}", json_data);

let mut file = File::create(&path_config_file).map_err(|err| err.to_string())?;
file.write_all(json_data.as_bytes())
Expand Down
3 changes: 2 additions & 1 deletion src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"http://172.17.0.2:8000/stream/*",
"http://127.0.0.1:16780/*",
"http://127.0.0.1:9997/*",
"http://localhost:8888/*"
"http://localhost:8888/*",
"http://127.0.0.1:9997/v2/config/set"
]
},
"dialog": {
Expand Down
8 changes: 6 additions & 2 deletions src/components/checkBox/checkBox.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { FaCheck } from "react-icons/fa";
import ICheckbox from "../../interfaces/ICheckbox";

export default function Checkbox({ checked, onChange, value }) {
export default function Checkbox({ checked, onChange, value, className }:ICheckbox) {
const checkboxClassname =
"outline-none outline-2 focus:outline-accent-color1-700 text-text-dark w-4 h-4 border border-gray-400 rounded-sm transition duration-100 mx-2 ease-in-out " +
className;
return (
<div className="cursor-pointer flex items-center">
<input
Expand All @@ -11,7 +15,7 @@ export default function Checkbox({ checked, onChange, value }) {
value={value}
/>
<div
className={`outline-none outline-2 focus:outline-accent-color1-700 text-text-dark w-4 h-4 border border-gray-400 rounded-sm transition duration-100 mx-2 ease-in-out ${
className={`${checkboxClassname} ${
checked ? "bg-accent-color1-700" : "bg-window-dark-300"
}`}
>
Expand Down
7 changes: 7 additions & 0 deletions src/interfaces/ICheckbox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default interface ICheckbox {
checked: boolean;
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
value: any
className?: string;

}
49 changes: 46 additions & 3 deletions src/views/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import SideMenu from "../components/sideMenu/sideMenu";
import Toast from "../components/toast/Toast";
import SrtSetting from "./serverSetting/SrtSetting";

import axios from "axios";

export default function Setting() {
const [configData, setConfigData] = useState<IServer | null>(null);
const [error, setError] = useState<string | null>(null);
Expand Down Expand Up @@ -103,6 +105,7 @@ export default function Setting() {
srt: configData?.srt || true,
srtAddress: configData?.srtAddress || ":8890"
});
console.log(apiSettings);

useEffect(() => {
setError(null);
Expand All @@ -111,13 +114,52 @@ export default function Setting() {
.then((response: string) => {
const parsedResponse: IServer = JSON.parse(response);
setConfigData(parsedResponse);
console.log(parsedResponse);
})

.catch(() => {
setError(
"Unable to connect to the server. Please check your connection."
);
});
}, []);
async function i() {
const response = await axios.post(
"http://127.0.0.1:9997/v2/config/set",
configData
);
console.log(response);
}

const updateConfigDataWithProtocol = (fieldName, newValue) => {
if (configData) {
// Create a new configuration object with the updated field
const updatedConfigData = {
...configData,
[fieldName]: newValue
};

fetch("http://127.0.0.1:9997/v2/config/set", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(updatedConfigData)
})
.then((parsedResponse) => {
console.log(parsedResponse);
setConfigData(parsedResponse);
console.log(parsedResponse);
})
.catch((error) => {
setError(
"Unable to connect to the server. Please check your connection."
);
console.error(error);
});
}
};

const menuItems = [
{ label: "API Setting" },
{ label: "HLS Setting" },
Expand Down Expand Up @@ -149,9 +191,10 @@ export default function Setting() {
{currentSetting === "API Setting" && (
<ApiSetting
settings={apiSettings}
onSave={(updatedApiSettings) =>
setApiSettings(updatedApiSettings)
}
onSave={(updatedApiSettings) => {
setApiSettings(updatedApiSettings);
i();
}}
/>
)}
{currentSetting === "Logging Setting" && (
Expand Down
2 changes: 2 additions & 0 deletions src/views/serverSetting/ApiSetting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export default function ApiSetting({ settings, onSave }) {
const [runOnConnectRestart, setRunOnConnectRestart] = useState(
settings.runOnConnectRestart || false
);
console.log(settings);

const handleApiEnabledChange = (event) => {
setApiEnabled(event.target.checked);
Expand Down Expand Up @@ -66,6 +67,7 @@ export default function ApiSetting({ settings, onSave }) {
runOnConnect: runOnConnect,
runOnConnectRestart: runOnConnectRestart
};
console.log(updatedSettings);

// Call the onSave prop to save the changes
onSave(updatedSettings);
Expand Down
50 changes: 50 additions & 0 deletions tools/fetch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import requests

# API endpoint and authentication
# Replace with the actual API endpoint
api_url = 'http://127.0.0.1:9997/v2/config/set'

headers = {
'Content-Type': 'application/json',
}

# New configuration data
new_config = {
"logLevel": "info",
"logDestinations": ["stdout"],
"logFile": "mediamtx.log",
"readTimeout": "10s",
"writeTimeout": "10s",
"readBufferCount": 512,
"udpMaxPayloadSize": 1472,
"externalAuthenticationURL": "",
"api": True,
"apiAddress": "127.0.0.1:9997",
"metrics": True,
"metricsAddress": "127.0.0.1:9998",
"pprof": False,
"pprofAddress": "127.0.0.1:9999",
"runOnConnect": "",
"runOnConnectRestart": False,
"rtsp": True,
"rtspDisable": False,
"protocols": ["multicast", "tcp", "udp"],
"encryption": "no",
"rtspAddress": ":8554",
"rtspsAddress": ":8322",
"rtpAddress": ":8000",
"rtcpAddress": ":8001",
"multicastIPRange": "224.1.0.0/16",
"multicastRTPPort": 8002,
"multicastRTCPPort": 8003,
# Add other configuration options and values as needed
}

# Make a POST request to update the configuration
response = requests.post(api_url, headers=headers, json=new_config)

# Check the response
if response.status_code == 200:
print('Configuration updated successfully')
else:
print('Failed to update configuration')
Loading

0 comments on commit 3bc4d6b

Please sign in to comment.