|
| 1 | +use std::thread; |
| 2 | +use std::time::Instant; |
| 3 | + |
| 4 | +use crossbeam_channel::Sender; |
| 5 | +use dbus::ffidisp::{BusType, Connection, ConnectionItem}; |
| 6 | +use serde::{Deserialize as des, Serialize as ser}; |
| 7 | +use serde_derive::Deserialize; |
| 8 | + |
| 9 | +use crate::blocks::{Block, ConfigBlock, Update}; |
| 10 | +use crate::config::SharedConfig; |
| 11 | +use crate::errors::*; |
| 12 | +use crate::formatting::value::Value; |
| 13 | +use crate::formatting::FormatTemplate; |
| 14 | +use crate::http; |
| 15 | +use crate::scheduler::Task; |
| 16 | +use crate::util::country_flag_from_iso_code; |
| 17 | +use crate::widgets::text::TextWidget; |
| 18 | +use crate::widgets::{I3BarWidget, State}; |
| 19 | +use crate::Duration; |
| 20 | + |
| 21 | +const API_ENDPOINT: &str = "http://ip-api.com/json"; |
| 22 | + |
| 23 | +#[derive(ser, des, Default)] |
| 24 | +struct IPAddressInfo { |
| 25 | + #[serde(rename = "query")] |
| 26 | + address: String, |
| 27 | + status: String, |
| 28 | + country: String, |
| 29 | + #[serde(rename = "countryCode")] |
| 30 | + country_code: String, |
| 31 | + region: String, |
| 32 | + #[serde(rename = "regionName")] |
| 33 | + region_name: String, |
| 34 | + city: String, |
| 35 | + zip: String, |
| 36 | + lat: f64, |
| 37 | + lon: f64, |
| 38 | + timezone: String, |
| 39 | + isp: String, |
| 40 | + org: String, |
| 41 | + #[serde(rename = "as")] |
| 42 | + autonomous_system: String, |
| 43 | +} |
| 44 | + |
| 45 | +pub struct ExternalIP { |
| 46 | + id: usize, |
| 47 | + output: TextWidget, |
| 48 | + format: FormatTemplate, |
| 49 | +} |
| 50 | + |
| 51 | +#[derive(Deserialize, Debug, Clone)] |
| 52 | +#[serde(deny_unknown_fields, default)] |
| 53 | +pub struct ExternalIPConfig { |
| 54 | + /// External IP formatter. |
| 55 | + pub format: FormatTemplate, |
| 56 | +} |
| 57 | + |
| 58 | +impl Default for ExternalIPConfig { |
| 59 | + fn default() -> Self { |
| 60 | + Self { |
| 61 | + format: FormatTemplate::default(), |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +impl ConfigBlock for ExternalIP { |
| 67 | + type Config = ExternalIPConfig; |
| 68 | + |
| 69 | + fn new( |
| 70 | + id: usize, |
| 71 | + block_config: Self::Config, |
| 72 | + shared_config: SharedConfig, |
| 73 | + send: Sender<Task>, |
| 74 | + ) -> Result<Self> { |
| 75 | + thread::Builder::new() |
| 76 | + .name("externalip".into()) |
| 77 | + .spawn(move || { |
| 78 | + let c = Connection::get_private(BusType::System).unwrap(); |
| 79 | + c.add_match( |
| 80 | + "type='signal',\ |
| 81 | + path='/org/freedesktop/NetworkManager',\ |
| 82 | + interface='org.freedesktop.DBus.Properties',\ |
| 83 | + member='PropertiesChanged'", |
| 84 | + ) |
| 85 | + .unwrap(); |
| 86 | + c.add_match( |
| 87 | + "type='signal',\ |
| 88 | + path_namespace='/org/freedesktop/NetworkManager/ActiveConnection',\ |
| 89 | + interface='org.freedesktop.DBus.Properties',\ |
| 90 | + member='PropertiesChanged'", |
| 91 | + ) |
| 92 | + .unwrap(); |
| 93 | + c.add_match( |
| 94 | + "type='signal',\ |
| 95 | + path_namespace='/org/freedesktop/NetworkManager/IP4Config',\ |
| 96 | + interface='org.freedesktop.DBus',\ |
| 97 | + member='PropertiesChanged'", |
| 98 | + ) |
| 99 | + .unwrap(); |
| 100 | + |
| 101 | + loop { |
| 102 | + let timeout = 300_000; |
| 103 | + |
| 104 | + for event in c.iter(timeout) { |
| 105 | + match event { |
| 106 | + ConnectionItem::Nothing => (), |
| 107 | + _ => { |
| 108 | + send.send(Task { |
| 109 | + id, |
| 110 | + update_time: Instant::now(), |
| 111 | + }) |
| 112 | + .unwrap(); |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + }) |
| 118 | + .unwrap(); |
| 119 | + |
| 120 | + Ok(ExternalIP { |
| 121 | + id, |
| 122 | + output: TextWidget::new(id, 0, shared_config), |
| 123 | + format: block_config |
| 124 | + .format |
| 125 | + .with_default("{address} {country_flag}")?, |
| 126 | + }) |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +impl Block for ExternalIP { |
| 131 | + fn id(&self) -> usize { |
| 132 | + self.id |
| 133 | + } |
| 134 | + |
| 135 | + fn update(&mut self) -> Result<Option<Update>> { |
| 136 | + let external_ip = { |
| 137 | + let ip_info = |
| 138 | + match http::http_get_json(API_ENDPOINT, Some(Duration::from_secs(3)), vec![]) { |
| 139 | + Ok(ip_info_json) => serde_json::from_value(ip_info_json.content).unwrap(), |
| 140 | + _ => IPAddressInfo::default(), |
| 141 | + }; |
| 142 | + match ip_info.status.as_ref() { |
| 143 | + "success" => { |
| 144 | + self.output.set_state(State::Idle); |
| 145 | + let flag = country_flag_from_iso_code(ip_info.country_code.as_str()); |
| 146 | + let values = map!( |
| 147 | + "address" => Value::from_string (ip_info.address), |
| 148 | + "country" => Value::from_string (ip_info.country), |
| 149 | + "country_code" => Value::from_string (ip_info.country_code), |
| 150 | + "region" => Value::from_string (ip_info.region), |
| 151 | + "region_name" => Value::from_string (ip_info.region_name), |
| 152 | + "city" => Value::from_string (ip_info.city), |
| 153 | + "zip" => Value::from_string (ip_info.zip), |
| 154 | + "latitude" => Value::from_float (ip_info.lat), |
| 155 | + "longitude" => Value::from_float (ip_info.lon), |
| 156 | + "timezone" => Value::from_string (ip_info.timezone), |
| 157 | + "isp" => Value::from_string (ip_info.isp), |
| 158 | + "org" => Value::from_string (ip_info.org), |
| 159 | + "autonomous_system" => Value::from_string (ip_info.autonomous_system), |
| 160 | + "country_flag" => Value::from_string(flag), |
| 161 | + ); |
| 162 | + let s = self.format.render(&values)?; |
| 163 | + s.0 |
| 164 | + } |
| 165 | + _ => { |
| 166 | + self.output.set_state(State::Critical); |
| 167 | + "Request to IP service failed".to_string() |
| 168 | + } |
| 169 | + } |
| 170 | + }; |
| 171 | + self.output.set_text(external_ip); |
| 172 | + /* The external IP address can change without triggering a |
| 173 | + * notification (for example a refresh between the router and |
| 174 | + * the ISP) so check from time to time */ |
| 175 | + Ok(Some(Duration::from_secs(300).into())) |
| 176 | + } |
| 177 | + |
| 178 | + fn view(&self) -> Vec<&dyn I3BarWidget> { |
| 179 | + vec![&self.output] |
| 180 | + } |
| 181 | +} |
0 commit comments