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
|
};
use lazy_static::lazy_static;
use mailin_embedded::{
Response,
response::*,
};
use regex::Regex;
use teloxide::{
Bot,
prelude::{
Requester,
RequesterExt,
},
types::{
ChatId,
InputMedia,
Message,
ParseMode::MarkdownV2,
},
};
use thiserror::Error;
use std::{
borrow::Cow,
collections::{
HashMap,
HashSet,
},
os::unix::fs::PermissionsExt,
path::Path,
vec::Vec,
};
#[derive(Error, Debug)]
pub enum MyError {
#[error("Failed to parse mail")]
BadMail,
#[error("Missing default address in recipient table")]
NoDefault,
#[error("No headers found")]
NoHeaders,
#[error("No recipient addresses")]
NoRecipient,
#[error("Failed to extract text from message")]
NoText,
#[error(transparent)]
RequestError(#[from] teloxide::RequestError),
#[error(transparent)]
TryFromIntError(#[from] std::num::TryFromIntError),
}
/// `SomeHeaders` object to store data through SMTP session
#[derive(Clone, Debug)]
struct SomeHeaders {
from: String,
to: Vec<String>,
}
/// `TelegramTransport` Central object with TG api and configuration
#[derive(Clone)]
struct TelegramTransport {
data: Vec<u8>,
headers: Option<SomeHeaders>,
recipients: HashMap<String, ChatId>,
relay: bool,
tg: teloxide::adaptors::DefaultParseMode<teloxide::adaptors::Throttle<Bot>>,
fields: HashSet<String>,
}
lazy_static! {
static ref RE_SPECIAL: Regex = Regex::new(r"([\-_*\[\]()~`>#+|{}\.!])").unwrap();
}
|
|
|
<
<
<
<
|
>
>
|
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
|
|
|
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
|
};
use lazy_static::lazy_static;
use mailin_embedded::{
Response,
response::*,
};
use regex::Regex;
use tgbot::{
api::Client,
types::{
ChatPeerId,
InputFile,
InputFileReader,
InputMediaDocument,
MediaGroup,
MediaGroupItem,
Message,
ParseMode::MarkdownV2,
SendDocument,
SendMediaGroup,
SendMessage,
},
};
use thiserror::Error;
use std::{
borrow::Cow,
collections::{
HashMap,
HashSet,
},
io::Cursor,
os::unix::fs::PermissionsExt,
path::Path,
vec::Vec,
};
#[derive(Error, Debug)]
pub enum MyError {
#[error("Failed to parse mail")]
BadMail,
#[error("Missing default address in recipient table")]
NoDefault,
#[error("No headers found")]
NoHeaders,
#[error("No recipient addresses")]
NoRecipient,
#[error("Failed to extract text from message")]
NoText,
#[error(transparent)]
RequestError(#[from] tgbot::api::ExecuteError),
#[error(transparent)]
TryFromIntError(#[from] std::num::TryFromIntError),
#[error(transparent)]
InputMediaError(#[from] tgbot::types::InputMediaError),
#[error(transparent)]
MediaGroupError(#[from] tgbot::types::MediaGroupError),
}
/// `SomeHeaders` object to store data through SMTP session
#[derive(Clone, Debug)]
struct SomeHeaders {
from: String,
to: Vec<String>,
}
struct Attachment {
data: Cursor<Vec<u8>>,
name: String,
}
/// `TelegramTransport` Central object with TG api and configuration
#[derive(Clone)]
struct TelegramTransport {
data: Vec<u8>,
headers: Option<SomeHeaders>,
recipients: HashMap<String, ChatPeerId>,
relay: bool,
tg: Client,
fields: HashSet<String>,
}
lazy_static! {
static ref RE_SPECIAL: Regex = Regex::new(r"([\-_*\[\]()~`>#+|{}\.!])").unwrap();
}
|
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
assert_eq!(res, "\\-\\_\\*\\[\\]\\(\\)\\~\\`\\>\\#\\+\\|\\{\\}\\.\\!");
}
}
impl TelegramTransport {
/// Initialize API and read configuration
fn new(settings: config::Config) -> TelegramTransport {
let tg = Bot::new(settings.get_string("api_key")
.expect("[smtp2tg.toml] missing \"api_key\" parameter.\n"))
.throttle(teloxide::adaptors::throttle::Limits::default())
.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, 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");
}
let fields = HashSet::<String>::from_iter(settings.get_array("fields")
|
|
|
<
|
|
|
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
|
assert_eq!(res, "\\-\\_\\*\\[\\]\\(\\)\\~\\`\\>\\#\\+\\|\\{\\}\\.\\!");
}
}
impl TelegramTransport {
/// Initialize API and read configuration
fn new(settings: config::Config) -> TelegramTransport {
let tg = Client::new(settings.get_string("api_key")
.expect("[smtp2tg.toml] missing \"api_key\" parameter.\n"))
.expect("Failed to create API.\n");
let recipients: HashMap<String, ChatPeerId> = settings.get_table("recipients")
.expect("[smtp2tg.toml] missing table \"recipients\".\n")
.into_iter().map(|(a, b)| (a, ChatPeerId::from(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");
}
let fields = HashSet::<String>::from_iter(settings.get_array("fields")
|
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
|
tg,
fields,
}
}
/// Send message to default user, used for debug/log/info purposes
async fn debug (&self, msg: &str) -> Result<Message, MyError> {
Ok(self.tg.send_message(*self.recipients.get("_").ok_or(MyError::NoDefault)?, encode(msg)).await?)
}
/// Send message to specified user
async fn send <S> (&self, to: &ChatId, msg: S) -> Result<Message, MyError>
where S: Into<String> {
Ok(self.tg.send_message(*to, msg).await?)
}
/// Attempt to deliver one message
async fn relay_mail (&self) -> Result<(), MyError> {
if let Some(headers) = &self.headers {
let mail = mail_parser::MessageParser::new().parse(&self.data)
.ok_or(MyError::BadMail)?;
// Adding all known addresses to recipient list, for anyone else adding default
// Also if list is empty also adding default
let mut rcpt: HashSet<&ChatId> = HashSet::new();
if headers.to.is_empty() {
return Err(MyError::NoRecipient);
}
for item in &headers.to {
match self.recipients.get(item) {
Some(addr) => rcpt.insert(addr),
None => {
|
|
|
|
>
>
>
|
|
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
|
tg,
fields,
}
}
/// Send message to default user, used for debug/log/info purposes
async fn debug (&self, msg: &str) -> Result<Message, MyError> {
self.send(self.recipients.get("_").ok_or(MyError::NoDefault)?, encode(msg)).await
}
/// Send message to specified user
async fn send <S> (&self, to: &ChatPeerId, msg: S) -> Result<Message, MyError>
where S: Into<String> {
Ok(self.tg.execute(
SendMessage::new(*to, msg)
.with_parse_mode(MarkdownV2)
).await?)
}
/// Attempt to deliver one message
async fn relay_mail (&self) -> Result<(), MyError> {
if let Some(headers) = &self.headers {
let mail = mail_parser::MessageParser::new().parse(&self.data)
.ok_or(MyError::BadMail)?;
// Adding all known addresses to recipient list, for anyone else adding default
// Also if list is empty also adding default
let mut rcpt: HashSet<&ChatPeerId> = HashSet::new();
if headers.to.is_empty() {
return Err(MyError::NoRecipient);
}
for item in &headers.to {
match self.recipients.get(item) {
Some(addr) => rcpt.insert(addr),
None => {
|
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
|
file_num += 1;
}
let msg = reply.join("\n");
for chat in rcpt {
if !files_to_send.is_empty() {
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());
}
},
_ => {
self.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)
} else {
item
};
files.push(InputMedia::Document(item));
}
self.sendgroup(chat, files).await?;
} else {
self.send(chat, &msg).await?;
}
}
} else {
return Err(MyError::NoHeaders);
}
Ok(())
}
/// Send media to specified user
pub async fn sendgroup <M> (&self, to: &ChatId, media: M) -> Result<Vec<Message>, MyError>
where M: IntoIterator<Item = InputMedia> {
Ok(self.tg.send_media_group(*to, media).await?)
}
}
impl mailin_embedded::Handler for TelegramTransport {
/// Just deny login auth
fn auth_login (&mut self, _username: &str, _password: &str) -> Response {
INVALID_CREDENTIALS
|
|
|
|
|
|
<
<
<
<
<
|
<
|
|
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
|
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
|
file_num += 1;
}
let msg = reply.join("\n");
for chat in rcpt {
if !files_to_send.is_empty() {
let mut files = vec![];
// let mut first_one = true;
for chunk in &files_to_send {
let data: Vec<u8> = chunk.contents().to_vec();
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());
}
},
_ => {
self.debug("Attachment has bad ContentType header.").await?;
},
};
};
};
let filename = if let Some(fname) = filename {
fname
} else {
"Attachment.txt".into()
};
files.push(Attachment {
data: Cursor::new(data),
name: filename,
});
}
self.sendgroup(chat, files, &msg).await?;
} else {
self.send(chat, &msg).await?;
}
}
} else {
return Err(MyError::NoHeaders);
}
Ok(())
}
/// Send media to specified user
pub async fn sendgroup (&self, to: &ChatPeerId, media: Vec<Attachment>, msg: &str) -> Result<(), MyError> {
if media.len() > 1 {
let mut attach = vec![];
let mut pos = media.len();
for file in media {
let mut caption = InputMediaDocument::default();
if pos == 1 {
caption = caption.with_caption(msg)
.with_caption_parse_mode(MarkdownV2);
}
pos -= 1;
attach.push(
MediaGroupItem::for_document(
InputFile::from(
InputFileReader::from(file.data)
.with_file_name(file.name)
),
caption
)
);
}
self.tg.execute(SendMediaGroup::new(*to, MediaGroup::new(attach)?)).await?;
} else {
self.tg.execute(
SendDocument::new(
*to,
InputFileReader::from(media[0].data.clone())
.with_file_name(media[0].name.clone())
).with_caption(msg)
.with_caption_parse_mode(MarkdownV2)
).await?;
}
Ok(())
}
}
impl mailin_embedded::Handler for TelegramTransport {
/// Just deny login auth
fn auth_login (&mut self, _username: &str, _password: &str) -> Response {
INVALID_CREDENTIALS
|