Files
EpistulaPublic/src/rules.rs
T

135 lines
4.4 KiB
Rust

//! Incoming rules: conditions on From / To / Subject ("contains", case-insensitive, all must hold), one action
//! (move to a folder), first match wins. The model is Sieve's `header :contains` + `fileinto`, so V2 can compile
//! the same rules to a server-side script (`to_sieve`).
use crate::Address;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Field {
From,
/// To and Cc.
To,
Subject,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Condition {
pub field: Field,
pub contains: String,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rule {
pub name: String,
pub conditions: Vec<Condition>,
pub folder: String,
}
impl std::fmt::Debug for Rule {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Rule").field("conditions", &self.conditions.len()).finish_non_exhaustive()
}
}
impl std::fmt::Debug for Condition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Condition").field("field", &self.field).finish_non_exhaustive()
}
}
/// Why a rule cannot be saved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RuleError {
NoConditions,
EmptyText,
NoFolder,
}
impl Rule {
/// A rule with no condition, an empty text or no folder would match everything or nothing.
pub fn validate(&self) -> Result<(), RuleError> {
if self.conditions.is_empty() {
return Err(RuleError::NoConditions);
}
if self.conditions.iter().any(|c| c.contains.trim().is_empty()) {
return Err(RuleError::EmptyText);
}
if self.folder.trim().is_empty() {
return Err(RuleError::NoFolder);
}
Ok(())
}
/// The rule "Rule from this mail": sender address -> folder.
pub fn from_sender(sender: &Address, folder: &str) -> Rule {
let email = sender.email.trim().to_lowercase();
Rule {
name: format!("From {email}"),
conditions: vec![Condition { field: Field::From, contains: email }],
folder: folder.trim().to_string(),
}
}
}
/// What a rule looks at.
pub struct RuleMessage<'a> {
pub from: &'a [Address],
pub to: &'a [Address],
pub cc: &'a [Address],
pub subject: &'a str,
}
/// The first valid rule whose conditions all hold, or `None` (the message stays where it is).
pub fn first_match<'r>(rules: &'r [Rule], message: &RuleMessage<'_>) -> Option<&'r Rule> {
rules.iter().find(|rule| rule.validate().is_ok() && rule.conditions.iter().all(|c| holds(c, message)))
}
fn holds(condition: &Condition, message: &RuleMessage<'_>) -> bool {
let needle = condition.contains.trim().to_lowercase();
let any = |list: &[Address]| list.iter().any(|a| a.display().to_lowercase().contains(&needle));
match condition.field {
Field::From => any(message.from),
Field::To => any(message.to) || any(message.cc),
Field::Subject => message.subject.to_lowercase().contains(&needle),
}
}
fn sieve_string(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars().filter(|c| !c.is_control()) {
if c == '"' || c == '\\' {
out.push('\\');
}
out.push(c);
}
out.push('"');
out
}
fn sieve_test(condition: &Condition) -> String {
let header = match condition.field {
Field::From => "\"from\"",
Field::To => "[\"to\", \"cc\"]",
Field::Subject => "\"subject\"",
};
format!("header :contains :comparator \"i;unicode-casemap\" {header} {}", sieve_string(condition.contains.trim()))
}
/// The same rules as a Sieve script (RFC 5228 + fileinto + RFC 5051 unicode-casemap).
pub fn to_sieve(rules: &[Rule]) -> String {
let mut out = String::from("require [\"fileinto\", \"comparator-i;unicode-casemap\"];\n");
for rule in rules.iter().filter(|r| r.validate().is_ok()) {
let name: String = rule.name.chars().filter(|c| !c.is_control()).collect();
let tests: Vec<String> = rule.conditions.iter().map(sieve_test).collect();
let test = if tests.len() == 1 { tests[0].clone() } else { format!("allof({})", tests.join(", ")) };
out.push_str(&format!(
"\n# {name}\nif {test} {{\n fileinto {};\n stop;\n}}\n",
sieve_string(rule.folder.trim())
));
}
out
}