// 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 }