1use core::fmt;
2use std::cmp::min;
3use std::{iter::once, ops::Deref, sync::Arc};
4
5use anyhow::Result;
6use humansize::{BINARY, format_size};
7
8use crate::events::EventType;
9use crate::imap::{FolderMeaning, scan_folders::get_watched_folder_configs};
10use crate::log::info;
11use crate::quota::{QUOTA_ERROR_THRESHOLD_PERCENTAGE, QUOTA_WARN_THRESHOLD_PERCENTAGE};
12use crate::stock_str;
13use crate::{context::Context, log::LogExt};
14
15use super::InnerSchedulerState;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumProperty, PartialOrd, Ord)]
19pub enum Connectivity {
20 NotConnected = 1000,
27
28 Connecting = 2000,
30
31 Working = 3000,
33
34 Connected = 4000,
43}
44
45#[derive(Debug, Default, Clone, PartialEq, Eq, EnumProperty, PartialOrd)]
50enum DetailedConnectivity {
51 Error(String),
52 #[default]
53 Uninitialized,
54
55 Connecting,
58
59 Preparing,
62
63 Working,
66
67 InterruptingIdle,
68
69 Idle,
71
72 NotConfigured,
74}
75
76impl DetailedConnectivity {
77 fn to_basic(&self) -> Option<Connectivity> {
78 match self {
79 DetailedConnectivity::Error(_) => Some(Connectivity::NotConnected),
80 DetailedConnectivity::Uninitialized => Some(Connectivity::NotConnected),
81 DetailedConnectivity::Connecting => Some(Connectivity::Connecting),
82 DetailedConnectivity::Working => Some(Connectivity::Working),
83 DetailedConnectivity::InterruptingIdle => Some(Connectivity::Working),
84
85 DetailedConnectivity::Preparing => Some(Connectivity::Working),
91
92 DetailedConnectivity::NotConfigured => None,
95
96 DetailedConnectivity::Idle => Some(Connectivity::Connected),
97 }
98 }
99
100 fn to_icon(&self) -> String {
101 match self {
102 DetailedConnectivity::Error(_)
103 | DetailedConnectivity::Uninitialized
104 | DetailedConnectivity::NotConfigured => "<span class=\"red dot\"></span>".to_string(),
105 DetailedConnectivity::Connecting => "<span class=\"yellow dot\"></span>".to_string(),
106 DetailedConnectivity::Preparing
107 | DetailedConnectivity::Working
108 | DetailedConnectivity::InterruptingIdle
109 | DetailedConnectivity::Idle => "<span class=\"green dot\"></span>".to_string(),
110 }
111 }
112
113 async fn to_string_imap(&self, context: &Context) -> String {
114 match self {
115 DetailedConnectivity::Error(e) => stock_str::error(context, e).await,
116 DetailedConnectivity::Uninitialized => "Not started".to_string(),
117 DetailedConnectivity::Connecting => stock_str::connecting(context).await,
118 DetailedConnectivity::Preparing | DetailedConnectivity::Working => {
119 stock_str::updating(context).await
120 }
121 DetailedConnectivity::InterruptingIdle | DetailedConnectivity::Idle => {
122 stock_str::connected(context).await
123 }
124 DetailedConnectivity::NotConfigured => "Not configured".to_string(),
125 }
126 }
127
128 async fn to_string_smtp(&self, context: &Context) -> String {
129 match self {
130 DetailedConnectivity::Error(e) => stock_str::error(context, e).await,
131 DetailedConnectivity::Uninitialized => {
132 "You did not try to send a message recently.".to_string()
133 }
134 DetailedConnectivity::Connecting => stock_str::connecting(context).await,
135 DetailedConnectivity::Working => stock_str::sending(context).await,
136
137 DetailedConnectivity::InterruptingIdle
141 | DetailedConnectivity::Preparing
142 | DetailedConnectivity::Idle => stock_str::last_msg_sent_successfully(context).await,
143 DetailedConnectivity::NotConfigured => "Not configured".to_string(),
144 }
145 }
146
147 fn all_work_done(&self) -> bool {
148 match self {
149 DetailedConnectivity::Error(_) => true,
150 DetailedConnectivity::Uninitialized => false,
151 DetailedConnectivity::Connecting => false,
152 DetailedConnectivity::Working => false,
153 DetailedConnectivity::InterruptingIdle => false,
154 DetailedConnectivity::Preparing => false, DetailedConnectivity::NotConfigured => true,
156 DetailedConnectivity::Idle => true,
157 }
158 }
159}
160
161#[derive(Clone, Default)]
162pub(crate) struct ConnectivityStore(Arc<parking_lot::Mutex<DetailedConnectivity>>);
163
164impl ConnectivityStore {
165 fn set(&self, context: &Context, v: DetailedConnectivity) {
166 {
167 *self.0.lock() = v;
168 }
169 context.emit_event(EventType::ConnectivityChanged);
170 }
171
172 pub(crate) fn set_err(&self, context: &Context, e: impl ToString) {
173 self.set(context, DetailedConnectivity::Error(e.to_string()));
174 }
175 pub(crate) fn set_connecting(&self, context: &Context) {
176 self.set(context, DetailedConnectivity::Connecting);
177 }
178 pub(crate) fn set_working(&self, context: &Context) {
179 self.set(context, DetailedConnectivity::Working);
180 }
181 pub(crate) fn set_preparing(&self, context: &Context) {
182 self.set(context, DetailedConnectivity::Preparing);
183 }
184 pub(crate) fn set_not_configured(&self, context: &Context) {
185 self.set(context, DetailedConnectivity::NotConfigured);
186 }
187 pub(crate) fn set_idle(&self, context: &Context) {
188 self.set(context, DetailedConnectivity::Idle);
189 }
190
191 fn get_detailed(&self) -> DetailedConnectivity {
192 self.0.lock().deref().clone()
193 }
194 fn get_basic(&self) -> Option<Connectivity> {
195 self.0.lock().to_basic()
196 }
197 fn get_all_work_done(&self) -> bool {
198 self.0.lock().all_work_done()
199 }
200}
201
202pub(crate) fn idle_interrupted(inbox: ConnectivityStore, oboxes: Vec<ConnectivityStore>) {
206 let mut connectivity_lock = inbox.0.lock();
207 if *connectivity_lock == DetailedConnectivity::Idle
213 || *connectivity_lock == DetailedConnectivity::NotConfigured
214 {
215 *connectivity_lock = DetailedConnectivity::InterruptingIdle;
216 }
217 drop(connectivity_lock);
218
219 for state in oboxes {
220 let mut connectivity_lock = state.0.lock();
221 if *connectivity_lock == DetailedConnectivity::Idle {
222 *connectivity_lock = DetailedConnectivity::InterruptingIdle;
223 }
224 }
225 }
228
229pub(crate) fn maybe_network_lost(context: &Context, stores: Vec<ConnectivityStore>) {
233 for store in &stores {
234 let mut connectivity_lock = store.0.lock();
235 if !matches!(
236 *connectivity_lock,
237 DetailedConnectivity::Uninitialized
238 | DetailedConnectivity::Error(_)
239 | DetailedConnectivity::NotConfigured,
240 ) {
241 *connectivity_lock = DetailedConnectivity::Error("Connection lost".to_string());
242 }
243 }
244 context.emit_event(EventType::ConnectivityChanged);
245}
246
247impl fmt::Debug for ConnectivityStore {
248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249 if let Some(guard) = self.0.try_lock() {
250 write!(f, "ConnectivityStore {:?}", &*guard)
251 } else {
252 write!(f, "ConnectivityStore [LOCKED]")
253 }
254 }
255}
256
257impl Context {
258 pub fn get_connectivity(&self) -> Connectivity {
273 let stores = self.connectivities.lock().clone();
274 let mut connectivities = Vec::new();
275 for s in stores {
276 if let Some(connectivity) = s.get_basic() {
277 connectivities.push(connectivity);
278 }
279 }
280 connectivities
281 .into_iter()
282 .min()
283 .unwrap_or(Connectivity::NotConnected)
284 }
285
286 pub(crate) fn update_connectivities(&self, sched: &InnerSchedulerState) {
287 let stores: Vec<_> = match sched {
288 InnerSchedulerState::Started(sched) => sched
289 .boxes()
290 .map(|b| b.conn_state.state.connectivity.clone())
291 .collect(),
292 _ => Vec::new(),
293 };
294 *self.connectivities.lock() = stores;
295 }
296
297 pub async fn get_connectivity_html(&self) -> Result<String> {
307 let mut ret = r#"<!DOCTYPE html>
308 <html>
309 <head>
310 <meta charset="UTF-8" />
311 <meta name="viewport" content="initial-scale=1.0; user-scalable=no" />
312 <style>
313 ul {
314 list-style-type: none;
315 padding-left: 1em;
316 }
317 .dot {
318 height: 0.9em; width: 0.9em;
319 border: 1px solid #888;
320 border-radius: 50%;
321 display: inline-block;
322 position: relative; left: -0.1em; top: 0.1em;
323 }
324 .bar {
325 width: 90%;
326 border: 1px solid #888;
327 border-radius: .5em;
328 margin-top: .2em;
329 margin-bottom: 1em;
330 position: relative; left: -0.2em;
331 }
332 .progress {
333 min-width:1.8em;
334 height: 1em;
335 border-radius: .45em;
336 color: white;
337 text-align: center;
338 padding-bottom: 2px;
339 }
340 .red {
341 background-color: #f33b2d;
342 }
343 .green {
344 background-color: #34c759;
345 }
346 .yellow {
347 background-color: #fdc625;
348 }
349 </style>
350 </head>
351 <body>"#
352 .to_string();
353
354 if self
359 .get_config_bool(crate::config::Config::ProxyEnabled)
360 .await?
361 {
362 let proxy_enabled = stock_str::proxy_enabled(self).await;
363 let proxy_description = stock_str::proxy_description(self).await;
364 ret += &format!("<h3>{proxy_enabled}</h3><ul><li>{proxy_description}</li></ul>");
365 }
366
367 let lock = self.scheduler.inner.read().await;
372 let (folders_states, smtp) = match *lock {
373 InnerSchedulerState::Started(ref sched) => (
374 sched
375 .boxes()
376 .map(|b| (b.meaning, b.conn_state.state.connectivity.clone()))
377 .collect::<Vec<_>>(),
378 sched.smtp.state.connectivity.clone(),
379 ),
380 _ => {
381 ret += &format!(
382 "<h3>{}</h3>\n</body></html>\n",
383 stock_str::not_connected(self).await
384 );
385 return Ok(ret);
386 }
387 };
388 drop(lock);
389
390 let watched_folders = get_watched_folder_configs(self).await?;
397 let incoming_messages = stock_str::incoming_messages(self).await;
398 ret += &format!("<h3>{incoming_messages}</h3><ul>");
399 for (folder, state) in &folders_states {
400 let mut folder_added = false;
401
402 if let Some(config) = folder.to_config().filter(|c| watched_folders.contains(c)) {
403 let f = self.get_config(config).await.log_err(self).ok().flatten();
404
405 if let Some(foldername) = f {
406 let detailed = &state.get_detailed();
407 ret += "<li>";
408 ret += &*detailed.to_icon();
409 ret += " <b>";
410 ret += &*escaper::encode_minimal(&foldername);
411 ret += ":</b> ";
412 ret += &*escaper::encode_minimal(&detailed.to_string_imap(self).await);
413 ret += "</li>";
414
415 folder_added = true;
416 }
417 }
418
419 if !folder_added && folder == &FolderMeaning::Inbox {
420 let detailed = &state.get_detailed();
421 if let DetailedConnectivity::Error(_) = detailed {
422 ret += "<li>";
425 ret += &*detailed.to_icon();
426 ret += " ";
427 ret += &*escaper::encode_minimal(&detailed.to_string_imap(self).await);
428 ret += "</li>";
429 }
430 }
431 }
432 ret += "</ul>";
433
434 let outgoing_messages = stock_str::outgoing_messages(self).await;
441 ret += &format!("<h3>{outgoing_messages}</h3><ul><li>");
442 let detailed = smtp.get_detailed();
443 ret += &*detailed.to_icon();
444 ret += " ";
445 ret += &*escaper::encode_minimal(&detailed.to_string_smtp(self).await);
446 ret += "</li></ul>";
447
448 let domain =
456 &deltachat_contact_tools::EmailAddress::new(&self.get_primary_self_addr().await?)?
457 .domain;
458 let storage_on_domain = stock_str::storage_on_domain(self, domain).await;
459 ret += &format!("<h3>{storage_on_domain}</h3><ul>");
460 let quota = self.quota.read().await;
461 if let Some(quota) = &*quota {
462 match "a.recent {
463 Ok(quota) => {
464 if !quota.is_empty() {
465 for (root_name, resources) in quota {
466 use async_imap::types::QuotaResourceName::*;
467 for resource in resources {
468 ret += "<li>";
469
470 if quota.len() > 1 && !root_name.is_empty() {
473 ret += &format!(
474 "<b>{}:</b> ",
475 &*escaper::encode_minimal(root_name)
476 );
477 } else {
478 info!(
479 self,
480 "connectivity: root name hidden: \"{}\"", root_name
481 );
482 }
483
484 let messages = stock_str::messages(self).await;
485 let part_of_total_used = stock_str::part_of_total_used(
486 self,
487 &resource.usage.to_string(),
488 &resource.limit.to_string(),
489 )
490 .await;
491 ret += &match &resource.name {
492 Atom(resource_name) => {
493 format!(
494 "<b>{}:</b> {}",
495 &*escaper::encode_minimal(resource_name),
496 part_of_total_used
497 )
498 }
499 Message => {
500 format!("<b>{part_of_total_used}:</b> {messages}")
501 }
502 Storage => {
503 let usage = &format_size(resource.usage * 1024, BINARY);
510 let limit = &format_size(resource.limit * 1024, BINARY);
511 stock_str::part_of_total_used(self, usage, limit).await
512 }
513 };
514
515 let percent = resource.get_usage_percentage();
516 let color = if percent >= QUOTA_ERROR_THRESHOLD_PERCENTAGE {
517 "red"
518 } else if percent >= QUOTA_WARN_THRESHOLD_PERCENTAGE {
519 "yellow"
520 } else {
521 "green"
522 };
523 let div_width_percent = min(100, percent);
524 ret += &format!(
525 "<div class=\"bar\"><div class=\"progress {color}\" style=\"width: {div_width_percent}%\">{percent}%</div></div>"
526 );
527
528 ret += "</li>";
529 }
530 }
531 } else {
532 ret += format!("<li>Warning: {domain} claims to support quota but gives no information</li>").as_str();
533 }
534 }
535 Err(e) => {
536 ret += format!("<li>{e}</li>").as_str();
537 }
538 }
539 } else {
540 let not_connected = stock_str::not_connected(self).await;
541 ret += &format!("<li>{not_connected}</li>");
542 }
543 ret += "</ul>";
544
545 ret += "</body></html>\n";
548 Ok(ret)
549 }
550
551 async fn all_work_done(&self) -> bool {
553 let lock = self.scheduler.inner.read().await;
554 let stores: Vec<_> = match *lock {
555 InnerSchedulerState::Started(ref sched) => sched
556 .boxes()
557 .map(|b| &b.conn_state.state)
558 .chain(once(&sched.smtp.state))
559 .map(|state| state.connectivity.clone())
560 .collect(),
561 _ => return false,
562 };
563 drop(lock);
564
565 for s in &stores {
566 if !s.get_all_work_done() {
567 return false;
568 }
569 }
570 true
571 }
572
573 pub async fn wait_for_all_work_done(&self) {
575 for _ in 0..10 {
580 if self.all_work_done().await {
581 break;
582 }
583 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
584 }
585
586 while !self.all_work_done().await {
588 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
589 }
590 }
591}