1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use crate::{
error::sink::Error as SinkError,
sink::{Media, Message},
};
use std::time::Duration;
use teloxide::{
payloads::{SendMediaGroupSetters, SendMessageSetters},
requests::{Request, Requester},
types::{
ChatId, InputFile, InputMedia, InputMediaPhoto, InputMediaVideo, Message as TelMessage,
MessageId, ParseMode,
},
ApiError, Bot, RequestError,
};
use url::Url;
const MAX_MEDIA_MSG_LEN: usize = 1024;
const MAX_TEXT_MSG_LEN: usize = 4096;
pub struct Telegram {
bot: Bot,
chat_id: ChatId,
link_location: LinkLocation,
}
#[derive(Clone, Copy, Default, Debug)]
pub enum LinkLocation {
PreferTitle,
#[default]
Bottom,
}
impl Telegram {
#[must_use]
pub fn new(token: String, chat_id: i64, link_location: LinkLocation) -> Self {
Self {
bot: Bot::new(token),
chat_id: ChatId(chat_id),
link_location,
}
}
#[tracing::instrument(skip_all)]
pub async fn send(&self, message: Message, tag: Option<&str>) -> Result<(), SinkError> {
let Message {
title,
body,
link,
media,
} = message;
tracing::debug!(
"Processing message: title: {title:?}, body len: {}, link: {}, media: {}",
body.as_ref().map_or(0, String::len),
link.is_some(),
media.is_some(),
);
let body = body.map(|s| teloxide::utils::html::escape(&s));
let (head, tail) = format_head_tail(
title.map(|s| teloxide::utils::html::escape(&s)),
link,
tag,
self.link_location,
);
let max_char_limit = if media.is_some() {
MAX_MEDIA_MSG_LEN
} else {
MAX_TEXT_MSG_LEN
};
if head.as_ref().map_or(0, |s| s.chars().count())
+ body.as_ref().map_or(0, |s| s.chars().count())
+ tail.as_ref().map_or(0, |s| s.chars().count())
> max_char_limit
{
let mut msg_parts = MsgParts {
head: head.as_deref(),
body: body.as_deref(),
tail: tail.as_deref(),
};
let mut previous_message = None;
if let Some(media) = media {
let media_caption = msg_parts
.split_msg_at(MAX_MEDIA_MSG_LEN)
.expect("should always return a valid split at least once since msg char len is > max_char_limit");
let sent_msg = self
.send_media_with_reply_id(&media, &media_caption, previous_message)
.await?;
previous_message = Some(sent_msg[0].id);
}
while let Some(text) = msg_parts.split_msg_at(MAX_TEXT_MSG_LEN) {
let sent_msg = self
.send_text_with_reply_id(&text, previous_message)
.await?;
previous_message = Some(sent_msg.id);
}
} else {
let text = format!(
"{}{}{}",
head.as_deref().unwrap_or_default(),
body.as_deref().unwrap_or_default(),
tail.as_deref().unwrap_or_default()
);
if let Some(media) = media {
self.send_media(&media, &text).await?;
} else {
self.send_text(&text).await?;
}
}
Ok(())
}
async fn send_text(&self, message: &str) -> Result<TelMessage, SinkError> {
self.send_text_with_reply_id(message, None).await
}
async fn send_text_with_reply_id(
&self,
message: &str,
reply_to_msg_id: Option<MessageId>,
) -> Result<TelMessage, SinkError> {
tracing::trace!("About to send a text message with contents: {message:?}");
loop {
tracing::info!("Sending text message");
let send_msg_cmd = self
.bot
.send_message(self.chat_id, message)
.parse_mode(ParseMode::Html)
.disable_web_page_preview(true);
let send_msg_cmd = if let Some(id) = reply_to_msg_id {
send_msg_cmd.reply_to_message_id(id)
} else {
send_msg_cmd
};
match send_msg_cmd.send().await {
Ok(message) => return Ok(message),
Err(RequestError::RetryAfter(retry_after)) => {
tracing::warn!(
"Exceeded rate limit, retrying in {}s",
retry_after.as_secs()
);
tokio::time::sleep(retry_after).await;
}
Err(e) => {
return Err(SinkError::Telegram {
source: e,
msg: Box::new(message.to_owned()),
});
}
}
}
}
async fn send_media(
&self,
media: &[Media],
caption: &str,
) -> Result<Vec<TelMessage>, SinkError> {
self.send_media_with_reply_id(media, caption, None).await
}
async fn send_media_with_reply_id(
&self,
media: &[Media],
caption: &str,
reply_to_msg_id: Option<MessageId>,
) -> Result<Vec<TelMessage>, SinkError> {
tracing::trace!(
"About to send a media message with caption: {caption:?}, and media: {media:?}"
);
let media = media
.iter()
.map(|x| match x {
Media::Photo(url) => InputMedia::Photo(
InputMediaPhoto::new(InputFile::url(url.clone()))
.caption(caption)
.parse_mode(ParseMode::Html),
),
Media::Video(url) => InputMedia::Video(
InputMediaVideo::new(InputFile::url(url.clone()))
.caption(caption)
.parse_mode(ParseMode::Html),
),
})
.collect::<Vec<InputMedia>>();
let mut retry_counter = 0;
loop {
tracing::info!("Sending media message");
let send_msg_cmd = self.bot.send_media_group(self.chat_id, media.clone());
let send_msg_cmd = if let Some(id) = reply_to_msg_id {
send_msg_cmd.reply_to_message_id(id)
} else {
send_msg_cmd
};
match send_msg_cmd.send().await {
Ok(messages) => return Ok(messages),
Err(RequestError::RetryAfter(retry_after)) => {
tracing::warn!(
"Exceeded rate limit, retrying in {}s",
retry_after.as_secs()
);
tokio::time::sleep(retry_after).await;
}
Err(e @ RequestError::Api(ApiError::FailedToGetUrlContent)) => {
if retry_counter > 5 {
tracing::error!(
"Telegram failed tp get URL content too many times, exiting..."
);
return Err(SinkError::Telegram {
source: e,
msg: Box::new(media),
});
}
tracing::warn!("Telegram failed to get URL content. Retrying in 30 seconds");
tokio::time::sleep(Duration::from_secs(30)).await;
retry_counter += 1;
}
Err(RequestError::Api(ApiError::WrongFileIdOrUrl)) => {
tracing::warn!("Telegram disliked the media URL (\"Bad Request: wrong file identifier/HTTP URL specified\"), sending the message as pure text");
self.send_text(caption).await?;
}
Err(e) => {
return Err(SinkError::Telegram {
source: e,
msg: Box::new(media),
});
}
}
}
}
}
fn format_head_tail(
title: Option<String>,
link: Option<Url>,
tag: Option<&str>,
link_location: LinkLocation,
) -> (Option<String>, Option<String>) {
let (mut head, tail) = match (title, link) {
(Some(title), Some(link)) => match link_location {
LinkLocation::PreferTitle => (Some(format!("<a href=\"{link}\">{title}</a>\n")), None),
LinkLocation::Bottom => (
Some(format!("{title}\n\n")),
Some(format!("\n<a href=\"{link}\">Link</a>")),
),
},
(Some(title), None) => (Some(format!("{title}\n\n")), None),
(None, Some(link)) => (None, Some(format!("\n<a href=\"{link}\">Link</a>"))),
(None, None) => (None, None),
};
if let Some(tag) = tag {
let tag = tag.replace(
|c| match c {
'_' => false,
c if c.is_alphabetic() || c.is_ascii_digit() => false,
_ => true,
},
"_",
);
let mut head_wip = head.unwrap_or_default();
head_wip.insert_str(0, &format!("#{tag}\n\n"));
head = Some(head_wip);
}
(head, tail)
}
#[derive(Debug)]
struct MsgParts<'a> {
head: Option<&'a str>,
body: Option<&'a str>,
tail: Option<&'a str>,
}
impl MsgParts<'_> {
fn split_msg_at(&mut self, len: usize) -> Option<String> {
if self.head.is_none() && self.body.is_none() && self.tail.is_none() {
return None;
}
assert!(len >= self.head.map_or(0, |s| s.chars().count()));
assert!(len >= self.tail.map_or(0, |s| s.chars().count()));
let mut split_part = String::with_capacity(len);
if let Some(head) = self.head.take() {
split_part.push_str(head);
}
if let Some(body) = self.body.take() {
let space_left_for_body = len.checked_sub(split_part.chars().count()).expect("only the head should've been pushed to the split and we asserted that it isn't longer than len");
let body_fits_till = body
.char_indices()
.nth(space_left_for_body)
.map_or_else(|| body.len(), |(idx, _)| idx);
if body_fits_till > 0 {
split_part.push_str(&body[..body_fits_till]);
let remaining_body = &body[body_fits_till..];
if !remaining_body.is_empty() {
self.body = Some(remaining_body);
}
}
}
if split_part.chars().count() > self.tail.map_or(0, |s| s.chars().count()) {
if let Some(tail) = self.tail.take() {
split_part.push_str(tail);
}
}
assert!(split_part.chars().count() <= len);
Some(split_part)
}
}
impl std::fmt::Debug for Telegram {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Telegram")
.field("chat_id", &self.chat_id)
.finish_non_exhaustive()
}
}