Diff
Logged in as anonymous

Differences From Artifact [b5c79e7814]:

To Artifact [51f665b0f6]:


1



2
3
4
5
6
7
8
use anyhow::Result;



use async_std::task;
use samotop::{
	mail::{
		Builder,
		DebugService,
		MailDir,
		Name
|
>
>
>







1
2
3
4
5
6
7
8
9
10
11
use anyhow::{
	anyhow,
	Result,
};
use async_std::task;
use samotop::{
	mail::{
		Builder,
		DebugService,
		MailDir,
		Name
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
	vec::Vec,
};

fn address_into_iter<'a>(addr: &'a mail_parser::Address<'a, >) -> impl Iterator<Item = Cow<'a, str>> {
	addr.clone().into_list().into_iter().map(|a| a.address.unwrap())
}

fn relay_mails(maildir: &Path, core: &TelegramTransport) -> Result<()> {
	let new_dir = maildir.join("new");

	std::fs::create_dir_all(&new_dir)?;

	let files = std::fs::read_dir(new_dir)?;
	for file in files {
		let file = file?;
		let mut buf = Vec::new();
		std::fs::File::open(file.path())?.read_to_end(&mut buf)?;

		task::block_on(async move {
			match mail_parser::MessageParser::default().parse(&buf[..]) {
				Some(mail) => {
					let mail = mail.clone();

					// Fetching address lists from fields we know
					let mut to = HashSet::new();
					if let Some(addr) = mail.to() {
						let _ = address_into_iter(addr).map(|x| to.insert(x));
					};
					if let Some(addr) = mail.header("X-Samotop-To") {
						match addr {
							mail_parser::HeaderValue::Address(addr) => {
								let _ = address_into_iter(addr).map(|x| to.insert(x));
							},
							mail_parser::HeaderValue::Text(text) => {
								to.insert(text.clone());
							},
							_ => {}
						}
					};

					// Adding all known addresses to recipient list, for anyone else adding default
					// Also if list is empty also adding default
					let mut rcpt: HashSet<&UserId> = HashSet::new();
					for item in to {
						let item = item.into_owned();
						match core.recipients.get(&item) {
							Some(addr) => rcpt.insert(addr),
							None => {
								core.debug(format!("Recipient [{}] not found.", &item)).await.unwrap();
								rcpt.insert(core.recipients.get("_").unwrap())

							}
						};
					};
					if rcpt.is_empty() {
						core.debug("No recipient or envelope address.").await.unwrap();
						rcpt.insert(core.recipients.get("_").unwrap());

					};

					// prepating message header
					let mut reply: Vec<Cow<str>> = vec![];
					if let Some(subject) = mail.subject() {
						reply.push(format!("**Subject:** `{}`", subject).into());
					} else if let Some(thread) = mail.thread_name() {
						reply.push(format!("**Thread:** `{}`", thread).into());
					}
					if let Some(from) = mail.from() {
						reply.push(format!("**From:** `{:?}`", address_into_iter(from).collect::<Vec<_>>().join(", ")).into());
					}
					if let Some(sender) = mail.sender() {
						reply.push(format!("**Sender:** `{:?}`", address_into_iter(sender).collect::<Vec<_>>().join(", ")).into());
					}
					reply.push("".into());
					let header_size = reply.join("\n").len() + 1;

					let html_parts = mail.html_body_count();
					let text_parts = mail.text_body_count();
					let attachments = mail.attachment_count();
					if html_parts != text_parts {
						core.debug(format!("Hm, we have {} HTML parts and {} text parts.", html_parts, text_parts)).await.unwrap();
					}
					//let mut html_num = 0;
					let mut text_num = 0;
					let mut file_num = 0;
					// let's display first html or text part as body
					let mut body = "".into();
					/*
					 * actually I don't wanna parse that html stuff
					if html_parts > 0 {
						let text = mail.body_html(0).unwrap();
						if text.len() < 4096 - header_size {
							body = text;
							html_num = 1;
						}
					};
					*/
					if body == "" && text_parts > 0 {
						let text = mail.body_text(0).unwrap();

						if text.len() < 4096 - header_size {
							body = text;
							text_num = 1;
						}
					};
					reply.push("```".into());
					for line in body.lines() {
						reply.push(line.into());
					}
					reply.push("```".into());

					// and let's collect all other attachment parts
					let mut files_to_send = vec![];
					/*
					 * let's just skip html parts for now, they just duplicate text?
					while html_num < html_parts {
						files_to_send.push(mail.html_part(html_num).unwrap());
						html_num += 1;
					}
					*/
					while text_num < text_parts {
						files_to_send.push(mail.text_part(text_num).unwrap());

						text_num += 1;
					}
					while file_num < attachments {
						files_to_send.push(mail.attachment(file_num).unwrap());

						file_num += 1;
					}

					for chat in rcpt {
						let base_post = core.send(chat, reply.join("\n")).await.unwrap();
						for chunk in &files_to_send {
							let data = chunk.contents().to_vec();
							let obj = telegram_bot::types::InputFileUpload::with_data(data, "Attachment");
							core.sendfile(chat, obj, Some(&base_post)).await.unwrap();
						}
					}
				},
				None => { core.debug("None mail.").await.unwrap(); },
			};
		});

		std::fs::remove_file(file.path())?;
	}
	Ok(())
}

fn my_prudence() -> Prudence {







|










<
|
<
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
>
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
>
|
|

|
|
|
|
|
|
|
|
<
<
<
<







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
	vec::Vec,
};

fn address_into_iter<'a>(addr: &'a mail_parser::Address<'a, >) -> impl Iterator<Item = Cow<'a, str>> {
	addr.clone().into_list().into_iter().map(|a| a.address.unwrap())
}

async fn relay_mails(maildir: &Path, core: &TelegramTransport) -> Result<()> {
	let new_dir = maildir.join("new");

	std::fs::create_dir_all(&new_dir)?;

	let files = std::fs::read_dir(new_dir)?;
	for file in files {
		let file = file?;
		let mut buf = Vec::new();
		std::fs::File::open(file.path())?.read_to_end(&mut buf)?;


		let mail = mail_parser::MessageParser::default().parse(&buf[..])

			.ok_or(anyhow!("Failed to parse mail `{:?}`.", file))?.clone();

		// Fetching address lists from fields we know
		let mut to = HashSet::new();
		if let Some(addr) = mail.to() {
			let _ = address_into_iter(addr).map(|x| to.insert(x));
		};
		if let Some(addr) = mail.header("X-Samotop-To") {
			match addr {
				mail_parser::HeaderValue::Address(addr) => {
					let _ = address_into_iter(addr).map(|x| to.insert(x));
				},
				mail_parser::HeaderValue::Text(text) => {
					to.insert(text.clone());
				},
				_ => {}
			}
		};

		// Adding all known addresses to recipient list, for anyone else adding default
		// Also if list is empty also adding default
		let mut rcpt: HashSet<&UserId> = HashSet::new();
		for item in to {
			let item = item.into_owned();
			match core.recipients.get(&item) {
				Some(addr) => rcpt.insert(addr),
				None => {
					core.debug(format!("Recipient [{}] not found.", &item)).await?;
					rcpt.insert(core.recipients.get("_")
						.ok_or(anyhow!("Missing default address in recipient table."))?)
				}
			};
		};
		if rcpt.is_empty() {
			core.debug("No recipient or envelope address.").await?;
			rcpt.insert(core.recipients.get("_")
				.ok_or(anyhow!("Missing default address in recipient table."))?);
		};

		// prepating message header
		let mut reply: Vec<Cow<str>> = vec![];
		if let Some(subject) = mail.subject() {
			reply.push(format!("**Subject:** `{}`", subject).into());
		} else if let Some(thread) = mail.thread_name() {
			reply.push(format!("**Thread:** `{}`", thread).into());
		}
		if let Some(from) = mail.from() {
			reply.push(format!("**From:** `{:?}`", address_into_iter(from).collect::<Vec<_>>().join(", ")).into());
		}
		if let Some(sender) = mail.sender() {
			reply.push(format!("**Sender:** `{:?}`", address_into_iter(sender).collect::<Vec<_>>().join(", ")).into());
		}
		reply.push("".into());
		let header_size = reply.join("\n").len() + 1;

		let html_parts = mail.html_body_count();
		let text_parts = mail.text_body_count();
		let attachments = mail.attachment_count();
		if html_parts != text_parts {
			core.debug(format!("Hm, we have {} HTML parts and {} text parts.", html_parts, text_parts)).await?;
		}
		//let mut html_num = 0;
		let mut text_num = 0;
		let mut file_num = 0;
		// let's display first html or text part as body
		let mut body = "".into();
		/*
		 * actually I don't wanna parse that html stuff
		if html_parts > 0 {
			let text = mail.body_html(0).unwrap();
			if text.len() < 4096 - header_size {
				body = text;
				html_num = 1;
			}
		};
		*/
		if body == "" && text_parts > 0 {
			let text = mail.body_text(0)
				.ok_or(anyhow!("Failed to extract text from message."))?;
			if text.len() < 4096 - header_size {
				body = text;
				text_num = 1;
			}
		};
		reply.push("```".into());
		for line in body.lines() {
			reply.push(line.into());
		}
		reply.push("```".into());

		// and let's collect all other attachment parts
		let mut files_to_send = vec![];
		/*
		 * let's just skip html parts for now, they just duplicate text?
		while html_num < html_parts {
			files_to_send.push(mail.html_part(html_num).unwrap());
			html_num += 1;
		}
		*/
		while text_num < text_parts {
			files_to_send.push(mail.text_part(text_num)
				.ok_or(anyhow!("Failed to get text part from message"))?);
			text_num += 1;
		}
		while file_num < attachments {
			files_to_send.push(mail.attachment(file_num)
				.ok_or(anyhow!("Failed to get file part from message"))?);
			file_num += 1;
		}

		for chat in rcpt {
			let base_post = core.send(chat, reply.join("\n")).await?;
			for chunk in &files_to_send {
				let data = chunk.contents().to_vec();
				let obj = telegram_bot::types::InputFileUpload::with_data(data, "Attachment");
				core.sendfile(chat, obj, Some(&base_post)).await?;
			}
		}





		std::fs::remove_file(file.path())?;
	}
	Ok(())
}

fn my_prudence() -> Prudence {
254
255
256
257
258
259
260

261







262
263
264
265
266
267
268
	let sink = Builder + Name::new("smtp2tg") + DebugService +
		my_prudence() + MailDir::new(maildir.clone()).unwrap();

	env_logger::init();

	task::spawn(async move {
		loop {

			relay_mails(&maildir, &core).unwrap();







			task::sleep(Duration::from_secs(5)).await;
		}
	});

	match listen_on.as_str() {
		"socket" => {
			let socket_path = "./smtp2tg.sock";







>
|
>
>
>
>
>
>
>







256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
	let sink = Builder + Name::new("smtp2tg") + DebugService +
		my_prudence() + MailDir::new(maildir.clone()).unwrap();

	env_logger::init();

	task::spawn(async move {
		loop {
			// relay mails
			if let Err(err) = relay_mails(&maildir, &core).await {
				// in case that fails - inform default recipient
				if let Err(err) = core.debug(format!("Sending emails failed:\n{:?}", err)).await {
					// in case that also fails - write some logs and bail
					eprintln!("Failed to contact Telegram:\n{:?}", err);
					task::sleep(Duration::from_secs(5 * 60)).await;
				};
			};
			task::sleep(Duration::from_secs(5)).await;
		}
	});

	match listen_on.as_str() {
		"socket" => {
			let socket_path = "./smtp2tg.sock";