tiny_mailcatcher/
repository.rs

1use std::collections::HashMap;
2
3use chrono::{DateTime, Utc};
4
5#[derive(Debug, PartialEq)]
6pub struct Message {
7    pub id: Option<usize>,
8    pub size: usize,
9    pub subject: Option<String>,
10    pub sender: Option<String>,
11    pub recipients: Vec<String>,
12    pub created_at: DateTime<Utc>,
13    pub typ: String,
14    pub parts: Vec<MessagePart>,
15    pub charset: String,
16    pub source: Vec<u8>,
17}
18
19impl Message {
20    pub fn plain(&self) -> Option<&MessagePart> {
21        return self.parts.iter().find(|&p| p.typ == "text/plain");
22    }
23
24    pub fn html(&self) -> Option<&MessagePart> {
25        return self
26            .parts
27            .iter()
28            .find(|&p| p.typ == "text/html" || p.typ == "application/xhtml+xml");
29    }
30}
31
32#[derive(Debug, PartialEq)]
33pub struct MessagePart {
34    pub cid: String,
35    pub typ: String,
36    pub filename: String,
37    pub size: usize,
38    pub charset: String,
39    pub body: Vec<u8>,
40    pub is_attachment: bool,
41}
42
43pub struct MessageRepository {
44    last_insert_id: usize,
45    messages: HashMap<usize, Message>,
46}
47
48impl MessageRepository {
49    pub fn new() -> Self {
50        MessageRepository {
51            last_insert_id: 0,
52            messages: HashMap::new(),
53        }
54    }
55
56    pub fn persist(&mut self, mut message: Message) {
57        let id = self.last_insert_id + 1;
58        self.last_insert_id += 1;
59        message.id = Some(id);
60        self.messages.insert(id, message);
61    }
62
63    pub fn find_all(&self) -> Vec<&Message> {
64        self.messages.values().collect()
65    }
66
67    pub fn find(&self, id: usize) -> Option<&Message> {
68        self.messages.get(&id)
69    }
70
71    pub fn delete_all(&mut self) {
72        self.messages.clear();
73        self.last_insert_id = 0;
74    }
75
76    pub fn delete(&mut self, id: usize) -> Option<Message> {
77        self.messages.remove(&id)
78    }
79}