/*
* meli - notmuch backend
*
* Copyright 2019 - 2020 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 .
*/
use crate::backends::*;
use crate::conf::AccountSettings;
use crate::email::{Envelope, EnvelopeHash, Flag};
use crate::error::{MeliError, Result, ResultIntoMeliError};
use crate::shellexpand::ShellExpandTrait;
use smallvec::SmallVec;
use std::collections::{
hash_map::{DefaultHasher, HashMap},
BTreeMap,
};
use std::error::Error;
use std::ffi::{CStr, CString, OsStr};
use std::hash::{Hash, Hasher};
use std::io::Read;
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};
macro_rules! call {
($lib:expr, $func:ty) => {{
let func: libloading::Symbol<$func> = $lib.get(stringify!($func).as_bytes()).unwrap();
func
}};
}
macro_rules! try_call {
($lib:expr, $call:expr) => {{
let status = $call;
if status == _notmuch_status_NOTMUCH_STATUS_SUCCESS {
Ok(())
} else {
let c_str = call!($lib, notmuch_status_to_string)(status);
Err(NotmuchError(
CStr::from_ptr(c_str).to_string_lossy().into_owned(),
))
}
}};
}
pub mod bindings;
use bindings::*;
mod message;
pub use message::*;
mod tags;
pub use tags::*;
mod thread;
pub use thread::*;
#[derive(Debug)]
pub struct DbConnection {
pub lib: Arc,
pub inner: Arc>,
pub revision_uuid: Arc>,
pub database_ph: std::marker::PhantomData<&'static mut notmuch_database_t>,
}
impl DbConnection {
pub fn get_revision_uuid(&self) -> u64 {
unsafe {
call!(self.lib, notmuch_database_get_revision)(
*self.inner.read().unwrap(),
std::ptr::null_mut(),
)
}
}
fn refresh(
&mut self,
mailboxes: Arc>>,
index: Arc>>,
mailbox_index: Arc>>>,
tag_index: Arc>>,
account_hash: AccountHash,
event_consumer: BackendEventConsumer,
new_revision_uuid: u64,
) -> Result<()> {
use RefreshEventKind::*;
let query_str = format!(
"lastmod:{}..{}",
*self.revision_uuid.read().unwrap(),
new_revision_uuid
);
let query: Query = Query::new(self.lib.clone(), &self, &query_str)?;
let iter = query.search()?;
let mailbox_index_lck = mailbox_index.write().unwrap();
let mailboxes_lck = mailboxes.read().unwrap();
for message in iter {
let env_hash = message.env_hash();
if let Some(mailbox_hashes) = mailbox_index_lck.get(&env_hash) {
let tags: (Flag, Vec) = message.tags().collect_flags_and_tags();
let mut tag_lock = tag_index.write().unwrap();
for tag in tags.1.iter() {
let mut hasher = DefaultHasher::new();
hasher.write(tag.as_bytes());
let num = hasher.finish();
if !tag_lock.contains_key(&num) {
tag_lock.insert(num, tag.clone());
}
}
for &mailbox_hash in mailbox_hashes {
(event_consumer)(
account_hash,
BackendEvent::Refresh(RefreshEvent {
account_hash,
mailbox_hash,
kind: NewFlags(env_hash, tags.clone()),
}),
);
}
} else {
let message_id = message.msg_id_cstr().to_string_lossy().to_string();
match message.into_envelope(index.clone(), tag_index.clone()) {
Ok(env) => {
for (&mailbox_hash, m) in mailboxes_lck.iter() {
let query_str = format!("{} id:{}", m.query_str.as_str(), &message_id);
let query: Query = Query::new(self.lib.clone(), self, &query_str)?;
if query.count().unwrap_or(0) > 0 {
let mut total_lck = m.total.lock().unwrap();
let mut unseen_lck = m.unseen.lock().unwrap();
*total_lck += 1;
if !env.is_seen() {
*unseen_lck += 1;
}
(event_consumer)(
account_hash,
BackendEvent::Refresh(RefreshEvent {
account_hash,
mailbox_hash,
kind: Create(Box::new(env.clone())),
}),
);
}
}
}
Err(err) => {
debug!("could not parse message {:?}", err);
}
}
}
}
drop(query);
index.write().unwrap().retain(|&env_hash, msg_id| {
if Message::find_message(&self, &msg_id).is_err() {
if let Some(mailbox_hashes) = mailbox_index_lck.get(&env_hash) {
for &mailbox_hash in mailbox_hashes {
let m = &mailboxes_lck[&mailbox_hash];
let mut total_lck = m.total.lock().unwrap();
*total_lck = total_lck.saturating_sub(1);
(event_consumer)(
account_hash,
BackendEvent::Refresh(RefreshEvent {
account_hash,
mailbox_hash,
kind: Remove(env_hash),
}),
);
}
}
false
} else {
true
}
});
Ok(())
}
}
unsafe impl Send for DbConnection {}
unsafe impl Sync for DbConnection {}
#[derive(Debug)]
pub struct NotmuchError(String);
impl std::fmt::Display for NotmuchError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
impl Error for NotmuchError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
None
}
}
impl Drop for DbConnection {
fn drop(&mut self) {
let inner = self.inner.write().unwrap();
unsafe {
if let Err(err) = try_call!(self.lib, call!(self.lib, notmuch_database_close)(*inner)) {
debug!(err);
return;
}
if let Err(err) = try_call!(self.lib, call!(self.lib, notmuch_database_destroy)(*inner))
{
debug!(err);
}
}
}
}
#[derive(Debug)]
pub struct NotmuchDb {
lib: Arc,
revision_uuid: Arc>,
mailboxes: Arc>>,
index: Arc>>,
mailbox_index: Arc>>>,
tag_index: Arc>>,
path: PathBuf,
account_name: Arc,
event_consumer: BackendEventConsumer,
save_messages_to: Option,
}
unsafe impl Send for NotmuchDb {}
unsafe impl Sync for NotmuchDb {}
#[derive(Debug, Clone, Default)]
struct NotmuchMailbox {
hash: MailboxHash,
children: Vec,
parent: Option,
name: String,
path: String,
query_str: String,
usage: Arc>,
total: Arc>,
unseen: Arc>,
}
impl BackendMailbox for NotmuchMailbox {
fn hash(&self) -> MailboxHash {
self.hash
}
fn name(&self) -> &str {
self.name.as_str()
}
fn path(&self) -> &str {
self.path.as_str()
}
fn change_name(&mut self, _s: &str) {}
fn clone(&self) -> Mailbox {
Box::new(std::clone::Clone::clone(self))
}
fn children(&self) -> &[MailboxHash] {
&self.children
}
fn parent(&self) -> Option {
self.parent
}
fn special_usage(&self) -> SpecialUsageMailbox {
*self.usage.read().unwrap()
}
fn permissions(&self) -> MailboxPermissions {
MailboxPermissions::default()
}
fn is_subscribed(&self) -> bool {
true
}
fn set_is_subscribed(&mut self, _new_val: bool) -> Result<()> {
Ok(())
}
fn set_special_usage(&mut self, new_val: SpecialUsageMailbox) -> Result<()> {
*self.usage.write()? = new_val;
Ok(())
}
fn count(&self) -> Result<(usize, usize)> {
Ok((*self.unseen.lock()?, *self.total.lock()?))
}
}
unsafe impl Send for NotmuchMailbox {}
unsafe impl Sync for NotmuchMailbox {}
impl NotmuchDb {
pub fn new(
s: &AccountSettings,
_is_subscribed: Box bool>,
event_consumer: BackendEventConsumer,
) -> Result> {
let lib = Arc::new(libloading::Library::new("libnotmuch.so.5")?);
let path = Path::new(s.root_mailbox.as_str()).expand();
if !path.exists() {
return Err(MeliError::new(format!(
"\"root_mailbox\" {} for account {} is not a valid path.",
s.root_mailbox.as_str(),
s.name()
)));
}
let mut mailboxes = HashMap::default();
for (k, f) in s.mailboxes.iter() {
if let Some(query_str) = f.extra.get("query") {
let hash = {
let mut h = DefaultHasher::new();
k.hash(&mut h);
h.finish()
};
mailboxes.insert(
hash,
NotmuchMailbox {
hash,
name: k.to_string(),
path: k.to_string(),
children: vec![],
parent: None,
query_str: query_str.to_string(),
usage: Arc::new(RwLock::new(SpecialUsageMailbox::Normal)),
total: Arc::new(Mutex::new(0)),
unseen: Arc::new(Mutex::new(0)),
},
);
} else {
return Err(MeliError::new(format!(
"notmuch mailbox configuration entry \"{}\" should have a \"query\" value set.",
k
)));
}
}
Ok(Box::new(NotmuchDb {
lib,
revision_uuid: Arc::new(RwLock::new(0)),
path,
index: Arc::new(RwLock::new(Default::default())),
mailbox_index: Arc::new(RwLock::new(Default::default())),
tag_index: Arc::new(RwLock::new(Default::default())),
mailboxes: Arc::new(RwLock::new(mailboxes)),
save_messages_to: None,
account_name: Arc::new(s.name().to_string()),
event_consumer,
}))
}
pub fn validate_config(s: &AccountSettings) -> Result<()> {
let path = Path::new(s.root_mailbox.as_str()).expand();
if !path.exists() {
return Err(MeliError::new(format!(
"\"root_mailbox\" {} for account {} is not a valid path.",
s.root_mailbox.as_str(),
s.name()
)));
}
for (k, f) in s.mailboxes.iter() {
if f.extra.get("query").is_none() {
return Err(MeliError::new(format!(
"notmuch mailbox configuration entry \"{}\" should have a \"query\" value set.",
k
)));
}
}
Ok(())
}
pub fn search(&self, query_s: &str) -> Result> {
let database = Self::new_connection(
self.path.as_path(),
self.revision_uuid.clone(),
self.lib.clone(),
false,
)?;
let query: Query = Query::new(self.lib.clone(), &database, query_s)?;
let mut ret = SmallVec::new();
let iter = query.search()?;
for message in iter {
ret.push(message.env_hash());
}
Ok(ret)
}
fn new_connection(
path: &Path,
revision_uuid: Arc>,
lib: Arc,
write: bool,
) -> Result {
let path_c = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
let path_ptr = path_c.as_ptr();
let mut database: *mut notmuch_database_t = std::ptr::null_mut();
let status = unsafe {
call!(lib, notmuch_database_open)(
path_ptr,
if write {
notmuch_database_mode_t_NOTMUCH_DATABASE_MODE_READ_WRITE
} else {
notmuch_database_mode_t_NOTMUCH_DATABASE_MODE_READ_ONLY
},
&mut database as *mut _,
)
};
if status != 0 {
return Err(MeliError::new(format!(
"Could not open notmuch database at path {}. notmuch_database_open returned {}.",
path.display(),
status
)));
}
assert!(!database.is_null());
let ret = DbConnection {
lib,
revision_uuid,
inner: Arc::new(RwLock::new(database)),
database_ph: std::marker::PhantomData,
};
if *ret.revision_uuid.read().unwrap() == 0 {
let new = ret.get_revision_uuid();
*ret.revision_uuid.write().unwrap() = new;
}
Ok(ret)
}
}
impl MailBackend for NotmuchDb {
fn capabilities(&self) -> MailBackendCapabilities {
const CAPABILITIES: MailBackendCapabilities = MailBackendCapabilities {
is_async: false,
is_remote: false,
supports_search: true,
extensions: None,
supports_tags: true,
supports_submission: false,
};
CAPABILITIES
}
fn is_online(&self) -> ResultFuture<()> {
Ok(Box::pin(async { Ok(()) }))
}
fn fetch(
&mut self,
mailbox_hash: MailboxHash,
) -> Result>> + Send + 'static>>> {
struct FetchState {
mailbox_hash: MailboxHash,
database: Arc,
index: Arc>>,
mailbox_index: Arc>>>,
mailboxes: Arc>>,
tag_index: Arc>>,
iter: std::vec::IntoIter,
}
impl FetchState {
async fn fetch(&mut self) -> Result