use crate::error::Error;
use crate::parse::{parse_until_done, MapOrNot};
use crate::types::UnsolicitedResponse;
#[cfg(doc)]
use crate::Session;
use imap_proto::types::AclRight;
use imap_proto::Response;
use ouroboros::self_referencing;
use std::borrow::Cow;
use std::collections::HashSet;
use std::fmt::{Display, Formatter};
use std::sync::mpsc;
#[derive(Debug, Clone, Copy)]
pub enum AclModifyMode {
Replace,
Add,
Remove,
}
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct AclRights {
pub(crate) data: HashSet<AclRight>,
}
impl AclRights {
pub fn contains<T: Into<AclRight>>(&self, right: T) -> bool {
self.data.contains(&right.into())
}
}
impl Display for AclRights {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut v: Vec<char> = self.data.iter().map(|c| char::from(*c)).collect();
v.sort_unstable();
write!(f, "{}", v.into_iter().collect::<String>())
}
}
impl From<HashSet<AclRight>> for AclRights {
fn from(hash: HashSet<AclRight>) -> Self {
Self { data: hash }
}
}
impl From<Vec<AclRight>> for AclRights {
fn from(vec: Vec<AclRight>) -> Self {
AclRights {
data: vec.into_iter().collect(),
}
}
}
impl TryFrom<&str> for AclRights {
type Error = AclRightError;
fn try_from(input: &str) -> Result<Self, Self::Error> {
if !input
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
{
return Err(AclRightError::InvalidRight);
}
Ok(input
.chars()
.map(|c| c.into())
.collect::<HashSet<AclRight>>()
.into())
}
}
#[derive(Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum AclRightError {
InvalidRight,
}
impl Display for AclRightError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match *self {
AclRightError::InvalidRight => {
write!(f, "Rights may only be lowercase alpha numeric characters")
}
}
}
}
impl std::error::Error for AclRightError {}
#[self_referencing]
pub struct AclResponse {
data: Vec<u8>,
#[borrows(data)]
#[covariant]
pub(crate) acl: Acl<'this>,
}
impl AclResponse {
pub(crate) fn parse(
owned: Vec<u8>,
unsolicited: &mut mpsc::Sender<UnsolicitedResponse>,
) -> Result<Self, Error> {
AclResponseTryBuilder {
data: owned,
acl_builder: |input| {
parse_until_done(input, unsolicited, |response| match response {
Response::Acl(a) => Ok(MapOrNot::Map(Acl {
mailbox: a.mailbox,
acls: a
.acls
.into_iter()
.map(|e| AclEntry {
identifier: e.identifier,
rights: e.rights.into(),
})
.collect(),
})),
resp => Ok(MapOrNot::Not(resp)),
})
},
}
.try_build()
}
pub fn parsed(&self) -> &Acl<'_> {
self.borrow_acl()
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct Acl<'a> {
pub(crate) mailbox: Cow<'a, str>,
pub(crate) acls: Vec<AclEntry<'a>>,
}
impl<'a> Acl<'a> {
pub fn mailbox(&self) -> &str {
&self.mailbox
}
pub fn acls(&self) -> &[AclEntry<'_>] {
&self.acls
}
}
#[derive(Debug, Eq, PartialEq, Clone)]
#[non_exhaustive]
pub struct AclEntry<'a> {
pub identifier: Cow<'a, str>,
pub rights: AclRights,
}
#[self_referencing]
pub struct ListRightsResponse {
data: Vec<u8>,
#[borrows(data)]
#[covariant]
pub(crate) rights: ListRights<'this>,
}
impl ListRightsResponse {
pub(crate) fn parse(
owned: Vec<u8>,
unsolicited: &mut mpsc::Sender<UnsolicitedResponse>,
) -> Result<Self, Error> {
ListRightsResponseTryBuilder {
data: owned,
rights_builder: |input| {
parse_until_done(input, unsolicited, |response| match response {
Response::ListRights(a) => Ok(MapOrNot::Map(ListRights {
mailbox: a.mailbox,
identifier: a.identifier,
required: a.required.into(),
optional: a.optional.into(),
})),
resp => Ok(MapOrNot::Not(resp)),
})
},
}
.try_build()
}
pub fn parsed(&self) -> &ListRights<'_> {
self.borrow_rights()
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct ListRights<'a> {
pub(crate) mailbox: Cow<'a, str>,
pub(crate) identifier: Cow<'a, str>,
pub(crate) required: AclRights,
pub(crate) optional: AclRights,
}
impl ListRights<'_> {
pub fn mailbox(&self) -> &str {
&self.mailbox
}
pub fn identifier(&self) -> &str {
&self.identifier
}
pub fn required(&self) -> &AclRights {
&self.required
}
pub fn optional(&self) -> &AclRights {
&self.optional
}
}
#[self_referencing]
pub struct MyRightsResponse {
data: Vec<u8>,
#[borrows(data)]
#[covariant]
pub(crate) rights: MyRights<'this>,
}
impl MyRightsResponse {
pub(crate) fn parse(
owned: Vec<u8>,
unsolicited: &mut mpsc::Sender<UnsolicitedResponse>,
) -> Result<Self, Error> {
MyRightsResponseTryBuilder {
data: owned,
rights_builder: |input| {
parse_until_done(input, unsolicited, |response| match response {
Response::MyRights(a) => Ok(MapOrNot::Map(MyRights {
mailbox: a.mailbox,
rights: a.rights.into(),
})),
resp => Ok(MapOrNot::Not(resp)),
})
},
}
.try_build()
}
pub fn parsed(&self) -> &MyRights<'_> {
self.borrow_rights()
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct MyRights<'a> {
pub(crate) mailbox: Cow<'a, str>,
pub(crate) rights: AclRights,
}
impl MyRights<'_> {
pub fn mailbox(&self) -> &str {
&self.mailbox
}
pub fn rights(&self) -> &AclRights {
&self.rights
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_acl_rights_to_string() {
let rights: AclRights = vec![
AclRight::Lookup,
AclRight::Read,
AclRight::Seen,
AclRight::Custom('0'),
]
.into();
let expected = "0lrs";
assert_eq!(rights.to_string(), expected);
}
#[test]
fn test_str_to_acl_rights() {
let right_string = "lrskx0";
let rights: Result<AclRights, _> = right_string.try_into();
assert_eq!(
rights,
Ok(vec![
AclRight::Lookup,
AclRight::Read,
AclRight::Seen,
AclRight::CreateMailbox,
AclRight::DeleteMailbox,
AclRight::Custom('0'),
]
.into())
);
}
#[test]
fn test_str_to_acl_rights_invalid_right_character() {
let right_string = "l_";
let rights: Result<AclRights, _> = right_string.try_into();
assert_eq!(rights, Err(AclRightError::InvalidRight));
assert_eq!(
format!("{}", rights.unwrap_err()),
"Rights may only be lowercase alpha numeric characters"
);
}
#[test]
fn test_acl_rights_contains() {
let rights: AclRights = "lrskx".try_into().unwrap();
assert!(rights.contains('l'));
assert!(rights.contains(AclRight::Lookup));
assert!(!rights.contains('0'));
assert!(!rights.contains(AclRight::Custom('0')));
}
}