|
| 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 = "https://ipapi.co/json/"; |
| 22 | +const BLOCK_NAME: &str = "external_ip"; |
| 23 | + |
| 24 | +#[derive(ser, des, Default)] |
| 25 | +#[serde(default)] |
| 26 | +struct IPAddressInfo { |
| 27 | + error: bool, |
| 28 | + reason: String, |
| 29 | + ip: String, |
| 30 | + version: String, |
| 31 | + city: String, |
| 32 | + region: String, |
| 33 | + region_code: String, |
| 34 | + country: String, |
| 35 | + country_name: String, |
| 36 | + country_code: String, |
| 37 | + country_code_iso3: String, |
| 38 | + country_capital: String, |
| 39 | + country_tld: String, |
| 40 | + continent_code: String, |
| 41 | + in_eu: bool, |
| 42 | + postal: Option<String>, |
| 43 | + latitude: f64, |
| 44 | + longitude: f64, |
| 45 | + timezone: String, |
| 46 | + utc_offset: String, |
| 47 | + country_calling_code: String, |
| 48 | + currency: String, |
| 49 | + currency_name: String, |
| 50 | + languages: String, |
| 51 | + country_area: f64, |
| 52 | + country_population: f64, |
| 53 | + asn: String, |
| 54 | + org: String, |
| 55 | +} |
| 56 | + |
| 57 | +pub struct ExternalIP { |
| 58 | + id: usize, |
| 59 | + output: TextWidget, |
| 60 | + format: FormatTemplate, |
| 61 | + refresh_interval_success: u64, |
| 62 | + refresh_interval_failure: u64, |
| 63 | +} |
| 64 | + |
| 65 | +#[derive(Deserialize, Debug, Clone)] |
| 66 | +#[serde(deny_unknown_fields, default)] |
| 67 | +pub struct ExternalIPConfig { |
| 68 | + /// External IP formatter. |
| 69 | + pub format: FormatTemplate, |
| 70 | + pub refresh_interval_success: u64, |
| 71 | + pub refresh_interval_failure: u64, |
| 72 | + pub with_network_manager: bool, |
| 73 | +} |
| 74 | + |
| 75 | +impl Default for ExternalIPConfig { |
| 76 | + fn default() -> Self { |
| 77 | + Self { |
| 78 | + format: FormatTemplate::default(), |
| 79 | + refresh_interval_success: 300, |
| 80 | + refresh_interval_failure: 15, |
| 81 | + with_network_manager: true, |
| 82 | + } |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +impl ConfigBlock for ExternalIP { |
| 87 | + type Config = ExternalIPConfig; |
| 88 | + |
| 89 | + fn new( |
| 90 | + id: usize, |
| 91 | + block_config: Self::Config, |
| 92 | + shared_config: SharedConfig, |
| 93 | + send: Sender<Task>, |
| 94 | + ) -> Result<Self> { |
| 95 | + if block_config.with_network_manager { |
| 96 | + thread::Builder::new() |
| 97 | + .name("externalip".into()) |
| 98 | + .spawn(move || { |
| 99 | + let c = Connection::get_private(BusType::System).unwrap(); |
| 100 | + c.add_match( |
| 101 | + "type='signal',\ |
| 102 | + path='/org/freedesktop/NetworkManager',\ |
| 103 | + interface='org.freedesktop.DBus.Properties',\ |
| 104 | + member='PropertiesChanged'", |
| 105 | + ) |
| 106 | + .unwrap(); |
| 107 | + c.add_match( |
| 108 | + "type='signal',\ |
| 109 | + path_namespace='/org/freedesktop/NetworkManager/ActiveConnection',\ |
| 110 | + interface='org.freedesktop.DBus.Properties',\ |
| 111 | + member='PropertiesChanged'", |
| 112 | + ) |
| 113 | + .unwrap(); |
| 114 | + c.add_match( |
| 115 | + "type='signal',\ |
| 116 | + path_namespace='/org/freedesktop/NetworkManager/IP4Config',\ |
| 117 | + interface='org.freedesktop.DBus',\ |
| 118 | + member='PropertiesChanged'", |
| 119 | + ) |
| 120 | + .unwrap(); |
| 121 | + |
| 122 | + loop { |
| 123 | + let timeout = 300_000; |
| 124 | + |
| 125 | + for event in c.iter(timeout) { |
| 126 | + match event { |
| 127 | + ConnectionItem::Nothing => (), |
| 128 | + _ => { |
| 129 | + send.send(Task { |
| 130 | + id, |
| 131 | + update_time: Instant::now(), |
| 132 | + }) |
| 133 | + .unwrap(); |
| 134 | + } |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + }) |
| 139 | + .unwrap(); |
| 140 | + } |
| 141 | + Ok(ExternalIP { |
| 142 | + id, |
| 143 | + output: TextWidget::new(id, 0, shared_config), |
| 144 | + format: block_config.format.with_default("{ip} {country_flag}")?, |
| 145 | + refresh_interval_success: block_config.refresh_interval_success, |
| 146 | + refresh_interval_failure: block_config.refresh_interval_failure, |
| 147 | + }) |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +impl Block for ExternalIP { |
| 152 | + fn id(&self) -> usize { |
| 153 | + self.id |
| 154 | + } |
| 155 | + |
| 156 | + fn update(&mut self) -> Result<Option<Update>> { |
| 157 | + let (external_ip, success) = { |
| 158 | + let ip_info: Result<IPAddressInfo> = |
| 159 | + match http::http_get_json(API_ENDPOINT, Some(Duration::from_secs(3)), vec![]) { |
| 160 | + Ok(ip_info_json) => serde_json::from_value(ip_info_json.content) |
| 161 | + .block_error(BLOCK_NAME, "Failed to decode JSON"), |
| 162 | + _ => Err(BlockError( |
| 163 | + BLOCK_NAME.to_string(), |
| 164 | + "Failed to contact API".to_string(), |
| 165 | + )), |
| 166 | + }; |
| 167 | + match ip_info { |
| 168 | + Ok(ip_info) => match ip_info.error { |
| 169 | + false => { |
| 170 | + self.output.set_state(State::Idle); |
| 171 | + let flag = country_flag_from_iso_code(ip_info.country_code.as_str()); |
| 172 | + let values = map!( |
| 173 | + "ip" => Value::from_string (ip_info.ip), |
| 174 | + "version" => Value::from_string (ip_info.version), |
| 175 | + "city" => Value::from_string (ip_info.city), |
| 176 | + "region" => Value::from_string (ip_info.region), |
| 177 | + "region_code" => Value::from_string (ip_info.region_code), |
| 178 | + "country" => Value::from_string (ip_info.country), |
| 179 | + "country_name" => Value::from_string (ip_info.country_name), |
| 180 | + "country_code" => Value::from_string (ip_info.country_code), |
| 181 | + "country_code_iso3" => Value::from_string (ip_info.country_code_iso3), |
| 182 | + "country_capital" => Value::from_string (ip_info.country_capital), |
| 183 | + "country_tld" => Value::from_string (ip_info.country_tld), |
| 184 | + "continent_code" => Value::from_string (ip_info.continent_code), |
| 185 | + "in_eu" => Value::from_boolean (ip_info.in_eu), |
| 186 | + "postal" => Value::from_string (ip_info.postal.unwrap_or_else(|| "No postal code".to_string())), |
| 187 | + "latitude" => Value::from_float (ip_info.latitude), |
| 188 | + "longitude" => Value::from_float (ip_info.longitude), |
| 189 | + "timezone" => Value::from_string (ip_info.timezone), |
| 190 | + "utc_offset" => Value::from_string (ip_info.utc_offset), |
| 191 | + "country_calling_code" => Value::from_string (ip_info.country_calling_code), |
| 192 | + "currency" => Value::from_string (ip_info.currency), |
| 193 | + "currency_name" => Value::from_string (ip_info.currency_name), |
| 194 | + "languages" => Value::from_string (ip_info.languages), |
| 195 | + "country_area" => Value::from_float (ip_info.country_area), |
| 196 | + "country_population" => Value::from_float (ip_info.country_population), |
| 197 | + "asn" => Value::from_string (ip_info.asn), |
| 198 | + "org" => Value::from_string (ip_info.org), |
| 199 | + "country_flag" => Value::from_string(flag), |
| 200 | + ); |
| 201 | + let s = self.format.render(&values)?; |
| 202 | + (s.0, true) |
| 203 | + } |
| 204 | + true => { |
| 205 | + self.output.set_state(State::Critical); |
| 206 | + (format!("Error: {}", ip_info.reason), false) |
| 207 | + } |
| 208 | + }, |
| 209 | + Err(err) => { |
| 210 | + self.output.set_state(State::Critical); |
| 211 | + (err.to_string(), false) |
| 212 | + } |
| 213 | + } |
| 214 | + }; |
| 215 | + |
| 216 | + self.output.set_text(external_ip); |
| 217 | + match success { |
| 218 | + /* The external IP address can change without triggering a |
| 219 | + * notification (for example a refresh between the router and |
| 220 | + * the ISP) so check from time to time even on success */ |
| 221 | + true => Ok(Some( |
| 222 | + Duration::from_secs(self.refresh_interval_success).into(), |
| 223 | + )), |
| 224 | + false => Ok(Some( |
| 225 | + Duration::from_secs(self.refresh_interval_failure).into(), |
| 226 | + )), |
| 227 | + } |
| 228 | + } |
| 229 | + |
| 230 | + fn view(&self) -> Vec<&dyn I3BarWidget> { |
| 231 | + vec![&self.output] |
| 232 | + } |
| 233 | +} |
0 commit comments