aerogramme/src/imap/mailbox_view.rs

773 lines
27 KiB
Rust
Raw Permalink Normal View History

2024-01-18 17:03:21 +00:00
use std::collections::HashSet;
use std::num::{NonZeroU32, NonZeroU64};
use std::sync::Arc;
2024-01-08 20:18:45 +00:00
use anyhow::{anyhow, Error, Result};
2023-10-09 10:00:16 +00:00
2024-02-22 10:35:39 +00:00
use futures::stream::{StreamExt, TryStreamExt};
2023-10-09 10:00:16 +00:00
2024-02-22 16:30:40 +00:00
use imap_codec::imap_types::core::{Charset, Vec1};
use imap_codec::imap_types::fetch::MessageDataItem;
2024-01-02 14:35:23 +00:00
use imap_codec::imap_types::flag::{Flag, FlagFetch, FlagPerm, StoreResponse, StoreType};
2024-01-09 16:40:23 +00:00
use imap_codec::imap_types::response::{Code, CodeOther, Data, Status};
use imap_codec::imap_types::search::SearchKey;
2024-01-06 10:07:53 +00:00
use imap_codec::imap_types::sequence::SequenceSet;
2023-10-09 10:00:16 +00:00
2024-01-05 17:59:19 +00:00
use crate::mail::mailbox::Mailbox;
use crate::mail::query::QueryScope;
2024-01-06 10:33:56 +00:00
use crate::mail::snapshot::FrozenMailbox;
2024-01-10 16:07:07 +00:00
use crate::mail::uidindex::{ImapUid, ImapUidvalidity, ModSeq};
2024-01-18 17:03:21 +00:00
use crate::mail::unique_ident::UniqueIdent;
2024-01-05 17:59:19 +00:00
2024-01-05 09:05:30 +00:00
use crate::imap::attributes::AttributesProxy;
2024-01-04 19:54:21 +00:00
use crate::imap::flags;
2024-01-06 10:33:56 +00:00
use crate::imap::index::Index;
2024-01-05 17:59:19 +00:00
use crate::imap::mail_view::{MailView, SeenFlag};
2024-01-02 14:35:23 +00:00
use crate::imap::response::Body;
2024-01-06 10:33:40 +00:00
use crate::imap::search;
const DEFAULT_FLAGS: [Flag; 5] = [
Flag::Seen,
Flag::Answered,
Flag::Flagged,
Flag::Deleted,
Flag::Draft,
];
2024-01-11 22:02:03 +00:00
pub struct UpdateParameters {
pub silence: HashSet<UniqueIdent>,
pub with_modseq: bool,
pub with_uid: bool,
}
impl Default for UpdateParameters {
fn default() -> Self {
Self {
silence: HashSet::new(),
with_modseq: false,
with_uid: false,
}
}
}
/// A MailboxView is responsible for giving the client the information
/// it needs about a mailbox, such as an initial summary of the mailbox's
/// content and continuous updates indicating when the content
/// of the mailbox has been changed.
/// To do this, it keeps a variable `known_state` that corresponds to
/// what the client knows, and produces IMAP messages to be sent to the
/// client that go along updates to `known_state`.
2024-01-09 16:40:23 +00:00
pub struct MailboxView {
pub internal: FrozenMailbox,
pub is_condstore: bool,
}
impl MailboxView {
/// Creates a new IMAP view into a mailbox.
2024-01-09 16:40:23 +00:00
pub async fn new(mailbox: Arc<Mailbox>, is_cond: bool) -> Self {
2024-01-18 17:03:21 +00:00
Self {
2024-01-09 16:40:23 +00:00
internal: mailbox.frozen().await,
is_condstore: is_cond,
}
}
2024-01-02 14:35:23 +00:00
/// Create an updated view, useful to make a diff
/// between what the client knows and new stuff
/// Produces a set of IMAP responses describing the change between
/// what the client knows and what is actually in the mailbox.
/// This does NOT trigger a sync, it bases itself on what is currently
/// loaded in RAM by Bayou.
2024-01-11 22:02:03 +00:00
pub async fn update(&mut self, params: UpdateParameters) -> Result<Vec<Body<'static>>> {
2024-01-09 16:40:23 +00:00
let old_snapshot = self.internal.update().await;
let new_snapshot = &self.internal.snapshot;
2022-06-29 15:58:31 +00:00
let mut data = Vec::<Body>::new();
2022-07-13 09:39:13 +00:00
// Calculate diff between two mailbox states
// See example in IMAP RFC in section on NOOP command:
// we want to produce something like this:
// C: a047 NOOP
// S: * 22 EXPUNGE
// S: * 23 EXISTS
// S: * 14 FETCH (UID 1305 FLAGS (\Seen \Deleted))
// S: a047 OK Noop completed
// In other words:
// - notify client of expunged mails
// - if new mails arrived, notify client of number of existing mails
// - if flags changed for existing mails, tell client
// (for this last step: if uidvalidity changed, do nothing,
// just notify of new uidvalidity and they will resync)
// - notify client of expunged mails
let mut n_expunge = 0;
2024-01-05 17:59:19 +00:00
for (i, (_uid, uuid)) in old_snapshot.idx_by_uid.iter().enumerate() {
if !new_snapshot.table.contains_key(uuid) {
2022-07-13 09:39:13 +00:00
data.push(Body::Data(Data::Expunge(
NonZeroU32::try_from((i + 1 - n_expunge) as u32).unwrap(),
)));
n_expunge += 1;
}
}
// - if new mails arrived, notify client of number of existing mails
2024-01-05 17:59:19 +00:00
if new_snapshot.table.len() != old_snapshot.table.len() - n_expunge
|| new_snapshot.uidvalidity != old_snapshot.uidvalidity
2022-07-13 09:39:13 +00:00
{
2024-01-05 17:59:19 +00:00
data.push(self.exists_status()?);
2022-07-13 09:39:13 +00:00
}
2024-01-05 17:59:19 +00:00
if new_snapshot.uidvalidity != old_snapshot.uidvalidity {
2022-06-29 15:58:31 +00:00
// TODO: do we want to push less/more info than this?
2024-01-05 17:59:19 +00:00
data.push(self.uidvalidity_status()?);
data.push(self.uidnext_status()?);
2022-06-29 15:58:31 +00:00
} else {
// - if flags changed for existing mails, tell client
2024-01-05 17:59:19 +00:00
for (i, (_uid, uuid)) in new_snapshot.idx_by_uid.iter().enumerate() {
2024-01-11 22:02:03 +00:00
if params.silence.contains(uuid) {
continue;
}
2024-01-05 17:59:19 +00:00
let old_mail = old_snapshot.table.get(uuid);
let new_mail = new_snapshot.table.get(uuid);
2022-06-29 15:58:31 +00:00
if old_mail.is_some() && old_mail != new_mail {
2024-01-11 22:02:03 +00:00
if let Some((uid, modseq, flags)) = new_mail {
2024-01-18 17:03:21 +00:00
let mut items = vec![MessageDataItem::Flags(
flags.iter().filter_map(|f| flags::from_str(f)).collect(),
)];
2024-01-11 22:02:03 +00:00
if params.with_uid {
items.push(MessageDataItem::Uid(*uid));
}
if params.with_modseq {
items.push(MessageDataItem::ModSeq(*modseq));
}
2022-06-29 15:58:31 +00:00
data.push(Body::Data(Data::Fetch {
2024-01-02 14:35:23 +00:00
seq: NonZeroU32::try_from((i + 1) as u32).unwrap(),
2024-01-11 22:02:03 +00:00
items: items.try_into()?,
2022-06-29 15:58:31 +00:00
}));
}
}
}
}
2024-01-02 14:35:23 +00:00
Ok(data)
}
/// Generates the necessary IMAP messages so that the client
/// has a satisfactory summary of the current mailbox's state.
/// These are the messages that are sent in response to a SELECT command.
pub fn summary(&self) -> Result<Vec<Body<'static>>> {
let mut data = Vec::<Body>::new();
data.push(self.exists_status()?);
data.push(self.recent_status()?);
data.extend(self.flags_status()?.into_iter());
data.push(self.uidvalidity_status()?);
data.push(self.uidnext_status()?);
2024-01-09 16:40:23 +00:00
if self.is_condstore {
data.push(self.highestmodseq_status()?);
}
/*self.unseen_first_status()?
2024-01-18 17:03:21 +00:00
.map(|unseen_status| data.push(unseen_status));*/
2022-06-29 15:58:31 +00:00
Ok(data)
}
2024-01-02 14:35:23 +00:00
pub async fn store<'a>(
2022-07-12 15:32:57 +00:00
&mut self,
sequence_set: &SequenceSet,
kind: &StoreType,
2024-01-11 22:02:03 +00:00
response: &StoreResponse,
2024-01-02 14:35:23 +00:00
flags: &[Flag<'a>],
2024-01-11 22:02:03 +00:00
unchanged_since: Option<NonZeroU64>,
is_uid_store: &bool,
2024-01-11 22:02:03 +00:00
) -> Result<(Vec<Body<'static>>, Vec<NonZeroU32>)> {
2024-01-09 16:40:23 +00:00
self.internal.sync().await?;
2022-07-12 15:32:57 +00:00
let flags = flags.iter().map(|x| x.to_string()).collect::<Vec<_>>();
2024-01-08 10:13:13 +00:00
let idx = self.index()?;
2024-01-18 17:03:21 +00:00
let (editable, in_conflict) =
idx.fetch_unchanged_since(sequence_set, unchanged_since, *is_uid_store)?;
2024-01-11 22:02:03 +00:00
for mi in editable.iter() {
2022-07-12 15:32:57 +00:00
match kind {
StoreType::Add => {
2024-01-09 16:40:23 +00:00
self.internal.mailbox.add_flags(mi.uuid, &flags[..]).await?;
2022-07-12 15:32:57 +00:00
}
StoreType::Remove => {
2024-01-09 16:40:23 +00:00
self.internal.mailbox.del_flags(mi.uuid, &flags[..]).await?;
2022-07-12 15:32:57 +00:00
}
StoreType::Replace => {
2024-01-09 16:40:23 +00:00
self.internal.mailbox.set_flags(mi.uuid, &flags[..]).await?;
2022-07-12 15:32:57 +00:00
}
}
}
2024-01-11 22:02:03 +00:00
let silence = match response {
StoreResponse::Answer => HashSet::new(),
StoreResponse::Silent => editable.iter().map(|midx| midx.uuid).collect(),
};
let conflict_id_or_uid = match is_uid_store {
true => in_conflict.into_iter().map(|midx| midx.uid).collect(),
_ => in_conflict.into_iter().map(|midx| midx.i).collect(),
};
2024-01-18 17:03:21 +00:00
let summary = self
.update(UpdateParameters {
with_uid: *is_uid_store,
with_modseq: unchanged_since.is_some(),
silence,
})
.await?;
2024-01-11 22:02:03 +00:00
Ok((summary, conflict_id_or_uid))
2022-07-12 15:32:57 +00:00
}
2024-01-18 16:33:57 +00:00
pub async fn idle_sync(&mut self) -> Result<Vec<Body<'static>>> {
2024-01-18 17:03:21 +00:00
self.internal
.mailbox
.notify()
.await
.upgrade()
.ok_or(anyhow!("test"))?
.notified()
.await;
2024-01-18 16:33:57 +00:00
self.internal.mailbox.opportunistic_sync().await?;
self.update(UpdateParameters::default()).await
}
2024-01-19 16:40:08 +00:00
pub async fn expunge(
&mut self,
maybe_seq_set: &Option<SequenceSet>,
) -> Result<Vec<Body<'static>>> {
2024-01-19 16:39:55 +00:00
// Get a recent view to apply our change
2024-01-09 16:40:23 +00:00
self.internal.sync().await?;
let state = self.internal.peek().await;
2024-01-19 16:39:55 +00:00
let idx = Index::new(&state)?;
2024-01-19 16:40:08 +00:00
2024-01-19 16:39:55 +00:00
// Build a default sequence set for the default case
2024-01-19 16:40:08 +00:00
use imap_codec::imap_types::sequence::{SeqOrUid, Sequence};
2024-01-19 16:39:55 +00:00
let seq = match maybe_seq_set {
Some(s) => s.clone(),
2024-01-19 16:40:08 +00:00
None => SequenceSet(
vec![Sequence::Range(
SeqOrUid::Value(NonZeroU32::MIN),
SeqOrUid::Asterisk,
)]
.try_into()
.unwrap(),
),
2024-01-19 16:39:55 +00:00
};
2022-07-13 09:19:08 +00:00
let deleted_flag = Flag::Deleted.to_string();
2024-01-19 16:39:55 +00:00
let msgs = idx
.fetch_on_uid(&seq)
.into_iter()
.filter(|midx| midx.flags.iter().any(|x| *x == deleted_flag))
.map(|midx| midx.uuid);
2022-07-13 09:19:08 +00:00
for msg in msgs {
2024-01-09 16:40:23 +00:00
self.internal.mailbox.delete(msg).await?;
2022-07-13 09:19:08 +00:00
}
2024-01-11 22:02:03 +00:00
self.update(UpdateParameters::default()).await
2022-07-13 09:00:35 +00:00
}
2022-07-21 10:44:58 +00:00
pub async fn copy(
&self,
sequence_set: &SequenceSet,
to: Arc<Mailbox>,
is_uid_copy: &bool,
) -> Result<(ImapUidvalidity, Vec<(ImapUid, ImapUid)>)> {
2024-01-08 10:13:13 +00:00
let idx = self.index()?;
let mails = idx.fetch(sequence_set, *is_uid_copy)?;
2022-07-21 10:44:58 +00:00
let mut new_uuids = vec![];
2023-10-10 15:59:34 +00:00
for mi in mails.iter() {
2024-01-09 16:40:23 +00:00
new_uuids.push(to.copy_from(&self.internal.mailbox, mi.uuid).await?);
2022-07-21 10:44:58 +00:00
}
let mut ret = vec![];
let to_state = to.current_uid_index().await;
2023-10-10 15:59:34 +00:00
for (mi, new_uuid) in mails.iter().zip(new_uuids.iter()) {
2022-07-21 10:44:58 +00:00
let dest_uid = to_state
.table
.get(new_uuid)
.ok_or(anyhow!("copied mail not in destination mailbox"))?
.0;
2023-10-10 15:59:34 +00:00
ret.push((mi.uid, dest_uid));
2022-07-21 10:44:58 +00:00
}
Ok((to_state.uidvalidity, ret))
}
2024-01-03 14:00:05 +00:00
pub async fn r#move(
&mut self,
sequence_set: &SequenceSet,
to: Arc<Mailbox>,
is_uid_copy: &bool,
) -> Result<(ImapUidvalidity, Vec<(ImapUid, ImapUid)>, Vec<Body<'static>>)> {
2024-01-08 10:13:13 +00:00
let idx = self.index()?;
let mails = idx.fetch(sequence_set, *is_uid_copy)?;
2024-01-03 14:00:05 +00:00
for mi in mails.iter() {
2024-01-09 16:40:23 +00:00
to.move_from(&self.internal.mailbox, mi.uuid).await?;
2024-01-03 14:00:05 +00:00
}
let mut ret = vec![];
let to_state = to.current_uid_index().await;
2024-01-05 14:36:40 +00:00
for mi in mails.iter() {
2024-01-03 14:00:05 +00:00
let dest_uid = to_state
.table
2024-01-05 14:36:40 +00:00
.get(&mi.uuid)
2024-01-03 14:00:05 +00:00
.ok_or(anyhow!("moved mail not in destination mailbox"))?
.0;
ret.push((mi.uid, dest_uid));
}
2024-01-18 17:03:21 +00:00
let update = self
.update(UpdateParameters {
with_uid: *is_uid_copy,
..UpdateParameters::default()
})
.await?;
2024-01-03 14:00:05 +00:00
Ok((to_state.uidvalidity, ret, update))
}
2022-06-29 17:24:21 +00:00
/// Looks up state changes in the mailbox and produces a set of IMAP
/// responses describing the new state.
2024-01-02 14:35:23 +00:00
pub async fn fetch<'b>(
2022-06-29 17:24:21 +00:00
&self,
sequence_set: &SequenceSet,
ap: &AttributesProxy,
2024-01-11 22:02:03 +00:00
changed_since: Option<NonZeroU64>,
is_uid_fetch: &bool,
) -> Result<Vec<Body<'static>>> {
2024-01-05 17:59:19 +00:00
// [1/6] Pre-compute data
// a. what are the uuids of the emails we want?
// b. do we need to fetch the full body?
//let ap = AttributesProxy::new(attributes, *is_uid_fetch);
2024-01-05 17:59:19 +00:00
let query_scope = match ap.need_body() {
true => QueryScope::Full,
_ => QueryScope::Partial,
};
2024-01-08 20:18:45 +00:00
tracing::debug!("Query scope {:?}", query_scope);
2024-01-08 10:13:13 +00:00
let idx = self.index()?;
2024-01-18 17:03:21 +00:00
let mail_idx_list = idx.fetch_changed_since(sequence_set, changed_since, *is_uid_fetch)?;
2023-10-12 10:21:59 +00:00
2024-01-05 17:59:19 +00:00
// [2/6] Fetch the emails
2024-01-06 10:33:56 +00:00
let uuids = mail_idx_list
.iter()
.map(|midx| midx.uuid)
.collect::<Vec<_>>();
2024-02-22 10:35:39 +00:00
let query = self.internal.query(&uuids, query_scope);
//let query_result = self.internal.query(&uuids, query_scope).fetch().await?;
2024-02-22 10:35:39 +00:00
let query_stream = query
.fetch()
.zip(futures::stream::iter(mail_idx_list))
// [3/6] Derive an IMAP-specific view from the results, apply the filters
2024-02-22 16:31:03 +00:00
.map(|(maybe_qr, midx)| match maybe_qr {
2024-02-22 10:35:39 +00:00
Ok(qr) => Ok((MailView::new(&qr, midx)?.filter(&ap)?, midx)),
Err(e) => Err(e),
2023-10-12 10:21:59 +00:00
})
2024-02-22 10:35:39 +00:00
// [4/6] Apply the IMAP transformation
.then(|maybe_ret| async move {
let ((body, seen), midx) = maybe_ret?;
// [5/6] Register the \Seen flags
if matches!(seen, SeenFlag::MustAdd) {
let seen_flag = Flag::Seen.to_string();
2024-02-22 16:31:03 +00:00
self.internal
.mailbox
.add_flags(midx.uuid, &[seen_flag])
.await?;
2024-02-22 10:35:39 +00:00
}
Ok::<_, anyhow::Error>(body)
});
2023-10-09 10:00:16 +00:00
2024-01-05 17:59:19 +00:00
// [6/6] Build the final result that will be sent to the client.
2024-02-22 10:35:39 +00:00
query_stream.try_collect().await
2022-06-29 17:24:21 +00:00
}
2024-01-06 10:33:40 +00:00
/// A naive search implementation...
pub async fn search<'a>(
&self,
_charset: &Option<Charset<'a>>,
2024-01-06 10:33:40 +00:00
search_key: &SearchKey<'a>,
uid: bool,
) -> Result<(Vec<Body<'static>>, bool)> {
2024-01-05 14:26:57 +00:00
// 1. Compute the subset of sequence identifiers we need to fetch
2024-01-06 10:33:40 +00:00
// based on the search query
let crit = search::Criteria(search_key);
let (seq_set, seq_type) = crit.to_sequence_set();
// 2. Get the selection
2024-01-08 10:13:13 +00:00
let idx = self.index()?;
let selection = idx.fetch(&seq_set, seq_type.is_uid())?;
2024-01-06 10:33:40 +00:00
// 3. Filter the selection based on the ID / UID / Flags
2024-01-06 17:51:21 +00:00
let (kept_idx, to_fetch) = crit.filter_on_idx(&selection);
2024-01-05 14:26:57 +00:00
2024-02-22 10:35:39 +00:00
// 4.a Fetch additional info about the emails
2024-01-06 17:01:44 +00:00
let query_scope = crit.query_scope();
2024-01-06 22:35:23 +00:00
let uuids = to_fetch.iter().map(|midx| midx.uuid).collect::<Vec<_>>();
2024-02-22 10:35:39 +00:00
let query = self.internal.query(&uuids, query_scope);
// 4.b We don't want to keep all data in memory, so we do the computing in a stream
let query_stream = query
.fetch()
.zip(futures::stream::iter(&to_fetch))
// 5.a Build a mailview with the body, might fail with an error
// 5.b If needed, filter the selection based on the body, but keep the errors
// 6. Drop the query+mailbox, keep only the mail index
// Here we release a lot of memory, this is the most important part ^^
.filter_map(|(maybe_qr, midx)| {
let r = match maybe_qr {
Ok(qr) => match MailView::new(&qr, midx).map(|mv| crit.is_keep_on_query(&mv)) {
Ok(true) => Some(Ok(*midx)),
Ok(_) => None,
Err(e) => Some(Err(e)),
2024-02-22 16:31:03 +00:00
},
2024-02-22 10:35:39 +00:00
Err(e) => Some(Err(e)),
};
futures::future::ready(r)
});
// 7. Chain both streams (part resolved from index, part resolved from metadata+body)
let main_stream = futures::stream::iter(kept_idx)
.map(Ok)
.chain(query_stream)
.map_ok(|idx| match uid {
true => (idx.uid, idx.modseq),
_ => (idx.i, idx.modseq),
});
// 8. Do the actual computation
let internal_result: Vec<_> = main_stream.try_collect().await?;
let (selection, modseqs): (Vec<_>, Vec<_>) = internal_result.into_iter().unzip();
// 9. Aggregate the maximum modseq value
let maybe_modseq = match crit.is_modseq() {
true => modseqs.into_iter().max(),
_ => None,
};
2024-02-22 10:35:39 +00:00
// 10. Return the final result
2024-01-18 17:03:21 +00:00
Ok((
2024-02-22 10:35:39 +00:00
vec![Body::Data(Data::Search(selection, maybe_modseq))],
maybe_modseq.is_some(),
2024-01-18 17:03:21 +00:00
))
}
// ----
2024-01-08 10:13:13 +00:00
/// @FIXME index should be stored for longer than a single request
/// Instead they should be tied to the FrozenMailbox refresh
/// It's not trivial to refactor the code to do that, so we are doing
/// some useless computation for now...
fn index<'a>(&'a self) -> Result<Index<'a>> {
2024-01-09 16:40:23 +00:00
Index::new(&self.internal.snapshot)
2022-07-12 15:32:57 +00:00
}
/// Produce an OK [UIDVALIDITY _] message corresponding to `known_state`
2024-01-02 14:35:23 +00:00
fn uidvalidity_status(&self) -> Result<Body<'static>> {
let uid_validity = Status::ok(
None,
2022-07-12 13:59:13 +00:00
Some(Code::UidValidity(self.uidvalidity())),
"UIDs valid",
)
.map_err(Error::msg)?;
Ok(Body::Status(uid_validity))
}
2022-07-12 13:59:13 +00:00
pub(crate) fn uidvalidity(&self) -> ImapUidvalidity {
2024-01-09 16:40:23 +00:00
self.internal.snapshot.uidvalidity
2022-07-12 13:59:13 +00:00
}
/// Produce an OK [UIDNEXT _] message corresponding to `known_state`
2024-01-02 14:35:23 +00:00
fn uidnext_status(&self) -> Result<Body<'static>> {
let next_uid = Status::ok(
None,
2022-07-12 13:59:13 +00:00
Some(Code::UidNext(self.uidnext())),
"Predict next UID",
)
.map_err(Error::msg)?;
Ok(Body::Status(next_uid))
}
2022-07-12 13:59:13 +00:00
pub(crate) fn uidnext(&self) -> ImapUid {
2024-01-09 16:40:23 +00:00
self.internal.snapshot.uidnext
}
pub(crate) fn highestmodseq_status(&self) -> Result<Body<'static>> {
Ok(Body::Status(Status::ok(
2024-01-18 17:03:21 +00:00
None,
Some(Code::Other(CodeOther::unvalidated(
format!("HIGHESTMODSEQ {}", self.highestmodseq()).into_bytes(),
))),
2024-01-09 16:40:23 +00:00
"Highest",
)?))
2022-07-12 13:59:13 +00:00
}
2024-01-10 16:07:07 +00:00
pub(crate) fn highestmodseq(&self) -> ModSeq {
self.internal.snapshot.highestmodseq
}
/// Produce an EXISTS message corresponding to the number of mails
/// in `known_state`
2024-01-02 14:35:23 +00:00
fn exists_status(&self) -> Result<Body<'static>> {
2022-07-12 13:59:13 +00:00
Ok(Body::Data(Data::Exists(self.exists()?)))
}
pub(crate) fn exists(&self) -> Result<u32> {
2024-01-09 16:40:23 +00:00
Ok(u32::try_from(self.internal.snapshot.idx_by_uid.len())?)
}
/// Produce a RECENT message corresponding to the number of
/// recent mails in `known_state`
2024-01-02 14:35:23 +00:00
fn recent_status(&self) -> Result<Body<'static>> {
2022-07-12 13:59:13 +00:00
Ok(Body::Data(Data::Recent(self.recent()?)))
}
#[allow(dead_code)]
2024-01-08 14:07:02 +00:00
fn unseen_first_status(&self) -> Result<Option<Body<'static>>> {
Ok(self
.unseen_first()?
.map(|unseen_id| {
Status::ok(None, Some(Code::Unseen(unseen_id)), "First unseen.").map(Body::Status)
})
.transpose()?)
2024-01-08 14:07:02 +00:00
}
#[allow(dead_code)]
2024-01-08 14:07:02 +00:00
fn unseen_first(&self) -> Result<Option<NonZeroU32>> {
Ok(self
2024-01-09 16:40:23 +00:00
.internal
.snapshot
.table
2024-01-08 14:07:02 +00:00
.values()
.enumerate()
2024-01-10 11:55:38 +00:00
.find(|(_i, (_imap_uid, _modseq, flags))| !flags.contains(&"\\Seen".to_string()))
.map(|(i, _)| NonZeroU32::try_from(i as u32 + 1))
2024-01-08 14:07:02 +00:00
.transpose()?)
}
2022-07-12 13:59:13 +00:00
pub(crate) fn recent(&self) -> Result<u32> {
let recent = self
2024-01-09 16:40:23 +00:00
.internal
2024-01-05 17:59:19 +00:00
.snapshot
.idx_by_flag
.get(&"\\Recent".to_string())
.map(|os| os.len())
.unwrap_or(0);
2022-07-12 13:59:13 +00:00
Ok(u32::try_from(recent)?)
}
/// Produce a FLAGS and a PERMANENTFLAGS message that indicates
/// the flags that are in `known_state` + default flags
2024-01-02 14:35:23 +00:00
fn flags_status(&self) -> Result<Vec<Body<'static>>> {
let mut body = vec![];
// 1. Collecting all the possible flags in the mailbox
// 1.a Fetch them from our index
2024-01-06 10:33:56 +00:00
let mut known_flags: Vec<Flag> = self
2024-01-09 16:40:23 +00:00
.internal
2024-01-05 17:59:19 +00:00
.snapshot
.idx_by_flag
.flags()
2024-01-04 19:54:21 +00:00
.filter_map(|f| match flags::from_str(f) {
2024-01-02 14:35:23 +00:00
Some(FlagFetch::Flag(fl)) => Some(fl),
_ => None,
})
.collect();
2024-01-02 14:35:23 +00:00
// 1.b Merge it with our default flags list
for f in DEFAULT_FLAGS.iter() {
2024-01-02 14:35:23 +00:00
if !known_flags.contains(f) {
known_flags.push(f.clone());
}
}
2024-01-02 14:35:23 +00:00
// 1.c Create the IMAP message
body.push(Body::Data(Data::Flags(known_flags.clone())));
2024-01-02 14:35:23 +00:00
// 2. Returning flags that are persisted
// 2.a Always advertise our default flags
let mut permanent = DEFAULT_FLAGS
.iter()
.map(|f| FlagPerm::Flag(f.clone()))
.collect::<Vec<_>>();
// 2.b Say that we support any keyword flag
permanent.push(FlagPerm::Asterisk);
// 2.c Create the IMAP message
let permanent_flags = Status::ok(
None,
Some(Code::PermanentFlags(permanent)),
"Flags permitted",
)
.map_err(Error::msg)?;
body.push(Body::Status(permanent_flags));
2024-01-02 14:35:23 +00:00
// Done!
Ok(body)
}
pub(crate) fn unseen_count(&self) -> usize {
2024-01-09 16:40:23 +00:00
let total = self.internal.snapshot.table.len();
2024-01-06 10:33:56 +00:00
let seen = self
2024-01-09 16:40:23 +00:00
.internal
2024-01-05 17:59:19 +00:00
.snapshot
.idx_by_flag
.get(&Flag::Seen.to_string())
.map(|x| x.len())
.unwrap_or(0);
total - seen
}
}
2022-06-29 15:58:31 +00:00
#[cfg(test)]
mod tests {
use super::*;
2024-01-02 21:09:45 +00:00
use imap_codec::encode::Encoder;
2024-02-22 16:30:40 +00:00
use imap_codec::imap_types::core::Vec1;
2024-01-02 14:35:23 +00:00
use imap_codec::imap_types::fetch::Section;
2024-01-05 09:05:30 +00:00
use imap_codec::imap_types::fetch::{MacroOrMessageDataItemNames, MessageDataItemName};
2024-01-02 21:09:45 +00:00
use imap_codec::imap_types::response::Response;
use imap_codec::ResponseCodec;
2022-07-05 13:21:14 +00:00
use std::fs;
2024-01-04 19:54:21 +00:00
use crate::cryptoblob;
2024-01-06 10:33:56 +00:00
use crate::imap::index::MailIndex;
2024-01-06 10:14:55 +00:00
use crate::imap::mail_view::MailView;
2024-01-04 19:54:21 +00:00
use crate::imap::mime_view;
2024-01-05 09:05:30 +00:00
use crate::mail::mailbox::MailMeta;
2024-01-06 10:14:55 +00:00
use crate::mail::query::QueryResult;
2024-01-06 10:33:56 +00:00
use crate::mail::unique_ident;
2024-01-04 19:54:21 +00:00
2023-10-12 10:21:59 +00:00
#[test]
fn mailview_body_ext() -> Result<()> {
let ap = AttributesProxy::new(
2024-01-02 21:09:45 +00:00
&MacroOrMessageDataItemNames::MessageDataItemNames(vec![
MessageDataItemName::BodyExt {
section: Some(Section::Header(None)),
partial: None,
peek: false,
},
]),
2024-01-12 08:54:58 +00:00
&[],
2023-10-12 10:21:59 +00:00
false,
);
let key = cryptoblob::gen_key();
let meta = MailMeta {
internaldate: 0u64,
headers: vec![],
message_key: key,
rfc822_size: 8usize,
};
2024-01-06 10:14:55 +00:00
2024-01-12 08:54:58 +00:00
let index_entry = (NonZeroU32::MIN, NonZeroU64::MIN, vec![]);
2024-01-06 10:14:55 +00:00
let mail_in_idx = MailIndex {
2023-10-12 10:21:59 +00:00
i: NonZeroU32::MIN,
2024-01-06 10:14:55 +00:00
uid: index_entry.0,
2024-01-12 08:54:58 +00:00
modseq: index_entry.1,
2023-10-12 10:21:59 +00:00
uuid: unique_ident::gen_ident(),
2024-01-12 08:54:58 +00:00
flags: &index_entry.2,
2023-10-12 10:21:59 +00:00
};
let rfc822 = b"Subject: hello\r\nFrom: a@a.a\r\nTo: b@b.b\r\nDate: Thu, 12 Oct 2023 08:45:28 +0000\r\n\r\nhello world";
2024-01-06 10:14:55 +00:00
let qr = QueryResult::FullResult {
uuid: mail_in_idx.uuid.clone(),
metadata: meta,
content: rfc822.to_vec(),
2023-10-12 10:21:59 +00:00
};
2024-01-06 10:14:55 +00:00
2024-02-22 10:51:58 +00:00
let mv = MailView::new(&qr, &mail_in_idx)?;
2024-01-02 21:09:45 +00:00
let (res_body, _seen) = mv.filter(&ap)?;
2023-10-12 10:21:59 +00:00
let fattr = match res_body {
Body::Data(Data::Fetch {
2024-01-02 14:35:23 +00:00
seq: _seq,
items: attr,
2023-10-12 10:21:59 +00:00
}) => Ok(attr),
_ => Err(anyhow!("Not a fetch body")),
}?;
2024-01-02 21:09:45 +00:00
assert_eq!(fattr.as_ref().len(), 1);
2023-10-12 10:21:59 +00:00
2024-01-02 21:09:45 +00:00
let (sec, _orig, _data) = match &fattr.as_ref()[0] {
MessageDataItem::BodyExt {
2023-10-12 10:21:59 +00:00
section,
origin,
data,
} => Ok((section, origin, data)),
_ => Err(anyhow!("not a body ext message attribute")),
}?;
assert_eq!(sec.as_ref().unwrap(), &Section::Header(None));
Ok(())
}
2022-07-05 16:27:49 +00:00
/// Future automated test. We use lossy utf8 conversion + lowercase everything,
2022-07-05 13:21:14 +00:00
/// so this test might allow invalid results. But at least it allows us to quickly test a
/// large variety of emails.
/// Keep in mind that special cases must still be tested manually!
#[test]
2022-07-05 13:21:14 +00:00
fn fetch_body() -> Result<()> {
2022-07-05 15:48:10 +00:00
let prefixes = [
2023-07-25 17:08:48 +00:00
/* *** MY OWN DATASET *** */
2022-07-05 15:48:10 +00:00
"tests/emails/dxflrs/0001_simple",
"tests/emails/dxflrs/0002_mime",
2022-07-05 16:27:49 +00:00
"tests/emails/dxflrs/0003_mime-in-mime",
2022-07-20 13:14:34 +00:00
"tests/emails/dxflrs/0004_msg-in-msg",
2023-07-25 17:08:48 +00:00
// eml_codec do not support continuation for the moment
2022-07-20 11:58:24 +00:00
//"tests/emails/dxflrs/0005_mail-parser-readme",
2023-03-09 10:30:44 +00:00
"tests/emails/dxflrs/0006_single-mime",
2023-07-25 17:08:48 +00:00
"tests/emails/dxflrs/0007_raw_msg_in_rfc822",
/* *** (STRANGE) RFC *** */
//"tests/emails/rfc/000", // must return text/enriched, we return text/plain
//"tests/emails/rfc/001", // does not recognize the multipart/external-body, breaks the
// whole parsing
//"tests/emails/rfc/002", // wrong date in email
//"tests/emails/rfc/003", // dovecot fixes \r\r: the bytes number is wrong + text/enriched
/* *** THIRD PARTY *** */
//"tests/emails/thirdparty/000", // dovecot fixes \r\r: the bytes number is wrong
//"tests/emails/thirdparty/001", // same
"tests/emails/thirdparty/002", // same
2023-10-12 10:21:59 +00:00
/* *** LEGACY *** */
//"tests/emails/legacy/000", // same issue with \r\r
2022-07-05 15:48:10 +00:00
];
2022-07-05 15:48:10 +00:00
for pref in prefixes.iter() {
println!("{}", pref);
let txt = fs::read(format!("{}.eml", pref))?;
2024-01-02 21:09:45 +00:00
let oracle = fs::read(format!("{}.dovecot.body", pref))?;
2023-07-25 17:08:48 +00:00
let message = eml_codec::parse_message(&txt).unwrap().1;
2024-01-02 21:09:45 +00:00
let test_repr = Response::Data(Data::Fetch {
seq: NonZeroU32::new(1).unwrap(),
2024-02-22 16:30:40 +00:00
items: Vec1::from(MessageDataItem::Body(mime_view::bodystructure(
2024-01-02 21:09:45 +00:00
&message.child,
2024-01-08 20:18:45 +00:00
false,
2024-01-02 21:09:45 +00:00
)?)),
});
let test_bytes = ResponseCodec::new().encode(&test_repr).dump();
let test_str = String::from_utf8_lossy(&test_bytes).to_lowercase();
2022-07-05 13:21:14 +00:00
2024-01-02 21:09:45 +00:00
let oracle_str =
format!("* 1 FETCH {}\r\n", String::from_utf8_lossy(&oracle)).to_lowercase();
2022-07-05 15:48:10 +00:00
2024-01-02 21:09:45 +00:00
println!("aerogramme: {}\n\ndovecot: {}\n\n", test_str, oracle_str);
2022-07-08 08:23:07 +00:00
//println!("\n\n {} \n\n", String::from_utf8_lossy(&resp));
2024-01-02 21:09:45 +00:00
assert_eq!(test_str, oracle_str);
2022-07-05 15:48:10 +00:00
}
Ok(())
}
}