meli/melib/src/backends/jmap/protocol.rs

296 lines
8.9 KiB
Rust
Raw Normal View History

2019-12-03 13:25:49 +02:00
/*
* meli - jmap module.
*
* Copyright 2019 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/>.
*/
use super::mailbox::JmapMailbox;
2019-12-03 13:25:49 +02:00
use super::*;
2019-12-07 14:03:54 +02:00
use serde::Serialize;
2019-12-03 13:25:49 +02:00
use serde_json::{json, Value};
2019-12-04 19:42:31 +02:00
use std::convert::TryFrom;
2019-12-03 13:25:49 +02:00
2019-12-03 21:29:26 +02:00
pub type UtcDate = String;
use super::rfc8620::Object;
2019-12-04 01:04:38 +02:00
macro_rules! get_request_no {
($lock:expr) => {{
let mut lck = $lock.lock().unwrap();
let ret = *lck;
*lck += 1;
ret
}};
}
2019-12-04 19:42:31 +02:00
pub trait Response<OBJ: Object> {
2019-12-03 21:29:26 +02:00
const NAME: &'static str;
}
2019-12-04 19:42:31 +02:00
pub trait Method<OBJ: Object>: Serialize {
const NAME: &'static str;
2019-12-03 21:29:26 +02:00
}
2019-12-04 19:42:31 +02:00
2020-07-05 15:28:55 +03:00
static USING: &[&str] = &["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"];
2019-12-03 13:25:49 +02:00
2019-12-03 21:29:26 +02:00
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Request {
using: &'static [&'static str],
/* Why is this Value instead of Box<dyn Method<_>>? The Method trait cannot be made into a
* Trait object because its serialize() will be generic. */
method_calls: Vec<Value>,
2019-12-04 01:04:38 +02:00
2019-12-04 19:42:31 +02:00
#[serde(skip)]
2019-12-04 01:04:38 +02:00
request_no: Arc<Mutex<usize>>,
2019-12-03 21:29:26 +02:00
}
impl Request {
2019-12-04 01:04:38 +02:00
pub fn new(request_no: Arc<Mutex<usize>>) -> Self {
2019-12-03 21:29:26 +02:00
Request {
using: USING,
method_calls: Vec::new(),
2019-12-04 01:04:38 +02:00
request_no,
2019-12-03 21:29:26 +02:00
}
}
2019-12-05 00:04:03 +02:00
pub fn add_call<M: Method<O>, O: Object>(&mut self, call: &M) -> usize {
2019-12-04 01:04:38 +02:00
let seq = get_request_no!(self.request_no);
2019-12-03 21:29:26 +02:00
self.method_calls
2019-12-04 01:04:38 +02:00
.push(serde_json::to_value((M::NAME, call, &format!("m{}", seq))).unwrap());
seq
2019-12-03 21:29:26 +02:00
}
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct JsonResponse<'a> {
#[serde(borrow)]
method_responses: Vec<MethodResponse<'a>>,
}
pub async fn get_mailboxes(conn: &JmapConnection) -> Result<HashMap<MailboxHash, JmapMailbox>> {
2019-12-04 01:04:38 +02:00
let seq = get_request_no!(conn.request_no);
let mut res = conn
2019-12-03 13:25:49 +02:00
.client
.post_async(
&conn.session.api_url,
serde_json::to_string(&json!({
"using": ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"],
"methodCalls": [["Mailbox/get", {
"accountId": conn.mail_account_id()
},
format!("#m{}",seq).as_str()]],
}))?,
2019-12-13 00:01:59 +02:00
)
.await?;
let res_text = res.text_async().await?;
2019-12-04 19:42:31 +02:00
let mut v: MethodResponse = serde_json::from_str(&res_text).unwrap();
2020-09-21 16:17:37 +03:00
*conn.store.online_status.lock().await = (std::time::Instant::now(), Ok(()));
2019-12-04 19:42:31 +02:00
let m = GetResponse::<MailboxObject>::try_from(v.method_responses.remove(0))?;
let GetResponse::<MailboxObject> {
list, account_id, ..
} = m;
2020-09-21 16:17:37 +03:00
*conn.store.account_id.lock().unwrap() = account_id;
2019-12-04 19:42:31 +02:00
Ok(list
.into_iter()
.map(|r| {
let MailboxObject {
id,
is_subscribed,
my_rights,
name,
parent_id,
role,
sort_order,
total_emails,
total_threads,
unread_emails,
unread_threads,
} = r;
let hash = id.into_hash();
let parent_hash = parent_id.clone().map(|id| id.into_hash());
2019-12-04 19:42:31 +02:00
(
hash,
JmapMailbox {
2019-12-04 19:42:31 +02:00
name: name.clone(),
hash,
path: name,
2020-09-21 16:17:37 +03:00
children: Vec::new(),
2019-12-03 13:25:49 +02:00
id,
is_subscribed,
my_rights,
parent_id,
parent_hash,
2019-12-03 13:25:49 +02:00
role,
2019-12-04 19:42:31 +02:00
usage: Default::default(),
2019-12-03 13:25:49 +02:00
sort_order,
total_emails: Arc::new(Mutex::new(total_emails)),
2019-12-03 13:25:49 +02:00
total_threads,
unread_emails: Arc::new(Mutex::new(unread_emails)),
2019-12-03 13:25:49 +02:00
unread_threads,
2019-12-04 19:42:31 +02:00
},
)
})
.collect())
2019-12-03 13:25:49 +02:00
}
pub async fn get_message_list(
conn: &JmapConnection,
mailbox: &JmapMailbox,
) -> Result<Vec<Id<EmailObject>>> {
2019-12-13 00:01:59 +02:00
let email_call: EmailQuery = EmailQuery::new(
Query::new()
.account_id(conn.mail_account_id().clone())
.filter(Some(Filter::Condition(
EmailFilterCondition::new()
.in_mailbox(Some(mailbox.id.clone()))
.into(),
)))
2019-12-13 00:01:59 +02:00
.position(0),
)
.collapse_threads(false);
2019-12-03 21:29:26 +02:00
2019-12-04 01:04:38 +02:00
let mut req = Request::new(conn.request_no.clone());
2019-12-05 00:04:03 +02:00
req.add_call(&email_call);
2019-12-03 21:29:26 +02:00
let mut res = conn
2019-12-03 13:25:49 +02:00
.client
.post_async(&conn.session.api_url, serde_json::to_string(&req)?)
.await?;
2019-12-03 13:25:49 +02:00
let res_text = res.text_async().await?;
2019-12-04 19:42:31 +02:00
let mut v: MethodResponse = serde_json::from_str(&res_text).unwrap();
2020-09-21 16:17:37 +03:00
*conn.store.online_status.lock().await = (std::time::Instant::now(), Ok(()));
2019-12-04 19:42:31 +02:00
let m = QueryResponse::<EmailObject>::try_from(v.method_responses.remove(0))?;
let QueryResponse::<EmailObject> { ids, .. } = m;
Ok(ids)
2019-12-03 13:25:49 +02:00
}
2020-09-21 16:17:37 +03:00
/*
pub async fn get_message(conn: &JmapConnection, ids: &[String]) -> Result<Vec<Envelope>> {
2019-12-04 19:42:31 +02:00
let email_call: EmailGet = EmailGet::new(
Get::new()
2020-07-05 15:28:55 +03:00
.ids(Some(JmapArgument::value(ids.to_vec())))
2019-12-13 00:01:59 +02:00
.account_id(conn.mail_account_id().to_string()),
2019-12-04 19:42:31 +02:00
);
2019-12-04 01:04:38 +02:00
let mut req = Request::new(conn.request_no.clone());
2019-12-05 00:04:03 +02:00
req.add_call(&email_call);
let mut res = conn
2019-12-03 13:25:49 +02:00
.client
.post_async(&conn.session.api_url, serde_json::to_string(&req)?)
.await?;
2019-12-04 01:04:38 +02:00
let res_text = res.text_async().await?;
2019-12-04 19:42:31 +02:00
let mut v: MethodResponse = serde_json::from_str(&res_text).unwrap();
let e = GetResponse::<EmailObject>::try_from(v.method_responses.remove(0))?;
let GetResponse::<EmailObject> { list, .. } = e;
Ok(list
.into_iter()
.map(std::convert::Into::into)
.collect::<Vec<Envelope>>())
2019-12-04 01:04:38 +02:00
}
2020-09-21 16:17:37 +03:00
*/
2019-12-04 01:04:38 +02:00
pub async fn fetch(
2019-12-06 10:06:15 +02:00
conn: &JmapConnection,
2020-09-21 16:17:37 +03:00
store: &Store,
mailbox_hash: MailboxHash,
2019-12-06 10:06:15 +02:00
) -> Result<Vec<Envelope>> {
2020-09-21 16:17:37 +03:00
let mailbox_id = store.mailboxes.read().unwrap()[&mailbox_hash].id.clone();
2019-12-13 00:01:59 +02:00
let email_query_call: EmailQuery = EmailQuery::new(
Query::new()
.account_id(conn.mail_account_id().clone())
.filter(Some(Filter::Condition(
EmailFilterCondition::new()
.in_mailbox(Some(mailbox_id))
.into(),
)))
2019-12-13 00:01:59 +02:00
.position(0),
)
.collapse_threads(false);
2019-12-05 00:04:03 +02:00
let mut req = Request::new(conn.request_no.clone());
let prev_seq = req.add_call(&email_query_call);
let email_call: EmailGet = EmailGet::new(
Get::new()
.ids(Some(JmapArgument::reference(
prev_seq,
2019-12-13 00:01:59 +02:00
EmailQuery::RESULT_FIELD_IDS,
2019-12-05 00:04:03 +02:00
)))
.account_id(conn.mail_account_id().clone()),
2019-12-05 00:04:03 +02:00
);
req.add_call(&email_call);
let mut res = conn
2019-12-05 00:04:03 +02:00
.client
.post_async(&conn.session.api_url, serde_json::to_string(&req)?)
.await?;
2019-12-05 00:04:03 +02:00
let res_text = res.text_async().await?;
2019-12-05 00:04:03 +02:00
let mut v: MethodResponse = serde_json::from_str(&res_text).unwrap();
let e = GetResponse::<EmailObject>::try_from(v.method_responses.pop().unwrap())?;
2019-12-06 14:12:27 +02:00
let GetResponse::<EmailObject> { list, state, .. } = e;
{
let (is_empty, is_equal) = {
let current_state_lck = conn.store.email_state.lock().unwrap();
(current_state_lck.is_empty(), *current_state_lck != state)
};
if is_empty {
2020-09-21 16:17:37 +03:00
debug!("{:?}: inserting state {}", EmailObject::NAME, &state);
*conn.store.email_state.lock().unwrap() = state;
} else if !is_equal {
conn.email_changes().await?;
2019-12-06 14:12:27 +02:00
}
}
2020-09-21 16:17:37 +03:00
let mut ret = Vec::with_capacity(list.len());
for obj in list {
ret.push(store.add_envelope(obj));
2019-12-06 10:06:15 +02:00
}
Ok(ret)
2019-12-05 00:04:03 +02:00
}
pub fn keywords_to_flags(keywords: Vec<String>) -> (Flag, Vec<String>) {
let mut f = Flag::default();
let mut tags = vec![];
for k in keywords {
match k.as_str() {
"$draft" => {
f |= Flag::DRAFT;
}
"$seen" => {
f |= Flag::SEEN;
}
"$flagged" => {
f |= Flag::FLAGGED;
}
"$answered" => {
f |= Flag::REPLIED;
}
"$junk" | "$notjunk" => { /* ignore */ }
_ => tags.push(k),
}
}
(f, tags)
}