fix(telegram): improve media notification template

This commit is contained in:
yebuwudong
2026-06-19 13:54:44 +08:00
committed by ShukeBta
parent dff19801b6
commit 8e43f66513
3 changed files with 678 additions and 17 deletions
+77
View File
@@ -1,11 +1,13 @@
package service
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
@@ -120,6 +122,81 @@ func telegramPostJSON(ctx context.Context, cfg map[string]string, method string,
return telegramDoWithFallback(ctx, cfg, http.MethodPost, apiURL, string(body), "application/json", timeout)
}
func telegramPostMultipart(ctx context.Context, cfg map[string]string, method string, fields map[string]string, fileField, fileName string, file []byte, timeout time.Duration) error {
apiURL, err := telegramMethodURL(cfg, cfg["bot_token"], method)
if err != nil {
return err
}
var body bytes.Buffer
writer := multipart.NewWriter(&body)
for key, value := range fields {
if strings.TrimSpace(value) == "" {
continue
}
if err := writer.WriteField(key, value); err != nil {
_ = writer.Close()
return err
}
}
part, err := writer.CreateFormFile(fileField, fileName)
if err != nil {
_ = writer.Close()
return err
}
if _, err := part.Write(file); err != nil {
_ = writer.Close()
return err
}
if err := writer.Close(); err != nil {
return err
}
return telegramDoWithFallback(ctx, cfg, http.MethodPost, apiURL, body.String(), writer.FormDataContentType(), timeout)
}
func telegramFetchRemotePhoto(ctx context.Context, cfg map[string]string, rawURL string, timeout time.Duration) ([]byte, string, error) {
rawURL = strings.TrimSpace(rawURL)
if rawURL == "" {
return nil, "", errors.New("telegram photo url required")
}
var lastErr error
for _, client := range telegramHTTPClients(timeout, cfg) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, "", err
}
req.Header.Set("User-Agent", "MediaStationGo/1.0")
resp, err := client.Do(req)
if err != nil {
lastErr = sanitizeTelegramError(err)
continue
}
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 10*1024*1024+1))
_ = resp.Body.Close()
if readErr != nil {
lastErr = readErr
continue
}
if resp.StatusCode >= 400 {
lastErr = fmt.Errorf("photo fetch error %d", resp.StatusCode)
continue
}
if len(body) == 0 {
lastErr = errors.New("photo fetch returned empty body")
continue
}
if len(body) > 10*1024*1024 {
lastErr = errors.New("photo too large")
continue
}
contentType := strings.TrimSpace(resp.Header.Get("Content-Type"))
return body, contentType, nil
}
if lastErr != nil {
return nil, "", lastErr
}
return nil, "", errors.New("photo fetch failed")
}
func deleteTelegramWebhook(ctx context.Context, cfg map[string]string) error {
payload := map[string]any{
"drop_pending_updates": false,