1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
/*
* meli - email module
*
* Copyright 2017 Manos Pitsidianakis
*
* This file is part of meli.
*
* meli is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* meli is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with meli. If not, see <http://www.gnu.org/licenses/>.
*/
//! Email parsing and composing.
//!
//! # Parsing bytes into an `Envelope`
//!
//! An [`Envelope`] represents the information you can get from an email's
//! headers and body structure. Addresses in `To`, `From` fields etc are parsed
//! into [`Address`] types.
//!
//! ```
//! use melib::{Attachment, Envelope};
//!
//! let raw_mail = r#"From: "some name" <some@example.com>
//! To: "me" <myself@example.com>
//! Cc:
//! Subject: =?utf-8?Q?gratuitously_encoded_subject?=
//! Message-ID: <h2g7f.z0gy2pgaen5m@example.com>
//! MIME-Version: 1.0
//! Content-Type: multipart/mixed; charset="utf-8";
//! boundary="bzz_bzz__bzz__"
//!
//! This is a MIME formatted message with attachments. Use a MIME-compliant client to view it properly.
//! --bzz_bzz__bzz__
//!
//! hello world.
//! --bzz_bzz__bzz__
//! Content-Type: image/gif; name="test_image.gif"; charset="utf-8"
//! Content-Disposition: attachment
//! Content-Transfer-Encoding: base64
//!
//! R0lGODdhKAAXAOfZAAABzAADzQAEzgQFtBEAxAAGxBcAxwALvRcFwAAPwBcLugATuQEUuxoNuxYQ
//! sxwOvAYVvBsStSAVtx8YsRUcuhwhth4iuCQsyDAwuDc1vTc3uDg4uT85rkc9ukJBvENCvURGukdF
//! wUVKt0hLuUxPvVZSvFlYu1hbt2BZuFxdul5joGhqlnNuf3FvlnBvwXJyt3Jxw3N0oXx1gH12gV99
//! z317f3N7spFxwHp5wH99gYB+goF/g25+26tziIOBhWqD3oiBjICAuudkjIN+zHeC2n6Bzc1vh4eF
//! iYaBw8F0kImHi4KFxYyHmIWIvI2Lj4uIvYaJyY+IuJGMi5iJl4qKxZSMmIuLxpONnpGPk42NvI2M
//! 1LKGl46OvZePm5ORlZiQnJqSnpaUmLyJnJuTn5iVmZyUoJGVyZ2VoZSVw5iXoZmWrO18rJiUyp6W
//! opuYnKaVnZ+Xo5yZncaMoaCYpJiaqo+Z2Z2annuf5qGZpa2WoJybpZmayZ2Z0KCZypydrZ6dp6Cd
//! oZ6a0aGay5ucy5+eqKGeouWMgp+b0qKbzKCfqdqPnp2ezaGgqqOgpKafqrScpp+gz6ajqKujr62j
//! qayksKmmq62lsaiosqqorOyWnaqqtKeqzLGptaurta2rr7Kqtq+ssLOrt6+uuLGusuqhfbWtubCv
//! ubKvs7GwurOwtPSazbevu+ali7SxtbiwvOykjLOyvLWytuCmqOankrSzvbazuLmyvrW0vre0uba1
//! wLi1ury0wLm2u721wbe3wbq3vMC2vLi4wr+3w7m5w8C4xLi6yry6vsG5xbu7xcC6zMK6xry8xry+
//! u8O7x729x8C9wb++yMG+wsO+vMK/w8a+y8e/zMnBzcXH18nL2///////////////////////////
//! ////////////////////////////////////////////////////////////////////////////
//! /////////////////////////////////////////////////////ywAAAAAKAAXAAAI/gBP4Cjh
//! IYMLEh0w4EgBgsMLEyFGFBEB5cOFABgzatS4AVssZAOsLOHCxooVMzCyoNmzaBOkJlS0VEDyZMjG
//! mxk3XOMF60CDBgsoPABK9KcDCRImPCiQYAECAgQCRMU4VSrGCjFarBgUSJCgQ10FBTrkNRCfPnz4
//! dA3UNa1btnDZqgU7Ntqzu3ej2X2mFy9eaHuhNRtMGJrhwYYN930G2K7eaNIY34U2mfJkwpgzI9Yr
//! GBqwR2KSvAlMOXHnw5pTNzPdLNoWIWtU9XjGjDEYS8LAlFm1SrVvzIKj5TH0KpORSZOryPgCZgqL
//! Ob+jG0YVRBErUrOiiGJ8KxgtYsh27xWL/tswnTtEbsiRVYdJNMHk4yOGhswGjR88UKjQ9Ey+/8TL
//! XKKGGn7Akph/8XX2WDTTcAYfguVt9hhrEPqmzIOJ3VUheb48WJiHG6amC4i+WVJKKCimqGIoYxyj
//! WWK8kKjaJ9bA18sxvXjYhourmbbMMrjI+OIn1QymDCVXANGFK4S1gQw0PxozzC+33FLLKUJq9gk1
//! gyWDhyNwrMLkYGUEM4wvuLRiCiieXIJJJVlmJskcZ9TZRht1lnFGGmTMkMoonVQSSSOFAGJHHI0w
//! ouiijDaaCCGQRgrpH3q4QYYXWDihxBE+7KCDDjnUIEVAADs=
//! --bzz_bzz__bzz__--"#;
//!
//! let envelope = Envelope::from_bytes(raw_mail.as_bytes(), None).expect("Could not parse mail");
//! assert_eq!(envelope.subject().as_ref(), "gratuitously encoded subject");
//! assert_eq!(
//! envelope.message_id_display().as_ref(),
//! "<h2g7f.z0gy2pgaen5m@example.com>"
//! );
//!
//! let body = envelope.body_bytes(raw_mail.as_bytes());
//! assert_eq!(body.content_type().to_string().as_str(), "multipart/mixed");
//!
//! let body_text = body.text();
//! assert_eq!(body_text.as_str(), "hello world.");
//!
//! let subattachments: Vec<Attachment> = body.attachments();
//! assert_eq!(subattachments.len(), 3);
//! assert_eq!(
//! subattachments[2].content_type().name().unwrap(),
//! "test_image.gif"
//! );
//! ```
pub mod address;
pub mod attachment_types;
pub mod attachments;
pub mod compose;
pub mod headers;
pub mod list_management;
pub mod mailto;
pub mod parser;
pub mod pgp;
use std::{borrow::Cow, ops::Deref};
pub use address::{Address, MessageID, References, StrBuild, StrBuilder};
pub use attachments::{Attachment, AttachmentBuilder};
pub use compose::{attachment_from_file, Draft};
pub use headers::*;
#[cfg(feature = "imap")]
use imap_codec::imap_types::{
core::{AString, Atom, NonEmptyVec},
fetch::{MacroOrMessageDataItemNames, MessageDataItemName, Section},
flag::Flag as ImapCodecFlag,
};
use indexmap::IndexSet;
use smallvec::SmallVec;
use crate::{
error::{Error, Result},
parser::BytesExt,
thread::ThreadNodeHash,
TagHash, UnixTimestamp,
};
#[cfg(feature = "imap")]
// [ref:TODO]: (#222) Make this `const` as soon as it is possible.
pub(crate) fn common_attributes() -> MacroOrMessageDataItemNames<'static> {
MacroOrMessageDataItemNames::MessageDataItemNames(vec![
MessageDataItemName::Uid,
MessageDataItemName::Flags,
MessageDataItemName::Envelope,
MessageDataItemName::BodyExt {
section: Some(Section::HeaderFields(
None,
NonEmptyVec::from(AString::from(Atom::unvalidated("REFERENCES"))),
)),
partial: None,
peek: true,
},
MessageDataItemName::BodyStructure,
])
}
bitflags! {
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct Flag: u8 {
const PASSED = 0b0000_0001;
const REPLIED = 0b0000_0010;
const SEEN = 0b0000_0100;
const TRASHED = 0b0000_1000;
const DRAFT = 0b0001_0000;
const FLAGGED = 0b0010_0000;
}
}
impl PartialEq<&str> for Flag {
fn eq(&self, other: &&str) -> bool {
(other.eq_ignore_ascii_case("passed") && self.contains(Self::PASSED))
|| (other.eq_ignore_ascii_case("replied") && self.contains(Self::REPLIED))
|| (other.eq_ignore_ascii_case("seen") && self.contains(Self::SEEN))
|| (other.eq_ignore_ascii_case("read") && self.contains(Self::SEEN))
|| (other.eq_ignore_ascii_case("junk") && self.contains(Self::TRASHED))
|| (other.eq_ignore_ascii_case("trash") && self.contains(Self::TRASHED))
|| (other.eq_ignore_ascii_case("trashed") && self.contains(Self::TRASHED))
|| (other.eq_ignore_ascii_case("draft") && self.contains(Self::DRAFT))
|| (other.eq_ignore_ascii_case("flagged") && self.contains(Self::FLAGGED))
}
}
macro_rules! flag_impl {
(fn $name:ident, $val:expr) => {
pub const fn $name(&self) -> bool {
self.contains($val)
}
};
}
impl Flag {
flag_impl!(fn is_passed, Self::PASSED);
flag_impl!(fn is_replied, Self::REPLIED);
flag_impl!(fn is_seen, Self::SEEN);
flag_impl!(fn is_trashed, Self::TRASHED);
flag_impl!(fn is_draft, Self::DRAFT);
flag_impl!(fn is_flagged, Self::FLAGGED);
#[cfg(feature = "imap")]
pub(crate) fn derive_imap_codec_flags(&self) -> Vec<ImapCodecFlag> {
let mut flags = Vec::new();
if self.is_passed() {
// This is from http://cr.yp.to/proto/maildir.html and not meaningful in IMAP.
}
if self.is_replied() {
flags.push(ImapCodecFlag::Answered);
}
if self.is_seen() {
flags.push(ImapCodecFlag::Seen);
}
if self.is_trashed() {
flags.push(ImapCodecFlag::Deleted);
}
if self.is_draft() {
flags.push(ImapCodecFlag::Draft);
}
if self.is_flagged() {
flags.push(ImapCodecFlag::Flagged);
}
flags
}
}
///`Mail` holds both the envelope info of an email in its `envelope` field and
/// the raw bytes that describe the email in `bytes`. Its body as an
/// `melib::email::Attachment` can be parsed on demand
/// with the `melib::email::Mail::body` method.
#[derive(Clone, Debug, Default)]
pub struct Mail {
pub envelope: Envelope,
pub bytes: Vec<u8>,
}
impl Deref for Mail {
type Target = Envelope;
fn deref(&self) -> &Envelope {
&self.envelope
}
}
impl Mail {
pub fn new(bytes: Vec<u8>, flags: Option<Flag>) -> Result<Self> {
Ok(Self {
envelope: Envelope::from_bytes(&bytes, flags)?,
bytes,
})
}
pub fn envelope(&self) -> &Envelope {
&self.envelope
}
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
pub fn body(&self) -> Attachment {
self.envelope.body_bytes(&self.bytes)
}
}
crate::declare_u64_hash!(EnvelopeHash);
/// `Envelope` represents all the header and structure data of an email we need
/// to know.
///
/// Attachments (the email's body) is parsed on demand with `body` method.
///
///To access the email attachments, you need to parse them from the raw email
/// bytes into an `Attachment` object.
#[derive(Clone, Deserialize, Serialize)]
pub struct Envelope {
// ----- IMAP4rev1 -----
pub date: String,
pub subject: Option<String>,
pub from: SmallVec<[Address; 1]>,
// pub sender
// pub reply_to
pub to: SmallVec<[Address; 1]>,
pub cc: SmallVec<[Address; 1]>,
pub bcc: Vec<Address>,
pub in_reply_to: Option<MessageID>,
pub message_id: MessageID,
// ----- Other -----
pub hash: EnvelopeHash,
pub timestamp: UnixTimestamp,
pub references: Option<References>,
pub other_headers: HeaderMap,
pub thread: ThreadNodeHash,
pub flags: Flag,
pub has_attachments: bool,
pub tags: IndexSet<TagHash>,
}
impl std::fmt::Debug for Envelope {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("Envelope")
.field("Subject", &self.subject())
.field("Date", &self.date)
.field("From", &self.from)
.field("To", &self.to)
.field("Message-ID", &self.message_id_display())
.field("In-Reply-To", &self.in_reply_to_display())
.field("References", &self.references)
.field("Flags", &self.flags)
.field("Hash", &self.hash)
.finish()
}
}
impl Default for Envelope {
fn default() -> Self {
Self::new(EnvelopeHash::default())
}
}
impl Envelope {
pub fn new(hash: EnvelopeHash) -> Self {
Self {
hash,
date: String::new(),
timestamp: 0,
from: SmallVec::new(),
to: SmallVec::new(),
cc: SmallVec::new(),
bcc: Vec::new(),
subject: None,
message_id: MessageID::default(),
in_reply_to: None,
references: None,
other_headers: Default::default(),
thread: ThreadNodeHash::null(),
has_attachments: false,
flags: Flag::default(),
tags: IndexSet::new(),
}
}
pub fn set_hash(&mut self, new_hash: EnvelopeHash) -> &mut Self {
self.hash = new_hash;
self
}
pub fn from_bytes(bytes: &[u8], flags: Option<Flag>) -> Result<Self> {
let mut e = Self::new(EnvelopeHash::from_bytes(bytes.trim()));
let res = e.populate_headers(bytes).ok();
if res.is_some() {
if let Some(f) = flags {
e.flags = f;
}
return Ok(e);
}
Err(Error::new("Couldn't parse mail."))
}
pub fn hash(&self) -> EnvelopeHash {
self.hash
}
pub fn populate_headers(&mut self, mut bytes: &[u8]) -> Result<()> {
if bytes.starts_with(b"From ") {
/* Attempt to recover if message includes the mbox From label as first line */
if let Some(offset) = bytes.find(b"\n") {
bytes = &bytes[offset + 1..];
}
}
let (headers, body) = match parser::mail(bytes) {
Ok(v) => v,
Err(e) => {
debug!("error in parsing mail\n{:?}\n", e);
let error_msg = String::from("Mail cannot be shown because of errors.");
return Err(Error::new(error_msg));
}
};
for (name, value) in headers {
match name {
HeaderName::TO => {
let parse_result = parser::address::rfc2822address_list(value);
if let Ok((_, value)) = parse_result {
self.set_to(value);
};
}
HeaderName::CC => {
let parse_result = parser::address::rfc2822address_list(value);
if let Ok((_, value)) = parse_result {
self.set_cc(value);
};
}
HeaderName::BCC => {
let parse_result = parser::address::rfc2822address_list(value);
if let Ok((_, value)) = parse_result {
self.set_bcc(value.to_vec());
};
}
HeaderName::FROM => {
let parse_result = parser::address::rfc2822address_list(value);
if let Ok((_, value)) = parse_result {
self.set_from(value);
}
}
HeaderName::SUBJECT => {
let parse_result = parser::encodings::phrase(value.trim(), false);
if let Ok((_, value)) = parse_result {
self.set_subject(value);
};
}
HeaderName::MESSAGE_ID => {
self.set_message_id(value);
}
HeaderName::REFERENCES => {
self.set_references(value);
}
HeaderName::IN_REPLY_TO => {
self.set_in_reply_to(value);
}
HeaderName::DATE => {
let parse_result = parser::encodings::phrase(value, false);
if let Ok((_, value)) = parse_result {
self.set_date(value.as_slice());
} else {
self.set_date(value);
}
}
HeaderName::CONTENT_TYPE => match parser::attachments::content_type(value) {
Ok((_, (ct, cst, ref params)))
if ct.eq_ignore_ascii_case(b"multipart")
&& cst.eq_ignore_ascii_case(b"mixed") =>
{
let mut builder = AttachmentBuilder::default();
builder.set_content_type_from_bytes(value);
let mut boundary = None;
for (n, v) in params {
if n.eq_ignore_ascii_case(b"boundary") {
boundary = Some(v);
break;
}
}
if let Some(boundary) = boundary {
self.has_attachments =
Attachment::check_if_has_attachments_quick(body, boundary);
} else {
debug!(
"{:?} has no boundary field set in multipart/mixed content-type \
field.",
&self
);
}
}
_ => {}
},
_ => {}
}
self.other_headers.insert(
name,
parser::encodings::phrase(value, false)
.map(|(_, value)| {
String::from_utf8(value)
.unwrap_or_else(|err| String::from_utf8_lossy(&err.into_bytes()).into())
})
.unwrap_or_else(|_| String::from_utf8_lossy(value).into()),
);
}
/*
* https://tools.ietf.org/html/rfc5322#section-3.6.4
*
* if self.message_id.is_none() ...
*/
if let Some(x) = self.in_reply_to.clone() {
self.push_references(x);
}
if let Ok(d) = parser::dates::rfc5322_date(self.date.as_bytes()) {
self.set_datetime(d);
}
if self.message_id.raw().is_empty() {
let hash = self.hash;
self.set_message_id(format!("<{:x}>", hash.0).as_bytes());
}
if self.references.is_some() {
if let Some(pos) = self
.references
.as_ref()
.map(|r| &r.refs)
.unwrap()
.iter()
.position(|r| r == &self.message_id)
{
self.references.as_mut().unwrap().refs.remove(pos);
}
}
Ok(())
}
pub fn date(&self) -> UnixTimestamp {
self.timestamp
}
pub fn datetime(&self) -> UnixTimestamp {
self.timestamp
}
pub fn date_as_str(&self) -> &str {
&self.date
}
pub fn from(&self) -> &[Address] {
self.from.as_slice()
}
pub fn field_bcc_to_string(&self) -> String {
if self.bcc.is_empty() {
self.other_headers
.get("Bcc")
.unwrap_or_default()
.to_string()
} else {
self.bcc.iter().fold(String::new(), |mut acc, x| {
if !acc.is_empty() {
acc.push_str(", ");
}
acc.push_str(&x.to_string());
acc
})
}
}
pub fn field_cc_to_string(&self) -> String {
if self.cc.is_empty() {
self.other_headers.get("Cc").unwrap_or_default().to_string()
} else {
self.cc.iter().fold(String::new(), |mut acc, x| {
if !acc.is_empty() {
acc.push_str(", ");
}
acc.push_str(&x.to_string());
acc
})
}
}
pub fn field_from_to_string(&self) -> String {
if self.from.is_empty() {
self.other_headers
.get("From")
.unwrap_or_default()
.to_string()
} else {
self.from.iter().fold(String::new(), |mut acc, x| {
if !acc.is_empty() {
acc.push_str(", ");
}
acc.push_str(&x.to_string());
acc
})
}
}
pub fn to(&self) -> &[Address] {
self.to.as_slice()
}
pub fn cc(&self) -> &[Address] {
self.cc.as_slice()
}
pub fn bcc(&self) -> &[Address] {
self.bcc.as_slice()
}
pub fn field_to_to_string(&self) -> String {
if self.to.is_empty() {
self.other_headers.get("To").unwrap_or_default().to_string()
} else {
self.to
.iter()
.map(|a| format!("{}", a))
.fold(String::new(), |mut acc, x| {
if !acc.is_empty() {
acc.push_str(", ");
}
acc.push_str(&x);
acc
})
}
}
pub fn field_references_to_string(&self) -> String {
let refs = self.references();
if refs.is_empty() {
self.other_headers
.get("References")
.unwrap_or_default()
.to_string()
} else {
refs.iter()
.map(|a| a.to_string())
.fold(String::new(), |mut acc, x| {
if !acc.is_empty() {
acc.push_str(", ");
}
acc.push_str(&x);
acc
})
}
}
pub fn body_bytes(&self, bytes: &[u8]) -> Attachment {
let builder = AttachmentBuilder::new(bytes);
builder.build()
}
pub fn headers<'a>(&self, bytes: &'a [u8]) -> Result<Vec<(HeaderName, &'a str)>> {
let ret = parser::headers::headers(bytes)?.1;
let len = ret.len();
ret.into_iter()
.try_fold(Vec::with_capacity(len), |mut acc, (a, b)| {
Ok({
acc.push((a, std::str::from_utf8(b)?));
acc
})
})
}
pub fn subject(&self) -> Cow<str> {
match self.subject {
Some(ref s) => Cow::from(s),
_ => Cow::from(String::new()),
}
}
pub fn in_reply_to(&self) -> Option<&MessageID> {
self.in_reply_to
.as_ref()
.or_else(|| self.references.as_ref().and_then(|r| r.refs.last()))
}
pub fn in_reply_to_display(&self) -> Option<Cow<str>> {
self.in_reply_to
.as_ref()
.map(|m| String::from_utf8_lossy(m.val()))
}
pub fn in_reply_to_raw(&self) -> Option<Cow<str>> {
self.in_reply_to
.as_ref()
.map(|m| String::from_utf8_lossy(m.raw()))
}
pub fn message_id(&self) -> &MessageID {
&self.message_id
}
pub fn message_id_display(&self) -> Cow<str> {
String::from_utf8_lossy(self.message_id.val())
}
pub fn message_id_raw(&self) -> Cow<str> {
String::from_utf8_lossy(self.message_id.raw())
}
pub fn set_date(&mut self, new_val: &[u8]) -> &mut Self {
let new_val = new_val.trim();
self.date = String::from_utf8_lossy(new_val).into_owned();
self
}
pub fn set_bcc(&mut self, new_val: Vec<Address>) -> &mut Self {
self.bcc = new_val;
self
}
pub fn set_cc(&mut self, new_val: SmallVec<[Address; 1]>) -> &mut Self {
self.cc = new_val;
self
}
pub fn set_from(&mut self, new_val: SmallVec<[Address; 1]>) -> &mut Self {
self.from = new_val;
self
}
pub fn set_to(&mut self, new_val: SmallVec<[Address; 1]>) -> &mut Self {
self.to = new_val;
self
}
pub fn set_in_reply_to(&mut self, new_val: &[u8]) -> &mut Self {
// [ref:FIXME]: msg_id_list
let new_val = new_val.trim();
if !new_val.is_empty() {
let val = match parser::address::msg_id(new_val) {
Ok(v) => v.1,
Err(_) => {
self.in_reply_to = Some(MessageID::new(new_val, new_val));
return self;
}
};
self.in_reply_to = Some(val);
} else {
self.in_reply_to = None;
}
self
}
pub fn set_subject(&mut self, new_val: Vec<u8>) -> &mut Self {
let mut new_val = String::from_utf8(new_val)
.unwrap_or_else(|err| String::from_utf8_lossy(&err.into_bytes()).into());
while new_val
.chars()
.last()
.map(char::is_control)
.unwrap_or(false)
{
new_val.pop();
}
self.subject = Some(new_val);
self
}
pub fn set_message_id(&mut self, new_val: &[u8]) -> &mut Self {
let new_val = new_val.trim();
match parser::address::msg_id(new_val) {
Ok((_, val)) => {
self.message_id = val;
}
Err(_) => {
self.message_id = MessageID::new(new_val, new_val);
}
}
self
}
pub fn push_references(&mut self, new_ref: MessageID) {
match self.references {
Some(ref mut s) => {
if s.refs.contains(&new_ref) {
if s.refs[s.refs.len() - 1] != new_ref {
if let Some(index) = s.refs.iter().position(|x| *x == new_ref) {
s.refs.remove(index);
} else {
panic!();
}
} else {
return;
}
}
s.refs.push(new_ref);
}
None => {
let v = vec![new_ref];
self.references = Some(References {
raw: "".into(),
refs: v,
});
}
}
}
pub fn set_references(&mut self, new_val: &[u8]) -> &mut Self {
let new_val = new_val.trim();
if !new_val.is_empty() {
self.references = None;
{
let parse_result = parser::address::msg_id_list(new_val);
if let Ok((_, value)) = parse_result {
for v in value {
self.push_references(v);
}
}
}
match self.references {
Some(ref mut s) => {
s.raw = new_val.into();
}
None => {
self.references = Some(References {
raw: new_val.into(),
refs: Vec::new(),
});
}
}
}
self
}
pub fn references(&self) -> SmallVec<[&MessageID; 8]> {
match self.references {
Some(ref s) => s.refs.iter().fold(SmallVec::new(), |mut acc, x| {
acc.push(x);
acc
}),
None => SmallVec::new(),
}
}
pub fn other_headers(&self) -> &HeaderMap {
&self.other_headers
}
pub fn other_headers_mut(&mut self) -> &mut HeaderMap {
&mut self.other_headers
}
pub fn thread(&self) -> ThreadNodeHash {
self.thread
}
pub fn set_thread(&mut self, new_val: ThreadNodeHash) -> &mut Self {
self.thread = new_val;
self
}
pub fn set_datetime(&mut self, new_val: UnixTimestamp) -> &mut Self {
self.timestamp = new_val;
self
}
pub fn set_flag(&mut self, f: Flag, value: bool) -> &mut Self {
self.flags.set(f, value);
self
}
pub fn set_flags(&mut self, f: Flag) -> &mut Self {
self.flags = f;
self
}
pub fn flags(&self) -> Flag {
self.flags
}
pub fn set_seen(&mut self) -> &mut Self {
self.set_flag(Flag::SEEN, true);
self
}
pub fn set_unseen(&mut self) -> &mut Self {
self.set_flag(Flag::SEEN, false);
self
}
pub fn is_seen(&self) -> bool {
self.flags.contains(Flag::SEEN)
}
pub fn set_has_attachments(&mut self, new_val: bool) -> &mut Self {
self.has_attachments = new_val;
self
}
pub fn has_attachments(&self) -> bool {
self.has_attachments
}
pub fn tags(&self) -> &IndexSet<TagHash> {
&self.tags
}
pub fn tags_mut(&mut self) -> &mut IndexSet<TagHash> {
&mut self.tags
}
/// Returns `true` if `is_recipient` address is included in To:, Cc: or Bcc:
/// headers.
pub fn recipient_any(&self, is_recipient: &Address) -> bool {
self.to()
.iter()
.chain(self.cc().iter())
.chain(self.bcc().iter())
.any(|a| a == is_recipient)
}
}
impl Eq for Envelope {}
impl Ord for Envelope {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.datetime().cmp(&other.datetime())
}
}
impl PartialOrd for Envelope {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Envelope {
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash
}
}