Skip to content

Commit

Permalink
refactor: various tasks for refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
ZanzyTHEbar committed Mar 3, 2023
1 parent b5888bb commit d6bd6a7
Show file tree
Hide file tree
Showing 11 changed files with 164 additions and 130 deletions.
2 changes: 1 addition & 1 deletion GUI/ETVR/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ async fn run_mdns_query(service_type: String, scan_time: u64) -> Result<String,
); // get's an array of the base urls found
let json = m_dnsquery::generate_json(&*ref_mdns)
.await
.expect("Failed to generate JSON object"); // generates a json file with the base urls foundµ
.expect("Failed to generate JSON object"); // generates a json file with the base urls found
//tokio::fs::write("config/config.json", json)
// .await
// .expect("Failed to write JSON file");
Expand Down
221 changes: 111 additions & 110 deletions GUI/ETVR/src-tauri/src/modules/m_dnsquery/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

#![allow(dead_code, unused_imports, unused_variables)]
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]

use log::{error, info};
Expand All @@ -19,9 +19,9 @@ pub type MdnsMap = Arc<Mutex<HashMap<String, String>>>; // Arc<Mutex<HashMap<Str
/// - `name`: a vector of the names of the devices found
#[derive(Debug)]
pub struct Mdns {
pub base_url: MdnsMap,
pub names: Vec<String>,
pub ip: Vec<String>,
pub base_url: MdnsMap,
pub names: Vec<String>,
pub ip: Vec<String>,
}

