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