1#![allow(missing_docs)]
5
6use std::borrow::Cow;
7use std::io::{Cursor, Write};
8use std::mem;
9use std::ops::{AddAssign, Deref};
10use std::path::{Path, PathBuf};
11use std::str::from_utf8;
12use std::time::Duration;
20pub use std::time::SystemTime as Time;
21#[cfg(not(test))]
22pub use std::time::SystemTime;
23
24use anyhow::{Context as _, Result, bail, ensure};
25use base64::Engine as _;
26use chrono::{Local, NaiveDateTime, NaiveTime, TimeZone};
27use deltachat_contact_tools::EmailAddress;
28#[cfg(test)]
29pub use deltachat_time::SystemTimeTools as SystemTime;
30use futures::TryStreamExt;
31use mailparse::MailHeaderMap;
32use mailparse::dateparse;
33use mailparse::headers::Headers;
34use num_traits::PrimInt;
35use tokio::{fs, io};
36use url::Url;
37use uuid::Uuid;
38
39use crate::chat::{add_device_msg, add_device_msg_with_importance};
40use crate::config::Config;
41use crate::constants::{self, DC_ELLIPSIS, DC_OUTDATED_WARNING_DAYS};
42use crate::context::Context;
43use crate::events::EventType;
44use crate::log::warn;
45use crate::message::{Message, Viewtype};
46use crate::stock_str;
47
48#[expect(clippy::arithmetic_side_effects)]
51pub(crate) fn truncate(buf: &str, approx_chars: usize) -> Cow<'_, str> {
52 let count = buf.chars().count();
53 if count <= approx_chars + DC_ELLIPSIS.len() {
54 return Cow::Borrowed(buf);
55 }
56 let end_pos = buf
57 .char_indices()
58 .nth(approx_chars)
59 .map(|(n, _)| n)
60 .unwrap_or_default();
61
62 if let Some(index) = buf.get(..end_pos).and_then(|s| s.rfind([' ', '\n'])) {
63 Cow::Owned(format!(
64 "{}{}",
65 &buf.get(..=index).unwrap_or_default(),
66 DC_ELLIPSIS
67 ))
68 } else {
69 Cow::Owned(format!(
70 "{}{}",
71 &buf.get(..end_pos).unwrap_or_default(),
72 DC_ELLIPSIS
73 ))
74 }
75}
76
77#[expect(clippy::arithmetic_side_effects)]
82pub(crate) fn truncate_by_lines(
83 buf: String,
84 max_lines: usize,
85 max_line_len: usize,
86) -> (String, bool) {
87 let mut lines = 0;
88 let mut line_chars = 0;
89 let mut break_point: Option<usize> = None;
90
91 for (index, char) in buf.char_indices() {
92 if char == '\n' {
93 line_chars = 0;
94 lines += 1;
95 } else {
96 line_chars += 1;
97 if line_chars > max_line_len {
98 line_chars = 1;
99 lines += 1;
100 }
101 }
102 if lines == max_lines {
103 break_point = Some(index);
104 break;
105 }
106 }
107
108 if let Some(end_pos) = break_point {
109 let text = {
111 if let Some(buffer) = buf.get(..end_pos) {
112 if let Some(index) = buffer.rfind([' ', '\n']) {
113 buf.get(..=index)
114 } else {
115 buf.get(..end_pos)
116 }
117 } else {
118 None
119 }
120 };
121
122 if let Some(truncated_text) = text {
123 (format!("{truncated_text}{DC_ELLIPSIS}"), true)
124 } else {
125 let error_text = "[Truncation of the message failed, this is a bug in the Delta Chat core. Please report it.\nYou can still open the full text to view the original message.]";
129 (error_text.to_string(), true)
130 }
131 } else {
132 (buf, false)
134 }
135}
136
137pub(crate) async fn truncate_msg_text(context: &Context, text: String) -> Result<(String, bool)> {
142 if context.get_config_bool(Config::Bot).await? {
143 return Ok((text, false));
144 }
145 Ok(truncate_by_lines(
147 text,
148 constants::DC_DESIRED_TEXT_LINES,
149 constants::DC_DESIRED_TEXT_LINE_LEN,
150 ))
151}
152
153pub fn timestamp_to_str(wanted: i64) -> String {
159 if let Some(ts) = Local.timestamp_opt(wanted, 0).single() {
160 ts.format("%Y.%m.%d %H:%M:%S").to_string()
161 } else {
162 "??.??.?? ??:??:??".to_string()
164 }
165}
166
167pub fn duration_to_str(duration: Duration) -> String {
169 let secs = duration.as_secs();
170 let h = secs / 3600;
171 let m = (secs % 3600) / 60;
172 let s = (secs % 3600) % 60;
173 format!("{h}h {m}m {s}s")
174}
175
176pub(crate) fn gm2local_offset() -> i64 {
177 let lt = Local::now();
180 i64::from(lt.offset().local_minus_utc())
181}
182
183pub(crate) fn smeared_time(context: &Context) -> i64 {
187 let now = time();
188 let ts = context.smeared_timestamp.current();
189 std::cmp::max(ts, now)
190}
191
192pub(crate) fn create_smeared_timestamp(context: &Context) -> i64 {
194 let now = time();
195 context.smeared_timestamp.create(now)
196}
197
198pub(crate) fn create_smeared_timestamps(context: &Context, count: usize) -> i64 {
202 let now = time();
203 context.smeared_timestamp.create_n(now, count as i64)
204}
205
206pub fn get_release_timestamp() -> i64 {
209 NaiveDateTime::new(
210 *crate::release::DATE,
211 NaiveTime::from_hms_opt(0, 0, 0).unwrap(),
212 )
213 .and_utc()
214 .timestamp_millis()
215 / 1_000
216}
217
218pub(crate) async fn maybe_add_time_based_warnings(context: &Context) {
222 if !maybe_warn_on_bad_time(context, time(), get_release_timestamp()).await {
223 maybe_warn_on_outdated(context, time(), get_release_timestamp()).await;
224 }
225}
226
227async fn maybe_warn_on_bad_time(context: &Context, now: i64, known_past_timestamp: i64) -> bool {
228 if now < known_past_timestamp {
229 let mut msg = Message::new(Viewtype::Text);
230 msg.text = stock_str::bad_time_msg_body(
231 context,
232 &Local.timestamp_opt(now, 0).single().map_or_else(
233 || "YY-MM-DD hh:mm:ss".to_string(),
234 |ts| ts.format("%Y-%m-%d %H:%M:%S").to_string(),
235 ),
236 );
237 if let Some(timestamp) = chrono::DateTime::<chrono::Utc>::from_timestamp(now, 0) {
238 add_device_msg_with_importance(
239 context,
240 Some(
241 format!(
242 "bad-time-warning-{}",
243 timestamp.format("%Y-%m-%d") )
245 .as_str(),
246 ),
247 Some(&mut msg),
248 true,
249 )
250 .await
251 .ok();
252 } else {
253 warn!(context, "Can't convert current timestamp");
254 }
255 return true;
256 }
257 false
258}
259
260#[expect(clippy::arithmetic_side_effects)]
261async fn maybe_warn_on_outdated(context: &Context, now: i64, approx_compile_time: i64) {
262 if now > approx_compile_time + DC_OUTDATED_WARNING_DAYS * 24 * 60 * 60 {
263 let mut msg = Message::new_text(stock_str::update_reminder_msg_body(context));
264 if let Some(timestamp) = chrono::DateTime::<chrono::Utc>::from_timestamp(now, 0) {
265 add_device_msg(
266 context,
267 Some(
268 format!(
269 "outdated-warning-{}",
270 timestamp.format("%Y-%m") )
272 .as_str(),
273 ),
274 Some(&mut msg),
275 )
276 .await
277 .ok();
278 }
279 }
280}
281
282pub(crate) fn create_id() -> String {
294 let mut arr = [0u8; 18];
296 rand::fill(&mut arr[..]);
297
298 base64::engine::general_purpose::URL_SAFE.encode(arr)
299}
300
301pub(crate) fn create_broadcast_secret() -> String {
308 let mut arr = [0u8; 33];
311 rand::fill(&mut arr[..]);
312
313 let mut res = base64::engine::general_purpose::URL_SAFE.encode(arr);
314 res.truncate(43);
315 res
316}
317
318pub(crate) fn validate_id(s: &str) -> bool {
322 let alphabet = base64::alphabet::URL_SAFE.as_str();
323 s.chars().all(|c| alphabet.contains(c)) && s.len() > 10 && s.len() <= 32
324}
325
326pub(crate) fn validate_broadcast_secret(s: &str) -> bool {
327 let alphabet = base64::alphabet::URL_SAFE.as_str();
328 s.chars().all(|c| alphabet.contains(c)) && s.len() >= 43 && s.len() <= 100
329}
330
331pub(crate) fn create_outgoing_rfc724_mid() -> String {
336 let uuid = Uuid::new_v4();
344 format!("{uuid}@localhost")
345}
346
347pub fn get_filesuffix_lc(path_filename: &str) -> Option<String> {
349 Path::new(path_filename)
350 .extension()
351 .map(|p| p.to_string_lossy().to_lowercase())
352}
353
354pub fn get_filemeta(buf: &[u8]) -> Result<(u32, u32)> {
356 let image = image::ImageReader::new(Cursor::new(buf)).with_guessed_format()?;
357 let dimensions = image.into_dimensions()?;
358 Ok(dimensions)
359}
360
361pub(crate) fn get_abs_path(context: &Context, path: &Path) -> PathBuf {
366 if let Ok(p) = path.strip_prefix("$BLOBDIR") {
367 context.get_blobdir().join(p)
368 } else {
369 path.into()
370 }
371}
372
373pub(crate) async fn get_filebytes(context: &Context, path: &Path) -> Result<u64> {
374 let path_abs = get_abs_path(context, path);
375 let meta = fs::metadata(&path_abs).await?;
376 Ok(meta.len())
377}
378
379pub(crate) async fn delete_file(context: &Context, path: &Path) -> Result<()> {
380 let path_abs = get_abs_path(context, path);
381 if !path_abs.exists() {
382 bail!("path {} does not exist", path_abs.display());
383 }
384 if !path_abs.is_file() {
385 warn!(context, "refusing to delete non-file {}.", path.display());
386 bail!("not a file: \"{}\"", path.display());
387 }
388
389 let dpath = format!("{}", path.to_string_lossy());
390 fs::remove_file(path_abs)
391 .await
392 .with_context(|| format!("cannot delete {dpath:?}"))?;
393 context.emit_event(EventType::DeletedBlobFile(dpath));
394 Ok(())
395}
396
397pub(crate) fn sanitize_filename(mut name: &str) -> String {
405 for part in name.rsplit('/') {
406 if !part.is_empty() {
407 name = part;
408 break;
409 }
410 }
411 for part in name.rsplit('\\') {
412 if !part.is_empty() {
413 name = part;
414 break;
415 }
416 }
417
418 let opts = sanitize_filename::Options {
419 truncate: true,
420 windows: true,
421 replacement: "",
422 };
423 let name = sanitize_filename::sanitize_with_options(name, opts);
424
425 if name.starts_with('.') || name.is_empty() {
426 format!("file{name}")
427 } else {
428 name
429 }
430}
431
432#[derive(Debug)]
436pub(crate) struct TempPathGuard {
437 path: PathBuf,
438}
439
440impl TempPathGuard {
441 pub(crate) fn new(path: PathBuf) -> Self {
442 Self { path }
443 }
444}
445
446impl Drop for TempPathGuard {
447 fn drop(&mut self) {
448 let path = self.path.clone();
449 std::fs::remove_file(path).ok();
450 }
451}
452
453impl Deref for TempPathGuard {
454 type Target = Path;
455
456 fn deref(&self) -> &Self::Target {
457 &self.path
458 }
459}
460
461impl AsRef<Path> for TempPathGuard {
462 fn as_ref(&self) -> &Path {
463 self
464 }
465}
466
467pub(crate) async fn create_folder(context: &Context, path: &Path) -> Result<(), io::Error> {
468 let path_abs = get_abs_path(context, path);
469 if !path_abs.exists() {
470 match fs::create_dir_all(path_abs).await {
471 Ok(_) => Ok(()),
472 Err(err) => {
473 warn!(
474 context,
475 "Cannot create directory \"{}\": {}",
476 path.display(),
477 err
478 );
479 Err(err)
480 }
481 }
482 } else {
483 Ok(())
484 }
485}
486
487pub(crate) async fn write_file(
489 context: &Context,
490 path: &Path,
491 buf: &[u8],
492) -> Result<(), io::Error> {
493 let path_abs = get_abs_path(context, path);
494 fs::write(&path_abs, buf).await.map_err(|err| {
495 warn!(
496 context,
497 "Cannot write {} bytes to \"{}\": {}",
498 buf.len(),
499 path.display(),
500 err
501 );
502 err
503 })
504}
505
506pub async fn read_file(context: &Context, path: &Path) -> Result<Vec<u8>> {
508 let path_abs = get_abs_path(context, path);
509
510 match fs::read(&path_abs).await {
511 Ok(bytes) => Ok(bytes),
512 Err(err) => {
513 warn!(
514 context,
515 "Cannot read \"{}\" or file is empty: {}",
516 path.display(),
517 err
518 );
519 Err(err.into())
520 }
521 }
522}
523
524pub async fn open_file(context: &Context, path: &Path) -> Result<fs::File> {
525 let path_abs = get_abs_path(context, path);
526
527 match fs::File::open(&path_abs).await {
528 Ok(bytes) => Ok(bytes),
529 Err(err) => {
530 warn!(
531 context,
532 "Cannot read \"{}\" or file is empty: {}",
533 path.display(),
534 err
535 );
536 Err(err.into())
537 }
538 }
539}
540
541pub fn open_file_std(context: &Context, path: impl AsRef<Path>) -> Result<std::fs::File> {
542 let path_abs = get_abs_path(context, path.as_ref());
543
544 match std::fs::File::open(path_abs) {
545 Ok(bytes) => Ok(bytes),
546 Err(err) => {
547 warn!(
548 context,
549 "Cannot read \"{}\" or file is empty: {}",
550 path.as_ref().display(),
551 err
552 );
553 Err(err.into())
554 }
555 }
556}
557
558pub async fn read_dir(path: &Path) -> Result<Vec<fs::DirEntry>> {
560 let res = tokio_stream::wrappers::ReadDirStream::new(fs::read_dir(path).await?)
561 .try_collect()
562 .await?;
563 Ok(res)
564}
565
566pub(crate) fn time() -> i64 {
567 SystemTime::now()
568 .duration_since(SystemTime::UNIX_EPOCH)
569 .unwrap_or_default()
570 .as_secs() as i64
571}
572
573pub(crate) fn time_elapsed(time: &Time) -> Duration {
574 time.elapsed().unwrap_or_default()
575}
576
577#[derive(Debug, Default, Eq, PartialEq)]
579pub struct MailTo {
580 pub to: Vec<EmailAddress>,
581 pub subject: Option<String>,
582 pub body: Option<String>,
583}
584
585pub fn parse_mailto(mailto_url: &str) -> Option<MailTo> {
587 if let Ok(url) = Url::parse(mailto_url) {
588 if url.scheme() == "mailto" {
589 let mut mailto: MailTo = Default::default();
590 url.path().split(',').for_each(|email| {
592 if let Ok(email) = EmailAddress::new(email) {
593 mailto.to.push(email);
594 }
595 });
596
597 for (key, value) in url.query_pairs() {
599 if key == "subject" {
600 mailto.subject = Some(value.to_string());
601 } else if key == "body" {
602 mailto.body = Some(value.to_string());
603 }
604 }
605 Some(mailto)
606 } else {
607 None
608 }
609 } else {
610 None
611 }
612}
613
614pub(crate) trait IsNoneOrEmpty<T> {
615 fn is_none_or_empty(&self) -> bool;
618}
619impl<T> IsNoneOrEmpty<T> for Option<T>
620where
621 T: AsRef<str>,
622{
623 fn is_none_or_empty(&self) -> bool {
624 !matches!(self, Some(s) if !s.as_ref().is_empty())
625 }
626}
627
628pub(crate) trait ToOption<T> {
629 fn to_option(self) -> Option<T>;
630}
631impl<'a> ToOption<&'a str> for &'a String {
632 fn to_option(self) -> Option<&'a str> {
633 if self.is_empty() { None } else { Some(self) }
634 }
635}
636impl ToOption<String> for u16 {
637 fn to_option(self) -> Option<String> {
638 if self == 0 {
639 None
640 } else {
641 Some(self.to_string())
642 }
643 }
644}
645impl ToOption<String> for Option<i32> {
646 fn to_option(self) -> Option<String> {
647 match self {
648 None | Some(0) => None,
649 Some(v) => Some(v.to_string()),
650 }
651 }
652}
653
654#[expect(clippy::arithmetic_side_effects)]
655pub fn remove_subject_prefix(last_subject: &str) -> String {
656 let subject_start = if last_subject.starts_with("Chat:") {
657 0
658 } else {
659 match last_subject.chars().take(5).position(|c| c == ':') {
663 Some(prefix_end) => prefix_end + 1,
664 None => 0,
665 }
666 };
667 last_subject
668 .chars()
669 .skip(subject_start)
670 .collect::<String>()
671 .trim()
672 .to_string()
673}
674
675#[expect(clippy::arithmetic_side_effects)]
678fn extract_address_from_receive_header<'a>(header: &'a str, start: &str) -> Option<&'a str> {
679 let header_len = header.len();
680 header.find(start).and_then(|mut begin| {
681 begin += start.len();
682 let end = header
683 .get(begin..)?
684 .find(|c: char| c.is_whitespace())
685 .unwrap_or(header_len);
686 header.get(begin..begin + end)
687 })
688}
689
690#[expect(clippy::arithmetic_side_effects)]
691pub(crate) fn parse_receive_header(header: &str) -> String {
692 let header = header.replace(&['\r', '\n'][..], "");
693 let mut hop_info = String::from("Hop: ");
694
695 if let Some(from) = extract_address_from_receive_header(&header, "from ") {
696 hop_info += &format!("From: {}; ", from.trim());
697 }
698
699 if let Some(by) = extract_address_from_receive_header(&header, "by ") {
700 hop_info += &format!("By: {}; ", by.trim());
701 }
702
703 if let Ok(date) = dateparse(&header) {
704 #[cfg(test)]
706 let date_obj = chrono::Utc.timestamp_opt(date, 0).single();
707 #[cfg(not(test))]
708 let date_obj = Local.timestamp_opt(date, 0).single();
709
710 hop_info += &format!(
711 "Date: {}",
712 date_obj.map_or_else(|| "?".to_string(), |x| x.to_rfc2822())
713 );
714 };
715
716 hop_info
717}
718
719pub(crate) fn parse_receive_headers(headers: &Headers) -> String {
721 headers
722 .get_all_headers("Received")
723 .iter()
724 .rev()
725 .filter_map(|header_map_item| from_utf8(header_map_item.get_value_raw()).ok())
726 .map(parse_receive_header)
727 .collect::<Vec<_>>()
728 .join("\n")
729}
730
731pub(crate) fn single_value<T>(collection: impl IntoIterator<Item = T>) -> Option<T> {
734 let mut iter = collection.into_iter();
735 if let Some(value) = iter.next()
736 && iter.next().is_none()
737 {
738 return Some(value);
739 }
740 None
741}
742
743const BROTLI_BUFSZ: usize = 4096;
745
746pub(crate) fn buf_compress(buf: &[u8]) -> Result<Vec<u8>> {
753 if buf.is_empty() {
754 return Ok(Vec::new());
755 }
756 let q: u32 = if buf.len() > 1_000_000 { 4 } else { 6 };
761 let lgwin: u32 = 22; let mut compressor = brotli::CompressorWriter::new(Vec::new(), BROTLI_BUFSZ, q, lgwin);
763 compressor.write_all(buf)?;
764 Ok(compressor.into_inner())
765}
766
767pub(crate) fn buf_decompress(buf: &[u8]) -> Result<Vec<u8>> {
770 if buf.is_empty() {
771 return Ok(Vec::new());
772 }
773 let mut decompressor = brotli::DecompressorWriter::new(Vec::new(), BROTLI_BUFSZ);
774 decompressor.write_all(buf)?;
775 decompressor.flush()?;
776 Ok(mem::take(decompressor.get_mut()))
777}
778
779pub(crate) fn to_lowercase(s: &str) -> Cow<'_, str> {
781 match s.chars().all(char::is_lowercase) {
782 true => Cow::Borrowed(s),
783 false => Cow::Owned(s.to_lowercase()),
784 }
785}
786
787pub(crate) fn normalize_text(text: &str) -> Option<String> {
790 if text.is_ascii() {
791 return None;
792 };
793 Some(text.to_lowercase()).filter(|t| t != text)
794}
795
796#[expect(clippy::arithmetic_side_effects)]
798pub(crate) fn inc_and_check<T: PrimInt + AddAssign + std::fmt::Debug>(
799 t: &mut T,
800 expected: T,
801) -> Result<()> {
802 *t += T::one();
803 ensure!(*t == expected, "Incremented value != {expected:?}");
804 Ok(())
805}
806
807pub(crate) fn usize_to_u64(v: usize) -> u64 {
824 u64::try_from(v).unwrap_or(u64::MAX)
825}
826
827#[macro_export]
830macro_rules! ensure_and_debug_assert {
831 ($cond:expr, $($arg:tt)*) => {
832 let cond_val = $cond;
833 debug_assert!(cond_val, $($arg)*);
834 anyhow::ensure!(cond_val, $($arg)*);
835 };
836}
837
838#[macro_export]
841macro_rules! ensure_and_debug_assert_eq {
842 ($left:expr, $right:expr, $($arg:tt)*) => {
843 match (&$left, &$right) {
844 (left_val, right_val) => {
845 debug_assert_eq!(left_val, right_val, $($arg)*);
846 anyhow::ensure!(left_val == right_val, $($arg)*);
847 }
848 }
849 };
850}
851
852#[macro_export]
855macro_rules! ensure_and_debug_assert_ne {
856 ($left:expr, $right:expr, $($arg:tt)*) => {
857 match (&$left, &$right) {
858 (left_val, right_val) => {
859 debug_assert_ne!(left_val, right_val, $($arg)*);
860 anyhow::ensure!(left_val != right_val, $($arg)*);
861 }
862 }
863 };
864}
865
866#[macro_export]
869macro_rules! logged_debug_assert {
870 ($ctx:expr, $cond:expr, $($arg:tt)*) => {
871 let cond_val = $cond;
872 if !cond_val {
873 warn!($ctx, $($arg)*);
874 }
875 debug_assert!(cond_val, $($arg)*);
876 };
877}
878
879#[cfg(test)]
880mod tools_tests;