/// Runs a mDNS query for X seconds
Expand All @@ -44,66 +44,66 @@ pub struct Mdns {
/// ***The service type should not have a '.' or a 'local' at the end.*** <br>
/// ***The program adds ".local." automatically.***
pub async fn run_query(
instance: &mut Mdns,
mut service_type: String,
scan_time: u64,
instance: &mut Mdns,
mut service_type: String,
scan_time: u64,
) -> Result<(), Box<dyn std::error::Error>> {
let mdns = ServiceDaemon::new()
.expect("Failed to create daemon. Please install Bonjour on your system");
//* Browse for a service type.
service_type.push_str(".local.");
let receiver = mdns.browse(&service_type).map_err(|e| e.to_string())?;
let now = std::time::Instant::now();
//* listen for event then stop the event loop after 5 seconds.
// while let Ok(event) = receiver.recv() {}
while now.elapsed().as_secs() < scan_time {
//* let event = receiver.recv().expect("Failed to receive event");
if let Ok(event) = receiver.recv_async().await {
match event {
ServiceEvent::ServiceResolved(info) => {
info!(
"At {:?}: Resolved a new service: {} IP: {:#?}:{:#?} Hostname: {:#?}",
now.elapsed(),
info.get_fullname(),
info.get_addresses(),
info.get_port(),
info.get_hostname(),
);
//* split the fullname by '.' and take the first element
let name = info.get_hostname();
info!("Service name: {}", name);
//* remove the period at the end of the name
let mut name = name.trim_end_matches('.');
//* append name to 'http://' to get the base url
let mut base_url = String::from("http://");
base_url.push_str(name);
info!("Base URL: {}", base_url);
//* add the base url to the hashmap
instance
.base_url
.lock()
.map_err(|e| e.to_string())?
.insert(name.to_string(), base_url);
//* remove the `.local` from the name
name = name.trim_end_matches(".local");
instance.names.push(name.to_string());
let ip = info.get_addresses();
// grab the ip adress' from the hashset and add them to the vector
for i in ip {
instance.ip.push(i.to_string());
}
}
other_event => {
info!(
"At {:?} : Received other event: {:?}",
now.elapsed(),
&other_event
);
}
}
let mdns =
ServiceDaemon::new().expect("Failed to create daemon. Please install Bonjour on your system");
//* Browse for a service type.
service_type.push_str(".local.");
let receiver = mdns.browse(&service_type).map_err(|e| e.to_string())?;
let now = std::time::Instant::now();
//* listen for event then stop the event loop after 5 seconds.
// while let Ok(event) = receiver.recv() {}
while now.elapsed().as_secs() < scan_time {
//* let event = receiver.recv().expect("Failed to receive event");
if let Ok(event) = receiver.recv_async().await {
match event {
ServiceEvent::ServiceResolved(info) => {
println!(
"At {:?}: Resolved a new service: {} IP: {:#?}:{:#?} Hostname: {:#?}",
now.elapsed(),
info.get_fullname(),
info.get_addresses(),
info.get_port(),
info.get_hostname(),
);
//* split the fullname by '.' and take the first element
let name = info.get_hostname();
println!("Service name: {}", name);
//* remove the period at the end of the name
let mut name = name.trim_end_matches('.');
//* append name to 'http://' to get the base url
let mut base_url = String::from("http://");
base_url.push_str(name);
println!("Base URL: {}", base_url);
//* add the base url to the hashmap
instance
.base_url
.lock()
.map_err(|e| e.to_string())?
.insert(name.to_string(), base_url);
//* remove the `.local` from the name
name = name.trim_end_matches(".local");
instance.names.push(name.to_string());
let ip = info.get_addresses();
// grab the ip adress' from the hashset and add them to the vector
for i in ip {
instance.ip.push(i.to_string());
}
}
other_event => {
println!(
"At {:?} : Received other event: {:?}",
now.elapsed(),
&other_event
);
}
}
}
Ok(())
}
Ok(())
}

/// Returns a map of the base urls found
Expand All @@ -125,7 +125,8 @@ pub async fn run_query(
///let urls_map = m_dnsquery::get_url_map(ref_mdns);
/// ```
pub fn get_url_map(instance: &mut Mdns) -> &mut MdnsMap {
&mut instance.base_url
println!("Base URL: {:?}", &instance.base_url);
&mut instance.base_url
}

/// Returns a vector of the base urls found
Expand All @@ -147,56 +148,56 @@ pub fn get_url_map(instance: &mut Mdns) -> &mut MdnsMap {
/// let vec = m_dnsquery::get_urls(ref_mdns);
/// ```
pub fn get_urls(instance: &Mdns) -> Vec<String> {
let mut urls: Vec<String> = Vec::new();

let instance_lock = instance.base_url.lock();
let instance_check_result = match instance_lock {
Ok(instance_lock) => instance_lock,
Err(err) => {
error!(
"Failed to lock the instance: {:?} with error: {} in get_urls",
instance, err
);
return urls;
}
};
let mut urls: Vec<String> = Vec::new();

for (_, url) in instance_check_result.iter() {
urls.push(url.to_string());
let instance_lock = instance.base_url.lock();
let instance_check_result = match instance_lock {
Ok(instance_lock) => instance_lock,
Err(err) => {
error!(
"Failed to lock the instance: {:?} with error: {} in get_urls",
instance, err
);
return urls;
}
urls
};

for (_, url) in instance_check_result.iter() {
urls.push(url.to_string());
}
urls
}

pub async fn generate_json(instance: &Mdns) -> Result<String, Box<dyn std::error::Error>> {
let data = get_urls(instance);
//let mut json: serde_json::Value = serde_json::from_str("{}").unwrap();
let mut json: Option<serde_json::Value> = None;
// create a data iterator
for (i, url) in data.iter().enumerate() {
json = Some(serde_json::json!({
"ips": [instance.ip[i].to_string()],
"urls": {
instance.names[i].to_string(): url.to_string()
},
}));
}
let config: serde_json::Value;
if let Some(json) = json {
let _serde_json = serde_json::from_value(json);
let serde_json_result = match _serde_json {
Ok(serde_json) => serde_json,
Err(err) => {
error!("Error configuring JSON config file: {}", err);
return Err("Error configuring JSON config file".into());
}
};
config = serde_json_result;
} else {
config = serde_json::json!({});
}
info!("{:?}", config);
// write the json object to a file
let to_string_json = serde_json::to_string_pretty(&config)?;
// return the json object as a string
Ok(to_string_json)
let data = get_urls(instance);
//let mut json: serde_json::Value = serde_json::from_str("{}").unwrap();
let mut json: Option<serde_json::Value> = None;
// create a data iterator
for (i, url) in data.iter().enumerate() {
json = Some(serde_json::json!({
"ips": [instance.ip[i].to_string()],
"urls": {
instance.names[i].to_string(): url.to_string()
},
}));
}
let config: serde_json::Value;
if let Some(json) = json {
let _serde_json = serde_json::from_value(json);
let serde_json_result = match _serde_json {
Ok(serde_json) => serde_json,
Err(err) => {
error!("Error configuring JSON config file: {}", err);
return Err("Error configuring JSON config file".into());
}
};
config = serde_json_result;
} else {
config = serde_json::json!({});
}
info!("{:?}", config);
// write the json object to a file
let to_string_json = serde_json::to_string_pretty(&config)?;
// return the json object as a string
Ok(to_string_json)
}
19 changes: 11 additions & 8 deletions GUI/ETVR/src/app.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { onMount, Suspense, lazy } from 'solid-js'
import { MdnsProvider } from '@utils/context/mdns'
import { handleTitlebar, handleAppBoot } from '@utils/hooks/app'

const AppRoutes = lazy(() => import('@routes/Routes'))
Expand All @@ -17,14 +18,16 @@ const App = () => {
return (
<div class="App overflow-y-auto items-center">
<Suspense>
<AppRoutes />
<NewWindow ref={ref} name="test">
<ExampleMenu />
</NewWindow>
<ModalMenu>
<CameraSettingsModal />
</ModalMenu>
<ToastNotificationWindow />
<MdnsProvider>
<AppRoutes />
<NewWindow ref={ref} name="test">
<ExampleMenu />
</NewWindow>
<ModalMenu>
<CameraSettingsModal />
</ModalMenu>
<ToastNotificationWindow />
</MdnsProvider>
</Suspense>
</div>
)
Expand Down
6 changes: 3 additions & 3 deletions GUI/ETVR/src/components/Loader/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ const Loader = (props: LoaderProps) => {
)
}

export const OrangeLoader = () => {
export const OrangeLoader = (width: number, height: number) => {
return (
<div class="flex justify-center items-center">
<Loader
gradient="orange"
gradientMid="rgba(255, 153, 0, 0.594)"
gradientBot="rgba(255, 153, 0, 0.144)"
width="100px"
height="100px"
width={`${width}px`}
height={`${height}px`}
/>
</div>
)
Expand Down
4 changes: 2 additions & 2 deletions GUI/ETVR/src/components/RangeInput/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { RANGE_INPUT_FORMAT } from '@src/static/types/enums'
import { BULLET_POSITION_ADJUSTMENT, getBulletPosition } from '@src/utils/utils'
import { createEffect, createSignal } from 'solid-js'
import { RANGE_INPUT_FORMAT } from '@static/types/enums'
import { BULLET_POSITION_ADJUSTMENT, getBulletPosition } from '@utils/utils'
import './styles.css'

export interface IProps {
Expand Down
1 change: 0 additions & 1 deletion GUI/ETVR/src/components/RangeInput/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ body {
height: 100vh;
background-color: #000;
font-family: 'Roboto', sans-serif;
background: linear-gradient(180deg, #db302a 0%, #62186b 100%) no-repeat;
}

.box-minmax {
Expand Down
2 changes: 1 addition & 1 deletion GUI/ETVR/src/components/Settings/CameraSettings/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { For } from 'solid-js'
import RangeInput from '@components/RangeInput'
import { RANGE_INPUT_FORMAT } from '@src/static/types/enums'
import { For } from 'solid-js'

export interface IProps {
header: string
Expand Down
6 changes: 3 additions & 3 deletions GUI/ETVR/src/components/Settings/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { RANGE_INPUT_FORMAT } from '@src/static/types/enums'
import { CameraStatus, CameraType } from '@store/camera/camera'
import CameraAddress from './CameraAddress/CameraAddress'
import CameraConfigOptions from './CameraConfigOptions'
import CameraInfo from './CameraInfo/CameraInfo'
import CameraSettings from './CameraSettings'
import CamerasModal from './CamerasModal/index'
import CamerasModal from './CamerasModal'
import { RANGE_INPUT_FORMAT } from '@src/static/types/enums'
import { CameraStatus, CameraType } from '@store/camera/camera'

// TODO: stuff todo requested by lorow
// honestly it looks good, I like that preview window. The camera ID I'd rename to camera IP though I'm not really sure if that's gonna be necessary,
Expand Down
23 changes: 23 additions & 0 deletions GUI/ETVR/src/utils/context/mdns/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { createContext, JSX } from 'solid-js'
import { useMDNSScanner } from '@utils/hooks/api/useMDNSScanner'

export const MdnsContext = createContext()

export const MdnsProvider = (props: {
children:
| number
| boolean
| Node
| JSX.ArrayElement
| JSX.FunctionElement
| (string & object)
| null
| undefined
}) => {
const { data, mutate, refetch, resData, setResData } = useMDNSScanner('openiristracker', 30)
return (
<MdnsContext.Provider value={{ data, mutate, refetch, resData, setResData }}>
{props.children}
</MdnsContext.Provider>
)
}
Empty file.
Loading

0 comments on commit d6bd6a7

Please sign in to comment.