Chore(Stage): Some Refactoring

This commit is contained in:
Tochukwu Nkemdilim
2018-07-18 17:23:31 +01:00
parent cb161ba6c2
commit 468368bc30
7 changed files with 60 additions and 166 deletions
+12 -25
View File
@@ -1,32 +1,23 @@
pub mod profile_network;
mod providers;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
mod handlers; mod handlers;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
mod stubs; mod stubs;
mod providers;
use platforms::WifiError;
use std::{fmt, io}; use std::{fmt, io};
pub trait Network: fmt::Debug { pub trait Network: fmt::Debug {
/// Makes an attempt to connect to a selected wireless network with password specified. /// Makes an attempt to connect to a selected wireless network with password specified.
fn connect(&self, password: &str) -> Result<bool, WifiConnectionError>; fn connect(&mut self, ssid: &str, password: &str) -> Result<bool, WifiConnectionError>;
fn disconnect(&self) -> Result<bool, WifiConnectionError>;
fn is_wifi_enabled(&self) -> bool;
fn connnection_up(&self) -> bool;
fn connnection_down(&self) -> bool;
// Hotspot /// Disconnects from a wireless network currently connected to.
// fn create_hotspot(&self, ssid: &str, password: &str) -> Result<bool, WifiHotspotError>; fn disconnect(&self) -> Result<bool, WifiConnectionError>;
} }
// #[derive(Debug)] /// Configuration for a wifi network.
// pub enum NetworkType {
// WEP,
// WPA,
// WPA2,
// }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Config<'a> { pub struct Config<'a> {
pub interface: Option<&'a str>, pub interface: Option<&'a str>,
@@ -35,21 +26,17 @@ pub struct Config<'a> {
#[derive(Debug)] #[derive(Debug)]
pub enum WifiConnectionError { pub enum WifiConnectionError {
SsidNotFound, SsidNotFound,
OsNotSupported,
IpAssignFailed, IpAssignFailed,
AddNetworkProfileFailed, AddNetworkProfileFailed,
IoError(io::Error),
FailedToConnect(String), FailedToConnect(String),
FailedToDisconnect(String), FailedToDisconnect(String),
WiFiInterfaceDisabled, Other { kind: WifiError },
}
pub enum WifiHotspotError {
CreationFailed,
} }
impl From<io::Error> for WifiConnectionError { impl From<io::Error> for WifiConnectionError {
fn from(error: io::Error) -> Self { fn from(error: io::Error) -> Self {
WifiConnectionError::IoError(error) WifiConnectionError::Other {
kind: WifiError::IoError(error),
}
} }
} }
-36
View File
@@ -1,36 +0,0 @@
use connectivity::{providers::Machine, Config, Network, WifiConnectionError};
#[derive(Debug)]
pub struct ProfileNetwork {
handler: Box<Network>,
}
/// Profile Network handler responsible to connect to a wireless network.
impl ProfileNetwork {
pub fn new(name: &str, config: Option<Config>) -> Result<Self, WifiConnectionError> {
if !(cfg!(target_os = "linux") || cfg!(target_os = "windows")) {
return Err(WifiConnectionError::OsNotSupported);
}
let handler = Machine::new(
name,
config.map_or(None, |cfg| cfg.interface.map_or(None, |x| Some(x))),
);
Ok(ProfileNetwork {
handler: Box::new(handler),
})
}
pub fn connect(&self, password: &str) -> Result<bool, WifiConnectionError> {
if !self.handler.is_wifi_enabled() {
return Err(WifiConnectionError::WiFiInterfaceDisabled);
}
self.handler.connect(password)
}
pub fn connection_up(&self) -> bool {
false
}
}
+14 -56
View File
@@ -1,29 +1,15 @@
use connectivity::{Network, WifiConnectionError}; use connectivity::{Network, WifiConnectionError};
use platforms::{Connection, Linux};
use std::process::Command; use std::process::Command;
#[derive(Debug)]
pub struct Linux {
pub name: String,
interface: String,
}
impl Linux {
pub fn new(name: &str, interface: Option<&str>) -> Self {
Linux {
name: name.into(),
interface: interface.unwrap_or("wlan0").into(),
}
}
}
impl Network for Linux { impl Network for Linux {
fn connect(&self, password: &str) -> Result<bool, WifiConnectionError> { fn connect(&mut self, ssid: &str, password: &str) -> Result<bool, WifiConnectionError> {
let output = Command::new("nmcli") let output = Command::new("nmcli")
.args(&[ .args(&[
"d", "d",
"wifi", "wifi",
"connect", "connect",
&self.name, ssid,
"password", "password",
&password, &password,
"ifname", "ifname",
@@ -32,9 +18,18 @@ impl Network for Linux {
.output() .output()
.map_err(|err| WifiConnectionError::FailedToConnect(format!("{}", err)))?; .map_err(|err| WifiConnectionError::FailedToConnect(format!("{}", err)))?;
Ok(String::from_utf8_lossy(&output.stdout) if !String::from_utf8_lossy(&output.stdout)
.as_ref() .as_ref()
.contains("successfully activated")) .contains("successfully activated")
{
return Ok(false);
}
self.connection = Some(Connection {
ssid: String::from(ssid),
});
Ok(true)
} }
fn disconnect(&self) -> Result<bool, WifiConnectionError> { fn disconnect(&self) -> Result<bool, WifiConnectionError> {
@@ -47,41 +42,4 @@ impl Network for Linux {
.as_ref() .as_ref()
.contains("disconnect")) .contains("disconnect"))
} }
fn is_wifi_enabled(&self) -> bool {
let output = Command::new("nmcli").args(&["radio", "wifi"]).output();
if let Err(_) = output {
return false;
}
String::from_utf8_lossy(&output.unwrap().stdout)
.replace(" ", "")
.replace("\n", "")
.contains("enabled")
}
fn connnection_up(&self) -> bool {
let output = Command::new("nmcli")
.args(&["radio", "wifi", "on"])
.output();
if let Err(_) = output {
return false;
}
false
}
fn connnection_down(&self) -> bool {
let output = Command::new("nmcli")
.args(&["radio", "wifi", "off"])
.output();
if let Err(_) = output {
return false;
}
false
}
} }
+3 -9
View File
@@ -1,14 +1,8 @@
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
pub(crate) use self::windows::Windows as Machine;
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
mod linux; mod linux;
#[cfg(target_os = "linux")]
pub(crate) use self::linux::Linux as Machine;
#[cfg(target_os = "osx")] #[cfg(target_os = "osx")]
mod osx; mod osx;
#[cfg(target_os = "osx")]
pub(crate) use self::osx::OSX as Machine; // #[cfg(target_os = "windows")]
mod windows;
+2 -18
View File
@@ -1,15 +1,11 @@
use connectivity::handlers::NetworkXmlProfileHandler; use connectivity::handlers::NetworkXmlProfileHandler;
use connectivity::{Network, WifiConnectionError}; use connectivity::{Network, WifiConnectionError};
use platforms::Windows;
use std::process::Command; use std::process::Command;
#[derive(Debug)]
pub(crate) struct Windows {
name: String,
}
impl Windows { impl Windows {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub fn new(name: &str, interface: Option<&str>) -> Self { pub fn new(name: &str, _interface: Option<&str>) -> Self {
Windows { Windows {
name: String::from(name), name: String::from(name),
} }
@@ -63,16 +59,4 @@ impl Network for Windows {
.as_ref() .as_ref()
.contains("disconnect")) .contains("disconnect"))
} }
fn is_wifi_enabled(&self) -> bool {
unimplemented!()
}
fn connnection_up(&self) -> bool {
unimplemented!()
}
fn connnection_down(&self) -> bool {
unimplemented!()
}
} }
+10 -6
View File
@@ -1,7 +1,11 @@
#![allow(dead_code)] #![allow(dead_code)]
mod connectivity; mod connectivity;
pub use connectivity::{profile_network::ProfileNetwork as WiFi, Config}; mod hotspot;
mod platforms;
pub use connectivity::{Config, *};
pub use hotspot::*;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
@@ -9,12 +13,12 @@ mod tests {
#[test] #[test]
fn connect_to_wifi_failed() { fn connect_to_wifi_failed() {
let config = Some(Config { // let config = Some(Config {
interface: Some("wlo1"), // interface: Some("wlo1"),
}); // });
let wifi = WiFi::new("hello", config).unwrap(); // let wifi = WiFi::new("hello", config).unwrap();
assert_eq!(wifi.connect("password").unwrap(), false); // assert_eq!(wifi.connect("password").unwrap(), false);
} }
} }
+19 -16
View File
@@ -1,24 +1,27 @@
mod connectivity; mod connectivity;
pub use connectivity::{profile_network::ProfileNetwork as WiFi, Config, WifiConnectionError}; mod hotspot;
mod platforms;
pub use connectivity::{Config, WifiConnectionError};
fn main() -> Result<(), WifiConnectionError> { fn main() -> Result<(), WifiConnectionError> {
let config = Some(Config { // let config = Some(Config {
interface: Some("wlo1"), // interface: Some("wlo1"),
}); // });
let wifi = WiFi::new("AndroidAPSD22", config)?; // let wifi = WiFi::new("AndroidAPSD22", config);
match wifi.connect("belm4235") { // match wifi.connect("belm4235") {
Ok(result) => println!( // Ok(result) => println!(
"{}", // "{}",
if result == true { // if result == true {
"Connection Successfull." // "Connection Successfull."
} else { // } else {
"Invalid password." // "Invalid password."
} // }
), // ),
Err(err) => println!("The following error occurred: {:?}", err), // Err(err) => println!("The following error occurred: {:?}", err),
} // }
Ok(()) Ok(())
} }