1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
mod auth;
mod filters;
mod view_mode;
pub use auth::Auth;
pub use filters::Filters;
pub use view_mode::ViewMode;
use self::auth::GoogleAuthExt;
use super::{Fetch, MarkAsRead, Source};
use crate::{
auth::google::GoogleOAuth2Error as GoogleAuthError,
auth::Google as GoogleAuth,
entry::{Entry, EntryId},
error::Error,
sink::message::Message,
source::error::SourceError,
};
use async_trait::async_trait;
use mailparse::ParsedMail;
use std::fmt::{Debug, Write as _};
const IMAP_PORT: u16 = 993;
pub struct Email {
pub imap: String,
pub email: String,
pub auth: Auth,
pub filters: Filters,
pub view_mode: ViewMode,
}
#[allow(missing_docs)] #[allow(clippy::large_enum_variant)] #[derive(thiserror::Error, Debug)]
pub enum EmailError {
#[error("IMAP connection error")]
Imap(#[from] ImapError),
#[error("Error parsing email")]
Parse(#[from] mailparse::MailParseError),
}
#[allow(missing_docs)] #[derive(thiserror::Error, Debug)]
pub enum ImapError {
#[error("Failed to init TLS")]
TlsInitFailed(#[source] imap::Error),
#[error(transparent)]
GoogleOAuth2(#[from] GoogleAuthError),
#[error("Authentication error")]
Auth(#[source] imap::Error),
#[error(transparent)]
Other(#[from] imap::Error),
}
macro_rules! authenticate {
($login:expr, $auth:expr, $client:expr) => {{
let auth = $auth;
match auth {
Auth::GmailOAuth2(auth) => {
tracing::trace!("Logging in to IMAP with Google OAuth2");
let session = $client.authenticate(
"XOAUTH2",
&auth
.as_imap_oauth2($login)
.await
.map_err(ImapError::GoogleOAuth2)?,
);
match session {
Ok(session) => session,
Err((e, client)) => {
tracing::error!("Denied access to IMAP via OAuth2: {e}");
tracing::info!("Refreshing OAuth2 access token and trying again");
auth.get_new_access_token()
.await
.map_err(ImapError::GoogleOAuth2)?;
client
.authenticate(
"XOAUTH2",
&auth
.as_imap_oauth2($login)
.await
.map_err(ImapError::GoogleOAuth2)?,
)
.map_err(|(e, _)| ImapError::Auth(e))?
}
}
}
Auth::Password(password) => {
tracing::warn!("Logging in to IMAP with a password, this is insecure");
$client
.login($login, password)
.map_err(|(e, _)| ImapError::Auth(e))?
}
}
}};
}
impl Email {
#[must_use]
pub fn new_gmail(
email: String,
auth: GoogleAuth,
filters: Filters,
view_mode: ViewMode,
) -> Self {
Self {
imap: "imap.gmail.com".to_owned(),
email,
auth: Auth::GmailOAuth2(auth),
filters,
view_mode,
}
}
#[must_use]
pub fn new_generic(
imap: String,
email: String,
password: String,
filters: Filters,
view_mode: ViewMode,
) -> Self {
Self {
imap,
email,
auth: Auth::Password(password),
filters,
view_mode,
}
}
}
#[async_trait]
impl Fetch for Email {
async fn fetch(&mut self) -> Result<Vec<Entry>, SourceError> {
self.fetch_impl().await.map_err(Into::into)
}
}
#[async_trait]
impl MarkAsRead for Email {
async fn mark_as_read(&mut self, id: &EntryId) -> Result<(), Error> {
self.mark_as_read_impl(id)
.await
.map_err(|e| Error::from(SourceError::from(EmailError::from(e))))
}
async fn set_read_only(&mut self) {
self.view_mode = ViewMode::ReadOnly;
}
}
impl Source for Email {}
impl Email {
async fn fetch_impl(&mut self) -> Result<Vec<Entry>, EmailError> {
tracing::debug!("Fetching emails");
let client = imap::ClientBuilder::new(&self.imap, IMAP_PORT)
.rustls()
.map_err(ImapError::TlsInitFailed)?;
let mut session = authenticate!(&self.email, &mut self.auth, client);
session.examine("INBOX").map_err(ImapError::Other)?;
let search_string = {
let mut tmp = "UNSEEN ".to_string();
if let Some(sender) = &self.filters.sender {
_ = write!(tmp, r#"FROM "{sender}" "#);
}
if let Some(subjects) = &self.filters.subjects {
for s in subjects {
_ = write!(tmp, r#"SUBJECT "{s}" "#);
}
}
if let Some(ex_subjects) = &self.filters.exclude_subjects {
for exs in ex_subjects {
_ = write!(tmp, r#"NOT SUBJECT "{exs}" "#);
}
}
tmp.trim_end().to_string()
};
let mail_ids = session
.uid_search(&search_string)
.map_err(ImapError::Other)?
.into_iter()
.map(|x| x.to_string())
.collect::<Vec<_>>()
.join(",");
let unread_num = mail_ids.len();
if unread_num > 0 {
tracing::info!("Got {unread_num} unread filtered mails");
} else {
tracing::debug!(
"All email for the search query have already been read, none remaining to send"
);
}
if mail_ids.is_empty() {
return Ok(Vec::new());
}
let mails = session
.uid_fetch(&mail_ids, "BODY[]")
.map_err(ImapError::Other)?;
session.logout().map_err(ImapError::Other)?;
mails
.iter()
.map(|x| {
let body = x
.body()
.expect("Body should always be present because we explicitly requested it");
let uid =
x.uid.expect("UIDs should always be present because we used uid_fetch(). The server probably doesn't support them which isn't something ~we~ support for now").to_string();
parse(
&mailparse::parse_mail(body)?,
uid,
)
})
.collect::<Result<Vec<Entry>, EmailError>>()
}
async fn mark_as_read_impl(&mut self, id: &str) -> Result<(), ImapError> {
if let ViewMode::ReadOnly = self.view_mode {
return Ok(());
}
let client = imap::ClientBuilder::new(&self.imap, IMAP_PORT)
.rustls()
.map_err(ImapError::TlsInitFailed)?;
let mut session = authenticate!(&self.email, &mut self.auth, client);
session.select("INBOX")?;
match self.view_mode {
ViewMode::MarkAsRead => {
session.uid_store(id, "+FLAGS.SILENT (\\Seen)")?;
tracing::debug!("Marked email uid {id} as read");
}
ViewMode::Delete => {
session.uid_store(id, "+FLAGS.SILENT (\\Deleted)")?;
session.uid_expunge(id)?;
tracing::debug!("Deleted email uid {id}");
}
ViewMode::ReadOnly => unreachable!(),
};
session.logout()?;
Ok(())
}
}
fn parse(mail: &ParsedMail, id: String) -> Result<Entry, EmailError> {
let subject = mail.headers.iter().find_map(|x| {
if x.get_key_ref() == "Subject" {
Some(x.get_value())
} else {
None
}
});
let body = {
if mail.subparts.is_empty() {
mail
} else {
mail.subparts
.iter()
.find(|x| x.ctype.mimetype == "text/plain")
.unwrap_or(&mail.subparts[0])
}
.get_body()?
};
Ok(Entry {
id: Some(id.into()),
msg: Message {
title: subject,
body: Some(body),
..Default::default()
},
..Default::default()
})
}
impl Debug for Email {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Email")
.field("imap", &self.imap)
.field(
"auth_type",
match self.auth {
Auth::Password(_) => &"password",
Auth::GmailOAuth2(_) => &"gmail_oauth2",
},
)
.field("email", &self.email)
.field("filters", &self.filters)
.field("view_mode", &self.view_mode)
.finish()
}
}