Merge branch 'jmap'
commit
8465864dc0
File diff suppressed because it is too large
Load Diff
|
@ -26,9 +26,11 @@ bincode = "1.2.0"
|
|||
uuid = { version = "0.7.4", features = ["serde", "v4"] }
|
||||
text_processing = { path = "../text_processing", version = "*", optional= true }
|
||||
libc = {version = "0.2.59", features = ["extra_traits",]}
|
||||
reqwest = { version ="0.10.0-alpha.2", optional=true, features = ["json", "blocking" ]}
|
||||
serde_json = { version = "1.0", optional = true, features = ["raw_value",] }
|
||||
|
||||
[features]
|
||||
default = ["unicode_algorithms", "imap_backend", "maildir_backend", "mbox_backend", "vcard"]
|
||||
default = ["unicode_algorithms", "imap_backend", "maildir_backend", "mbox_backend", "jmap_backend", "vcard"]
|
||||
|
||||
debug-tracing = []
|
||||
unicode_algorithms = ["text_processing"]
|
||||
|
@ -36,4 +38,5 @@ imap_backend = ["native-tls"]
|
|||
maildir_backend = ["notify", "notify-rust", "memmap"]
|
||||
mbox_backend = ["notify", "notify-rust", "memmap"]
|
||||
notmuch_backend = []
|
||||
jmap_backend = ["reqwest", "serde_json" ]
|
||||
vcard = []
|
||||
|
|
|
@ -38,6 +38,10 @@ pub mod mbox;
|
|||
pub mod notmuch;
|
||||
#[cfg(feature = "notmuch_backend")]
|
||||
pub use self::notmuch::NotmuchDb;
|
||||
#[cfg(feature = "jmap_backend")]
|
||||
pub mod jmap;
|
||||
#[cfg(feature = "jmap_backend")]
|
||||
pub use self::jmap::JmapType;
|
||||
|
||||
#[cfg(feature = "imap_backend")]
|
||||
pub use self::imap::ImapType;
|
||||
|
@ -129,6 +133,16 @@ impl Backends {
|
|||
},
|
||||
);
|
||||
}
|
||||
#[cfg(feature = "jmap_backend")]
|
||||
{
|
||||
b.register(
|
||||
"jmap".to_string(),
|
||||
Backend {
|
||||
create_fn: Box::new(|| Box::new(|f, i| JmapType::new(f, i))),
|
||||
validate_conf_fn: Box::new(JmapType::validate_config),
|
||||
},
|
||||
);
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
|
@ -356,6 +370,28 @@ impl Default for SpecialUsageMailbox {
|
|||
}
|
||||
}
|
||||
|
||||
impl SpecialUsageMailbox {
|
||||
pub fn detect_usage(name: &str) -> Option<SpecialUsageMailbox> {
|
||||
if name.eq_ignore_ascii_case("inbox") {
|
||||
Some(SpecialUsageMailbox::Inbox)
|
||||
} else if name.eq_ignore_ascii_case("archive") {
|
||||
Some(SpecialUsageMailbox::Archive)
|
||||
} else if name.eq_ignore_ascii_case("drafts") {
|
||||
Some(SpecialUsageMailbox::Drafts)
|
||||
} else if name.eq_ignore_ascii_case("junk") {
|
||||
Some(SpecialUsageMailbox::Junk)
|
||||
} else if name.eq_ignore_ascii_case("spam") {
|
||||
Some(SpecialUsageMailbox::Junk)
|
||||
} else if name.eq_ignore_ascii_case("sent") {
|
||||
Some(SpecialUsageMailbox::Sent)
|
||||
} else if name.eq_ignore_ascii_case("trash") {
|
||||
Some(SpecialUsageMailbox::Trash)
|
||||
} else {
|
||||
Some(SpecialUsageMailbox::Normal)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait BackendFolder: Debug {
|
||||
fn hash(&self) -> FolderHash;
|
||||
fn name(&self) -> &str;
|
||||
|
|
|
@ -0,0 +1,303 @@
|
|||
/*
|
||||
* 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 crate::async_workers::{Async, AsyncBuilder, AsyncStatus, WorkContext};
|
||||
use crate::backends::BackendOp;
|
||||
use crate::backends::FolderHash;
|
||||
use crate::backends::{BackendFolder, Folder, FolderOperation, MailBackend, RefreshEventConsumer};
|
||||
use crate::conf::AccountSettings;
|
||||
use crate::email::*;
|
||||
use crate::error::{MeliError, Result};
|
||||
use fnv::FnvHashMap;
|
||||
use reqwest::blocking::Client;
|
||||
use std::collections::BTreeMap;
|
||||
use std::str::FromStr;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! _impl {
|
||||
($(#[$outer:meta])*$field:ident : $t:ty) => {
|
||||
$(#[$outer])*
|
||||
pub fn $field(mut self, new_val: $t) -> Self {
|
||||
self.$field = new_val;
|
||||
self
|
||||
}
|
||||
};
|
||||
(get_mut $(#[$outer:meta])*$method:ident, $field:ident : $t:ty) => {
|
||||
$(#[$outer])*
|
||||
pub fn $method(&mut self) -> &mut $t {
|
||||
&mut self.$field
|
||||
}
|
||||
};
|
||||
(get $(#[$outer:meta])*$method:ident, $field:ident : $t:ty) => {
|
||||
$(#[$outer])*
|
||||
pub fn $method(&self) -> &$t {
|
||||
&self.$field
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod operations;
|
||||
use operations::*;
|
||||
|
||||
pub mod connection;
|
||||
use connection::*;
|
||||
|
||||
pub mod protocol;
|
||||
use protocol::*;
|
||||
|
||||
pub mod rfc8620;
|
||||
use rfc8620::*;
|
||||
|
||||
pub mod objects;
|
||||
use objects::*;
|
||||
|
||||
pub mod folder;
|
||||
use folder::*;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct EnvelopeCache {
|
||||
bytes: Option<String>,
|
||||
headers: Option<String>,
|
||||
body: Option<String>,
|
||||
flags: Option<Flag>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct JmapServerConf {
|
||||
pub server_hostname: String,
|
||||
pub server_username: String,
|
||||
pub server_password: String,
|
||||
pub server_port: u16,
|
||||
pub danger_accept_invalid_certs: bool,
|
||||
}
|
||||
|
||||
macro_rules! get_conf_val {
|
||||
($s:ident[$var:literal]) => {
|
||||
$s.extra.get($var).ok_or_else(|| {
|
||||
MeliError::new(format!(
|
||||
"Configuration error ({}): JMAP connection requires the field `{}` set",
|
||||
$s.name.as_str(),
|
||||
$var
|
||||
))
|
||||
})
|
||||
};
|
||||
($s:ident[$var:literal], $default:expr) => {
|
||||
$s.extra
|
||||
.get($var)
|
||||
.map(|v| {
|
||||
<_>::from_str(v).map_err(|e| {
|
||||
MeliError::new(format!(
|
||||
"Configuration error ({}): Invalid value for field `{}`: {}\n{}",
|
||||
$s.name.as_str(),
|
||||
$var,
|
||||
v,
|
||||
e
|
||||
))
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|| Ok($default))
|
||||
};
|
||||
}
|
||||
|
||||
impl JmapServerConf {
|
||||
pub fn new(s: &AccountSettings) -> Result<Self> {
|
||||
Ok(JmapServerConf {
|
||||
server_hostname: get_conf_val!(s["server_hostname"])?.to_string(),
|
||||
server_username: get_conf_val!(s["server_username"])?.to_string(),
|
||||
server_password: get_conf_val!(s["server_password"])?.to_string(),
|
||||
server_port: get_conf_val!(s["server_port"], 443)?,
|
||||
danger_accept_invalid_certs: get_conf_val!(s["danger_accept_invalid_certs"], false)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct IsSubscribedFn(Box<dyn Fn(&str) -> bool + Send + Sync>);
|
||||
|
||||
impl std::fmt::Debug for IsSubscribedFn {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "IsSubscribedFn Box")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for IsSubscribedFn {
|
||||
type Target = Box<dyn Fn(&str) -> bool + Send + Sync>;
|
||||
fn deref(&self) -> &Box<dyn Fn(&str) -> bool + Send + Sync> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
macro_rules! get_conf_val {
|
||||
($s:ident[$var:literal]) => {
|
||||
$s.extra.get($var).ok_or_else(|| {
|
||||
MeliError::new(format!(
|
||||
"Configuration error ({}): JMAP connection requires the field `{}` set",
|
||||
$s.name.as_str(),
|
||||
$var
|
||||
))
|
||||
})
|
||||
};
|
||||
($s:ident[$var:literal], $default:expr) => {
|
||||
$s.extra
|
||||
.get($var)
|
||||
.map(|v| {
|
||||
<_>::from_str(v).map_err(|e| {
|
||||
MeliError::new(format!(
|
||||
"Configuration error ({}): Invalid value for field `{}`: {}\n{}",
|
||||
$s.name.as_str(),
|
||||
$var,
|
||||
v,
|
||||
e
|
||||
))
|
||||
})
|
||||
})
|
||||
.unwrap_or_else(|| Ok($default))
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Store {
|
||||
byte_cache: FnvHashMap<EnvelopeHash, EnvelopeCache>,
|
||||
id_store: FnvHashMap<EnvelopeHash, Id>,
|
||||
blob_id_store: FnvHashMap<EnvelopeHash, Id>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct JmapType {
|
||||
account_name: String,
|
||||
online: Arc<Mutex<bool>>,
|
||||
is_subscribed: Arc<IsSubscribedFn>,
|
||||
server_conf: JmapServerConf,
|
||||
connection: Arc<JmapConnection>,
|
||||
store: Arc<RwLock<Store>>,
|
||||
tag_index: Arc<RwLock<BTreeMap<u64, String>>>,
|
||||
folders: Arc<RwLock<FnvHashMap<FolderHash, JmapFolder>>>,
|
||||
}
|
||||
|
||||
impl MailBackend for JmapType {
|
||||
fn is_online(&self) -> bool {
|
||||
*self.online.lock().unwrap()
|
||||
}
|
||||
fn get(&mut self, folder: &Folder) -> Async<Result<Vec<Envelope>>> {
|
||||
let mut w = AsyncBuilder::new();
|
||||
let folders = self.folders.clone();
|
||||
let store = self.store.clone();
|
||||
let tag_index = self.tag_index.clone();
|
||||
let connection = self.connection.clone();
|
||||
let folder_hash = folder.hash();
|
||||
let handle = {
|
||||
let tx = w.tx();
|
||||
let closure = move |_work_context| {
|
||||
tx.send(AsyncStatus::Payload(protocol::get(
|
||||
&connection,
|
||||
&store,
|
||||
&tag_index,
|
||||
&folders.read().unwrap()[&folder_hash],
|
||||
)))
|
||||
.unwrap();
|
||||
tx.send(AsyncStatus::Finished).unwrap();
|
||||
};
|
||||
Box::new(closure)
|
||||
};
|
||||
w.build(handle)
|
||||
}
|
||||
|
||||
fn watch(
|
||||
&self,
|
||||
_sender: RefreshEventConsumer,
|
||||
_work_context: WorkContext,
|
||||
) -> Result<std::thread::ThreadId> {
|
||||
Err(MeliError::from("sadfsa"))
|
||||
}
|
||||
|
||||
fn folders(&self) -> Result<FnvHashMap<FolderHash, Folder>> {
|
||||
if self.folders.read().unwrap().is_empty() {
|
||||
let folders = std::dbg!(protocol::get_mailboxes(&self.connection))?;
|
||||
let ret = Ok(folders
|
||||
.iter()
|
||||
.map(|(&h, f)| (h, BackendFolder::clone(f) as Folder))
|
||||
.collect());
|
||||
*self.folders.write().unwrap() = folders;
|
||||
ret
|
||||
} else {
|
||||
Ok(self
|
||||
.folders
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|(&h, f)| (h, BackendFolder::clone(f) as Folder))
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
fn operation(&self, hash: EnvelopeHash) -> Box<dyn BackendOp> {
|
||||
Box::new(JmapOp::new(
|
||||
hash,
|
||||
self.connection.clone(),
|
||||
self.store.clone(),
|
||||
))
|
||||
}
|
||||
|
||||
fn save(&self, _bytes: &[u8], _folder: &str, _flags: Option<Flag>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn folder_operation(&mut self, _path: &str, _op: FolderOperation) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn::std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn tags(&self) -> Option<Arc<RwLock<BTreeMap<u64, String>>>> {
|
||||
Some(self.tag_index.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl JmapType {
|
||||
pub fn new(
|
||||
s: &AccountSettings,
|
||||
is_subscribed: Box<dyn Fn(&str) -> bool + Send + Sync>,
|
||||
) -> Result<Box<dyn MailBackend>> {
|
||||
let online = Arc::new(Mutex::new(false));
|
||||
let server_conf = JmapServerConf::new(s)?;
|
||||
|
||||
Ok(Box::new(JmapType {
|
||||
connection: Arc::new(JmapConnection::new(&server_conf, online.clone())?),
|
||||
store: Arc::new(RwLock::new(Store::default())),
|
||||
tag_index: Arc::new(RwLock::new(Default::default())),
|
||||
folders: Arc::new(RwLock::new(FnvHashMap::default())),
|
||||
account_name: s.name.clone(),
|
||||
online,
|
||||
is_subscribed: Arc::new(IsSubscribedFn(is_subscribed)),
|
||||
server_conf,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn validate_config(s: &AccountSettings) -> Result<()> {
|
||||
get_conf_val!(s["server_hostname"])?;
|
||||
get_conf_val!(s["server_username"])?;
|
||||
get_conf_val!(s["server_password"])?;
|
||||
get_conf_val!(s["server_port"], 443)?;
|
||||
get_conf_val!(s["danger_accept_invalid_certs"], false)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
/*
|
||||
* 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::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct JmapConnection {
|
||||
pub session: JmapSession,
|
||||
pub request_no: Arc<Mutex<usize>>,
|
||||
pub client: Arc<Mutex<Client>>,
|
||||
pub online_status: Arc<Mutex<bool>>,
|
||||
pub server_conf: JmapServerConf,
|
||||
pub account_id: Arc<Mutex<String>>,
|
||||
pub method_call_states: Arc<Mutex<FnvHashMap<&'static str, String>>>,
|
||||
}
|
||||
|
||||
impl JmapConnection {
|
||||
pub fn new(server_conf: &JmapServerConf, online_status: Arc<Mutex<bool>>) -> Result<Self> {
|
||||
use reqwest::header;
|
||||
let mut headers = header::HeaderMap::new();
|
||||
headers.insert(
|
||||
header::ACCEPT,
|
||||
header::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
let client = reqwest::blocking::ClientBuilder::new()
|
||||
.danger_accept_invalid_certs(server_conf.danger_accept_invalid_certs)
|
||||
.default_headers(headers)
|
||||
.build()?;
|
||||
let req = client
|
||||
.get(&server_conf.server_hostname)
|
||||
.basic_auth(
|
||||
&server_conf.server_username,
|
||||
Some(&server_conf.server_password),
|
||||
)
|
||||
.send()?;
|
||||
let res_text = req.text()?;
|
||||
debug!(&res_text);
|
||||
|
||||
let session: JmapSession = serde_json::from_str(&res_text)?;
|
||||
|
||||
if !session
|
||||
.capabilities
|
||||
.contains_key("urn:ietf:params:jmap:core")
|
||||
{
|
||||
return Err(MeliError::new(format!("Server {} did not return JMAP Core capability (urn:ietf:params:jmap:core). Returned capabilities were: {}", &server_conf.server_hostname, session.capabilities.keys().map(String::as_str).collect::<Vec<&str>>().join(", "))));
|
||||
}
|
||||
if !session
|
||||
.capabilities
|
||||
.contains_key("urn:ietf:params:jmap:mail")
|
||||
{
|
||||
return Err(MeliError::new(format!("Server {} does not support JMAP Mail capability (urn:ietf:params:jmap:mail). Returned capabilities were: {}", &server_conf.server_hostname, session.capabilities.keys().map(String::as_str).collect::<Vec<&str>>().join(", "))));
|
||||
}
|
||||
|
||||
let server_conf = server_conf.clone();
|
||||
Ok(JmapConnection {
|
||||
session,
|
||||
request_no: Arc::new(Mutex::new(0)),
|
||||
client: Arc::new(Mutex::new(client)),
|
||||
online_status,
|
||||
server_conf,
|
||||
account_id: Arc::new(Mutex::new(String::new())),
|
||||
method_call_states: Arc::new(Mutex::new(Default::default())),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn mail_account_id(&self) -> &Id {
|
||||
&self.session.primary_accounts["urn:ietf:params:jmap:mail"]
|
||||
}
|
||||
}
|
|
@ -0,0 +1,94 @@
|
|||
/*
|
||||
* 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::*;
|
||||
use crate::backends::{FolderPermissions, SpecialUsageMailbox};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct JmapFolder {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub hash: FolderHash,
|
||||
pub v: Vec<FolderHash>,
|
||||
pub id: String,
|
||||
pub is_subscribed: bool,
|
||||
pub my_rights: JmapRights,
|
||||
pub parent_id: Option<String>,
|
||||
pub role: Option<String>,
|
||||
pub sort_order: u64,
|
||||
pub total_emails: u64,
|
||||
pub total_threads: u64,
|
||||
pub unread_emails: u64,
|
||||
pub unread_threads: u64,
|
||||
pub usage: SpecialUsageMailbox,
|
||||
}
|
||||
|
||||
impl BackendFolder for JmapFolder {
|
||||
fn hash(&self) -> FolderHash {
|
||||
self.hash
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
|
||||
fn change_name(&mut self, _s: &str) {}
|
||||
|
||||
fn clone(&self) -> Folder {
|
||||
Box::new(std::clone::Clone::clone(self))
|
||||
}
|
||||
|
||||
fn children(&self) -> &[FolderHash] {
|
||||
&self.v
|
||||
}
|
||||
|
||||
fn parent(&self) -> Option<FolderHash> {
|
||||
None
|
||||
}
|
||||
|
||||
fn permissions(&self) -> FolderPermissions {
|
||||
FolderPermissions::default()
|
||||
}
|
||||
|
||||
fn special_usage(&self) -> SpecialUsageMailbox {
|
||||
match self.role.as_ref().map(String::as_str) {
|
||||
Some("inbox") => SpecialUsageMailbox::Inbox,
|
||||
Some("archive") => SpecialUsageMailbox::Archive,
|
||||
Some("junk") => SpecialUsageMailbox::Junk,
|
||||
Some("trash") => SpecialUsageMailbox::Trash,
|
||||
Some("drafts") => SpecialUsageMailbox::Drafts,
|
||||
Some("sent") => SpecialUsageMailbox::Sent,
|
||||
Some(other) => {
|
||||
debug!(
|
||||
"unknown JMAP mailbox role for folder {}: {}",
|
||||
self.path(),
|
||||
other
|
||||
);
|
||||
SpecialUsageMailbox::Normal
|
||||
}
|
||||
None => SpecialUsageMailbox::Normal,
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
/*
|
||||
* 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::*;
|
||||
|
||||
mod email;
|
||||
pub use email::*;
|
||||
|
||||
mod mailbox;
|
||||
pub use mailbox::*;
|
|
@ -0,0 +1,566 @@
|
|||
/*
|
||||
* 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::*;
|
||||
use crate::backends::jmap::rfc8620::bool_false;
|
||||
use core::marker::PhantomData;
|
||||
use serde::de::{Deserialize, Deserializer};
|
||||
use serde_json::Value;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hasher;
|
||||
|
||||
// 4.1.1.
|
||||
// Metadata
|
||||
// These properties represent metadata about the message in the mail
|
||||
// store and are not derived from parsing the message itself.
|
||||
//
|
||||
// o id: "Id" (immutable; server-set)
|
||||
//
|
||||
// The id of the Email object. Note that this is the JMAP object id,
|
||||
// NOT the Message-ID header field value of the message [RFC5322].
|
||||
//
|
||||
// o blobId: "Id" (immutable; server-set)
|
||||
//
|
||||
// The id representing the raw octets of the message [RFC5322] for
|
||||
// this Email. This may be used to download the raw original message
|
||||
// or to attach it directly to another Email, etc.
|
||||
//
|
||||
// o threadId: "Id" (immutable; server-set)
|
||||
//
|
||||
// The id of the Thread to which this Email belongs.
|
||||
//
|
||||
// o mailboxIds: "Id[Boolean]"
|
||||
//
|
||||
// The set of Mailbox ids this Email belongs to. An Email in the
|
||||
// mail store MUST belong to one or more Mailboxes at all times
|
||||
// (until it is destroyed). The set is represented as an object,
|
||||
// with each key being a Mailbox id. The value for each key in the
|
||||
// object MUST be true.
|
||||
//
|
||||
// o keywords: "String[Boolean]" (default: {})
|
||||
//
|
||||
// A set of keywords that apply to the Email. The set is represented
|
||||
// as an object, with the keys being the keywords. The value for
|
||||
// each key in the object MUST be true.
|
||||
//
|
||||
// Keywords are shared with IMAP. The six system keywords from IMAP
|
||||
// get special treatment. The following four keywords have their
|
||||
// first character changed from "\" in IMAP to "$" in JMAP and have
|
||||
// particular semantic meaning:
|
||||
//
|
||||
// * "$draft": The Email is a draft the user is composing.
|
||||
//
|
||||
// * "$seen": The Email has been read.
|
||||
//
|
||||
// * "$flagged": The Email has been flagged for urgent/special
|
||||
// attention.
|
||||
//
|
||||
// * "$answered": The Email has been replied to.
|
||||
//
|
||||
// The IMAP "\Recent" keyword is not exposed via JMAP. The IMAP
|
||||
// "\Deleted" keyword is also not present: IMAP uses a delete+expunge
|
||||
// model, which JMAP does not. Any message with the "\Deleted"
|
||||
// keyword MUST NOT be visible via JMAP (and so are not counted in
|
||||
// the "totalEmails", "unreadEmails", "totalThreads", and
|
||||
// "unreadThreads" Mailbox properties).
|
||||
//
|
||||
// Users may add arbitrary keywords to an Email. For compatibility
|
||||
// with IMAP, a keyword is a case-insensitive string of 1-255
|
||||
// characters in the ASCII subset %x21-%x7e (excludes control chars
|
||||
// and space), and it MUST NOT include any of these characters:
|
||||
//
|
||||
// ( ) { ] % * " \
|
||||
//
|
||||
// Because JSON is case sensitive, servers MUST return keywords in
|
||||
// lowercase.
|
||||
//
|
||||
// The IANA "IMAP and JMAP Keywords" registry at
|
||||
// <https://www.iana.org/assignments/imap-jmap-keywords/> as
|
||||
// established in [RFC5788] assigns semantic meaning to some other
|
||||
// keywords in common use. New keywords may be established here in
|
||||
// the future. In particular, note:
|
||||
//
|
||||
// * "$forwarded": The Email has been forwarded.
|
||||
//
|
||||
// * "$phishing": The Email is highly likely to be phishing.
|
||||
// Clients SHOULD warn users to take care when viewing this Email
|
||||
// and disable links and attachments.
|
||||
//
|
||||
// * "$junk": The Email is definitely spam. Clients SHOULD set this
|
||||
// flag when users report spam to help train automated spam-
|
||||
// detection systems.
|
||||
//
|
||||
// * "$notjunk": The Email is definitely not spam. Clients SHOULD
|
||||
// set this flag when users indicate an Email is legitimate, to
|
||||
// help train automated spam-detection systems.
|
||||
//
|
||||
// o size: "UnsignedInt" (immutable; server-set)
|
||||
//
|
||||
// The size, in octets, of the raw data for the message [RFC5322] (as
|
||||
// referenced by the "blobId", i.e., the number of octets in the file
|
||||
// the user would download).
|
||||
//
|
||||
// o receivedAt: "UTCDate" (immutable; default: time of creation on
|
||||
// server)
|
||||
//
|
||||
// The date the Email was received by the message store. This is the
|
||||
// "internal date" in IMAP [RFC3501]./
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EmailObject {
|
||||
#[serde(default)]
|
||||
pub id: Id,
|
||||
#[serde(default)]
|
||||
pub blob_id: String,
|
||||
#[serde(default)]
|
||||
mailbox_ids: HashMap<Id, bool>,
|
||||
#[serde(default)]
|
||||
size: u64,
|
||||
#[serde(default)]
|
||||
received_at: String,
|
||||
#[serde(default)]
|
||||
message_id: Vec<String>,
|
||||
#[serde(default)]
|
||||
to: Vec<EmailAddress>,
|
||||
#[serde(default)]
|
||||
bcc: Option<Vec<EmailAddress>>,
|
||||
#[serde(default)]
|
||||
reply_to: Option<Vec<EmailAddress>>,
|
||||
#[serde(default)]
|
||||
cc: Option<Vec<EmailAddress>>,
|
||||
#[serde(default)]
|
||||
sender: Option<Vec<EmailAddress>>,
|
||||
#[serde(default)]
|
||||
from: Vec<EmailAddress>,
|
||||
#[serde(default)]
|
||||
in_reply_to: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
references: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
keywords: HashMap<String, bool>,
|
||||
#[serde(default)]
|
||||
attached_emails: Option<Id>,
|
||||
#[serde(default)]
|
||||
attachments: Vec<Value>,
|
||||
#[serde(default)]
|
||||
has_attachment: bool,
|
||||
#[serde(default)]
|
||||
#[serde(deserialize_with = "deserialize_header")]
|
||||
headers: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
html_body: Vec<HtmlBody>,
|
||||
#[serde(default)]
|
||||
preview: Option<String>,
|
||||
#[serde(default)]
|
||||
sent_at: Option<String>,
|
||||
#[serde(default)]
|
||||
subject: Option<String>,
|
||||
#[serde(default)]
|
||||
text_body: Vec<TextBody>,
|
||||
#[serde(default)]
|
||||
thread_id: Id,
|
||||
#[serde(flatten)]
|
||||
extra: HashMap<String, Value>,
|
||||
}
|
||||
|
||||
impl EmailObject {
|
||||
_impl!(get keywords, keywords: HashMap<String, bool>);
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Header {
|
||||
name: String,
|
||||
value: String,
|
||||
}
|
||||
|
||||
fn deserialize_header<'de, D>(
|
||||
deserializer: D,
|
||||
) -> std::result::Result<HashMap<String, String>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let v = <Vec<Header>>::deserialize(deserializer)?;
|
||||
Ok(v.into_iter().map(|t| (t.name, t.value)).collect())
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct EmailAddress {
|
||||
email: String,
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
impl Into<crate::email::Address> for EmailAddress {
|
||||
fn into(self) -> crate::email::Address {
|
||||
let Self { email, mut name } = self;
|
||||
crate::make_address!((name.take().unwrap_or_default()), email)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EmailAddress {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
if self.name.is_some() {
|
||||
write!(f, "{} <{}>", self.name.as_ref().unwrap(), &self.email)
|
||||
} else {
|
||||
write!(f, "{}", &self.email)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::convert::From<EmailObject> for crate::Envelope {
|
||||
fn from(mut t: EmailObject) -> crate::Envelope {
|
||||
let mut env = crate::Envelope::new(0);
|
||||
if let Some(ref mut sent_at) = t.sent_at {
|
||||
env.set_date(std::mem::replace(sent_at, String::new()).as_bytes());
|
||||
}
|
||||
if let Ok(d) = crate::email::parser::date(env.date_as_str().as_bytes()) {
|
||||
env.set_datetime(d);
|
||||
}
|
||||
|
||||
if let Some(v) = t.message_id.get(0) {
|
||||
env.set_message_id(v.as_bytes());
|
||||
}
|
||||
if let Some(ref in_reply_to) = t.in_reply_to {
|
||||
env.set_in_reply_to(in_reply_to[0].as_bytes());
|
||||
env.push_references(in_reply_to[0].as_bytes());
|
||||
}
|
||||
if let Some(v) = t.headers.get("References") {
|
||||
let parse_result = crate::email::parser::references(v.as_bytes());
|
||||
if parse_result.is_done() {
|
||||
for v in parse_result.to_full_result().unwrap() {
|
||||
env.push_references(v);
|
||||
}
|
||||
}
|
||||
env.set_references(v.as_bytes());
|
||||
}
|
||||
if let Some(v) = t.headers.get("Date") {
|
||||
env.set_date(v.as_bytes());
|
||||
if let Ok(d) = crate::email::parser::date(v.as_bytes()) {
|
||||
env.set_datetime(d);
|
||||
}
|
||||
}
|
||||
env.set_has_attachments(t.has_attachment);
|
||||
if let Some(ref mut subject) = t.subject {
|
||||
env.set_subject(std::mem::replace(subject, String::new()).into_bytes());
|
||||
}
|
||||
|
||||
env.set_from(
|
||||
std::mem::replace(&mut t.from, Vec::new())
|
||||
.into_iter()
|
||||
.map(|addr| addr.into())
|
||||
.collect::<Vec<crate::email::Address>>(),
|
||||
);
|
||||
env.set_to(
|
||||
std::mem::replace(&mut t.to, Vec::new())
|
||||
.into_iter()
|
||||
.map(|addr| addr.into())
|
||||
.collect::<Vec<crate::email::Address>>(),
|
||||
);
|
||||
|
||||
if let Some(ref mut cc) = t.cc {
|
||||
env.set_cc(
|
||||
std::mem::replace(cc, Vec::new())
|
||||
.into_iter()
|
||||
.map(|addr| addr.into())
|
||||
.collect::<Vec<crate::email::Address>>(),
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(ref mut bcc) = t.bcc {
|
||||
env.set_bcc(
|
||||
std::mem::replace(bcc, Vec::new())
|
||||
.into_iter()
|
||||
.map(|addr| addr.into())
|
||||
.collect::<Vec<crate::email::Address>>(),
|
||||
);
|
||||
}
|
||||
|
||||
if env.references.is_some() {
|
||||
if let Some(pos) = env
|
||||
.references
|
||||
.as_ref()
|
||||
.map(|r| &r.refs)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.position(|r| r == env.message_id())
|
||||
{
|
||||
env.references.as_mut().unwrap().refs.remove(pos);
|
||||
}
|
||||
}
|
||||
|
||||
let mut h = DefaultHasher::new();
|
||||
h.write(t.id.as_bytes());
|
||||
env.set_hash(h.finish());
|
||||
env
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct HtmlBody {
|
||||
blob_id: Id,
|
||||
#[serde(default)]
|
||||
charset: String,
|
||||
#[serde(default)]
|
||||
cid: Option<String>,
|
||||
#[serde(default)]
|
||||
disposition: Option<String>,
|
||||
#[serde(default)]
|
||||
headers: Value,
|
||||
#[serde(default)]
|
||||
language: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
location: Option<String>,
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(default)]
|
||||
part_id: Option<String>,
|
||||
size: u64,
|
||||
#[serde(alias = "type")]
|
||||
content_type: String,
|
||||
#[serde(default)]
|
||||
sub_parts: Vec<Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct TextBody {
|
||||
blob_id: Id,
|
||||
#[serde(default)]
|
||||
charset: String,
|
||||
#[serde(default)]
|
||||
cid: Option<String>,
|
||||
#[serde(default)]
|
||||
disposition: Option<String>,
|
||||
#[serde(default)]
|
||||
headers: Value,
|
||||
#[serde(default)]
|
||||
language: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
location: Option<String>,
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
#[serde(default)]
|
||||
part_id: Option<String>,
|
||||
size: u64,
|
||||
#[serde(alias = "type")]
|
||||
content_type: String,
|
||||
#[serde(default)]
|
||||
sub_parts: Vec<Value>,
|
||||
}
|
||||
|
||||
impl Object for EmailObject {
|
||||
const NAME: &'static str = "Email";
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EmailQueryResponse {
|
||||
pub account_id: Id,
|
||||
pub can_calculate_changes: bool,
|
||||
pub collapse_threads: bool,
|
||||
// FIXME
|
||||
pub filter: String,
|
||||
pub ids: Vec<Id>,
|
||||
pub position: u64,
|
||||
pub query_state: String,
|
||||
pub sort: Option<String>,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EmailQuery {
|
||||
#[serde(flatten)]
|
||||
pub query_call: Query<EmailFilterCondition, EmailObject>,
|
||||
//pub filter: EmailFilterCondition, /* "inMailboxes": [ folder.id ] },*/
|
||||
pub collapse_threads: bool,
|
||||
}
|
||||
|
||||
impl Method<EmailObject> for EmailQuery {
|
||||
const NAME: &'static str = "Email/query";
|
||||
}
|
||||
|
||||
impl EmailQuery {
|
||||
pub const RESULT_FIELD_IDS: ResultField<EmailQuery, EmailObject> =
|
||||
ResultField::<EmailQuery, EmailObject> {
|
||||
field: "/ids",
|
||||
_ph: PhantomData,
|
||||
};
|
||||
|
||||
pub fn new(query_call: Query<EmailFilterCondition, EmailObject>) -> Self {
|
||||
EmailQuery {
|
||||
query_call,
|
||||
collapse_threads: false,
|
||||
}
|
||||
}
|
||||
|
||||
_impl!(collapse_threads: bool);
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EmailGet {
|
||||
#[serde(flatten)]
|
||||
pub get_call: Get<EmailObject>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub body_properties: Vec<String>,
|
||||
#[serde(default = "bool_false")]
|
||||
pub fetch_text_body_values: bool,
|
||||
#[serde(default = "bool_false")]
|
||||
#[serde(rename = "fetchHTMLBodyValues")]
|
||||
pub fetch_html_body_values: bool,
|
||||
#[serde(default = "bool_false")]
|
||||
pub fetch_all_body_values: bool,
|
||||
#[serde(default)]
|
||||
#[serde(skip_serializing_if = "u64_zero")]
|
||||
pub max_body_value_bytes: u64,
|
||||
}
|
||||
|
||||
impl Method<EmailObject> for EmailGet {
|
||||
const NAME: &'static str = "Email/get";
|
||||
}
|
||||
|
||||
impl EmailGet {
|
||||
pub fn new(get_call: Get<EmailObject>) -> Self {
|
||||
EmailGet {
|
||||
get_call,
|
||||
body_properties: Vec::new(),
|
||||
fetch_text_body_values: false,
|
||||
fetch_html_body_values: false,
|
||||
fetch_all_body_values: false,
|
||||
max_body_value_bytes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
_impl!(body_properties: Vec<String>);
|
||||
_impl!(fetch_text_body_values: bool);
|
||||
_impl!(fetch_html_body_values: bool);
|
||||
_impl!(fetch_all_body_values: bool);
|
||||
_impl!(max_body_value_bytes: u64);
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Default, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EmailFilterCondition {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub in_mailbox: Option<Id>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub in_mailbox_other_than: Vec<Id>,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub before: UtcDate,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub after: UtcDate,
|
||||
#[serde(default)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub min_size: Option<u64>,
|
||||
#[serde(default)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub max_size: Option<u64>,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub all_in_thread_have_keyword: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub some_in_thread_have_keyword: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub none_in_thread_have_keyword: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub has_keyword: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub not_keyword: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub has_attachment: Option<bool>,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub text: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub from: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub to: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub cc: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub bcc: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub subject: String,
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub body: String,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub header: Vec<Value>,
|
||||
}
|
||||
|
||||
impl EmailFilterCondition {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
_impl!(in_mailbox: Option<Id>);
|
||||
_impl!(in_mailbox_other_than: Vec<Id>);
|
||||
_impl!(before: UtcDate);
|
||||
_impl!(after: UtcDate);
|
||||
_impl!(min_size: Option<u64>);
|
||||
_impl!(max_size: Option<u64>);
|
||||
_impl!(all_in_thread_have_keyword: String);
|
||||
_impl!(some_in_thread_have_keyword: String);
|
||||
_impl!(none_in_thread_have_keyword: String);
|
||||
_impl!(has_keyword: String);
|
||||
_impl!(not_keyword: String);
|
||||
_impl!(has_attachment: Option<bool>);
|
||||
_impl!(text: String);
|
||||
_impl!(from: String);
|
||||
_impl!(to: String);
|
||||
_impl!(cc: String);
|
||||
_impl!(bcc: String);
|
||||
_impl!(subject: String);
|
||||
_impl!(body: String);
|
||||
_impl!(header: Vec<Value>);
|
||||
}
|
||||
|
||||
impl FilterTrait<EmailObject> for EmailFilterCondition {}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MessageProperty {
|
||||
ThreadId,
|
||||
MailboxIds,
|
||||
Keywords,
|
||||
Size,
|
||||
ReceivedAt,
|
||||
IsUnread,
|
||||
IsFlagged,
|
||||
IsAnswered,
|
||||
IsDraft,
|
||||
HasAttachment,
|
||||
From,
|
||||
To,
|
||||
Cc,
|
||||
Bcc,
|
||||
ReplyTo,
|
||||
Subject,
|
||||
SentAt,
|
||||
Preview,
|
||||
Id,
|
||||
BlobId,
|
||||
MessageId,
|
||||
InReplyTo,
|
||||
Sender,
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
/*
|
||||
* 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::*;
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MailboxObject {
|
||||
pub id: String,
|
||||
pub is_subscribed: bool,
|
||||
pub my_rights: JmapRights,
|
||||
pub name: String,
|
||||
pub parent_id: Option<String>,
|
||||
pub role: Option<String>,
|
||||
pub sort_order: u64,
|
||||
pub total_emails: u64,
|
||||
pub total_threads: u64,
|
||||
pub unread_emails: u64,
|
||||
pub unread_threads: u64,
|
||||
}
|
||||
|
||||
impl Object for MailboxObject {
|
||||
const NAME: &'static str = "Mailbox";
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JmapRights {
|
||||
pub may_add_items: bool,
|
||||
pub may_create_child: bool,
|
||||
pub may_delete: bool,
|
||||
pub may_read_items: bool,
|
||||
pub may_remove_items: bool,
|
||||
pub may_rename: bool,
|
||||
pub may_set_keywords: bool,
|
||||
pub may_set_seen: bool,
|
||||
pub may_submit: bool,
|
||||
}
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MailboxGet {
|
||||
#[serde(flatten)]
|
||||
pub get_call: Get<MailboxObject>,
|
||||
}
|
||||
impl MailboxGet {
|
||||
pub fn new(get_call: Get<MailboxObject>) -> Self {
|
||||
MailboxGet { get_call }
|
||||
}
|
||||
}
|
||||
|
||||
impl Method<MailboxObject> for MailboxGet {
|
||||
const NAME: &'static str = "Mailbox/get";
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
/*
|
||||
* meli - jmap module.
|
||||
*
|
||||
* Copyright 2017 - 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::*;
|
||||
|
||||
use crate::backends::BackendOp;
|
||||
use crate::error::Result;
|
||||
use std::cell::Cell;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
/// `BackendOp` implementor for Imap
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct JmapOp {
|
||||
hash: EnvelopeHash,
|
||||
connection: Arc<JmapConnection>,
|
||||
store: Arc<RwLock<Store>>,
|
||||
bytes: Option<String>,
|
||||
flags: Cell<Option<Flag>>,
|
||||
headers: Option<String>,
|
||||
body: Option<String>,
|
||||
}
|
||||
|
||||
impl JmapOp {
|
||||
pub fn new(
|
||||
hash: EnvelopeHash,
|
||||
connection: Arc<JmapConnection>,
|
||||
store: Arc<RwLock<Store>>,
|
||||
) -> Self {
|
||||
JmapOp {
|
||||
hash,
|
||||
connection,
|
||||
store,
|
||||
bytes: None,
|
||||
headers: None,
|
||||
body: None,
|
||||
flags: Cell::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BackendOp for JmapOp {
|
||||
fn description(&self) -> String {
|
||||
self.store
|
||||
.try_read()
|
||||
.and_then(|store_lck| Ok(store_lck.id_store[&self.hash].clone()))
|
||||
.unwrap_or(String::new())
|
||||
}
|
||||
|
||||
fn as_bytes(&mut self) -> Result<&[u8]> {
|
||||
if self.bytes.is_none() {
|
||||
let mut store_lck = self.store.write().unwrap();
|
||||
if !(store_lck.byte_cache.contains_key(&self.hash)
|
||||
&& store_lck.byte_cache[&self.hash].bytes.is_some())
|
||||
{
|
||||
let blob_id = &store_lck.blob_id_store[&self.hash];
|
||||
let res = self
|
||||
.connection
|
||||
.client
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&downloadRequestFormat(
|
||||
&self.connection.session,
|
||||
self.connection.mail_account_id(),
|
||||
blob_id,
|
||||
None,
|
||||
))
|
||||
.basic_auth(
|
||||
&self.connection.server_conf.server_username,
|
||||
Some(&self.connection.server_conf.server_password),
|
||||
)
|
||||
.send();
|
||||
|
||||
let res_text = res?.text()?;
|
||||
|
||||
store_lck.byte_cache.entry(self.hash).or_default().bytes = Some(res_text);
|
||||
}
|
||||
self.bytes = store_lck.byte_cache[&self.hash].bytes.clone();
|
||||
}
|
||||
Ok(&self.bytes.as_ref().unwrap().as_bytes())
|
||||
}
|
||||
|
||||
fn fetch_flags(&self) -> Flag {
|
||||
Flag::default()
|
||||
}
|
||||
|
||||
fn set_flag(&mut self, _envelope: &mut Envelope, _f: Flag, _value: bool) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_tag(&mut self, _envelope: &mut Envelope, _tag: String, value: bool) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,370 @@
|
|||
/*
|
||||
* 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::folder::JmapFolder;
|
||||
use super::*;
|
||||
use crate::structs::StackVec;
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::convert::TryFrom;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
pub type Id = String;
|
||||
pub type UtcDate = String;
|
||||
|
||||
use super::rfc8620::Object;
|
||||
|
||||
macro_rules! get_request_no {
|
||||
($lock:expr) => {{
|
||||
let mut lck = $lock.lock().unwrap();
|
||||
let ret = *lck;
|
||||
*lck += 1;
|
||||
ret
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! tag_hash {
|
||||
($t:ident) => {{
|
||||
let mut hasher = DefaultHasher::default();
|
||||
$t.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}};
|
||||
($t:literal) => {{
|
||||
let mut hasher = DefaultHasher::default();
|
||||
$t.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}};
|
||||
}
|
||||
|
||||
pub trait Response<OBJ: Object> {
|
||||
const NAME: &'static str;
|
||||
}
|
||||
|
||||
pub trait Method<OBJ: Object>: Serialize {
|
||||
const NAME: &'static str;
|
||||
}
|
||||
|
||||
macro_rules! get_path_hash {
|
||||
($path:expr) => {{
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = DefaultHasher::new();
|
||||
$path.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}};
|
||||
}
|
||||
|
||||
static USING: &'static [&'static str] = &["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail"];
|
||||
|
||||
#[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>,
|
||||
|
||||
#[serde(skip)]
|
||||
request_no: Arc<Mutex<usize>>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub fn new(request_no: Arc<Mutex<usize>>) -> Self {
|
||||
Request {
|
||||
using: USING,
|
||||
method_calls: Vec::new(),
|
||||
request_no,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_call<M: Method<O>, O: Object>(&mut self, call: &M) -> usize {
|
||||
let seq = get_request_no!(self.request_no);
|
||||
self.method_calls
|
||||
.push(serde_json::to_value((M::NAME, call, &format!("m{}", seq))).unwrap());
|
||||
seq
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_mailboxes(conn: &JmapConnection) -> Result<FnvHashMap<FolderHash, JmapFolder>> {
|
||||
let seq = get_request_no!(conn.request_no);
|
||||
let res = conn
|
||||
.client
|
||||
.lock()
|
||||
.unwrap()
|
||||
.post(&conn.session.api_url)
|
||||
.basic_auth(
|
||||
&conn.server_conf.server_username,
|
||||
Some(&conn.server_conf.server_password),
|
||||
)
|
||||
.json(&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()]],
|
||||
}))
|
||||
.send();
|
||||
|
||||
let res_text = res?.text()?;
|
||||
let mut v: MethodResponse = serde_json::from_str(&res_text).unwrap();
|
||||
*conn.online_status.lock().unwrap() = true;
|
||||
let m = GetResponse::<MailboxObject>::try_from(v.method_responses.remove(0))?;
|
||||
let GetResponse::<MailboxObject> {
|
||||
list, account_id, ..
|
||||
} = m;
|
||||
*conn.account_id.lock().unwrap() = account_id;
|
||||
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 = get_path_hash!(&name);
|
||||
(
|
||||
hash,
|
||||
JmapFolder {
|
||||
name: name.clone(),
|
||||
hash,
|
||||
path: name,
|
||||
v: Vec::new(),
|
||||
id,
|
||||
is_subscribed,
|
||||
my_rights,
|
||||
parent_id,
|
||||
role,
|
||||
usage: Default::default(),
|
||||
sort_order,
|
||||
total_emails,
|
||||
total_threads,
|
||||
unread_emails,
|
||||
unread_threads,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JsonResponse<'a> {
|
||||
#[serde(borrow)]
|
||||
method_responses: Vec<MethodResponse<'a>>,
|
||||
}
|
||||
|
||||
pub fn get_message_list(conn: &JmapConnection, folder: &JmapFolder) -> Result<Vec<String>> {
|
||||
let email_call: EmailQuery = EmailQuery::new(
|
||||
Query::new()
|
||||
.account_id(conn.mail_account_id().to_string())
|
||||
.filter(Some(
|
||||
EmailFilterCondition::new().in_mailbox(Some(folder.id.clone())),
|
||||
))
|
||||
.position(0),
|
||||
)
|
||||
.collapse_threads(false);
|
||||
|
||||
let mut req = Request::new(conn.request_no.clone());
|
||||
req.add_call(&email_call);
|
||||
|
||||
let res = conn
|
||||
.client
|
||||
.lock()
|
||||
.unwrap()
|
||||
.post(&conn.session.api_url)
|
||||
.basic_auth(
|
||||
&conn.server_conf.server_username,
|
||||
Some(&conn.server_conf.server_password),
|
||||
)
|
||||
.json(&req)
|
||||
.send();
|
||||
|
||||
let res_text = res?.text()?;
|
||||
let mut v: MethodResponse = serde_json::from_str(&res_text).unwrap();
|
||||
*conn.online_status.lock().unwrap() = true;
|
||||
let m = QueryResponse::<EmailObject>::try_from(v.method_responses.remove(0))?;
|
||||
let QueryResponse::<EmailObject> { ids, .. } = m;
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
pub fn get_message(conn: &JmapConnection, ids: &[String]) -> Result<Vec<Envelope>> {
|
||||
let email_call: EmailGet = EmailGet::new(
|
||||
Get::new()
|
||||
.ids(Some(JmapArgument::value(
|
||||
ids.iter().cloned().collect::<Vec<String>>(),
|
||||
)))
|
||||
.account_id(conn.mail_account_id().to_string()),
|
||||
);
|
||||
|
||||
let mut req = Request::new(conn.request_no.clone());
|
||||
req.add_call(&email_call);
|
||||
let res = conn
|
||||
.client
|
||||
.lock()
|
||||
.unwrap()
|
||||
.post(&conn.session.api_url)
|
||||
.basic_auth(
|
||||
&conn.server_conf.server_username,
|
||||
Some(&conn.server_conf.server_password),
|
||||
)
|
||||
.json(&req)
|
||||
.send();
|
||||
|
||||
let res_text = res?.text()?;
|
||||
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>>())
|
||||
}
|
||||
|
||||
pub fn get(
|
||||
conn: &JmapConnection,
|
||||
store: &Arc<RwLock<Store>>,
|
||||
tag_index: &Arc<RwLock<BTreeMap<u64, String>>>,
|
||||
folder: &JmapFolder,
|
||||
) -> Result<Vec<Envelope>> {
|
||||
let email_query_call: EmailQuery = EmailQuery::new(
|
||||
Query::new()
|
||||
.account_id(conn.mail_account_id().to_string())
|
||||
.filter(Some(
|
||||
EmailFilterCondition::new().in_mailbox(Some(folder.id.clone())),
|
||||
))
|
||||
.position(0),
|
||||
)
|
||||
.collapse_threads(false);
|
||||
|
||||
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,
|
||||
EmailQuery::RESULT_FIELD_IDS,
|
||||
)))
|
||||
.account_id(conn.mail_account_id().to_string()),
|
||||
);
|
||||
|
||||
req.add_call(&email_call);
|
||||
|
||||
let res = conn
|
||||
.client
|
||||
.lock()
|
||||
.unwrap()
|
||||
.post(&conn.session.api_url)
|
||||
.basic_auth(
|
||||
&conn.server_conf.server_username,
|
||||
Some(&conn.server_conf.server_password),
|
||||
)
|
||||
.json(&req)
|
||||
.send();
|
||||
|
||||
let res_text = res?.text()?;
|
||||
|
||||
let mut v: MethodResponse = serde_json::from_str(&res_text).unwrap();
|
||||
let e = GetResponse::<EmailObject>::try_from(v.method_responses.pop().unwrap())?;
|
||||
let GetResponse::<EmailObject> { list, state, .. } = e;
|
||||
{
|
||||
let mut states_lck = conn.method_call_states.lock().unwrap();
|
||||
|
||||
if let Some(prev_state) = states_lck.get_mut(&EmailGet::NAME) {
|
||||
debug!("{:?}: prev_state was {}", EmailGet::NAME, prev_state);
|
||||
|
||||
if *prev_state != state { /* FIXME Query Changes. */ }
|
||||
|
||||
*prev_state = state;
|
||||
debug!("{:?}: curr state is {}", EmailGet::NAME, prev_state);
|
||||
} else {
|
||||
debug!("{:?}: inserting state {}", EmailGet::NAME, &state);
|
||||
states_lck.insert(EmailGet::NAME, state);
|
||||
}
|
||||
}
|
||||
let mut tag_lck = tag_index.write().unwrap();
|
||||
let ids = list
|
||||
.iter()
|
||||
.map(|obj| {
|
||||
let tags = obj
|
||||
.keywords()
|
||||
.keys()
|
||||
.map(|tag| {
|
||||
let tag_hash = {
|
||||
let mut hasher = DefaultHasher::default();
|
||||
tag.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
};
|
||||
if !tag_lck.contains_key(&tag_hash) {
|
||||
tag_lck.insert(tag_hash, tag.to_string());
|
||||
}
|
||||
tag_hash
|
||||
})
|
||||
.collect::<StackVec<u64>>();
|
||||
(tags, obj.id.clone(), obj.blob_id.clone())
|
||||
})
|
||||
.collect::<Vec<(StackVec<u64>, Id, Id)>>();
|
||||
drop(tag_lck);
|
||||
let mut ret = list
|
||||
.into_iter()
|
||||
.map(std::convert::Into::into)
|
||||
.collect::<Vec<Envelope>>();
|
||||
|
||||
let mut store_lck = store.write().unwrap();
|
||||
debug_assert_eq!(tag_hash!("$draft"), 6613915297903591176);
|
||||
debug_assert_eq!(tag_hash!("$seen"), 1683863812294339685);
|
||||
debug_assert_eq!(tag_hash!("$flagged"), 2714010747478170100);
|
||||
debug_assert_eq!(tag_hash!("$answered"), 8940855303929342213);
|
||||
debug_assert_eq!(tag_hash!("$junk"), 2656839745430720464);
|
||||
debug_assert_eq!(tag_hash!("$notjunk"), 4091323799684325059);
|
||||
for (env, (tags, id, blob_id)) in ret.iter_mut().zip(ids.into_iter()) {
|
||||
store_lck.id_store.insert(env.hash(), id);
|
||||
store_lck.blob_id_store.insert(env.hash(), blob_id);
|
||||
for t in tags {
|
||||
match t {
|
||||
6613915297903591176 => {
|
||||
env.set_flags(env.flags() | Flag::DRAFT);
|
||||
}
|
||||
1683863812294339685 => {
|
||||
env.set_flags(env.flags() | Flag::SEEN);
|
||||
}
|
||||
2714010747478170100 => {
|
||||
env.set_flags(env.flags() | Flag::FLAGGED);
|
||||
}
|
||||
8940855303929342213 => {
|
||||
env.set_flags(env.flags() | Flag::REPLIED);
|
||||
}
|
||||
2656839745430720464 | 4091323799684325059 => { /* ignore */ }
|
||||
_ => env.labels_mut().push(t),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(ret)
|
||||
}
|
|
@ -0,0 +1,544 @@
|
|||
/*
|
||||
* 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::Id;
|
||||
use crate::email::parser::BytesExt;
|
||||
use core::marker::PhantomData;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::ser::{Serialize, SerializeStruct, Serializer};
|
||||
use serde_json::{value::RawValue, Value};
|
||||
|
||||
mod filters;
|
||||
pub use filters::*;
|
||||
mod comparator;
|
||||
pub use comparator::*;
|
||||
mod argument;
|
||||
pub use argument::*;
|
||||
|
||||
use super::protocol::Method;
|
||||
use std::collections::HashMap;
|
||||
pub trait Object {
|
||||
const NAME: &'static str;
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JmapSession {
|
||||
pub capabilities: HashMap<String, CapabilitiesObject>,
|
||||
pub accounts: HashMap<Id, Account>,
|
||||
pub primary_accounts: HashMap<String, Id>,
|
||||
pub username: String,
|
||||
pub api_url: String,
|
||||
pub download_url: String,
|
||||
|
||||
pub upload_url: String,
|
||||
pub event_source_url: String,
|
||||
pub state: String,
|
||||
#[serde(flatten)]
|
||||
pub extra_properties: HashMap<String, Value>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CapabilitiesObject {
|
||||
#[serde(default)]
|
||||
max_size_upload: u64,
|
||||
#[serde(default)]
|
||||
max_concurrent_upload: u64,
|
||||
#[serde(default)]
|
||||
max_size_request: u64,
|
||||
#[serde(default)]
|
||||
max_concurrent_requests: u64,
|
||||
#[serde(default)]
|
||||
max_calls_in_request: u64,
|
||||
#[serde(default)]
|
||||
max_objects_in_get: u64,
|
||||
#[serde(default)]
|
||||
max_objects_in_set: u64,
|
||||
#[serde(default)]
|
||||
collation_algorithms: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Account {
|
||||
name: String,
|
||||
is_personal: bool,
|
||||
is_read_only: bool,
|
||||
account_capabilities: HashMap<String, Value>,
|
||||
#[serde(flatten)]
|
||||
extra_properties: HashMap<String, Value>,
|
||||
}
|
||||
|
||||
/// #`get`
|
||||
///
|
||||
/// Objects of type `Foo` are fetched via a call to `Foo/get`.
|
||||
///
|
||||
/// It takes the following arguments:
|
||||
///
|
||||
/// - `account_id`: "Id"
|
||||
///
|
||||
/// The id of the account to use.
|
||||
///
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Get<OBJ: Object>
|
||||
where
|
||||
OBJ: std::fmt::Debug + Serialize,
|
||||
{
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub account_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(flatten)]
|
||||
pub ids: Option<JmapArgument<Vec<String>>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub properties: Option<Vec<String>>,
|
||||
#[serde(skip)]
|
||||
_ph: PhantomData<*const OBJ>,
|
||||
}
|
||||
|
||||
impl<OBJ: Object> Get<OBJ>
|
||||
where
|
||||
OBJ: std::fmt::Debug + Serialize,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
account_id: String::new(),
|
||||
ids: None,
|
||||
properties: None,
|
||||
_ph: PhantomData,
|
||||
}
|
||||
}
|
||||
_impl!(
|
||||
/// - accountId: "Id"
|
||||
///
|
||||
/// The id of the account to use.
|
||||
///
|
||||
account_id: String
|
||||
);
|
||||
_impl!(
|
||||
/// - ids: `Option<JmapArgument<Vec<String>>>`
|
||||
///
|
||||
/// The ids of the Foo objects to return. If `None`, then *all* records
|
||||
/// of the data type are returned, if this is supported for that data
|
||||
/// type and the number of records does not exceed the
|
||||
/// "max_objects_in_get" limit.
|
||||
///
|
||||
ids: Option<JmapArgument<Vec<String>>>
|
||||
);
|
||||
_impl!(
|
||||
/// - properties: Option<Vec<String>>
|
||||
///
|
||||
/// If supplied, only the properties listed in the array are returned
|
||||
/// for each `Foo` object. If `None`, all properties of the object are
|
||||
/// returned. The `id` property of the object is *always* returned,
|
||||
/// even if not explicitly requested. If an invalid property is
|
||||
/// requested, the call WILL be rejected with an "invalid_arguments"
|
||||
/// error.
|
||||
properties: Option<Vec<String>>
|
||||
);
|
||||
}
|
||||
|
||||
impl<OBJ: Object + Serialize + std::fmt::Debug> Serialize for Get<OBJ> {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let mut fields_no = 0;
|
||||
if !self.account_id.is_empty() {
|
||||
fields_no += 1;
|
||||
}
|
||||
if !self.ids.is_none() {
|
||||
fields_no += 1;
|
||||
}
|
||||
if !self.properties.is_none() {
|
||||
fields_no += 1;
|
||||
}
|
||||
|
||||
let mut state = serializer.serialize_struct("Get", fields_no)?;
|
||||
if !self.account_id.is_empty() {
|
||||
state.serialize_field("accountId", &self.account_id)?;
|
||||
}
|
||||
match self.ids.as_ref() {
|
||||
None => {}
|
||||
Some(JmapArgument::Value(ref v)) => state.serialize_field("ids", v)?,
|
||||
Some(JmapArgument::ResultReference {
|
||||
ref result_of,
|
||||
ref name,
|
||||
ref path,
|
||||
}) => {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct A<'a> {
|
||||
result_of: &'a str,
|
||||
name: &'a str,
|
||||
path: &'a str,
|
||||
}
|
||||
|
||||
state.serialize_field(
|
||||
"#ids",
|
||||
&A {
|
||||
result_of,
|
||||
name,
|
||||
path,
|
||||
},
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
if !self.properties.is_none() {
|
||||
state.serialize_field("properties", self.properties.as_ref().unwrap())?;
|
||||
}
|
||||
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MethodResponse<'a> {
|
||||
#[serde(borrow)]
|
||||
pub method_responses: Vec<&'a RawValue>,
|
||||
#[serde(default)]
|
||||
pub created_ids: HashMap<Id, Id>,
|
||||
#[serde(default)]
|
||||
pub session_state: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GetResponse<OBJ: Object> {
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub account_id: String,
|
||||
#[serde(default)]
|
||||
pub state: String,
|
||||
pub list: Vec<OBJ>,
|
||||
pub not_found: Vec<String>,
|
||||
}
|
||||
|
||||
impl<OBJ: Object + DeserializeOwned> std::convert::TryFrom<&RawValue> for GetResponse<OBJ> {
|
||||
type Error = crate::error::MeliError;
|
||||
fn try_from(t: &RawValue) -> Result<GetResponse<OBJ>, crate::error::MeliError> {
|
||||
let res: (String, GetResponse<OBJ>, String) = serde_json::from_str(t.get())?;
|
||||
assert_eq!(&res.0, &format!("{}/get", OBJ::NAME));
|
||||
Ok(res.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl<OBJ: Object> GetResponse<OBJ> {
|
||||
_impl!(get_mut account_id_mut, account_id: String);
|
||||
_impl!(get_mut state_mut, state: String);
|
||||
_impl!(get_mut list_mut, list: Vec<OBJ>);
|
||||
_impl!(get_mut not_found_mut, not_found: Vec<String>);
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
enum JmapError {
|
||||
RequestTooLarge,
|
||||
InvalidArguments,
|
||||
InvalidResultReference,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Query<F: FilterTrait<OBJ>, OBJ: Object>
|
||||
where
|
||||
OBJ: std::fmt::Debug + Serialize,
|
||||
{
|
||||
account_id: String,
|
||||
filter: Option<F>,
|
||||
sort: Option<Comparator<OBJ>>,
|
||||
#[serde(default)]
|
||||
position: u64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
anchor: Option<String>,
|
||||
#[serde(default)]
|
||||
#[serde(skip_serializing_if = "u64_zero")]
|
||||
anchor_offset: u64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
limit: Option<u64>,
|
||||
#[serde(default = "bool_false")]
|
||||
calculate_total: bool,
|
||||
#[serde(skip)]
|
||||
_ph: PhantomData<*const OBJ>,
|
||||
}
|
||||
|
||||
impl<F: FilterTrait<OBJ>, OBJ: Object> Query<F, OBJ>
|
||||
where
|
||||
OBJ: std::fmt::Debug + Serialize,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
account_id: String::new(),
|
||||
filter: None,
|
||||
sort: None,
|
||||
position: 0,
|
||||
anchor: None,
|
||||
anchor_offset: 0,
|
||||
limit: None,
|
||||
calculate_total: false,
|
||||
_ph: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
_impl!(account_id: String);
|
||||
_impl!(filter: Option<F>);
|
||||
_impl!(sort: Option<Comparator<OBJ>>);
|
||||
_impl!(position: u64);
|
||||
_impl!(anchor: Option<String>);
|
||||
_impl!(anchor_offset: u64);
|
||||
_impl!(limit: Option<u64>);
|
||||
_impl!(calculate_total: bool);
|
||||
}
|
||||
|
||||
pub fn u64_zero(num: &u64) -> bool {
|
||||
*num == 0
|
||||
}
|
||||
|
||||
pub fn bool_false() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn bool_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct QueryResponse<OBJ: Object> {
|
||||
#[serde(skip_serializing_if = "String::is_empty", default)]
|
||||
pub account_id: String,
|
||||
pub query_state: String,
|
||||
pub can_calculate_changes: bool,
|
||||
pub position: u64,
|
||||
pub ids: Vec<Id>,
|
||||
#[serde(default)]
|
||||
pub total: u64,
|
||||
#[serde(default)]
|
||||
pub limit: u64,
|
||||
#[serde(skip)]
|
||||
_ph: PhantomData<*const OBJ>,
|
||||
}
|
||||
|
||||
impl<OBJ: Object + DeserializeOwned> std::convert::TryFrom<&RawValue> for QueryResponse<OBJ> {
|
||||
type Error = crate::error::MeliError;
|
||||
fn try_from(t: &RawValue) -> Result<QueryResponse<OBJ>, crate::error::MeliError> {
|
||||
let res: (String, QueryResponse<OBJ>, String) = serde_json::from_str(t.get())?;
|
||||
assert_eq!(&res.0, &format!("{}/query", OBJ::NAME));
|
||||
Ok(res.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl<OBJ: Object> QueryResponse<OBJ> {
|
||||
_impl!(get_mut ids_mut, ids: Vec<Id>);
|
||||
}
|
||||
|
||||
pub struct ResultField<M: Method<OBJ>, OBJ: Object> {
|
||||
pub field: &'static str,
|
||||
pub _ph: PhantomData<*const (OBJ, M)>,
|
||||
}
|
||||
|
||||
// error[E0723]: trait bounds other than `Sized` on const fn parameters are unstable
|
||||
// --> melib/src/backends/jmap/rfc8620.rs:626:6
|
||||
// |
|
||||
// 626 | impl<M: Method<OBJ>, OBJ: Object> ResultField<M, OBJ> {
|
||||
// | ^
|
||||
// |
|
||||
// = note: for more information, see issue https://github.com/rust-lang/rust/issues/57563
|
||||
// = help: add `#![feature(const_fn)]` to the crate attributes to enable
|
||||
// impl<M: Method<OBJ>, OBJ: Object> ResultField<M, OBJ> {
|
||||
// pub const fn new(field: &'static str) -> Self {
|
||||
// Self {
|
||||
// field,
|
||||
// _ph: PhantomData,
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
/// #`changes`
|
||||
///
|
||||
/// The "Foo/changes" method allows a client to efficiently update the state of its Foo cache
|
||||
/// to match the new state on the server. It takes the following arguments:
|
||||
///
|
||||
/// - accountId: "Id" The id of the account to use.
|
||||
/// - sinceState: "String"
|
||||
/// The current state of the client. This is the string that was
|
||||
/// returned as the "state" argument in the "Foo/get" response. The
|
||||
/// server will return the changes that have occurred since this
|
||||
/// state.
|
||||
///
|
||||
/// - maxChanges: "UnsignedInt|null"
|
||||
/// The maximum number of ids to return in the response. The server
|
||||
/// MAY choose to return fewer than this value but MUST NOT return
|
||||
/// more. If not given by the client, the server may choose how many
|
||||
/// to return. If supplied by the client, the value MUST be a
|
||||
/// positive integer greater than 0. If a value outside of this range
|
||||
/// is given, the server MUST re
|
||||
///
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
/* ch-ch-ch-ch-ch-Changes */
|
||||
pub struct Changes<OBJ: Object>
|
||||
where
|
||||
OBJ: std::fmt::Debug + Serialize,
|
||||
{
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub account_id: String,
|
||||
pub since_state: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub max_changes: Option<u64>,
|
||||
#[serde(skip)]
|
||||
_ph: PhantomData<*const OBJ>,
|
||||
}
|
||||
|
||||
impl<OBJ: Object> Changes<OBJ>
|
||||
where
|
||||
OBJ: std::fmt::Debug + Serialize,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
account_id: String::new(),
|
||||
since_state: String::new(),
|
||||
max_changes: None,
|
||||
_ph: PhantomData,
|
||||
}
|
||||
}
|
||||
_impl!(
|
||||
/// - accountId: "Id"
|
||||
///
|
||||
/// The id of the account to use.
|
||||
///
|
||||
account_id: String
|
||||
);
|
||||
_impl!(
|
||||
/// - since_state: "String"
|
||||
/// The current state of the client. This is the string that was
|
||||
/// returned as the "state" argument in the "Foo/get" response. The
|
||||
/// server will return the changes that have occurred since this
|
||||
/// state.
|
||||
///
|
||||
///
|
||||
since_state: String
|
||||
);
|
||||
_impl!(
|
||||
/// - max_changes: "UnsignedInt|null"
|
||||
/// The maximum number of ids to return in the response. The server
|
||||
/// MAY choose to return fewer than this value but MUST NOT return
|
||||
/// more. If not given by the client, the server may choose how many
|
||||
/// to return. If supplied by the client, the value MUST be a
|
||||
/// positive integer greater than 0. If a value outside of this range
|
||||
/// is given, the server MUST re
|
||||
max_changes: Option<u64>
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ChangesResponse<OBJ: Object> {
|
||||
#[serde(skip_serializing_if = "String::is_empty")]
|
||||
pub account_id: String,
|
||||
pub old_state: String,
|
||||
pub new_state: String,
|
||||
pub has_more_changes: bool,
|
||||
pub created: Vec<Id>,
|
||||
pub updated: Vec<Id>,
|
||||
pub destroyed: Vec<Id>,
|
||||
#[serde(skip)]
|
||||
_ph: PhantomData<*const OBJ>,
|
||||
}
|
||||
|
||||
impl<OBJ: Object + DeserializeOwned> std::convert::TryFrom<&RawValue> for ChangesResponse<OBJ> {
|
||||
type Error = crate::error::MeliError;
|
||||
fn try_from(t: &RawValue) -> Result<ChangesResponse<OBJ>, crate::error::MeliError> {
|
||||
let res: (String, ChangesResponse<OBJ>, String) = serde_json::from_str(t.get())?;
|
||||
assert_eq!(&res.0, &format!("{}/changes", OBJ::NAME));
|
||||
Ok(res.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl<OBJ: Object> ChangesResponse<OBJ> {
|
||||
_impl!(get_mut account_id_mut, account_id: String);
|
||||
_impl!(get_mut old_state_mut, old_state: String);
|
||||
_impl!(get_mut new_state_mut, new_state: String);
|
||||
_impl!(get has_more_changes, has_more_changes: bool);
|
||||
_impl!(get_mut created_mut, created: Vec<String>);
|
||||
_impl!(get_mut updated_mut, updated: Vec<String>);
|
||||
_impl!(get_mut destroyed_mut, destroyed: Vec<String>);
|
||||
}
|
||||
|
||||
pub fn downloadRequestFormat(
|
||||
session: &JmapSession,
|
||||
account_id: &Id,
|
||||
blob_id: &Id,
|
||||
name: Option<String>,
|
||||
) -> String {
|
||||
// https://jmap.fastmail.com/download/{accountId}/{blobId}/{name}
|
||||
let mut ret = String::with_capacity(
|
||||
session.download_url.len()
|
||||
+ blob_id.len()
|
||||
+ name.as_ref().map(|n| n.len()).unwrap_or(0)
|
||||
+ account_id.len(),
|
||||
);
|
||||
let mut prev_pos = 0;
|
||||
|
||||
while let Some(pos) = session.download_url.as_bytes()[prev_pos..].find(b"{") {
|
||||
ret.push_str(&session.download_url[prev_pos..prev_pos + pos]);
|
||||
prev_pos += pos;
|
||||
if session.download_url[prev_pos..].starts_with("{accountId}") {
|
||||
ret.push_str(account_id);
|
||||
prev_pos += "{accountId}".len();
|
||||
} else if session.download_url[prev_pos..].starts_with("{blobId}") {
|
||||
ret.push_str(blob_id);
|
||||
prev_pos += "{blobId}".len();
|
||||
} else if session.download_url[prev_pos..].starts_with("{name}") {
|
||||
ret.push_str(name.as_ref().map(String::as_str).unwrap_or(""));
|
||||
prev_pos += "{name}".len();
|
||||
}
|
||||
}
|
||||
if prev_pos != session.download_url.len() {
|
||||
ret.push_str(&session.download_url[prev_pos..]);
|
||||
}
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn uploadRequestFormat(session: &JmapSession, account_id: &Id) -> String {
|
||||
//"uploadUrl": "https://jmap.fastmail.com/upload/{accountId}/",
|
||||
let mut ret = String::with_capacity(session.upload_url.len() + account_id.len());
|
||||
let mut prev_pos = 0;
|
||||
|
||||
while let Some(pos) = session.upload_url.as_bytes()[prev_pos..].find(b"{") {
|
||||
ret.push_str(&session.upload_url[prev_pos..prev_pos + pos]);
|
||||
prev_pos += pos;
|
||||
if session.upload_url[prev_pos..].starts_with("{accountId}") {
|
||||
ret.push_str(account_id);
|
||||
prev_pos += "{accountId}".len();
|
||||
break;
|
||||
} else {
|
||||
ret.push('{');
|
||||
prev_pos += 1;
|
||||
}
|
||||
}
|
||||
if prev_pos != session.upload_url.len() {
|
||||
ret.push_str(&session.upload_url[prev_pos..]);
|
||||
}
|
||||
ret
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
/*
|
||||
* 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 crate::backends::jmap::protocol::Method;
|
||||
use crate::backends::jmap::rfc8620::Object;
|
||||
use crate::backends::jmap::rfc8620::ResultField;
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum JmapArgument<T> {
|
||||
Value(T),
|
||||
ResultReference {
|
||||
result_of: String,
|
||||
name: String,
|
||||
path: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl<T> JmapArgument<T> {
|
||||
pub fn value(v: T) -> Self {
|
||||
JmapArgument::Value(v)
|
||||
}
|
||||
|
||||
pub fn reference<M, OBJ>(result_of: usize, path: ResultField<M, OBJ>) -> Self
|
||||
where
|
||||
M: Method<OBJ>,
|
||||
OBJ: Object,
|
||||
{
|
||||
JmapArgument::ResultReference {
|
||||
result_of: format!("m{}", result_of),
|
||||
name: M::NAME.to_string(),
|
||||
path: path.field.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,61 @@
|
|||
/*
|
||||
* 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::*;
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Comparator<OBJ: Object> {
|
||||
property: String,
|
||||
#[serde(default = "bool_true")]
|
||||
is_ascending: bool,
|
||||
//FIXME
|
||||
collation: Option<String>,
|
||||
//#[serde(flatten)]
|
||||
additional_properties: Vec<String>,
|
||||
|
||||
_ph: PhantomData<*const OBJ>,
|
||||
}
|
||||
|
||||
impl<OBJ: Object> Comparator<OBJ> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
property: String::new(),
|
||||
is_ascending: true,
|
||||
collation: None,
|
||||
additional_properties: Vec::new(),
|
||||
_ph: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
_impl!(property: String);
|
||||
_impl!(is_ascending: bool);
|
||||
_impl!(collation: Option<String>);
|
||||
_impl!(additional_properties: Vec<String>);
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
pub enum FilterOperator {
|
||||
And,
|
||||
Or,
|
||||
Not,
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
/*
|
||||
* 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::*;
|
||||
|
||||
pub trait FilterTrait<T> {}
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(untagged)]
|
||||
pub enum Filter<F: FilterTrait<OBJ>, OBJ: Object> {
|
||||
Operator {
|
||||
operator: FilterOperator,
|
||||
conditions: Vec<Filter<F, OBJ>>,
|
||||
},
|
||||
Condition(FilterCondition<F, OBJ>),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct FilterCondition<F: FilterTrait<OBJ>, OBJ: Object> {
|
||||
#[serde(flatten)]
|
||||
cond: F,
|
||||
#[serde(skip)]
|
||||
_ph: PhantomData<*const OBJ>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
pub enum FilterOperator {
|
||||
And,
|
||||
Or,
|
||||
Not,
|
||||
}
|
|
@ -125,7 +125,7 @@ pub struct Envelope {
|
|||
subject: Option<String>,
|
||||
message_id: MessageID,
|
||||
in_reply_to: Option<MessageID>,
|
||||
references: Option<References>,
|
||||
pub references: Option<References>,
|
||||
other_headers: FnvHashMap<String, String>,
|
||||
|
||||
timestamp: UnixTimestamp,
|
||||
|
@ -490,14 +490,14 @@ impl Envelope {
|
|||
self.subject = Some(new_val);
|
||||
}
|
||||
pub fn set_message_id(&mut self, new_val: &[u8]) {
|
||||
let slice = match parser::message_id(new_val).to_full_result() {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
debug!(e);
|
||||
return;
|
||||
match parser::message_id(new_val).to_full_result() {
|
||||
Ok(slice) => {
|
||||
self.message_id = MessageID::new(new_val, slice);
|
||||
}
|
||||
};
|
||||
self.message_id = MessageID::new(new_val, slice);
|
||||
Err(_) => {
|
||||
self.message_id = MessageID::new(new_val, new_val);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn push_references(&mut self, new_val: &[u8]) {
|
||||
let slice = match parser::message_id(new_val).to_full_result() {
|
||||
|
@ -557,6 +557,7 @@ impl Envelope {
|
|||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn other_headers(&self) -> &FnvHashMap<String, String> {
|
||||
&self.other_headers
|
||||
}
|
||||
|
|
|
@ -257,3 +257,34 @@ impl fmt::Debug for References {
|
|||
write!(f, "{:#?}", self.refs)
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! make_address {
|
||||
($d:expr, $a:expr) => {
|
||||
Address::Mailbox(if $d.is_empty() {
|
||||
MailboxAddress {
|
||||
raw: format!("{}", $a).into_bytes(),
|
||||
display_name: StrBuilder {
|
||||
offset: 0,
|
||||
length: 0,
|
||||
},
|
||||
address_spec: StrBuilder {
|
||||
offset: 0,
|
||||
length: $a.len(),
|
||||
},
|
||||
}
|
||||
} else {
|
||||
MailboxAddress {
|
||||
raw: format!("{} <{}>", $d, $a).into_bytes(),
|
||||
display_name: StrBuilder {
|
||||
offset: 0,
|
||||
length: $d.len(),
|
||||
},
|
||||
address_spec: StrBuilder {
|
||||
offset: $d.len() + 2,
|
||||
length: $a.len(),
|
||||
},
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
|
|
|
@ -1102,36 +1102,6 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
macro_rules! make_address {
|
||||
($d:literal, $a:literal) => {
|
||||
Address::Mailbox(if $d.is_empty() {
|
||||
MailboxAddress {
|
||||
raw: format!("<{}>", $a).into_bytes(),
|
||||
display_name: StrBuilder {
|
||||
offset: 0,
|
||||
length: 0,
|
||||
},
|
||||
address_spec: StrBuilder {
|
||||
offset: 1,
|
||||
length: $a.len(),
|
||||
},
|
||||
}
|
||||
} else {
|
||||
MailboxAddress {
|
||||
raw: format!("{} <{}>", $d, $a).into_bytes(),
|
||||
display_name: StrBuilder {
|
||||
offset: 0,
|
||||
length: $d.len(),
|
||||
},
|
||||
address_spec: StrBuilder {
|
||||
offset: $d.len() + 2,
|
||||
length: $a.len(),
|
||||
},
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_address_list() {
|
||||
let s = b"Obit Oppidum <user@domain>,
|
||||
|
|
|
@ -151,6 +151,22 @@ impl From<std::num::ParseIntError> for MeliError {
|
|||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "jmap_backend")]
|
||||
impl From<reqwest::Error> for MeliError {
|
||||
#[inline]
|
||||
fn from(kind: reqwest::Error) -> MeliError {
|
||||
MeliError::new(format!("{}", kind))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "jmap_backend")]
|
||||
impl From<serde_json::error::Error> for MeliError {
|
||||
#[inline]
|
||||
fn from(kind: serde_json::error::Error) -> MeliError {
|
||||
MeliError::new(format!("{}", kind))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for MeliError {
|
||||
#[inline]
|
||||
fn from(kind: &str) -> MeliError {
|
||||
|
|
|
@ -182,7 +182,8 @@ impl From<FileAccount> for AccountConf {
|
|||
.split(if s.contains('/') { '/' } else { '.' })
|
||||
.last()
|
||||
.unwrap_or("");
|
||||
folder_confs.get_mut(s).unwrap().folder_conf.usage = usage(name);
|
||||
folder_confs.get_mut(s).unwrap().folder_conf.usage =
|
||||
SpecialUsageMailbox::detect_usage(name);
|
||||
}
|
||||
|
||||
if folder_confs[s].folder_conf().ignore.is_unset() {
|
||||
|
@ -564,26 +565,6 @@ impl Serialize for CacheType {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn usage(name: &str) -> Option<SpecialUsageMailbox> {
|
||||
if name.eq_ignore_ascii_case("inbox") {
|
||||
Some(SpecialUsageMailbox::Inbox)
|
||||
} else if name.eq_ignore_ascii_case("archive") {
|
||||
Some(SpecialUsageMailbox::Archive)
|
||||
} else if name.eq_ignore_ascii_case("drafts") {
|
||||
Some(SpecialUsageMailbox::Drafts)
|
||||
} else if name.eq_ignore_ascii_case("junk") {
|
||||
Some(SpecialUsageMailbox::Junk)
|
||||
} else if name.eq_ignore_ascii_case("spam") {
|
||||
Some(SpecialUsageMailbox::Junk)
|
||||
} else if name.eq_ignore_ascii_case("sent") {
|
||||
Some(SpecialUsageMailbox::Sent)
|
||||
} else if name.eq_ignore_ascii_case("trash") {
|
||||
Some(SpecialUsageMailbox::Trash)
|
||||
} else {
|
||||
Some(SpecialUsageMailbox::Normal)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_config_file(p: &Path) -> Result<()> {
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
|
|
|
@ -353,7 +353,7 @@ impl Account {
|
|||
} else {
|
||||
let mut new = FileFolderConf::default();
|
||||
new.folder_conf.subscribe = super::ToggleFlag::InternalVal(true);
|
||||
new.folder_conf.usage = super::usage(f.name());
|
||||
new.folder_conf.usage = SpecialUsageMailbox::detect_usage(f.name());
|
||||
folder_confs.insert(f.hash(), new);
|
||||
}
|
||||
folder_names.insert(f.hash(), f.path().to_string());
|
||||
|
|
Loading…
Reference in New Issue