meli/melib/src/backends/maildir.rs

256 lines
7.1 KiB
Rust
Raw Normal View History

2018-09-05 16:08:11 +03:00
/*
* meli - mailbox module.
*
* Copyright 2017 Manos Pitsidianakis
*
* This file is part of meli.
*
* meli is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* meli is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with meli. If not, see <http://www.gnu.org/licenses/>.
*/
#[macro_use]
2018-09-05 16:08:11 +03:00
mod backend;
pub use self::backend::*;
2019-05-26 15:54:45 +03:00
use crate::backends::*;
use crate::email::parser;
use crate::email::{Envelope, Flag};
2019-04-04 14:21:52 +03:00
use crate::error::{MeliError, Result};
2018-09-05 16:08:11 +03:00
use memmap::{Mmap, Protection};
use std::collections::hash_map::DefaultHasher;
use std::fs;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
/// `BackendOp` implementor for Maildir
#[derive(Debug)]
pub struct MaildirOp {
hash_index: HashIndexes,
folder_hash: FolderHash,
2018-09-05 16:08:11 +03:00
hash: EnvelopeHash,
slice: Option<Mmap>,
}
impl Clone for MaildirOp {
fn clone(&self) -> Self {
MaildirOp {
hash_index: self.hash_index.clone(),
folder_hash: self.folder_hash,
2018-09-05 16:08:11 +03:00
hash: self.hash,
slice: None,
}
}
}
impl MaildirOp {
pub fn new(hash: EnvelopeHash, hash_index: HashIndexes, folder_hash: FolderHash) -> Self {
2018-09-05 16:08:11 +03:00
MaildirOp {
hash_index,
folder_hash,
2018-09-05 16:08:11 +03:00
hash,
slice: None,
}
}
fn path(&self) -> PathBuf {
let map = self.hash_index.lock().unwrap();
let map = &map[&self.folder_hash];
2019-05-01 19:20:33 +03:00
debug!("looking for {} in {} map", self.hash, self.folder_hash);
2018-10-14 19:49:16 +03:00
if !map.contains_key(&self.hash) {
2019-05-01 19:20:33 +03:00
debug!("doesn't contain it though len = {}\n{:#?}", map.len(), map);
2018-10-14 19:49:16 +03:00
for e in map.iter() {
2019-05-01 19:20:33 +03:00
debug!("{:#?}", e);
2018-10-14 19:49:16 +03:00
}
}
if let Some(path) = &map[&self.hash].modified {
path.clone()
} else {
map.get(&self.hash).unwrap().buf.to_path_buf()
}
2018-09-05 16:08:11 +03:00
}
}
impl<'a> BackendOp for MaildirOp {
fn description(&self) -> String {
format!("Path of file: {}", self.path().display())
}
fn as_bytes(&mut self) -> Result<&[u8]> {
if self.slice.is_none() {
self.slice = Some(Mmap::open_path(self.path(), Protection::Read)?);
}
/* Unwrap is safe since we use ? above. */
Ok(unsafe { self.slice.as_ref().unwrap().as_slice() })
}
fn fetch_headers(&mut self) -> Result<&[u8]> {
let raw = self.as_bytes()?;
let result = parser::headers_raw(raw).to_full_result()?;
Ok(result)
}
fn fetch_body(&mut self) -> Result<&[u8]> {
let raw = self.as_bytes()?;
let result = parser::headers_raw(raw).to_full_result()?;
Ok(result)
}
fn fetch_flags(&self) -> Flag {
let mut flag = Flag::default();
let path = self.path();
let path = path.to_str().unwrap(); // Assume UTF-8 validity
if !path.contains(":2,") {
return flag;
}
for f in path.chars().rev() {
match f {
',' => break,
'D' => flag |= Flag::DRAFT,
'F' => flag |= Flag::FLAGGED,
'P' => flag |= Flag::PASSED,
'R' => flag |= Flag::REPLIED,
'S' => flag |= Flag::SEEN,
'T' => flag |= Flag::TRASHED,
_ => {
2019-05-01 19:20:33 +03:00
debug!("DEBUG: in fetch_flags, path is {}", path);
}
2018-09-05 16:08:11 +03:00
}
}
flag
}
2019-03-03 22:11:15 +02:00
fn set_flag(&mut self, envelope: &mut Envelope, f: Flag) -> Result<()> {
2018-09-05 16:08:11 +03:00
let path = self.path();
let path = path.to_str().unwrap(); // Assume UTF-8 validity
let idx: usize = path
.rfind(":2,")
.ok_or_else(|| MeliError::new(format!("Invalid email filename: {:?}", self)))?
+ 3;
let mut new_name: String = path[..idx].to_string();
let mut flags = self.fetch_flags();
2019-03-03 22:11:15 +02:00
if !(flags & f).is_empty() {
2018-09-05 16:08:11 +03:00
return Ok(());
}
2019-03-03 22:11:15 +02:00
flags.toggle(f);
2018-09-05 16:08:11 +03:00
if !(flags & Flag::DRAFT).is_empty() {
new_name.push('D');
}
if !(flags & Flag::FLAGGED).is_empty() {
new_name.push('F');
}
if !(flags & Flag::PASSED).is_empty() {
new_name.push('P');
}
if !(flags & Flag::REPLIED).is_empty() {
new_name.push('R');
}
if !(flags & Flag::SEEN).is_empty() {
new_name.push('S');
}
if !(flags & Flag::TRASHED).is_empty() {
new_name.push('T');
}
2019-05-01 19:20:33 +03:00
debug!("renaming {:?} to {:?}", path, new_name);
2018-09-05 16:08:11 +03:00
fs::rename(&path, &new_name)?;
2019-05-01 19:20:33 +03:00
debug!("success in rename");
let old_hash = envelope.hash();
let new_name: PathBuf = new_name.into();
2018-09-05 16:08:11 +03:00
let hash_index = self.hash_index.clone();
let mut map = hash_index.lock().unwrap();
let map = map.entry(self.folder_hash).or_default();
2019-06-18 21:13:58 +03:00
map.entry(old_hash).or_default().modified = Some(new_name.clone());
2018-09-05 16:08:11 +03:00
Ok(())
}
}
#[derive(Debug, Default)]
pub struct MaildirFolder {
hash: FolderHash,
name: String,
path: PathBuf,
parent: Option<FolderHash>,
children: Vec<FolderHash>,
2018-09-05 16:08:11 +03:00
}
impl MaildirFolder {
pub fn new(
path: String,
file_name: String,
parent: Option<FolderHash>,
children: Vec<FolderHash>,
) -> Result<Self> {
2018-09-05 16:08:11 +03:00
let pathbuf = PathBuf::from(path);
let mut h = DefaultHasher::new();
pathbuf.hash(&mut h);
let ret = MaildirFolder {
hash: h.finish(),
name: file_name,
path: pathbuf,
parent,
2018-09-05 16:08:11 +03:00
children,
};
ret.is_valid()?;
Ok(ret)
}
pub fn path(&self) -> &Path {
self.path.as_path()
}
fn is_valid(&self) -> Result<()> {
let path = self.path();
let mut p = PathBuf::from(path);
for d in &["cur", "new", "tmp"] {
p.push(d);
if !p.is_dir() {
return Err(MeliError::new(format!(
"{} is not a valid maildir folder",
path.display()
)));
}
p.pop();
}
Ok(())
}
}
impl BackendFolder for MaildirFolder {
fn hash(&self) -> FolderHash {
self.hash
}
2018-09-17 07:53:16 +03:00
2018-09-05 16:08:11 +03:00
fn name(&self) -> &str {
&self.name
}
2018-09-17 07:53:16 +03:00
2018-09-05 16:08:11 +03:00
fn change_name(&mut self, s: &str) {
self.name = s.to_string();
}
2018-09-17 07:53:16 +03:00
fn children(&self) -> &Vec<FolderHash> {
2018-09-05 16:08:11 +03:00
&self.children
}
2018-09-17 07:53:16 +03:00
2018-09-05 16:08:11 +03:00
fn clone(&self) -> Folder {
Box::new(MaildirFolder {
hash: self.hash,
name: self.name.clone(),
path: self.path.clone(),
children: self.children.clone(),
2019-06-18 21:13:58 +03:00
parent: self.parent,
2018-09-05 16:08:11 +03:00
})
}
fn parent(&self) -> Option<FolderHash> {
2019-06-18 21:13:58 +03:00
self.parent
}
2018-09-05 16:08:11 +03:00
}