X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/09cde69fdffe2721434392036f98dc241177f5a1..6915dbdfeb246551bf1132823d820beb321fd58c:/telegram_api.go?ds=inline diff --git a/telegram_api.go b/telegram_api.go index 558d006..32ad9a9 100644 --- a/telegram_api.go +++ b/telegram_api.go @@ -9,6 +9,7 @@ import ( "io" "net/http" "net/url" + "path" "strings" "time" ) @@ -22,6 +23,9 @@ const ( // getUpdates call can take before the bot gives it up. telegramPollSlack = 20 * time.Second + // telegramPollTimeout is how long one getUpdates call can take. + telegramPollTimeout = telegramPollSeconds*time.Second + telegramPollSlack + // telegramSendTimeout is how long a sendMessage, sendRichMessage, or // sendChatAction call can take. A connection that stops without a // close, such as after a network change, then fails the call, and the @@ -34,10 +38,6 @@ const ( telegramAnswerBytes = 16 << 20 ) -// errTelegramNetwork tells that a Bot API call got no valid answer, such as -// after a network error. A later call can work. -var errTelegramNetwork = errors.New("no valid answer from the Bot API") - // newTelegramAPI returns the client of the Bot API at base with token. func newTelegramAPI(base, token string) *TelegramAPI { return &TelegramAPI{ @@ -52,11 +52,14 @@ func newTelegramAPI(base, token string) *TelegramAPI { // after a network error, HTTP 429, or a server error. It returns the wait that // the Bot API asks for, or 0. func telegramRetryable(err error) (bool, time.Duration) { - if errors.Is(err, errTelegramNetwork) { + var network *TelegramNetworkError + + if errors.As(err, &network) { return true, 0 } var answer *TelegramError + if errors.As(err, &answer) { return answer.Status == http.StatusTooManyRequests || answer.Status >= 500, answer.RetryAfter } @@ -70,13 +73,14 @@ func telegramRetryable(err error) (bool, time.Duration) { // tell this, so it is not a refusal. func telegramRejected(err error) bool { var answer *TelegramError + return errors.As(err, &answer) && answer.Refused && (answer.Status == http.StatusBadRequest || answer.Status == http.StatusNotFound) } // TelegramAPI calls the Telegram Bot API. The bot token is a part of each URL, -// so no error of TelegramAPI holds a URL, a net/http error, or the token. -// SendTimeout limits each sendMessage, sendRichMessage, and sendChatAction -// call. +// so no error of TelegramAPI holds a URL, a net/http error, or the token. Its +// sendTimeout field limits each sendMessage, sendRichMessage, and +// sendChatAction call. type TelegramAPI struct { base string token string @@ -88,11 +92,9 @@ type TelegramAPI struct { // and returns them. Telegram forgets each update before offset. Only new // messages are asked for. func (b *TelegramAPI) GetUpdates(ctx context.Context, offset int64) ([]TelegramUpdate, error) { - ctx, cancel := context.WithTimeout(ctx, telegramPollSeconds*time.Second+telegramPollSlack) - defer cancel() - var updates []TelegramUpdate - err := b.call(ctx, "getUpdates", map[string]any{ + + err := b.call(ctx, telegramPollTimeout, "getUpdates", map[string]any{ "offset": offset, "timeout": telegramPollSeconds, "allowed_updates": []string{"message"}, @@ -101,14 +103,71 @@ func (b *TelegramAPI) GetUpdates(ctx context.Context, offset int64) ([]TelegramU return updates, err } -// SendMessage sends text to chat with the format of entities, with no parse -// mode, so the text needs no escaping. With no entities, the text is plain. A -// call that takes longer than telegramSendTimeout fails with -// errTelegramNetwork. -func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, entities []TelegramEntity) error { +// GetImage downloads a file through the authenticated file endpoint. Errors +// never include its token or URL, and the body is limited before storage. +func (b *TelegramAPI) GetImage(ctx context.Context, id string) (data []byte, err error) { + var file struct { + Path string `json:"file_path"` + Size int64 `json:"file_size"` + } + + err = b.call(ctx, b.sendTimeout, "getFile", map[string]any{"file_id": id}, &file) + if err != nil { + return nil, fmt.Errorf("get image file: %w", err) + } + + if file.Size > imageMaxBytes { + return nil, errImageSize + } + + if file.Path == "" || path.Clean(file.Path) != file.Path || strings.HasPrefix(file.Path, "/") || strings.HasPrefix(file.Path, "../") || strings.ContainsAny(file.Path, "?%#\\") { + return nil, errors.New("invalid image file path") + } + ctx, cancel := context.WithTimeout(ctx, b.sendTimeout) defer cancel() + request, err := http.NewRequestWithContext(ctx, http.MethodGet, b.base+"/file/bot"+b.token+"/"+file.Path, nil) + if err != nil { + return nil, fmt.Errorf("make image request: %s", b.redact(err)) + } + + response, err := b.http.Do(request) + if err != nil { + return nil, b.networkError("image download failed", err, b.sendTimeout) + } + + defer func() { + closeErr := response.Body.Close() + if closeErr != nil { + err = errors.Join(err, b.networkError("close image download", closeErr, b.sendTimeout)) + } + }() + + if response.StatusCode != http.StatusOK { + return nil, &TelegramError{ + Status: response.StatusCode, + Description: http.StatusText(response.StatusCode), + } + } + + data, err = io.ReadAll(io.LimitReader(response.Body, imageMaxBytes+1)) + if err != nil { + return nil, b.networkError("image cut off", err, b.sendTimeout) + } + + if len(data) > imageMaxBytes { + return nil, errImageSize + } + + return data, nil +} + +// SendMessage sends text to chat with the format of entities, with no parse +// mode, so the text needs no escaping. With no entities, the text is plain. A +// call that takes longer than telegramSendTimeout fails with a +// TelegramNetworkError. +func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, entities []TelegramEntity) error { params := map[string]any{ "chat_id": chat, "text": text, @@ -118,17 +177,14 @@ func (b *TelegramAPI) SendMessage(ctx context.Context, chat int64, text string, params["entities"] = entities } - return b.call(ctx, "sendMessage", params, nil) + return b.call(ctx, b.sendTimeout, "sendMessage", params, nil) } // SendRichMessage sends markdown to chat as a rich message, which Telegram // renders itself, tables included. A call that takes longer than -// telegramSendTimeout fails with errTelegramNetwork. +// telegramSendTimeout fails with a TelegramNetworkError. func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown string) error { - ctx, cancel := context.WithTimeout(ctx, b.sendTimeout) - defer cancel() - - return b.call(ctx, "sendRichMessage", map[string]any{ + return b.call(ctx, b.sendTimeout, "sendRichMessage", map[string]any{ "chat_id": chat, "rich_message": map[string]any{ "markdown": markdown, @@ -137,20 +193,22 @@ func (b *TelegramAPI) SendRichMessage(ctx context.Context, chat int64, markdown } // SendTyping shows the typing action in chat for about five seconds. A call -// that takes longer than telegramSendTimeout fails with errTelegramNetwork. +// that takes longer than telegramSendTimeout fails with a TelegramNetworkError. func (b *TelegramAPI) SendTyping(ctx context.Context, chat int64) error { - ctx, cancel := context.WithTimeout(ctx, b.sendTimeout) - defer cancel() - - return b.call(ctx, "sendChatAction", map[string]any{ + return b.call(ctx, b.sendTimeout, "sendChatAction", map[string]any{ "chat_id": chat, "action": "typing", }, nil) } // call sends one call of method with the JSON params and decodes its result -// into result, when result is not nil. -func (b *TelegramAPI) call(ctx context.Context, method string, params, result any) error { +// into result, when result is not nil. The call can take up to timeout. Its +// errors tell the cause in plain words, with no method name, so that a log line +// can say first what the call was for. +func (b *TelegramAPI) call(ctx context.Context, timeout time.Duration, method string, params, result any) error { + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + body, err := json.Marshal(params) if err != nil { return fmt.Errorf("%s: encode request: %w", method, err) @@ -162,34 +220,34 @@ func (b *TelegramAPI) call(ctx context.Context, method string, params, result an } request.Header.Set("Content-Type", "application/json") + response, err := b.http.Do(request) if err != nil { - return fmt.Errorf("%s: %w: %s", method, errTelegramNetwork, b.redact(err)) + return b.networkError("no answer", err, timeout) } data, err := io.ReadAll(io.LimitReader(response.Body, telegramAnswerBytes)) err = errors.Join(err, response.Body.Close()) if err != nil { - return fmt.Errorf("%s: %w: read answer: %s", method, errTelegramNetwork, b.redact(err)) + return b.networkError("answer cut off", err, timeout) } var answer TelegramAnswer + err = json.Unmarshal(data, &answer) if err != nil && response.StatusCode != http.StatusOK { return &TelegramError{ - Method: method, Status: response.StatusCode, Description: http.StatusText(response.StatusCode), } } if err != nil { - return fmt.Errorf("%s: %w: decode answer: %s", method, errTelegramNetwork, b.redact(err)) + return b.networkError("invalid JSON", err, timeout) } if !answer.OK { return &TelegramError{ - Method: method, Status: response.StatusCode, Description: b.redact(errors.New(answer.Description)), RetryAfter: time.Duration(answer.Parameters.RetryAfter) * time.Second, @@ -203,17 +261,34 @@ func (b *TelegramAPI) call(ctx context.Context, method string, params, result an err = json.Unmarshal(answer.Result, result) if err != nil { - return fmt.Errorf("%s: %w: decode result: %s", method, errTelegramNetwork, b.redact(err)) + return b.networkError("invalid result", err, timeout) } return nil } +// networkError returns the TelegramNetworkError of err, which happened at the +// step that what names. When the call used all of its time timeout, the cause +// is "no answer in TIMEOUT", because the Go text of a deadline does not tell +// how long the wait was. +func (b *TelegramAPI) networkError(what string, err error, timeout time.Duration) error { + if errors.Is(err, context.DeadlineExceeded) { + return &TelegramNetworkError{ + Cause: "no answer in " + timeout.String(), + } + } + + return &TelegramNetworkError{ + Cause: what + ": " + b.redact(err), + } +} + // redact returns the text of err without a URL and without the token. A // *url.Error holds the URL of the call, which holds the token, so only its // cause is kept. func (b *TelegramAPI) redact(err error) string { var urlError *url.Error + if errors.As(err, &urlError) { err = urlError.Err } @@ -221,12 +296,23 @@ func (b *TelegramAPI) redact(err error) string { return strings.ReplaceAll(err.Error(), b.token, "TOKEN") } -// TelegramError is an answer of the Bot API that tells of a failure. RetryAfter -// is the wait that the Bot API asks for after HTTP 429. Refused tells that the -// answer is a Bot API answer with ok false, not a page of a proxy or of a -// server error. +// TelegramNetworkError tells that a Bot API call got no valid answer, such as +// after a network error. A later call can work. Cause tells why in plain words, +// with no URL and no token. +type TelegramNetworkError struct { + Cause string +} + +func (e *TelegramNetworkError) Error() string { + return e.Cause +} + +// TelegramError is an answer of the Bot API that tells of a failure. Its text +// gives the HTTP status and the description, such as "502 Bad Gateway". +// RetryAfter is the wait that the Bot API asks for after HTTP 429. Refused +// tells that the answer is a Bot API answer with ok false, not a page of a +// proxy or of a server error. type TelegramError struct { - Method string Status int Description string RetryAfter time.Duration @@ -234,7 +320,7 @@ type TelegramError struct { } func (e *TelegramError) Error() string { - return fmt.Sprintf("%s: Bot API answered %d: %s", e.Method, e.Status, e.Description) + return fmt.Sprintf("%d %s", e.Status, e.Description) } // TelegramUpdate is one update of getUpdates. Message is nil for the kinds of @@ -266,12 +352,29 @@ type TelegramAnswer struct { } `json:"parameters"` } -// TelegramMessage is a message to the bot. Text is empty for a message that is -// not text, such as a photo. +// TelegramMessage holds the text, caption, and image sizes of a bot message. type TelegramMessage struct { - Chat TelegramChat `json:"chat"` - From *TelegramUser `json:"from"` - Text string `json:"text"` + Chat TelegramChat `json:"chat"` + From *TelegramUser `json:"from"` + Text string `json:"text"` + Caption string `json:"caption"` + Photo []TelegramPhoto `json:"photo"` + Document *TelegramDocument `json:"document"` +} + +// TelegramPhoto is one supplied size of a photo. +type TelegramPhoto struct { + FileID string `json:"file_id"` + Width int `json:"width"` + Height int `json:"height"` + FileSize int64 `json:"file_size"` +} + +// TelegramDocument is a file sent without photo compression. +type TelegramDocument struct { + FileID string `json:"file_id"` + MimeType string `json:"mime_type"` + FileSize int64 `json:"file_size"` } // TelegramChat is the chat of a message. Type is private for a chat with one