Diff
Logged in as anonymous

Differences From Artifact [51f665b0f6]:

To Artifact [2e0e9ab78d]:


11
12
13
14
15
16
17
18
19
20
21









22
23

24
25
26
27
28
29
30
11
12
13
14
15
16
17




18
19
20
21
22
23
24
25
26


27
28
29
30
31
32
33
34







-
-
-
-
+
+
+
+
+
+
+
+
+
-
-
+







		Name
	},
	smtp::{
		SmtpParser,
		Prudence,
	},
};
use telegram_bot::{
	Api,
	MessageOrChannelPost,
	ParseMode,
use teloxide::{
	Bot,
	prelude::{
		Requester,
		RequesterExt,
	},
	types::{
		ChatId,
		ParseMode::MarkdownV2,
	SendMessage,
	UserId,
	},
};

use std::{
	borrow::Cow,
	collections::{
		HashMap,
		HashSet,
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
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







-
-
+
+

-
-
+
+




















-
+


















-
+







	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 mut buf: String = Default::default();
		std::fs::File::open(file.path())?.read_to_string(&mut buf)?;

		let mail = mail_parser::MessageParser::default().parse(&buf[..])
			.ok_or(anyhow!("Failed to parse mail `{:?}`.", file))?.clone();
		let mail = mail_parser::MessageParser::new().parse(&buf)
			.ok_or(anyhow!("Failed to parse mail `{:?}`.", file))?;

		// 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();
		let mut rcpt: HashSet<&ChatId> = 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![];
		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());
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
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







+

+
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+













-
-
+
+




-
-
-
+
+
+
+

-
+













-
-
+
+

-
+
-


-
-
+
+

-
+
-


-
-
+
+

-
-
-
-
-
-
+
-
-
-







		}
		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;
		}

		let msg = reply.join("\n");
		for chat in rcpt {
			if !files_to_send.is_empty() {
			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?;
				let mut files = vec![];
				let mut first_one = true;
				for chunk in &files_to_send {
					let data = chunk.contents();
					let mut filename: Option<String> = None;
					for header in chunk.headers() {
						if header.name() == "Content-Type" {
							match header.value() {
								mail_parser::HeaderValue::ContentType(contenttype) => {
									if let Some(fname) = contenttype.attribute("name") {
										filename = Some(fname.to_owned());
									}
								},
								_ => {
									core.debug("Attachment has bad ContentType header.").await?;
								},
							};
						};
					};
					let filename = if let Some(fname) = filename {
						fname
					} else {
						"Attachment.txt".into()
					};
					let item = teloxide::types::InputMediaDocument::new(
						teloxide::types::InputFile::memory(data.to_vec())
						.file_name(filename));
					let item = if first_one {
						first_one = false;
						item.caption(&msg).parse_mode(MarkdownV2)
					} else {
						item
					};
					files.push(teloxide::types::InputMedia::Document(item));
				}
				core.sendgroup(chat, files).await?;
			} else {
				core.send(chat, &msg).await?;
			}
		}

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

fn my_prudence() -> Prudence {
	Prudence::default().with_read_timeout(Duration::from_secs(60)).with_banner_delay(Duration::from_secs(1))
}

pub struct TelegramTransport {
	tg: Api,
	recipients: HashMap<String, UserId>,
	tg: teloxide::adaptors::DefaultParseMode<Bot>,
	recipients: HashMap<String, ChatId>,
}

impl TelegramTransport {
	pub fn new(settings: config::Config) -> TelegramTransport {
		let tg = Api::new(settings.get_string("api_key")
			.expect("[smtp2tg.toml] missing \"api_key\" parameter.\n"));
		let recipients: HashMap<String, UserId> = settings.get_table("recipients")
		let tg = Bot::new(settings.get_string("api_key")
			.expect("[smtp2tg.toml] missing \"api_key\" parameter.\n"))
			.parse_mode(MarkdownV2);
		let recipients: HashMap<String, ChatId> = settings.get_table("recipients")
			.expect("[smtp2tg.toml] missing table \"recipients\".\n")
			.into_iter().map(|(a, b)| (a, UserId::new(b.into_int()
			.into_iter().map(|(a, b)| (a, ChatId (b.into_int()
				.expect("[smtp2tg.toml] \"recipient\" table values should be integers.\n")
				))).collect();
		if !recipients.contains_key("_") {
			eprintln!("[smtp2tg.toml] \"recipient\" table misses \"default_recipient\".\n");
			panic!("no default recipient");
		}

		TelegramTransport {
			tg,
			recipients,
		}
	}

	pub async fn debug<'b, S>(&self, msg: S) -> Result<MessageOrChannelPost>
	where S: Into<Cow<'b, str>> {
	pub async fn debug<'b, S>(&self, msg: S) -> Result<teloxide::types::Message>
	where S: Into<String> {
		task::sleep(Duration::from_secs(5)).await;
		Ok(self.tg.send(SendMessage::new(self.recipients.get("_").unwrap(), msg)
		Ok(self.tg.send_message(*self.recipients.get("_").unwrap(), msg).await?)
			.parse_mode(ParseMode::Markdown)).await?)
	}

	pub async fn send<'b, S>(&self, to: &UserId, msg: S) -> Result<MessageOrChannelPost>
	where S: Into<Cow<'b, str>> {
	pub async fn send<'b, S>(&self, to: &ChatId, msg: S) -> Result<teloxide::types::Message>
	where S: Into<String> {
		task::sleep(Duration::from_secs(5)).await;
		Ok(self.tg.send(SendMessage::new(to, msg)
		Ok(self.tg.send_message(*to, msg).await?)
			.parse_mode(ParseMode::Markdown)).await?)
	}

	pub async fn sendfile<V>(&self, to: &UserId, chunk: V, basic_mail: Option<&MessageOrChannelPost>) -> Result<()>
	where V: Into<telegram_bot::InputFile> {
	pub async fn sendgroup<M>(&self, to: &ChatId, media: M) -> Result<Vec<teloxide::types::Message>>
	where M: IntoIterator<Item = teloxide::types::InputMedia> {
		task::sleep(Duration::from_secs(5)).await;
		match basic_mail {
			Some(post) => {
				self.tg.send(telegram_bot::SendDocument::new(to, chunk).reply_to(post)).await?;
			},
			None => {
				self.tg.send(telegram_bot::SendDocument::new(to, chunk)).await?;
		Ok(self.tg.send_media_group(*to, media).await?)
			},
		};
		Ok(())
	}
}

#[async_std::main]
async fn main() {
	let settings: config::Config = config::Config::builder()
		.add_source(config::File::with_name("smtp2tg.toml"))