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
}