]> git.giacomolli.uk - onechat/blob - telegram_image.go
Check the width of comment lines
[onechat] / telegram_image.go
1 package main
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "strings"
8 )
9
10 var (
11 errTelegramOtherMedia = errors.New("only text messages are supported")
12 errTelegramPhotoSize = errors.New("no photo size fits 1568 pixels")
13 )
14
15 // telegramImageText selects a supplied photo size, or an image document, and
16 // stores it before returning marker text with the unchanged caption.
17 func telegramImageText(ctx context.Context, api *TelegramAPI, store *ImageStore, message *TelegramMessage) (string, error) {
18 var (
19 id string
20 size int64
21 )
22
23 if len(message.Photo) > 0 {
24 var area int
25
26 for _, photo := range message.Photo {
27 if photo.Width <= 0 || photo.Height <= 0 || max(photo.Width, photo.Height) > 1568 {
28 continue
29 }
30
31 if photo.Width*photo.Height > area {
32 id = photo.FileID
33 size = photo.FileSize
34 area = photo.Width * photo.Height
35 }
36 }
37
38 if id == "" {
39 return "", errTelegramPhotoSize
40 }
41 } else if message.Document != nil {
42 document := message.Document
43 switch document.MimeType {
44 case "image/jpeg", "image/png", "image/webp":
45 id = document.FileID
46 size = document.FileSize
47 default:
48 if strings.HasPrefix(document.MimeType, "image/") {
49 return "", errImageFormat
50 }
51
52 return "", errTelegramOtherMedia
53 }
54 }
55
56 if size > imageMaxBytes {
57 return "", errImageSize
58 }
59
60 data, err := api.GetImage(ctx, id)
61 if err != nil {
62 return "", fmt.Errorf("download image: %w", err)
63 }
64
65 name, err := store.Save(data)
66 if err != nil {
67 return "", fmt.Errorf("store image: %w", err)
68 }
69
70 return imageText([]string{name}, message.Caption), nil
71 }