Annotation For src/main.rs
Logged in as anonymous

Origin for each line in src/main.rs from check-in 31aec3c4b0:

7620f854a7 2024-05-21        arcade: use anyhow::Result;
7620f854a7 2024-05-21        arcade: use async_std::task;
7620f854a7 2024-05-21        arcade: use samotop::{
7620f854a7 2024-05-21        arcade: 	mail::{
7620f854a7 2024-05-21        arcade: 		Builder,
7620f854a7 2024-05-21        arcade: 		DebugService,
7620f854a7 2024-05-21        arcade: 		MailDir,
7620f854a7 2024-05-21        arcade: 		Name
7620f854a7 2024-05-21        arcade: 	},
51adce1e7e 2024-05-22        arcade: 	smtp::{
51adce1e7e 2024-05-22        arcade: 		SmtpParser,
51adce1e7e 2024-05-22        arcade: 		Prudence,
51adce1e7e 2024-05-22        arcade: 	},
7620f854a7 2024-05-21        arcade: };
7620f854a7 2024-05-21        arcade: use telegram_bot::{
7620f854a7 2024-05-21        arcade: 	Api,
31aec3c4b0 2024-05-23        arcade: 	MessageOrChannelPost,
7620f854a7 2024-05-21        arcade: 	ParseMode,
7620f854a7 2024-05-21        arcade: 	SendMessage,
7620f854a7 2024-05-21        arcade: 	UserId,
7620f854a7 2024-05-21        arcade: };
7620f854a7 2024-05-21        arcade: 
7620f854a7 2024-05-21        arcade: use std::{
7620f854a7 2024-05-21        arcade: 	borrow::Cow,
61238a3618 2024-05-22        arcade: 	collections::{
61238a3618 2024-05-22        arcade: 		HashMap,
61238a3618 2024-05-22        arcade: 		HashSet,
61238a3618 2024-05-22        arcade: 	},
7620f854a7 2024-05-21        arcade: 	io::Read,
da7fc7983d 2024-05-23        arcade: 	os::unix::fs::{
da7fc7983d 2024-05-23        arcade: 		FileTypeExt,
da7fc7983d 2024-05-23        arcade: 		PermissionsExt,
da7fc7983d 2024-05-23        arcade: 	},
7620f854a7 2024-05-21        arcade: 	path::{
7620f854a7 2024-05-21        arcade: 		Path,
7620f854a7 2024-05-21        arcade: 		PathBuf
7620f854a7 2024-05-21        arcade: 	},
7620f854a7 2024-05-21        arcade: 	time::Duration,
7620f854a7 2024-05-21        arcade: 	vec::Vec,
7620f854a7 2024-05-21        arcade: };
7620f854a7 2024-05-21        arcade: 
61238a3618 2024-05-22        arcade: fn address_into_iter<'a>(addr: &'a mail_parser::Address<'a, >) -> impl Iterator<Item = Cow<'a, str>> {
61238a3618 2024-05-22        arcade: 	addr.clone().into_list().into_iter().map(|a| a.address.unwrap())
61238a3618 2024-05-22        arcade: }
7620f854a7 2024-05-21        arcade: 
61238a3618 2024-05-22        arcade: fn relay_mails(maildir: &Path, core: &TelegramTransport) -> Result<()> {
7620f854a7 2024-05-21        arcade: 	let new_dir = maildir.join("new");
7620f854a7 2024-05-21        arcade: 
7620f854a7 2024-05-21        arcade: 	std::fs::create_dir_all(&new_dir)?;
7620f854a7 2024-05-21        arcade: 
7620f854a7 2024-05-21        arcade: 	let files = std::fs::read_dir(new_dir)?;
7620f854a7 2024-05-21        arcade: 	for file in files {
7620f854a7 2024-05-21        arcade: 		let file = file?;
7620f854a7 2024-05-21        arcade: 		let mut buf = Vec::new();
7620f854a7 2024-05-21        arcade: 		std::fs::File::open(file.path())?.read_to_end(&mut buf)?;
7620f854a7 2024-05-21        arcade: 
7620f854a7 2024-05-21        arcade: 		task::block_on(async move {
61238a3618 2024-05-22        arcade: 			match mail_parser::MessageParser::default().parse(&buf[..]) {
7620f854a7 2024-05-21        arcade: 				Some(mail) => {
61238a3618 2024-05-22        arcade: 					let mail = mail.clone();
61238a3618 2024-05-22        arcade: 
61238a3618 2024-05-22        arcade: 					// Fetching address lists from fields we know
61238a3618 2024-05-22        arcade: 					let mut to = HashSet::new();
61238a3618 2024-05-22        arcade: 					if let Some(addr) = mail.to() {
61238a3618 2024-05-22        arcade: 						let _ = address_into_iter(addr).map(|x| to.insert(x));
61238a3618 2024-05-22        arcade: 					};
61238a3618 2024-05-22        arcade: 					if let Some(addr) = mail.header("X-Samotop-To") {
61238a3618 2024-05-22        arcade: 						match addr {
61238a3618 2024-05-22        arcade: 							mail_parser::HeaderValue::Address(addr) => {
61238a3618 2024-05-22        arcade: 								let _ = address_into_iter(addr).map(|x| to.insert(x));
61238a3618 2024-05-22        arcade: 							},
61238a3618 2024-05-22        arcade: 							mail_parser::HeaderValue::Text(text) => {
61238a3618 2024-05-22        arcade: 								to.insert(text.clone());
61238a3618 2024-05-22        arcade: 							},
61238a3618 2024-05-22        arcade: 							_ => {}
61238a3618 2024-05-22        arcade: 						}
61238a3618 2024-05-22        arcade: 					};
61238a3618 2024-05-22        arcade: 
61238a3618 2024-05-22        arcade: 					// Adding all known addresses to recipient list, for anyone else adding default
61238a3618 2024-05-22        arcade: 					// Also if list is empty also adding default
da7fc7983d 2024-05-23        arcade: 					let mut rcpt: HashSet<&UserId> = HashSet::new();
61238a3618 2024-05-22        arcade: 					for item in to {
61238a3618 2024-05-22        arcade: 						let item = item.into_owned();
da7fc7983d 2024-05-23        arcade: 						match core.recipients.get(&item) {
da7fc7983d 2024-05-23        arcade: 							Some(addr) => rcpt.insert(addr),
da7fc7983d 2024-05-23        arcade: 							None => {
da7fc7983d 2024-05-23        arcade: 								core.debug(format!("Recipient [{}] not found.", &item)).await.unwrap();
da7fc7983d 2024-05-23        arcade: 								rcpt.insert(core.recipients.get("_").unwrap())
da7fc7983d 2024-05-23        arcade: 							}
da7fc7983d 2024-05-23        arcade: 						};
61238a3618 2024-05-22        arcade: 					};
61238a3618 2024-05-22        arcade: 					if rcpt.is_empty() {
61238a3618 2024-05-22        arcade: 						core.debug("No recipient or envelope address.").await.unwrap();
da7fc7983d 2024-05-23        arcade: 						rcpt.insert(core.recipients.get("_").unwrap());
61238a3618 2024-05-22        arcade: 					};
61238a3618 2024-05-22        arcade: 
61238a3618 2024-05-22        arcade: 					// prepating message header
61238a3618 2024-05-22        arcade: 					let mut reply: Vec<Cow<str>> = vec![];
61238a3618 2024-05-22        arcade: 					if let Some(subject) = mail.subject() {
667b874fdb 2024-05-22        arcade: 						reply.push(format!("**Subject:** `{}`", subject).into());
61238a3618 2024-05-22        arcade: 					} else if let Some(thread) = mail.thread_name() {
667b874fdb 2024-05-22        arcade: 						reply.push(format!("**Thread:** `{}`", thread).into());
61238a3618 2024-05-22        arcade: 					}
61238a3618 2024-05-22        arcade: 					if let Some(from) = mail.from() {
03fe0265ac 2024-05-22        arcade: 						reply.push(format!("**From:** `{:?}`", address_into_iter(from).collect::<Vec<_>>().join(", ")).into());
61238a3618 2024-05-22        arcade: 					}
61238a3618 2024-05-22        arcade: 					if let Some(sender) = mail.sender() {
9c12e26fb6 2024-05-22        arcade: 						reply.push(format!("**Sender:** `{:?}`", address_into_iter(sender).collect::<Vec<_>>().join(", ")).into());
61238a3618 2024-05-22        arcade: 					}
61238a3618 2024-05-22        arcade: 					reply.push("".into());
61238a3618 2024-05-22        arcade: 					let header_size = reply.join("\n").len() + 1;
61238a3618 2024-05-22        arcade: 
61238a3618 2024-05-22        arcade: 					let html_parts = mail.html_body_count();
61238a3618 2024-05-22        arcade: 					let text_parts = mail.text_body_count();
61238a3618 2024-05-22        arcade: 					let attachments = mail.attachment_count();
61238a3618 2024-05-22        arcade: 					if html_parts != text_parts {
61238a3618 2024-05-22        arcade: 						core.debug(format!("Hm, we have {} HTML parts and {} text parts.", html_parts, text_parts)).await.unwrap();
61238a3618 2024-05-22        arcade: 					}
61238a3618 2024-05-22        arcade: 					//let mut html_num = 0;
61238a3618 2024-05-22        arcade: 					let mut text_num = 0;
61238a3618 2024-05-22        arcade: 					let mut file_num = 0;
61238a3618 2024-05-22        arcade: 					// let's display first html or text part as body
61238a3618 2024-05-22        arcade: 					let mut body = "".into();
7620f854a7 2024-05-21        arcade: 					/*
61238a3618 2024-05-22        arcade: 					 * actually I don't wanna parse that html stuff
61238a3618 2024-05-22        arcade: 					if html_parts > 0 {
61238a3618 2024-05-22        arcade: 						let text = mail.body_html(0).unwrap();
61238a3618 2024-05-22        arcade: 						if text.len() < 4096 - header_size {
61238a3618 2024-05-22        arcade: 							body = text;
61238a3618 2024-05-22        arcade: 							html_num = 1;
61238a3618 2024-05-22        arcade: 						}
61238a3618 2024-05-22        arcade: 					};
61238a3618 2024-05-22        arcade: 					*/
61238a3618 2024-05-22        arcade: 					if body == "" && text_parts > 0 {
61238a3618 2024-05-22        arcade: 						let text = mail.body_text(0).unwrap();
61238a3618 2024-05-22        arcade: 						if text.len() < 4096 - header_size {
61238a3618 2024-05-22        arcade: 							body = text;
61238a3618 2024-05-22        arcade: 							text_num = 1;
61238a3618 2024-05-22        arcade: 						}
7620f854a7 2024-05-21        arcade: 					};
667b874fdb 2024-05-22        arcade: 					reply.push("```".into());
03fe0265ac 2024-05-22        arcade: 					for line in body.lines() {
03fe0265ac 2024-05-22        arcade: 						reply.push(line.into());
03fe0265ac 2024-05-22        arcade: 					}
667b874fdb 2024-05-22        arcade: 					reply.push("```".into());
61238a3618 2024-05-22        arcade: 
31aec3c4b0 2024-05-23        arcade: 					// and let's collect all other attachment parts
61238a3618 2024-05-22        arcade: 					let mut files_to_send = vec![];
61238a3618 2024-05-22        arcade: 					/*
61238a3618 2024-05-22        arcade: 					 * let's just skip html parts for now, they just duplicate text?
61238a3618 2024-05-22        arcade: 					while html_num < html_parts {
61238a3618 2024-05-22        arcade: 						files_to_send.push(mail.html_part(html_num).unwrap());
61238a3618 2024-05-22        arcade: 						html_num += 1;
61238a3618 2024-05-22        arcade: 					}
7620f854a7 2024-05-21        arcade: 					*/
61238a3618 2024-05-22        arcade: 					while text_num < text_parts {
61238a3618 2024-05-22        arcade: 						files_to_send.push(mail.text_part(text_num).unwrap());
61238a3618 2024-05-22        arcade: 						text_num += 1;
61238a3618 2024-05-22        arcade: 					}
61238a3618 2024-05-22        arcade: 					while file_num < attachments {
61238a3618 2024-05-22        arcade: 						files_to_send.push(mail.attachment(file_num).unwrap());
61238a3618 2024-05-22        arcade: 						file_num += 1;
61238a3618 2024-05-22        arcade: 					}
61238a3618 2024-05-22        arcade: 
61238a3618 2024-05-22        arcade: 					for chat in rcpt {
31aec3c4b0 2024-05-23        arcade: 						let base_post = core.send(chat, reply.join("\n")).await.unwrap();
61238a3618 2024-05-22        arcade: 						for chunk in &files_to_send {
61238a3618 2024-05-22        arcade: 							let data = chunk.contents().to_vec();
61238a3618 2024-05-22        arcade: 							let obj = telegram_bot::types::InputFileUpload::with_data(data, "Attachment");
31aec3c4b0 2024-05-23        arcade: 							core.sendfile(chat, obj, Some(&base_post)).await.unwrap();
61238a3618 2024-05-22        arcade: 						}
61238a3618 2024-05-22        arcade: 					}
7620f854a7 2024-05-21        arcade: 				},
7620f854a7 2024-05-21        arcade: 				None => { core.debug("None mail.").await.unwrap(); },
7620f854a7 2024-05-21        arcade: 			};
7620f854a7 2024-05-21        arcade: 		});
7620f854a7 2024-05-21        arcade: 
7620f854a7 2024-05-21        arcade: 		std::fs::remove_file(file.path())?;
7620f854a7 2024-05-21        arcade: 	}
7620f854a7 2024-05-21        arcade: 	Ok(())
7620f854a7 2024-05-21        arcade: }
7620f854a7 2024-05-21        arcade: 
7620f854a7 2024-05-21        arcade: fn my_prudence() -> Prudence {
7620f854a7 2024-05-21        arcade: 	Prudence::default().with_read_timeout(Duration::from_secs(60)).with_banner_delay(Duration::from_secs(1))
7620f854a7 2024-05-21        arcade: }
7620f854a7 2024-05-21        arcade: 
61238a3618 2024-05-22        arcade: pub struct TelegramTransport {
7620f854a7 2024-05-21        arcade: 	tg: Api,
7620f854a7 2024-05-21        arcade: 	recipients: HashMap<String, UserId>,
7620f854a7 2024-05-21        arcade: }
7620f854a7 2024-05-21        arcade: 
61238a3618 2024-05-22        arcade: impl TelegramTransport {
da7fc7983d 2024-05-23        arcade: 	pub fn new(settings: config::Config) -> TelegramTransport {
da7fc7983d 2024-05-23        arcade: 		let tg = Api::new(settings.get_string("api_key")
da7fc7983d 2024-05-23        arcade: 			.expect("[smtp2tg.toml] missing \"api_key\" parameter.\n"));
da7fc7983d 2024-05-23        arcade: 		let recipients: HashMap<String, UserId> = settings.get_table("recipients")
da7fc7983d 2024-05-23        arcade: 			.expect("[smtp2tg.toml] missing table \"recipients\".\n")
da7fc7983d 2024-05-23        arcade: 			.into_iter().map(|(a, b)| (a, UserId::new(b.into_int()
da7fc7983d 2024-05-23        arcade: 				.expect("[smtp2tg.toml] \"recipient\" table values should be integers.\n")
da7fc7983d 2024-05-23        arcade: 				))).collect();
da7fc7983d 2024-05-23        arcade: 		if !recipients.contains_key("_") {
da7fc7983d 2024-05-23        arcade: 			eprintln!("[smtp2tg.toml] \"recipient\" table misses \"default_recipient\".\n");
da7fc7983d 2024-05-23        arcade: 			panic!("no default recipient");
da7fc7983d 2024-05-23        arcade: 		}
61238a3618 2024-05-22        arcade: 
61238a3618 2024-05-22        arcade: 		TelegramTransport {
7620f854a7 2024-05-21        arcade: 			tg,
7620f854a7 2024-05-21        arcade: 			recipients,
61238a3618 2024-05-22        arcade: 		}
61238a3618 2024-05-22        arcade: 	}
61238a3618 2024-05-22        arcade: 
31aec3c4b0 2024-05-23        arcade: 	pub async fn debug<'b, S>(&self, msg: S) -> Result<MessageOrChannelPost>
31aec3c4b0 2024-05-23        arcade: 	where S: Into<Cow<'b, str>> {
31aec3c4b0 2024-05-23        arcade: 		task::sleep(Duration::from_secs(5)).await;
31aec3c4b0 2024-05-23        arcade: 		Ok(self.tg.send(SendMessage::new(self.recipients.get("_").unwrap(), msg)
31aec3c4b0 2024-05-23        arcade: 			.parse_mode(ParseMode::Markdown)).await?)
31aec3c4b0 2024-05-23        arcade: 	}
31aec3c4b0 2024-05-23        arcade: 
31aec3c4b0 2024-05-23        arcade: 	pub async fn send<'b, S>(&self, to: &UserId, msg: S) -> Result<MessageOrChannelPost>
31aec3c4b0 2024-05-23        arcade: 	where S: Into<Cow<'b, str>> {
31aec3c4b0 2024-05-23        arcade: 		task::sleep(Duration::from_secs(5)).await;
31aec3c4b0 2024-05-23        arcade: 		Ok(self.tg.send(SendMessage::new(to, msg)
31aec3c4b0 2024-05-23        arcade: 			.parse_mode(ParseMode::Markdown)).await?)
31aec3c4b0 2024-05-23        arcade: 	}
31aec3c4b0 2024-05-23        arcade: 
31aec3c4b0 2024-05-23        arcade: 	pub async fn sendfile<V>(&self, to: &UserId, chunk: V, basic_mail: Option<&MessageOrChannelPost>) -> Result<()>
31aec3c4b0 2024-05-23        arcade: 	where V: Into<telegram_bot::InputFile> {
31aec3c4b0 2024-05-23        arcade: 		task::sleep(Duration::from_secs(5)).await;
31aec3c4b0 2024-05-23        arcade: 		match basic_mail {
31aec3c4b0 2024-05-23        arcade: 			Some(post) => {
31aec3c4b0 2024-05-23        arcade: 				self.tg.send(telegram_bot::SendDocument::new(to, chunk).reply_to(post)).await?;
31aec3c4b0 2024-05-23        arcade: 			},
31aec3c4b0 2024-05-23        arcade: 			None => {
31aec3c4b0 2024-05-23        arcade: 				self.tg.send(telegram_bot::SendDocument::new(to, chunk)).await?;
31aec3c4b0 2024-05-23        arcade: 			},
31aec3c4b0 2024-05-23        arcade: 		};
7620f854a7 2024-05-21        arcade: 		Ok(())
7620f854a7 2024-05-21        arcade: 	}
7620f854a7 2024-05-21        arcade: }
7620f854a7 2024-05-21        arcade: 
7620f854a7 2024-05-21        arcade: #[async_std::main]
7620f854a7 2024-05-21        arcade: async fn main() {
7620f854a7 2024-05-21        arcade: 	let settings: config::Config = config::Config::builder()
7620f854a7 2024-05-21        arcade: 		.add_source(config::File::with_name("smtp2tg.toml"))
da7fc7983d 2024-05-23        arcade: 		.build()
da7fc7983d 2024-05-23        arcade: 		.expect("[smtp2tg.toml] there was an error reading config\n\
da7fc7983d 2024-05-23        arcade: 			\tplease consult \"smtp2tg.toml.example\" for details");
7620f854a7 2024-05-21        arcade: 
da7fc7983d 2024-05-23        arcade: 	let maildir: PathBuf = settings.get_string("maildir")
da7fc7983d 2024-05-23        arcade: 		.expect("[smtp2tg.toml] missing \"maildir\" parameter.\n").into();
da7fc7983d 2024-05-23        arcade: 	let listen_on = settings.get_string("listen_on")
da7fc7983d 2024-05-23        arcade: 		.expect("[smtp2tg.toml] missing \"listen_on\" parameter.\n");
da7fc7983d 2024-05-23        arcade: 	let core = TelegramTransport::new(settings);
7620f854a7 2024-05-21        arcade: 	let sink = Builder + Name::new("smtp2tg") + DebugService +
51adce1e7e 2024-05-22        arcade: 		my_prudence() + MailDir::new(maildir.clone()).unwrap();
31aec3c4b0 2024-05-23        arcade: 
31aec3c4b0 2024-05-23        arcade: 	env_logger::init();
7620f854a7 2024-05-21        arcade: 
7620f854a7 2024-05-21        arcade: 	task::spawn(async move {
7620f854a7 2024-05-21        arcade: 		loop {
7620f854a7 2024-05-21        arcade: 			relay_mails(&maildir, &core).unwrap();
61238a3618 2024-05-22        arcade: 			task::sleep(Duration::from_secs(5)).await;
7620f854a7 2024-05-21        arcade: 		}
7620f854a7 2024-05-21        arcade: 	});
7620f854a7 2024-05-21        arcade: 
7620f854a7 2024-05-21        arcade: 	match listen_on.as_str() {
51adce1e7e 2024-05-22        arcade: 		"socket" => {
da7fc7983d 2024-05-23        arcade: 			let socket_path = "./smtp2tg.sock";
da7fc7983d 2024-05-23        arcade: 			match std::fs::symlink_metadata(socket_path) {
da7fc7983d 2024-05-23        arcade: 				Ok(metadata) => {
da7fc7983d 2024-05-23        arcade: 					if metadata.file_type().is_socket() {
da7fc7983d 2024-05-23        arcade: 						std::fs::remove_file(socket_path)
da7fc7983d 2024-05-23        arcade: 							.expect("[smtp2tg] failed to remove old socket.\n");
da7fc7983d 2024-05-23        arcade: 					} else {
da7fc7983d 2024-05-23        arcade: 						eprintln!("[smtp2tg] \"./smtp2tg.sock\" we wanted to use is actually not a socket.\n\
da7fc7983d 2024-05-23        arcade: 							[smtp2tg] please check the file and remove it manually.\n");
da7fc7983d 2024-05-23        arcade: 						panic!("socket path unavailable");
da7fc7983d 2024-05-23        arcade: 					}
da7fc7983d 2024-05-23        arcade: 				},
da7fc7983d 2024-05-23        arcade: 				Err(err) => {
da7fc7983d 2024-05-23        arcade: 					match err.kind() {
da7fc7983d 2024-05-23        arcade: 						std::io::ErrorKind::NotFound => {},
da7fc7983d 2024-05-23        arcade: 						_ => {
da7fc7983d 2024-05-23        arcade: 							eprintln!("{:?}", err);
da7fc7983d 2024-05-23        arcade: 							panic!("unhandled file type error");
da7fc7983d 2024-05-23        arcade: 						}
da7fc7983d 2024-05-23        arcade: 					};
da7fc7983d 2024-05-23        arcade: 				}
da7fc7983d 2024-05-23        arcade: 			};
da7fc7983d 2024-05-23        arcade: 
51adce1e7e 2024-05-22        arcade: 			let sink = sink + samotop::smtp::Lmtp.with(SmtpParser);
da7fc7983d 2024-05-23        arcade: 			task::spawn(async move {
da7fc7983d 2024-05-23        arcade: 				// Postpone mode change on the socket. I can't actually change
da7fc7983d 2024-05-23        arcade: 				// other way, as UnixServer just grabs path, and blocks
da7fc7983d 2024-05-23        arcade: 				task::sleep(Duration::from_secs(1)).await;
da7fc7983d 2024-05-23        arcade: 				std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o777)).unwrap();
da7fc7983d 2024-05-23        arcade: 			});
da7fc7983d 2024-05-23        arcade: 			samotop::server::UnixServer::on(socket_path)
51adce1e7e 2024-05-22        arcade: 				.serve(sink.build()).await.unwrap();
51adce1e7e 2024-05-22        arcade: 		},
51adce1e7e 2024-05-22        arcade: 		_ => {
51adce1e7e 2024-05-22        arcade: 			let sink = sink + samotop::smtp::Esmtp.with(SmtpParser);
51adce1e7e 2024-05-22        arcade: 			samotop::server::TcpServer::on(listen_on)
51adce1e7e 2024-05-22        arcade: 				.serve(sink.build()).await.unwrap();
51adce1e7e 2024-05-22        arcade: 		},
61238a3618 2024-05-22        arcade: 	};
7620f854a7 2024-05-21        arcade: }