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
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

//! A email source that uses IMAP to connect to an email server
//!
//! This module includes the [`Email`] source, the [`ViewMode`] enum, and the [`Filters`] struct

mod auth;
mod filters;
mod view_mode;

pub use auth::Auth;
pub use view_mode::ViewMode;
pub use filters::Filters;

use self::auth::GoogleAuthExt;
use crate::auth::Google as GoogleAuth;
use crate::entry::Entry;
use crate::error::source::EmailError;
use crate::error::source::ImapError;
use crate::sink::Message;

use mailparse::ParsedMail;
use std::fmt::Debug;
use std::fmt::Write as _;

const IMAP_PORT: u16 = 993;

/// Email source. Fetches an email's subject and body fields using IMAP
pub struct Email {
	imap: String,
	email: String,
	auth: Auth,
	filters: Filters,
	view_mode: ViewMode,
}

macro_rules! authenticate {
    ($login:expr, $auth:expr, $client:expr) => {{
		let auth = $auth;

		match auth {
			Auth::GoogleAuth(auth) => {
				tracing::trace!("Logging in to IMAP with Google OAuth2");

				$client
					.authenticate(
						"XOAUTH2",
						&auth
							.as_imap_oauth2($login)
							.await
							.map_err(|e| ImapError::GoogleAuth(Box::new(e)))?,
					)
					.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 {
	/// Creates an [`Email`] source for use with Gmail that uses [`Google OAuth2`](`crate::auth::Google`) to authenticate
	#[must_use]
	pub fn with_google_oauth2(
		email: String,
		auth: GoogleAuth,
		filters: Filters,
		view_mode: ViewMode,
	) -> Self {
		Self {
			imap: "imap.gmail.com".to_owned(),
			email,
			auth: Auth::GoogleAuth(auth),
			filters,
			view_mode,
		}
	}

	/// Creates an [`Email`] source that uses a password to authenticate via IMAP
	#[must_use]
	pub fn with_password(
		imap: String,
		email: String,
		password: String,
		filters: Filters,
		view_mode: ViewMode,
	) -> Self {
		Self {
			imap,
			email,
			auth: Auth::Password(password),
			filters,
			view_mode,
		}
	}

	/// Even though it's marked async, the fetching itself is not async yet
	/// It should be used with spawn_blocking probs
	/// TODO: make it async lol
	#[tracing::instrument(skip_all)]
	pub async fn get(&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 {
				let _ = write!(tmp, r#"FROM "{sender}" "#);
			}

			if let Some(subjects) = &self.filters.subjects {
				for s in subjects {
					let _ = write!(tmp, r#"SUBJECT "{s}" "#);
				}
			}

			if let Some(ex_subjects) = &self.filters.exclude_subjects {
				for exs in ex_subjects {
					let _ = 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>>()
	}

	pub(crate) async fn mark_as_read(&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),
		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::GoogleAuth(_) => &"google_auth",
				},
			)
			.field("email", &self.email)
			.field("filters", &self.filters)
			.field("view_mode", &self.view_mode)
			.finish()
	}
}