| 1 | use nmrs::{ConnectionError, Device, Network, NetworkManager, WifiSecurity}; |
| 2 | |
| 3 | #[derive()] |
| 4 | pub struct Manager { |
| 5 | pub network_manager: NetworkManager, |
| 6 | pub current_connection: Option<Network>, |
| 7 | pub devices: Vec<Device>, |
| 8 | pub enabled: bool, |
| 9 | } |
| 10 | |
| 11 | impl Manager { |
| 12 | pub async fn new() -> anyhow::Result<Self> { |
| 13 | let network_manager = NetworkManager::new().await?; |
| 14 | let current_connection = network_manager.current_network().await?; |
| 15 | |
| 16 | // Get the device |
| 17 | let devices = network_manager.list_devices().await?; |
| 18 | |
| 19 | let enabled = network_manager.wifi_enabled().await.unwrap_or(false); |
| 20 | |
| 21 | Ok(Self { |
| 22 | network_manager, |
| 23 | current_connection, |
| 24 | devices, |
| 25 | enabled, |
| 26 | }) |
| 27 | } |
| 28 | |
| 29 | pub async fn get_devices(&mut self) -> anyhow::Result<Vec<Device>> { |
| 30 | let devices = self.network_manager.list_devices().await?; |
| 31 | let wireless_devices: Vec<Device> = devices |
| 32 | .into_iter() |
| 33 | .filter(|dev| dev.is_wireless()) |
| 34 | .collect(); |
| 35 | if wireless_devices.is_empty() { |
| 36 | anyhow::bail!("No wireless device found") |
| 37 | } else { |
| 38 | Ok(wireless_devices) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | pub async fn get_wifi_scan(&mut self) -> anyhow::Result<Vec<Network>> { |
| 43 | self.network_manager.scan_networks().await?; |
| 44 | self.current_connection = self.network_manager.current_network().await?; |
| 45 | |
| 46 | let mut networks = self.network_manager.list_networks().await?; |
| 47 | networks.sort_by(|a, b| b.strength.cmp(&a.strength)); |
| 48 | Ok(networks) |
| 49 | } |
| 50 | |
| 51 | pub async fn get_saved_networks(&mut self) -> anyhow::Result<Vec<String>> { |
| 52 | let saved_networks = self.network_manager.list_saved_connections().await?; |
| 53 | Ok(saved_networks) |
| 54 | } |
| 55 | |
| 56 | pub async fn forget(&mut self, ssid: &str) -> anyhow::Result<()> { |
| 57 | self.network_manager.forget(ssid).await?; |
| 58 | Ok(()) |
| 59 | } |
| 60 | |
| 61 | pub async fn connect(&mut self, ssid: &str, password: &str) -> anyhow::Result<()> { |
| 62 | match self |
| 63 | .network_manager |
| 64 | .connect( |
| 65 | ssid, |
| 66 | WifiSecurity::WpaPsk { |
| 67 | psk: password.into(), |
| 68 | }, |
| 69 | ) |
| 70 | .await |
| 71 | { |
| 72 | Ok(_) => info!("Connected successfully"), |
| 73 | Err(ConnectionError::AuthFailed) => { |
| 74 | error!("Wrong password!"); |
| 75 | } |
| 76 | Err(ConnectionError::NotFound) => { |
| 77 | error!("Network not found or out of range"); |
| 78 | } |
| 79 | Err(ConnectionError::Timeout) => { |
| 80 | error!("Connection timed out"); |
| 81 | } |
| 82 | Err(ConnectionError::DhcpFailed) => { |
| 83 | error!("Failed to obtain IP address"); |
| 84 | } |
| 85 | Err(e) => { |
| 86 | error!("Error: {}", e); |
| 87 | } |
| 88 | }; |
| 89 | Ok(()) |
| 90 | } |
| 91 | |
| 92 | pub fn is_connected(&mut self, ssid: &String) -> bool { |
| 93 | self.current_connection.is_some() && self.current_connection.clone().unwrap().ssid == *ssid |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | // use std::collections::HashMap; |
| 98 | // use zbus::{Connection, Proxy}; |
| 99 | // |
| 100 | // #[derive(Clone)] |
| 101 | // pub struct WifiNetwork { |
| 102 | // pub ssid: String, |
| 103 | // pub signal: u8, |
| 104 | // pub security: String, |
| 105 | // pub active: bool, |
| 106 | // } |
| 107 | // |
| 108 | // const NM_DEVICE_TYPE_WIFI: u32 = 2; |
| 109 | // |
| 110 | // pub async fn get_saved_networks() -> zbus::Result<Vec<String>> { |
| 111 | // let connection = Connection::system().await?; |
| 112 | // |
| 113 | // let proxy = Proxy::new( |
| 114 | // &connection, |
| 115 | // "org.freedesktop.NetworkManager", |
| 116 | // "/org/freedesktop/NetworkManager/Settings", |
| 117 | // "org.freedesktop.NetworkManager.Settings", |
| 118 | // ) |
| 119 | // .await?; |
| 120 | // |
| 121 | // let connections_paths: Vec<zbus::zvariant::OwnedObjectPath> = |
| 122 | // proxy.call("ListConnections", &()).await?; |
| 123 | // |
| 124 | // let mut network_names = Vec::new(); |
| 125 | // |
| 126 | // for path in connections_paths { |
| 127 | // let conn_proxy = Proxy::new( |
| 128 | // &connection, |
| 129 | // "org.freedesktop.NetworkManager", |
| 130 | // path, |
| 131 | // "org.freedesktop.NetworkManager.Settings.Connection", |
| 132 | // ) |
| 133 | // .await?; |
| 134 | // |
| 135 | // let settings: HashMap<String, HashMap<String, zbus::zvariant::OwnedValue>> = |
| 136 | // conn_proxy.call("GetSettings", &()).await?; |
| 137 | // |
| 138 | // if let Some(connection_map) = settings.get("connection") |
| 139 | // && let Some(id_value) = connection_map.get("id") |
| 140 | // && let Ok(id_str) = id_value.downcast_ref::<zbus::zvariant::Str>() |
| 141 | // { |
| 142 | // network_names.push(id_str.to_string()); |
| 143 | // } |
| 144 | // } |
| 145 | // |
| 146 | // Ok(network_names) |
| 147 | // } |
| 148 | // |
| 149 | // pub async fn get_devices() -> zbus::Result<Vec<String>> { |
| 150 | // let conn = Connection::system().await?; |
| 151 | // let proxy = Proxy::new( |
| 152 | // &conn, |
| 153 | // "org.freedesktop.NetworkManager", |
| 154 | // "/org/freedesktop/NetworkManager", |
| 155 | // "org.freedesktop.NetworkManager", |
| 156 | // ) |
| 157 | // .await?; |
| 158 | // let device_paths: Vec<zbus::zvariant::OwnedObjectPath> = |
| 159 | // proxy.get_property("AllDevices").await?; |
| 160 | // |
| 161 | // let mut names = Vec::new(); |
| 162 | // for path in device_paths { |
| 163 | // let dev_proxy = Proxy::new( |
| 164 | // &conn, |
| 165 | // "org.freedesktop.NetworkManager", |
| 166 | // path, |
| 167 | // "org.freedesktop.NetworkManager.Device", |
| 168 | // ) |
| 169 | // .await?; |
| 170 | // let interface: String = dev_proxy.get_property("Interface").await?; |
| 171 | // names.push(interface); |
| 172 | // } |
| 173 | // Ok(names) |
| 174 | // } |
| 175 | // |
| 176 | // pub async fn get_wifi_scan(device_interface: &str) -> zbus::Result<Vec<WifiNetwork>> { |
| 177 | // let conn = Connection::system().await?; |
| 178 | // let nm_proxy = Proxy::new( |
| 179 | // &conn, |
| 180 | // "org.freedesktop.NetworkManager", |
| 181 | // "/org/freedesktop/NetworkManager", |
| 182 | // "org.freedesktop.NetworkManager", |
| 183 | // ) |
| 184 | // .await?; |
| 185 | // |
| 186 | // // 1. نجلب مسار الـ Active Connection عشان نعرف وش المشبوك عليه حالياً |
| 187 | // let active_connections: Vec<zbus::zvariant::OwnedObjectPath> = |
| 188 | // nm_proxy.get_property("ActiveConnections").await?; |
| 189 | // let mut active_ssids = Vec::new(); |
| 190 | // |
| 191 | // for a_path in active_connections { |
| 192 | // let a_proxy = Proxy::new( |
| 193 | // &conn, |
| 194 | // "org.freedesktop.NetworkManager", |
| 195 | // a_path, |
| 196 | // "org.freedesktop.NetworkManager.Connection.Active", |
| 197 | // ) |
| 198 | // .await?; |
| 199 | // // نجلب الـ ID (اسم الشبكة المتصل بها) |
| 200 | // let id: String = a_proxy.get_property("Id").await?; |
| 201 | // active_ssids.push(id); |
| 202 | // } |
| 203 | // |
| 204 | // // 2. نبحث عن كرت الواي فاي فقط (نفلتر Loopback و Bluetooth) |
| 205 | // let device_paths: Vec<zbus::zvariant::OwnedObjectPath> = |
| 206 | // nm_proxy.get_property("AllDevices").await?; |
| 207 | // let mut target_device_path = None; |
| 208 | // |
| 209 | // for path in device_paths { |
| 210 | // let dev_proxy = Proxy::new( |
| 211 | // &conn, |
| 212 | // "org.freedesktop.NetworkManager", |
| 213 | // &path, |
| 214 | // "org.freedesktop.NetworkManager.Device", |
| 215 | // ) |
| 216 | // .await?; |
| 217 | // |
| 218 | // let dtype: u32 = dev_proxy.get_property("DeviceType").await?; |
| 219 | // let iface: String = dev_proxy.get_property("Interface").await?; |
| 220 | // |
| 221 | // // شرطين: لازم يكون النوع واي فاي (2) والاسم يطابق wlan0 |
| 222 | // if dtype == NM_DEVICE_TYPE_WIFI && iface == device_interface { |
| 223 | // target_device_path = Some(path); |
| 224 | // break; |
| 225 | // } |
| 226 | // } |
| 227 | // |
| 228 | // let mut networks = Vec::new(); |
| 229 | // if let Some(path) = target_device_path { |
| 230 | // let wifi_proxy = Proxy::new( |
| 231 | // &conn, |
| 232 | // "org.freedesktop.NetworkManager", |
| 233 | // &path, |
| 234 | // "org.freedesktop.NetworkManager.Device.Wireless", |
| 235 | // ) |
| 236 | // .await?; |
| 237 | // let ap_paths: Vec<zbus::zvariant::OwnedObjectPath> = |
| 238 | // wifi_proxy.call("GetAllAccessPoints", &()).await?; |
| 239 | // |
| 240 | // for ap_path in ap_paths { |
| 241 | // let ap_proxy = Proxy::new( |
| 242 | // &conn, |
| 243 | // "org.freedesktop.NetworkManager", |
| 244 | // ap_path, |
| 245 | // "org.freedesktop.NetworkManager.AccessPoint", |
| 246 | // ) |
| 247 | // .await?; |
| 248 | // let ssid_bytes: Vec<u8> = ap_proxy.get_property("Ssid").await?; |
| 249 | // |
| 250 | // if let Ok(ssid_name) = String::from_utf8(ssid_bytes) |
| 251 | // && !ssid_name.is_empty() |
| 252 | // && !networks.iter().any(|n: &WifiNetwork| n.ssid == ssid_name) |
| 253 | // { |
| 254 | // let strength: u8 = ap_proxy.get_property("Strength").await?; |
| 255 | // let rsn_flags: u32 = ap_proxy.get_property("RsnFlags").await?; |
| 256 | // |
| 257 | // // هل هذه الشبكة هي النشطة حالياً؟ |
| 258 | // let is_active = active_ssids.contains(&ssid_name); |
| 259 | // |
| 260 | // networks.push(WifiNetwork { |
| 261 | // ssid: ssid_name, |
| 262 | // signal: strength, |
| 263 | // security: if rsn_flags > 0 { |
| 264 | // "WPA2/3".to_string() |
| 265 | // } else { |
| 266 | // "Open".to_string() |
| 267 | // }, |
| 268 | // active: is_active, |
| 269 | // }); |
| 270 | // } |
| 271 | // } |
| 272 | // } |
| 273 | // |
| 274 | // networks.sort_by(|a, b| b.signal.cmp(&a.signal)); |
| 275 | // Ok(networks) |
| 276 | // } |
| 277 | // |
| 278 | // // pub async fn connect_to_wifi(ssid: &str, password: &str) -> anyhow::Result<()> { |
| 279 | // // let connection = zbus::Connection::system().await?; |
| 280 | // // |
| 281 | // // let status = std::process::Command::new("nmcli") |
| 282 | // // .args(["dev", "wifi", "connect", ssid, "password", password]) |
| 283 | // // .status()?; |
| 284 | // // |
| 285 | // // if status.success() { |
| 286 | // // Ok(()) |
| 287 | // // } else { |
| 288 | // // Err(anyhow::anyhow!("Failed to connect via nmcli")) |
| 289 | // // } |
| 290 | // // } |
| 291 | // |
| 292 | // use zbus::zvariant::{Dict, OwnedObjectPath, OwnedValue, Value}; |
| 293 | // |
| 294 | // pub async fn connect_to_wifi(ssid: &str, password: &str) -> anyhow::Result<()> { |
| 295 | // let connection = zbus::Connection::system().await?; |
| 296 | // |
| 297 | // // نستخدم المسار الرئيسي للمدير |
| 298 | // let proxy = zbus::Proxy::new( |
| 299 | // &connection, |
| 300 | // "org.freedesktop.NetworkManager", |
| 301 | // "/org/freedesktop/NetworkManager", // المسار الرئيسي |
| 302 | // "org.freedesktop.NetworkManager", // الواجهة الرئيسية |
| 303 | // ).await?; |
| 304 | // |
| 305 | // // بناء الإعدادات (نفس كودك السابق) |
| 306 | // let mut conn_dict = HashMap::new(); |
| 307 | // conn_dict.insert("type".to_string(), Value::from("802-11-wireless")); |
| 308 | // conn_dict.insert("id".to_string(), Value::from(ssid)); |
| 309 | // |
| 310 | // let mut wifi_dict = HashMap::new(); |
| 311 | // wifi_dict.insert("ssid".to_string(), Value::from(ssid.as_bytes())); |
| 312 | // |
| 313 | // let mut security_dict = HashMap::new(); |
| 314 | // security_dict.insert("key-mgmt".to_string(), Value::from("wpa-psk")); |
| 315 | // security_dict.insert("psk".to_string(), Value::from(password)); |
| 316 | // |
| 317 | // let mut full_settings = HashMap::new(); |
| 318 | // full_settings.insert("connection".to_string(), conn_dict); |
| 319 | // full_settings.insert("802-11-wireless".to_string(), wifi_dict); |
| 320 | // full_settings.insert("802-11-wireless-security".to_string(), security_dict); |
| 321 | // |
| 322 | // // ملاحظة هامة: "/" في الـ device_path قد لا تعمل في كل الأنظمة |
| 323 | // // NetworkManager يفضل مسار كرت الشبكة الفعلي (مثل /org/freedesktop/NetworkManager/Devices/3) |
| 324 | // let device_path = zbus::zvariant::ObjectPath::from_str_unchecked("/"); |
| 325 | // let specific_object = zbus::zvariant::ObjectPath::from_str_unchecked("/"); |
| 326 | // |
| 327 | // // الترتيب الصحيح للـ Turbofish حسب إصدار zbus 5 |
| 328 | // proxy.call::<&str, _, (OwnedObjectPath, OwnedObjectPath)>( |
| 329 | // "AddAndActivateConnection", |
| 330 | // &(full_settings, &device_path, &specific_object), |
| 331 | // ).await?; |
| 332 | // |
| 333 | // Ok(()) |
| 334 | // } |
| 335 | // |
| 336 | // pub async fn forget_network(ssid: &str) -> anyhow::Result<()> { |
| 337 | // let connection = zbus::Connection::system().await?; |
| 338 | // let proxy = zbus::Proxy::new( |
| 339 | // &connection, |
| 340 | // "org.freedesktop.NetworkManager", |
| 341 | // "/org/freedesktop/NetworkManager/Settings", |
| 342 | // "org.freedesktop.NetworkManager.Settings", |
| 343 | // ).await?; |
| 344 | // |
| 345 | // // جلب كل المسارات للاتصالات المحفوظة |
| 346 | // let connections: Vec<zbus::zvariant::OwnedObjectPath> = proxy.call("ListConnections", &()).await?; |
| 347 | // |
| 348 | // for path in connections { |
| 349 | // let conn_proxy = zbus::Proxy::new( |
| 350 | // &connection, |
| 351 | // "org.freedesktop.NetworkManager", |
| 352 | // &path, |
| 353 | // "org.freedesktop.NetworkManager.Settings.Connection", |
| 354 | // ).await?; |
| 355 | // |
| 356 | // // جلب إعدادات هذا الاتصال |
| 357 | // let settings: std::collections::HashMap<String, std::collections::HashMap<String, zbus::zvariant::OwnedValue>> = |
| 358 | // conn_proxy.call("GetSettings", &()).await?; |
| 359 | // |
| 360 | // // إذا كان الـ SSID يطابق اللي نبي نحذفه |
| 361 | // if let Some(conn_settings) = settings.get("connection") { |
| 362 | // if let Some(id_value) = conn_settings.get("id") { |
| 363 | // // 1. نحاول نفك الـ Value إلى نوع zbus::zvariant::Str |
| 364 | // // 2. نحوله لـ &str العادي حق Rust |
| 365 | // if let Ok(id_str) = id_value.downcast_ref::<zbus::zvariant::Str>() { |
| 366 | // if id_str.as_str() == ssid { |
| 367 | // conn_proxy.call::<&str, (), ()>("Delete", &()).await?; |
| 368 | // return Ok(()); |
| 369 | // } |
| 370 | // } |
| 371 | // } |
| 372 | // } } |
| 373 | // Ok(()) |
| 374 | // } |
