use std::fmt;
use futures_util::Stream;
use serde::Deserialize;
use serde_repr::Deserialize_repr;
use zbus::zvariant::{Type, as_value};
use crate::{Error, proxy::Proxy};
#[derive(Deserialize, Type, Debug)]
#[zvariant(signature = "dict")]
pub struct NetworkStatus {
#[serde(with = "as_value")]
available: bool,
#[serde(with = "as_value")]
metered: bool,
#[serde(with = "as_value")]
connectivity: Connectivity,
}
impl NetworkStatus {
pub fn is_available(&self) -> bool {
self.available
}
pub fn is_metered(&self) -> bool {
self.metered
}
pub fn connectivity(&self) -> Connectivity {
self.connectivity
}
}
#[cfg_attr(feature = "glib", derive(glib::Enum))]
#[cfg_attr(feature = "glib", enum_type(name = "AshpdConnectivity"))]
#[derive(Deserialize_repr, PartialEq, Eq, Debug, Clone, Copy, Type)]
#[repr(u32)]
pub enum Connectivity {
Local = 1,
Limited = 2,
CaptivePortal = 3,
FullNetwork = 4,
}
impl fmt::Display for Connectivity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let connectivity = match self {
Self::Local => "local",
Self::Limited => "limited",
Self::CaptivePortal => "captive portal",
Self::FullNetwork => "full network",
};
f.write_str(connectivity)
}
}
#[derive(Debug)]
#[doc(alias = "org.freedesktop.portal.NetworkMonitor")]
pub struct NetworkMonitor(Proxy<'static>);
impl NetworkMonitor {
pub async fn new() -> Result<Self, Error> {
let proxy = Proxy::new_desktop("org.freedesktop.portal.NetworkMonitor").await?;
Ok(Self(proxy))
}
pub async fn with_connection(connection: zbus::Connection) -> Result<Self, Error> {
let proxy =
Proxy::new_desktop_with_connection(connection, "org.freedesktop.portal.NetworkMonitor")
.await?;
Ok(Self(proxy))
}
pub fn version(&self) -> u32 {
self.0.version()
}
#[doc(alias = "CanReach")]
pub async fn can_reach(&self, hostname: &str, port: u32) -> Result<bool, Error> {
self.0
.call_versioned("CanReach", &(hostname, port), 3)
.await
}
#[doc(alias = "GetAvailable")]
#[doc(alias = "get_available")]
pub async fn is_available(&self) -> Result<bool, Error> {
self.0.call_versioned("GetAvailable", &(), 2).await
}
#[doc(alias = "GetConnectivity")]
#[doc(alias = "get_connectivity")]
pub async fn connectivity(&self) -> Result<Connectivity, Error> {
self.0.call_versioned("GetConnectivity", &(), 2).await
}
#[doc(alias = "GetMetered")]
#[doc(alias = "get_metered")]
pub async fn is_metered(&self) -> Result<bool, Error> {
self.0.call_versioned("GetMetered", &(), 2).await
}
#[doc(alias = "GetStatus")]
#[doc(alias = "get_status")]
pub async fn status(&self) -> Result<NetworkStatus, Error> {
self.0.call_versioned("GetStatus", &(), 3).await
}
#[doc(alias = "changed")]
pub async fn receive_changed(&self) -> Result<impl Stream<Item = ()>, Error> {
self.0.signal("changed").await
}
}
impl std::ops::Deref for NetworkMonitor {
type Target = zbus::Proxy<'static>;
fn deref(&self) -> &Self::Target {
&self.0
}
}