Diff
Logged in as anonymous

Differences From Artifact [921384dec4]:

To Artifact [c4a8eb25d5]:


22
23
24
25
26
27
28




29
30
31
32
33
34
35
use std::{
	borrow::Cow,
	collections::{
		HashMap,
		HashSet,
	},
	io::Read,




	path::{
		Path,
		PathBuf
	},
	time::Duration,
	vec::Vec,
};







>
>
>
>







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use std::{
	borrow::Cow,
	collections::{
		HashMap,
		HashSet,
	},
	io::Read,
	os::unix::fs::{
		FileTypeExt,
		PermissionsExt,
	},
	path::{
		Path,
		PathBuf
	},
	time::Duration,
	vec::Vec,
};
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
							},
							_ => {}
						}
					};

					// 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();
						if core.recipients.contains_key(&item) {
							rcpt.insert(core.recipients[&item]);
						} else {
							core.debug(format!("Recipient [{}] not found.", &item)).await.unwrap();
							rcpt.insert(core.default);
						}
					};

					if rcpt.is_empty() {
						rcpt.insert(core.default);
						core.debug("No recipient or envelope address.").await.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() {







|


|
|
|
|
|
|
|
>

<

>







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
							},
							_ => {}
						}
					};

					// 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() {
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
							let data = chunk.contents().to_vec();
							let obj = telegram_bot::types::InputFileUpload::with_data(data, "Attachment");
							core.sendfile(chat, obj).await.unwrap();
						}
					}
				},
				None => { core.debug("None mail.").await.unwrap(); },
				//send_to_sendgrid(mail, sendgrid_api_key).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 {
	default: UserId,
	tg: Api,
	recipients: HashMap<String, UserId>,
}

impl TelegramTransport {
	pub fn new(settings: &config::Config) -> TelegramTransport {
		let api_key = settings.get_string("api_key").unwrap();
		let tg = Api::new(api_key);
		let default_recipient = settings.get_string("default").unwrap();
		let recipients: HashMap<String, UserId> = settings.get_table("recipients").unwrap().into_iter().map(|(a, b)| (a, UserId::new(b.into_int().unwrap()))).collect();




		// Barf if no default
		let default = recipients[&default_recipient];



		TelegramTransport {
			default,
			tg,
			recipients,
		}
	}

	pub async fn debug<'b, S>(&self, msg: S) -> Result<()>
	where S: Into<Cow<'b, str>> {
		task::sleep(Duration::from_secs(5)).await;
		self.tg.send(SendMessage::new(self.default, msg)
			.parse_mode(ParseMode::Markdown)).await?;
		Ok(())
	}

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

	pub async fn sendfile<V>(&self, to: UserId, chunk: V) -> Result<()>
	where V: Into<telegram_bot::InputFile> {
		task::sleep(Duration::from_secs(5)).await;
		self.tg.send(telegram_bot::SendDocument::new(to, chunk)).await?;
		Ok(())
	}
}

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



	let core = TelegramTransport::new(&settings);
	let maildir: PathBuf = settings.get_string("maildir").unwrap().into();

	let listen_on = settings.get_string("listen_on").unwrap();


	let sink = Builder + Name::new("smtp2tg") + DebugService +
		my_prudence() + MailDir::new(maildir.clone()).unwrap();

	task::spawn(async move {
		loop {
			relay_mails(&maildir, &core).unwrap();
			task::sleep(Duration::from_secs(5)).await;
		}
	});

	match listen_on.as_str() {
		"socket" => {























			let sink = sink + samotop::smtp::Lmtp.with(SmtpParser);






			samotop::server::UnixServer::on("./smtp2tg.sock")
				.serve(sink.build()).await.unwrap();
		},
		_ => {
			let sink = sink + samotop::smtp::Esmtp.with(SmtpParser);
			samotop::server::TcpServer::on(listen_on)
				.serve(sink.build()).await.unwrap();
		},
	};
}







<













<





|
|
|
<
|
>
>
>
>
|
|
>
|
>

<








|




|







|











|
>
>

<
|
>
|
>
>












>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
>
|









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
							let data = chunk.contents().to_vec();
							let obj = telegram_bot::types::InputFileUpload::with_data(data, "Attachment");
							core.sendfile(chat, obj).await.unwrap();
						}
					}
				},
				None => { core.debug("None mail.").await.unwrap(); },

			};
		});

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

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")
			.expect("[smtp2tg.toml] missing table \"recipients\".\n")
			.into_iter().map(|(a, b)| (a, UserId::new(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<()>
	where S: Into<Cow<'b, str>> {
		task::sleep(Duration::from_secs(5)).await;
		self.tg.send(SendMessage::new(self.recipients.get("_").unwrap(), msg)
			.parse_mode(ParseMode::Markdown)).await?;
		Ok(())
	}

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

	pub async fn sendfile<V>(&self, to: &UserId, chunk: V) -> Result<()>
	where V: Into<telegram_bot::InputFile> {
		task::sleep(Duration::from_secs(5)).await;
		self.tg.send(telegram_bot::SendDocument::new(to, chunk)).await?;
		Ok(())
	}
}

#[async_std::main]
async fn main() {
	let settings: config::Config = config::Config::builder()
		.add_source(config::File::with_name("smtp2tg.toml"))
		.build()
		.expect("[smtp2tg.toml] there was an error reading config\n\
			\tplease consult \"smtp2tg.toml.example\" for details");


	let maildir: PathBuf = settings.get_string("maildir")
		.expect("[smtp2tg.toml] missing \"maildir\" parameter.\n").into();
	let listen_on = settings.get_string("listen_on")
		.expect("[smtp2tg.toml] missing \"listen_on\" parameter.\n");
	let core = TelegramTransport::new(settings);
	let sink = Builder + Name::new("smtp2tg") + DebugService +
		my_prudence() + MailDir::new(maildir.clone()).unwrap();

	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";
			match std::fs::symlink_metadata(socket_path) {
				Ok(metadata) => {
					if metadata.file_type().is_socket() {
						std::fs::remove_file(socket_path)
							.expect("[smtp2tg] failed to remove old socket.\n");
					} else {
						eprintln!("[smtp2tg] \"./smtp2tg.sock\" we wanted to use is actually not a socket.\n\
							[smtp2tg] please check the file and remove it manually.\n");
						panic!("socket path unavailable");
					}
				},
				Err(err) => {
					match err.kind() {
						std::io::ErrorKind::NotFound => {},
						_ => {
							eprintln!("{:?}", err);
							panic!("unhandled file type error");
						}
					};
				}
			};

			let sink = sink + samotop::smtp::Lmtp.with(SmtpParser);
			task::spawn(async move {
				// Postpone mode change on the socket. I can't actually change
				// other way, as UnixServer just grabs path, and blocks
				task::sleep(Duration::from_secs(1)).await;
				std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o777)).unwrap();
			});
			samotop::server::UnixServer::on(socket_path)
				.serve(sink.build()).await.unwrap();
		},
		_ => {
			let sink = sink + samotop::smtp::Esmtp.with(SmtpParser);
			samotop::server::TcpServer::on(listen_on)
				.serve(sink.build()).await.unwrap();
		},
	};
}