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::quota::{QUOTA_ERROR_THRESHOLD_PERCENTAGE, QUOTA_WARN_THRESHOLD_PERCENTAGE};
11use crate::stock_str;
12use crate::{context::Context, log::LogExt};
13
14use super::InnerSchedulerState;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumProperty, PartialOrd, Ord)]
18pub enum Connectivity {
19 NotConnected = 1000,
26
27 Connecting = 2000,
29
30 Working = 3000,
32
33 Connected = 4000,
42}
43
44#[derive(Debug, Default, Clone, PartialEq, Eq, EnumProperty, PartialOrd)]
49enum DetailedConnectivity {
50 Error(String),
51 #[default]
52 Uninitialized,
53
54 Connecting,
57
58 Preparing,
61
62 Working,
65
66 InterruptingIdle,
67
68 Idle,
70
71 NotConfigured,
73}
74
75impl DetailedConnectivity {
76 fn to_basic(&self) -> Option<Connectivity> {
77 match self {
78 DetailedConnectivity::Error(_) => Some(Connectivity::NotConnected),
79 DetailedConnectivity::Uninitialized => Some(Connectivity::NotConnected),
80 DetailedConnectivity::Connecting => Some(Connectivity::Connecting),
81 DetailedConnectivity::Working => Some(Connectivity::Working),
82 DetailedConnectivity::InterruptingIdle => Some(Connectivity::Working),
83
84 DetailedConnectivity::Preparing => Some(Connectivity::Working),
90
91 DetailedConnectivity::NotConfigured => None,
94
95 DetailedConnectivity::Idle => Some(Connectivity::Connected),
96 }
97 }
98
99 fn to_icon(&self) -> String {
100 match self {
101 DetailedConnectivity::Error(_)
102 | DetailedConnectivity::Uninitialized
103 | DetailedConnectivity::NotConfigured => "<span class=\"red dot\"></span>".to_string(),
104 DetailedConnectivity::Connecting => "<span class=\"yellow dot\"></span>".to_string(),
105 DetailedConnectivity::Preparing
106 | DetailedConnectivity::Working
107 | DetailedConnectivity::InterruptingIdle
108 | DetailedConnectivity::Idle => "<span class=\"green dot\"></span>".to_string(),
109 }
110 }
111
112 async fn to_string_imap(&self, context: &Context) -> String {
113 match self {
114 DetailedConnectivity::Error(e) => stock_str::error(context, e).await,
115 DetailedConnectivity::Uninitialized => "Not started".to_string(),
116 DetailedConnectivity::Connecting => stock_str::connecting(context).await,
117 DetailedConnectivity::Preparing | DetailedConnectivity::Working => {
118 stock_str::updating(context).await
119 }
120 DetailedConnectivity::InterruptingIdle | DetailedConnectivity::Idle => {
121 stock_str::connected(context).await
122 }
123 DetailedConnectivity::NotConfigured => "Not configured".to_string(),
124 }
125 }
126
127 async fn to_string_smtp(&self, context: &Context) -> String {
128 match self {
129 DetailedConnectivity::Error(e) => stock_str::error(context, e).await,
130 DetailedConnectivity::Uninitialized => {
131 "You did not try to send a message recently.".to_string()
132 }
133 DetailedConnectivity::Connecting => stock_str::connecting(context).await,
134 DetailedConnectivity::Working => stock_str::sending(context).await,
135
136 DetailedConnectivity::InterruptingIdle
140 | DetailedConnectivity::Preparing
141 | DetailedConnectivity::Idle => stock_str::last_msg_sent_successfully(context).await,
142 DetailedConnectivity::NotConfigured => "Not configured".to_string(),
143 }
144 }
145
146 fn all_work_done(&self) -> bool {
147 match self {
148 DetailedConnectivity::Error(_) => true,
149 DetailedConnectivity::Uninitialized => false,
150 DetailedConnectivity::Connecting => false,
151 DetailedConnectivity::Working => false,
152 DetailedConnectivity::InterruptingIdle => false,
153 DetailedConnectivity::Preparing => false, DetailedConnectivity::NotConfigured => true,
155 DetailedConnectivity::Idle => true,
156 }
157 }
158}
159
160#[derive(Clone, Default)]
161pub(crate) struct ConnectivityStore(Arc<parking_lot::Mutex<DetailedConnectivity>>);
162
163impl ConnectivityStore {
164 fn set(&self, context: &Context, v: DetailedConnectivity) {
165 {
166 *self.0.lock() = v;
167 }
168 context.emit_event(EventType::ConnectivityChanged);
169 }
170
171 pub(crate) fn set_err(&self, context: &Context, e: impl ToString) {
172 self.set(context, DetailedConnectivity::Error(e.to_string()));
173 }
174 pub(crate) fn set_connecting(&self, context: &Context) {
175 self.set(context, DetailedConnectivity::Connecting);
176 }
177 pub(crate) fn set_working(&self, context: &Context) {
178 self.set(context, DetailedConnectivity::Working);
179 }
180 pub(crate) fn set_preparing(&self, context: &Context) {
181 self.set(context, DetailedConnectivity::Preparing);
182 }
183 pub(crate) fn set_not_configured(&self, context: &Context) {
184 self.set(context, DetailedConnectivity::NotConfigured);
185 }
186 pub(crate) fn set_idle(&self, context: &Context) {
187 self.set(context, DetailedConnectivity::Idle);
188 }
189
190 fn get_detailed(&self) -> DetailedConnectivity {
191 self.0.lock().deref().clone()
192 }
193 fn get_basic(&self) -> Option<Connectivity> {
194 self.0.lock().to_basic()
195 }
196 fn get_all_work_done(&self) -> bool {
197 self.0.lock().all_work_done()
198 }
199}
200
201pub(crate) fn idle_interrupted(inboxes: Vec<ConnectivityStore>, oboxes: Vec<ConnectivityStore>) {
205 for inbox in inboxes {
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 }
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 =
459 escaper::encode_minimal(&stock_str::storage_on_domain(self, domain).await);
460 ret += &format!("<h3>{storage_on_domain}</h3><ul>");
461 let quota = self.quota.read().await;
462 if let Some(quota) = &*quota {
463 match "a.recent {
464 Ok(quota) => {
465 if !quota.is_empty() {
466 for (root_name, resources) in quota {
467 use async_imap::types::QuotaResourceName::*;
468 for resource in resources {
469 ret += "<li>";
470
471 if quota.len() > 1 && !root_name.is_empty() {
474 ret += &format!(
475 "<b>{}:</b> ",
476 &*escaper::encode_minimal(root_name)
477 );
478 } else {
479 info!(
480 self,
481 "connectivity: root name hidden: \"{}\"", root_name
482 );
483 }
484
485 let messages = stock_str::messages(self).await;
486 let part_of_total_used = stock_str::part_of_total_used(
487 self,
488 &resource.usage.to_string(),
489 &resource.limit.to_string(),
490 )
491 .await;
492 ret += &match &resource.name {
493 Atom(resource_name) => {
494 format!(
495 "<b>{}:</b> {}",
496 &*escaper::encode_minimal(resource_name),
497 part_of_total_used
498 )
499 }
500 Message => {
501 format!("<b>{part_of_total_used}:</b> {messages}")
502 }
503 Storage => {
504 let usage = &format_size(resource.usage * 1024, BINARY);
511 let limit = &format_size(resource.limit * 1024, BINARY);
512 stock_str::part_of_total_used(self, usage, limit).await
513 }
514 };
515
516 let percent = resource.get_usage_percentage();
517 let color = if percent >= QUOTA_ERROR_THRESHOLD_PERCENTAGE {
518 "red"
519 } else if percent >= QUOTA_WARN_THRESHOLD_PERCENTAGE {
520 "yellow"
521 } else {
522 "green"
523 };
524 let div_width_percent = min(100, percent);
525 ret += &format!(
526 "<div class=\"bar\"><div class=\"progress {color}\" style=\"width: {div_width_percent}%\">{percent}%</div></div>"
527 );
528
529 ret += "</li>";
530 }
531 }
532 } else {
533 let domain_escaped = escaper::encode_minimal(domain);
534 ret += &format!(
535 "<li>Warning: {domain_escaped} claims to support quota but gives no information</li>"
536 );
537 }
538 }
539 Err(e) => {
540 let error_escaped = escaper::encode_minimal(&e.to_string());
541 ret += &format!("<li>{error_escaped}</li>");
542 }
543 }
544 } else {
545 let not_connected = stock_str::not_connected(self).await;
546 ret += &format!("<li>{not_connected}</li>");
547 }
548 ret += "</ul>";
549
550 ret += "</body></html>\n";
553 Ok(ret)
554 }
555
556 async fn all_work_done(&self) -> bool {
558 let lock = self.scheduler.inner.read().await;
559 let stores: Vec<_> = match *lock {
560 InnerSchedulerState::Started(ref sched) => sched
561 .boxes()
562 .map(|b| &b.conn_state.state)
563 .chain(once(&sched.smtp.state))
564 .map(|state| state.connectivity.clone())
565 .collect(),
566 _ => return false,
567 };
568 drop(lock);
569
570 for s in &stores {
571 if !s.get_all_work_done() {
572 return false;
573 }
574 }
575 true
576 }
577
578 pub async fn wait_for_all_work_done(&self) {
580 for _ in 0..10 {
585 if self.all_work_done().await {
586 break;
587 }
588 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
589 }
590
591 while !self.all_work_done().await {
593 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
594 }
595 }
596}