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>
This commit is contained in:
Michilis
2026-11-18 20:08:58 +00:00
co-authored by Claude Opus 5.5
parent 3c153af97f
commit 6843053582
52 changed files with 3369 additions and 271 deletions
+206
View File
@@ -0,0 +1,206 @@
// Package thumb turns a video's thumbnail image into the small JPEG that
// Telegram accepts as the thumbnail of an uploaded video: JPEG, at most
// 320 pixels wide and high, under 200 kB.
package thumb
import (
"bytes"
"context"
"errors"
"fmt"
"image"
"image/color"
"image/draw"
"image/jpeg"
"io"
"net"
"net/http"
"strings"
"syscall"
"time"
// Decoders for the formats sites serve thumbnails in.
_ "image/gif"
_ "image/png"
"github.com/noderunners/dlbot/internal/links"
)
// Telegram's limits for a video thumbnail.
const (
MaxSide = 320
MaxBytes = 200 << 10
)
// Limits on what is fetched.
const (
maxDownload = 5 << 20
maxPixels = 40_000_000
timeout = 8 * time.Second
)
// Fetcher downloads and shrinks thumbnails.
type Fetcher struct {
client *http.Client
}
// New returns a Fetcher that refuses local and private addresses, also
// when a public name resolves to one.
func New() *Fetcher {
dialer := &net.Dialer{Timeout: 5 * time.Second, Control: refusePrivate}
return &Fetcher{client: &http.Client{
Timeout: timeout,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: dialer.DialContext,
TLSHandshakeTimeout: 5 * time.Second,
MaxIdleConns: 8,
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 3 {
return errors.New("thumb: too many redirects")
}
return nil
},
}}
}
// NewWithClient uses the given HTTP client as is. Tests use it to reach a
// local server.
func NewWithClient(c *http.Client) *Fetcher { return &Fetcher{client: c} }
func refusePrivate(_, address string, _ syscall.RawConn) error {
host, _, err := net.SplitHostPort(address)
if err != nil {
return err
}
ip := net.ParseIP(host)
if ip == nil || ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsUnspecified() ||
ip.IsMulticast() || ip.IsLinkLocalMulticast() {
return fmt.Errorf("thumb: refusing address %s", host)
}
return nil
}
// Fetch returns a thumbnail Telegram accepts, or nil when the image cannot
// be had or read. A missing thumbnail is never an error: Telegram makes
// its own from the video.
func (f *Fetcher) Fetch(ctx context.Context, url string) []byte {
if f == nil || url == "" {
return nil
}
url = jpegVariant(url)
if _, err := links.Normalize(url); err != nil {
return nil
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil
}
req.Header.Set("Accept", "image/jpeg,image/png,image/gif;q=0.8")
resp, err := f.client.Do(req)
if err != nil {
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil
}
data, err := io.ReadAll(io.LimitReader(resp.Body, maxDownload+1))
if err != nil || len(data) > maxDownload {
return nil
}
out, err := Make(data)
if err != nil {
return nil
}
return out
}
// jpegVariant points a WebP thumbnail at the JPEG copy where a site is
// known to keep one, since the standard library cannot read WebP.
func jpegVariant(url string) string {
if strings.Contains(url, "i.ytimg.com/vi_webp/") && strings.HasSuffix(url, ".webp") {
url = strings.Replace(url, "/vi_webp/", "/vi/", 1)
return strings.TrimSuffix(url, ".webp") + ".jpg"
}
return url
}
// Make shrinks an image to fit Telegram's thumbnail rules.
func Make(data []byte) ([]byte, error) {
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return nil, err
}
if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width*cfg.Height > maxPixels {
return nil, errors.New("thumb: image size out of range")
}
src, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return nil, err
}
dst := Fit(src, MaxSide)
for _, q := range []int{85, 70, 55, 40} {
var buf bytes.Buffer
if err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: q}); err != nil {
return nil, err
}
if buf.Len() < MaxBytes {
return buf.Bytes(), nil
}
}
return nil, errors.New("thumb: cannot get under the size limit")
}
// Fit scales an image down so neither side exceeds max, keeping the aspect
// ratio. Each target pixel is the average of the source pixels it covers,
// which keeps a downscaled photo smooth. Smaller images are only copied
// onto an opaque background, since JPEG has no transparency.
func Fit(src image.Image, max int) *image.RGBA {
sb := src.Bounds()
sw, sh := sb.Dx(), sb.Dy()
dw, dh := sw, sh
if sw > max || sh > max {
if sw >= sh {
dw, dh = max, maxInt(1, sh*max/sw)
} else {
dw, dh = maxInt(1, sw*max/sh), max
}
}
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
draw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
if dw == sw && dh == sh {
draw.Draw(dst, dst.Bounds(), src, sb.Min, draw.Over)
return dst
}
for y := 0; y < dh; y++ {
y0, y1 := sb.Min.Y+y*sh/dh, sb.Min.Y+maxInt((y+1)*sh/dh, y*sh/dh+1)
for x := 0; x < dw; x++ {
x0, x1 := sb.Min.X+x*sw/dw, sb.Min.X+maxInt((x+1)*sw/dw, x*sw/dw+1)
var r, g, b, n uint64
for sy := y0; sy < y1; sy++ {
for sx := x0; sx < x1; sx++ {
c := color.RGBAModel.Convert(src.At(sx, sy)).(color.RGBA)
// Blend onto white for transparent sources.
a := uint64(c.A)
r += (uint64(c.R)*255 + 255*(255-a)) / 255
g += (uint64(c.G)*255 + 255*(255-a)) / 255
b += (uint64(c.B)*255 + 255*(255-a)) / 255
n++
}
}
dst.SetRGBA(x, y, color.RGBA{uint8(r / n), uint8(g / n), uint8(b / n), 255})
}
}
return dst
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
+142
View File
@@ -0,0 +1,142 @@
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)
}