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