Files
Media-download-telegram-bot/internal/thumb/thumb_test.go
T
MichilisandClaude Opus 5.5 6843053582 Phase 1: quick flow fixes
- One message per job: the status message is deleted once the file is
  sent, or shortened to "Sent." when Telegram keeps it.
- No reply quotes in private chats; groups keep them.
- Queue status only mentions the position when the wait is above
  QUEUE_NOTICE_THRESHOLD_SECONDS or somebody is ahead. Status edits are
  throttled to one per 2.5 s per message; a state that arrives too soon
  is shown later instead of dropped. The wait estimate is 0 with a free
  slot.
- Caption with title (uploader and date when generic), uploader,
  duration, a short source link without tracking parameters and an
  optional "via @bot" line (CAPTION_ATTRIBUTION). Uploaded videos get a
  320 px JPEG thumbnail; merged MP4s are written with faststart.
- Buttons under the result: Audio (MP3), Other quality, Thumbnail,
  Delete. Requester only in groups.
- Language resolved once per update and passed in the context. A
  fallback to English is logged as a bug; a test walks every screen in
  Spanish and Dutch. Language picker on the first /start.
- Sizes without a zero decimal ("50 MB").
- First link of a new user shows the card once and sets the default to
  "best that fits my limit".
- Errors offer the next step (Try again, Smaller quality, Upgrade, Open
  app); passing lookup failures are retried once.
- Up to MULTI_LINK_MAX links per message; a link sent a moment ago gets
  "already sent" with a Send again button.
- Mini App menu button, labelled per private chat in the user's
  language.
- Personal /settings in private chats with an "Add me to a group"
  button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:08:58 +00:00

143 lines
3.8 KiB
Go

package thumb
import (
"bytes"
"context"
"image"
"image/color"
"image/jpeg"
"image/png"
"math/rand"
"net/http"
"net/http/httptest"
"testing"
)
// noisy makes an image that compresses badly, the hard case for the size
// limit.
func noisy(w, h int) image.Image {
img := image.NewRGBA(image.Rect(0, 0, w, h))
r := rand.New(rand.NewSource(1))
for i := range img.Pix {
img.Pix[i] = uint8(r.Intn(256))
}
return img
}
func encodePNG(t *testing.T, img image.Image) []byte {
t.Helper()
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
t.Fatal(err)
}
return buf.Bytes()
}
func TestMakeFitsTelegramsRules(t *testing.T) {
cases := []struct{ w, h, wantW, wantH int }{
{1280, 720, 320, 180},
{720, 1280, 180, 320},
{4000, 100, 320, 8},
{200, 100, 200, 100}, // small images keep their size
}
for _, c := range cases {
out, err := Make(encodePNG(t, noisy(c.w, c.h)))
if err != nil {
t.Fatalf("%dx%d: %v", c.w, c.h, err)
}
if len(out) >= MaxBytes {
t.Errorf("%dx%d: %d bytes, the limit is %d", c.w, c.h, len(out), MaxBytes)
}
img, err := jpeg.Decode(bytes.NewReader(out))
if err != nil {
t.Fatalf("%dx%d: output is not a JPEG: %v", c.w, c.h, err)
}
if b := img.Bounds(); b.Dx() != c.wantW || b.Dy() != c.wantH {
t.Errorf("%dx%d became %dx%d, want %dx%d", c.w, c.h, b.Dx(), b.Dy(), c.wantW, c.wantH)
}
}
}
func TestMakeRefusesWhatIsNotAnImage(t *testing.T) {
if _, err := Make([]byte("<html>not an image</html>")); err == nil {
t.Fatal("HTML was accepted as an image")
}
}
func TestFitAveragesAndDropsTransparency(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 640, 640))
for i := 0; i < len(src.Pix); i += 4 {
src.Pix[i+3] = 0 // fully transparent
}
got := Fit(src, 320).RGBAAt(10, 10)
if got != (color.RGBA{255, 255, 255, 255}) {
t.Fatalf("a transparent pixel became %v, want white", got)
}
}
func TestJPEGVariantOfYouTubeWebP(t *testing.T) {
in := "https://i.ytimg.com/vi_webp/abc/maxresdefault.webp"
if got := jpegVariant(in); got != "https://i.ytimg.com/vi/abc/maxresdefault.jpg" {
t.Fatalf("jpegVariant = %q", got)
}
other := "https://example.com/a.webp"
if got := jpegVariant(other); got != other {
t.Fatalf("an unknown site was rewritten: %q", got)
}
}
func TestFetch(t *testing.T) {
img := encodePNG(t, noisy(640, 360))
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/t.png":
_, _ = w.Write(img)
case "/huge":
w.Write(bytes.Repeat([]byte{0}, maxDownload+10))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
// The test server listens on 127.0.0.1, which the real fetcher refuses.
if New().Fetch(context.Background(), srv.URL+"/t.png") != nil {
t.Fatal("the fetcher reached a loopback address")
}
f := NewWithClient(srv.Client())
// links.Normalize refuses loopback hosts too, so point a public name at
// the test server through the transport.
f.client.Transport = rewriteTo(srv.URL, srv.Client().Transport)
out := f.Fetch(context.Background(), "https://img.example.com/t.png")
if out == nil {
t.Fatal("no thumbnail")
}
if _, err := jpeg.Decode(bytes.NewReader(out)); err != nil {
t.Fatalf("not a JPEG: %v", err)
}
for _, path := range []string{"/missing", "/huge"} {
if f.Fetch(context.Background(), "https://img.example.com"+path) != nil {
t.Errorf("%s gave a thumbnail", path)
}
}
if f.Fetch(context.Background(), "http://127.0.0.1/t.png") != nil {
t.Error("a private link was fetched")
}
}
type rewrite struct {
target string
next http.RoundTripper
}
func rewriteTo(target string, next http.RoundTripper) http.RoundTripper {
return &rewrite{target: target, next: next}
}
func (r *rewrite) RoundTrip(req *http.Request) (*http.Response, error) {
u := *req.URL
t, _ := http.NewRequest(req.Method, r.target+u.Path, nil)
t = t.WithContext(req.Context())
return r.next.RoundTrip(t)
}