]> git.giacomolli.uk - onechat/blob - telegram_api.go
Log image and message sends
[onechat] / telegram_api.go
1 package main
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "mime/multipart"
11 "net/http"
12 "net/url"
13 "path"
14 "strconv"
15 "strings"
16 "time"
17 )
18
19 const (
20 // telegramUpdateWaitTimeout is how long one getUpdates call waits for
21 // an update.
22 telegramUpdateWaitTimeout = 50 * time.Second
23
24 // telegramPollSlack is how much longer than telegramUpdateWaitTimeout a
25 // getUpdates call can take before the bot gives it up.
26 telegramPollSlack = 20 * time.Second
27
28 // telegramPollTimeout is how long one getUpdates call can take.
29 telegramPollTimeout = telegramUpdateWaitTimeout + telegramPollSlack
30
31 // telegramSendTimeout is how long a sendMessage or sendRichMessage call
32 // can take. A connection that stops without a close, such as after a
33 // network change, then fails the call, and the sender tries again,
34 // instead of a wait until TCP gives up. The client has no timeout of
35 // its own, because the long poll of getUpdates needs a longer limit.
36 telegramSendTimeout = 30 * time.Second
37
38 // telegramFileLookupTimeout is the longest wait for image file details.
39 telegramFileLookupTimeout = 30 * time.Second
40
41 // telegramImageDownloadTimeout is the longest wait for image bytes.
42 telegramImageDownloadTimeout = 30 * time.Second
43
44 // telegramTypingTimeout is the longest wait to show the typing action.
45 telegramTypingTimeout = 30 * time.Second
46
47 // telegramAnswerBytes is the most bytes of one answer of the Bot API.
48 telegramAnswerBytes = 16 << 20
49 )
50
51 // newTelegramAPI returns the client of the Bot API at base with token.
52 func newTelegramAPI(base, token string) *TelegramAPI {
53 return &TelegramAPI{
54 base: base,
55 token: token,
56 http: &http.Client{},
57 }
58 }
59
60 // telegramRetryable tells if a later try of a failed Bot API call can work:
61 // after a network error, HTTP 429, or a server error. It returns the wait that
62 // the Bot API asks for, or 0.
63 func telegramRetryable(err error) (bool, time.Duration) {
64 var network *TelegramNetworkError
65
66 if errors.As(err, &network) {
67 return true, 0
68 }
69
70 var answer *TelegramError
71
72 if errors.As(err, &answer) {
73 return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter
74 }
75
76 return false, 0
77 }
78
79 // telegramRejected tells if the Bot API refused a call with ok false and HTTP
80 // 400 or 404. Then the call did nothing: 400 refuses the request, and 404 tells
81 // that the method is not there. An error page with no Bot API answer does not
82 // tell this, so it is not a refusal.
83 func telegramRejected(err error) bool {
84 var answer *TelegramError
85
86 return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound)
87 }
88
89 // TelegramAPI calls the Telegram Bot API. The bot token is a part of each URL,
90 // so no error of TelegramAPI holds a URL, a net/http error, or the token.
91 type TelegramAPI struct {
92 base string
93 token string
94 http *http.Client
95 }
96
97 // GetUpdates waits for the updates from offset on, up to
98 // telegramUpdateWaitTimeout, and returns them. Telegram forgets each update
99 // before offset. Only new messages are asked for.
100 func (b *TelegramAPI) GetUpdates(ctx context.Context, offset int64) ([]TelegramUpdate, error) {
101 var updates []TelegramUpdate
102
103 err := b.call(ctx, telegramPollTimeout, "getUpdates", map[string]any{
104 "offset": offset,
105 "timeout": int(telegramUpdateWaitTimeout / time.Second),
106 "allowed_updates": []string{"message"},
107 }, &updates)
108
109 return updates, err
110 }
111
112 // GetImage downloads a file through the authenticated file endpoint. Errors
113 // never include its token or URL, and the body is limited before storage.
114 func (b *TelegramAPI) GetImage(ctx context.Context, id string) (data []byte, err error) {
115 var file struct {
116 Path string `json:"file_path"`
117 Size int64 `json:"file_size"`
118 }
119
120 err = b.call(ctx, telegramFileLookupTimeout, "getFile", map[string]any{"file_id": id}, &file)
121 if err != nil {
122 return nil, fmt.Errorf("get image file: %w", err)
123 }
124
125 if file.Size > imageMaxBytes {
126 return nil, errImageSize
127 }
128
129 if file.Path == "" || path.Clean(file.Path) != file.Path || strings.HasPrefix(file.Path, "/") || strings.HasPrefix(file.Path, "../") || strings.ContainsAny(file.Path, "?%#\\") {
130 return nil, errors.New("invalid image file path")
131 }
132
133 ctx, cancel := context.WithTimeout(ctx, telegramImageDownloadTimeout)
134 defer cancel()
135
136 request, err := http.NewRequestWithContext(ctx, http.MethodGet, b.base+"/file/bot"+b.token+"/"+file.Path, nil)
137 if err != nil {
138 return nil, fmt.Errorf("make image request: %s", b.redact(err))
139 }
140
141 response, err := b.http.Do(request)
142 if err != nil {
143 return nil, b.networkError("image download failed", err, telegramImageDownloadTimeout)
144 }
145
146 defer func() {
147 closeErr := response.Body.Close()
148 if closeErr != nil {
149 err = errors.Join(err, b.networkError("close image download", closeErr, telegramImageDownloadTimeout))
150 }
151 }()
152
153 if response.StatusCode != http.StatusOK {
154 return nil, &TelegramError{
155 Status: response.StatusCode,
156 Description: http.StatusText(response.StatusCode),
157 }
158 }
159
160 data, err = io.ReadAll(io.LimitReader(response.Body, imageMaxBytes+1))
161 if err != nil {
162 return nil, b.networkError("image cut off", err, telegramImageDownloadTimeout)
163 }
164
165 if len(data) > imageMaxBytes {
166 return nil, errImageSize
167 }
168
169 return data, nil
170 }
171
172 // SendMessage sends text to chat with the format of entities, with no parse
173 // mode, so the text needs no escaping. With no entities, the text is plain. A
174 // call that takes longer than telegramSendTimeout fails with a
175 // TelegramNetworkError.
176 func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, entities []TelegramEntity) error {
177 params := map[string]any{
178 "chat_id": chat,
179 "text": text,
180 }
181
182 if len(entities) > 0 {
183 params["entities"] = entities
184 }
185
186 return b.call(ctx, telegramSendTimeout, "sendMessage", params, nil)
187 }
188
189 // SendRichMessage sends markdown to chat as a rich message, which Telegram
190 // renders itself, tables included. A call that takes longer than
191 // telegramSendTimeout fails with a TelegramNetworkError.
192 func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown string) error {
193 return b.call(ctx, telegramSendTimeout, "sendRichMessage", map[string]any{
194 "chat_id": chat,
195 "rich_message": map[string]any{
196 "markdown": markdown,
197 },
198 }, nil)
199 }
200
201 // SendImage uploads an image to the owner as a photo, or as a document when the
202 // Bot API refuses the photo. Network failures do not trigger a second send.
203 func (b *TelegramAPI) SendImage(ctx context.Context, chat int64, name string, data []byte, caption string) error {
204 err := b.sendImage(ctx, "sendPhoto", "photo", chat, name, data, caption)
205 if telegramRejected(err) {
206 err = b.sendImage(ctx, "sendDocument", "document", chat, name, data, caption)
207 }
208
209 return err
210 }
211
212 func (b *TelegramAPI) sendImage(ctx context.Context, method, field string, chat int64, name string, data []byte, caption string) error {
213 ctx, cancel := context.WithTimeout(ctx, telegramSendTimeout)
214 defer cancel()
215
216 var body bytes.Buffer
217
218 writer := multipart.NewWriter(&body)
219 err := writer.WriteField("chat_id", strconv.FormatInt(chat, 10))
220 if err != nil {
221 return fmt.Errorf("write image chat: %w", err)
222 }
223
224 err = writer.WriteField("caption", caption)
225 if err != nil {
226 return fmt.Errorf("write image caption: %w", err)
227 }
228
229 part, err := writer.CreateFormFile(field, name)
230 if err != nil {
231 return fmt.Errorf("make image part: %w", err)
232 }
233
234 _, err = part.Write(data)
235 if err != nil {
236 return fmt.Errorf("write image part: %w", err)
237 }
238
239 err = writer.Close()
240 if err != nil {
241 return fmt.Errorf("close image form: %w", err)
242 }
243
244 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, &body)
245 if err != nil {
246 return fmt.Errorf("make image upload: %s", b.redact(err))
247 }
248
249 request.Header.Set("Content-Type", writer.FormDataContentType())
250
251 err = b.answer(request, telegramSendTimeout, nil)
252 if err != nil {
253 return fmt.Errorf("upload image: %w", err)
254 }
255
256 return nil
257 }
258
259 // SendTyping shows the typing action in chat for about five seconds. A call
260 // that takes longer than telegramTypingTimeout fails with a
261 // TelegramNetworkError.
262 func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error {
263 return b.call(ctx, telegramTypingTimeout, "sendChatAction", map[string]any{
264 "chat_id": chat,
265 "action": "typing",
266 }, nil)
267 }
268
269 // call sends one call of method with the JSON params and decodes its result
270 // into result, when result is not nil. The call can take up to timeout. Its
271 // errors tell the cause in plain words, with no method name, so that a log line
272 // can say first what the call was for.
273 func (b *TelegramAPI) call(ctx context.Context, timeout time.Duration, method string, params, result any) error {
274 ctx, cancel := context.WithTimeout(ctx, timeout)
275 defer cancel()
276
277 body, err := json.Marshal(params)
278 if err != nil {
279 return fmt.Errorf("%s: encode request: %w", method, err)
280 }
281
282 request, err := http.NewRequestWithContext(ctx, http.MethodPost, b.base+"/bot"+b.token+"/"+method, bytes.NewReader(body))
283 if err != nil {
284 return fmt.Errorf("%s: make request: %s", method, b.redact(err))
285 }
286
287 request.Header.Set("Content-Type", "application/json")
288
289 return b.answer(request, timeout, result)
290 }
291
292 // answer reads the bounded Bot API response without keeping its request URL.
293 func (b *TelegramAPI) answer(request *http.Request, timeout time.Duration, result any) error {
294 response, err := b.http.Do(request)
295 if err != nil {
296 return b.networkError("no answer", err, timeout)
297 }
298
299 data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes))
300 err = errors.Join(err, response.Body.Close())
301 if err != nil {
302 return b.networkError("answer cut off", err, timeout)
303 }
304
305 var answer TelegramAnswer
306
307 err = json.Unmarshal(data, &answer)
308 if err != nil && response.StatusCode != http.StatusOK {
309 return &TelegramError{
310 Status: response.StatusCode,
311 Description: http.StatusText(response.StatusCode),
312 }
313 }
314
315 if err != nil {
316 return b.networkError("invalid JSON", err, timeout)
317 }
318
319 if !answer.OK {
320 return &TelegramError{
321 Status: response.StatusCode,
322 Description: b.redact(errors.New(answer.Description)),
323 RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second,
324 Refused: true,
325 }
326 }
327
328 if result == nil {
329 return nil
330 }
331
332 err = json.Unmarshal(answer.Result, result)
333 if err != nil {
334 return b.networkError("invalid result", err, timeout)
335 }
336
337 return nil
338 }
339
340 // networkError returns the TelegramNetworkError of err, which happened at the
341 // step that what names. When the call used all of its time timeout, the cause
342 // is "no answer in TIMEOUT", because the Go text of a deadline does not tell
343 // how long the wait was.
344 func (b *TelegramAPI) networkError(what string, err error, timeout time.Duration) error {
345 if errors.Is(err, context.DeadlineExceeded) {
346 return &TelegramNetworkError{
347 Cause: "no answer in " + timeout.String(),
348 }
349 }
350
351 return &TelegramNetworkError{
352 Cause: what + ": " + b.redact(err),
353 }
354 }
355
356 // redact returns the text of err without a URL and without the token. A
357 // *url.Error holds the URL of the call, which holds the token, so only its
358 // cause is kept.
359 func (b *TelegramAPI) redact(err error) string {
360 var urlError *url.Error
361
362 if errors.As(err, &urlError) {
363 err = urlError.Err
364 }
365
366 return strings.ReplaceAll(err.Error(), b.token, "TOKEN")
367 }
368
369 // TelegramNetworkError tells that a Bot API call got no valid answer, such as
370 // after a network error. A later call can work. Cause tells why in plain words,
371 // with no URL and no token.
372 type TelegramNetworkError struct {
373 Cause string
374 }
375
376 func (e *TelegramNetworkError) Error() string {
377 return e.Cause
378 }
379
380 // TelegramError is an answer of the Bot API that tells of a failure. Its text
381 // gives the HTTP status and the description, such as "502 Bad Gateway".
382 // RetryAfter is the wait that the Bot API asks for after HTTP 429. Refused
383 // tells that the answer is a Bot API answer with ok false, not a page of a
384 // proxy or of a server error.
385 type TelegramError struct {
386 Status int
387 Description string
388 RetryAfter time.Duration
389 Refused bool
390 }
391
392 func (e *TelegramError) Error() string {
393 return fmt.Sprintf("%d %s", e.Status, e.Description)
394 }
395
396 // TelegramUpdate is one update of getUpdates. Message is nil for the kinds of
397 // updates that are not a new message.
398 type TelegramUpdate struct {
399 UpdateID int64 `json:"update_id"`
400 Message *TelegramMessage `json:"message"`
401 }
402
403 // TelegramEntity is a message entity of sendMessage: a part of the text with a
404 // format, such as bold or a link. Offset and Length count UTF-16 code units.
405 // URL is the target of a text_link, and Language the language of a pre.
406 type TelegramEntity struct {
407 Type string `json:"type"`
408 Offset int `json:"offset"`
409 Length int `json:"length"`
410 URL string `json:"url,omitempty"`
411 Language string `json:"language,omitempty"`
412 }
413
414 // TelegramAnswer is the envelope of each answer of the Bot API.
415 type TelegramAnswer struct {
416 OK bool `json:"ok"`
417 Result json.RawMessage `json:"result"`
418 ErrorCode int `json:"error_code"`
419 Description string `json:"description"`
420 Parameters struct {
421 RetryAfter int `json:"retry_after"`
422 } `json:"parameters"`
423 }
424
425 // TelegramMessage holds the text, caption, and image sizes of a bot message.
426 type TelegramMessage struct {
427 Chat TelegramChat `json:"chat"`
428 From *TelegramUser `json:"from"`
429 Text string `json:"text"`
430 Caption string `json:"caption"`
431 Photo []TelegramPhoto `json:"photo"`
432 Document *TelegramDocument `json:"document"`
433 }
434
435 // TelegramPhoto is one supplied size of a photo.
436 type TelegramPhoto struct {
437 FileID string `json:"file_id"`
438 Width int `json:"width"`
439 Height int `json:"height"`
440 FileSize int64 `json:"file_size"`
441 }
442
443 // TelegramDocument is a file sent without photo compression.
444 type TelegramDocument struct {
445 FileID string `json:"file_id"`
446 MimeType string `json:"mime_type"`
447 FileSize int64 `json:"file_size"`
448 }
449
450 // TelegramChat is the chat of a message. Type is private for a chat with one
451 // user.
452 type TelegramChat struct {
453 ID int64 `json:"id"`
454 Type string `json:"type"`
455 }
456
457 // TelegramUser is the sender of a message.
458 type TelegramUser struct {
459 ID int64 `json:"id"`
460 }