Cotton code
180 lines · 6.0 KB · GoRaw
package mainimport (	"context"	"crypto/sha256"	"encoding/hex"	"errors"	"fmt"	"io"	"net/http"	"os"	"path/filepath"	"sort"	"strings"	"time"	"go.mau.fi/whatsmeow"	"go.mau.fi/whatsmeow/types")// Profile pictures (owner's decision, 11 Oct 2026): a person or group in Cotton whose picture is// empty, or still the one WhatsApp gave, takes the picture WhatsApp shows. Cotton tells the helper// which chats those are (`pictures`); the helper ASKS WhatsApp about them one at a time, slowly, and// writes a durable `picture` event when one is new or changed; Cotton then downloads it (`picture`).// Reading only: asking for a profile picture acts in no one's name, and TestHelperNeverSends stays// the guard over everything that would.const (	// One question to WhatsApp at most this often, across every number: a first pass over a few	// thousand contacts takes hours, never a burst WhatsApp would read as a bot.	pictureEvery = 3 * time.Second	// A chat already asked about is asked again after this long; WhatsApp answers "unchanged"	// without the picture when the id Cotton holds is still current.	pictureRecheck = 48 * time.Hour	// WhatsApp said too many questions: none at all for this long.	pictureBackoff = 15 * time.Minute	// A profile picture is a few hundred kilobytes; anything far larger is not one.	pictureMaxBytes = 8 << 20)var errPicturesRateLimited = errors.New("WhatsApp asked for fewer profile picture questions")// picturesDigest is what `hello` answers for the wanted list: the hex SHA-256 of the sorted chats,// one per line. The Rust side is whatsapp_link.rs `pictures_digest`; change both.func picturesDigest(chats []string) string {	sorted := append([]string(nil), chats...)	sort.Strings(sorted)	sum := sha256.Sum256([]byte(strings.Join(sorted, "\n")))	return hex.EncodeToString(sum[:])}// readingClient is the first connected number, in a fixed order: any linked number sees the same// profile pictures its contacts show it.func (h *Hub) readingClient() (string, *whatsmeow.Client) {	h.mu.Lock()	defer h.mu.Unlock()	accounts := make([]string, 0, len(h.sessions))	for account, s := range h.sessions {		if s.state == "connected" {			accounts = append(accounts, account)		}	}	if len(accounts) == 0 {		return "", nil	}	sort.Strings(accounts)	return accounts[0], h.sessions[accounts[0]].cli}// PictureLoop asks WhatsApp about one wanted chat per tick until ctx ends.func (h *Hub) PictureLoop(ctx context.Context) {	tick := time.NewTicker(pictureEvery)	defer tick.Stop()	var pausedUntil time.Time	for {		select {		case <-ctx.Done():			return		case now := <-tick.C:			if now.Before(pausedUntil) {				continue			}			if err := h.checkOnePicture(ctx, now); errors.Is(err, errPicturesRateLimited) {				h.log.Warnf("profile pictures paused for %s: %v", pictureBackoff, err)				pausedUntil = now.Add(pictureBackoff)			}		}	}}// checkOnePicture asks about the wanted chat checked longest ago (a newly wanted one first) and// announces its picture when the id differs from the one last announced.func (h *Hub) checkOnePicture(ctx context.Context, now time.Time) error {	account, cli := h.readingClient()	if cli == nil {		return nil	}	chat, known, ok, err := h.outbox.NextPicture(now.Add(-pictureRecheck).Unix())	if err != nil || !ok {		return err	}	jid, err := types.ParseJID(chat)	if err != nil {		return h.outbox.MarkPicture(chat, known, now.Unix())	}	cctx, cancel := context.WithTimeout(ctx, 20*time.Second)	defer cancel()	info, err := cli.GetProfilePictureInfo(cctx, jid, &whatsmeow.GetProfilePictureParams{ExistingID: known})	switch {	case errors.Is(err, whatsmeow.ErrIQRateOverLimit):		return errPicturesRateLimited	case errors.Is(err, whatsmeow.ErrProfilePictureUnauthorized), errors.Is(err, whatsmeow.ErrProfilePictureNotSet):		// Hidden from this number, or none: nothing to announce, and a picture that comes back		// later is new again.		return h.outbox.MarkPicture(chat, "", now.Unix())	case err != nil:		h.log.Debugf("profile picture of %s: %v", chat, err)		return h.outbox.MarkPicture(chat, known, now.Unix())	case info == nil || info.ID == "" || info.ID == known:		return h.outbox.MarkPicture(chat, known, now.Unix())	}	if err := h.outbox.MarkPicture(chat, info.ID, now.Unix()); err != nil {		return err	}	h.durable(&Event{Event: "picture", Account: account, Chat: chat, IsGroup: jid.Server == types.GroupServer, Target: info.ID})	return nil}// DownloadPicture writes the profile picture WhatsApp shows for chat to dest. ErrGone when there is// none, or its owner hides it from this number.func (h *Hub) DownloadPicture(ctx context.Context, account, chat, dest string) (int, error) {	cli, err := h.client(account)	if err != nil {		return 0, err	}	jid, err := types.ParseJID(chat)	if err != nil {		return 0, err	}	info, err := cli.GetProfilePictureInfo(ctx, jid, nil)	if errors.Is(err, whatsmeow.ErrProfilePictureUnauthorized) || errors.Is(err, whatsmeow.ErrProfilePictureNotSet) {		return 0, ErrGone	}	if err != nil {		return 0, err	}	if info == nil || info.URL == "" {		return 0, ErrGone	}	req, err := http.NewRequestWithContext(ctx, http.MethodGet, info.URL, nil)	if err != nil {		return 0, err	}	resp, err := http.DefaultClient.Do(req)	if err != nil {		return 0, err	}	defer resp.Body.Close()	switch {	case resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusGone:		return 0, ErrGone	case resp.StatusCode != http.StatusOK:		return 0, fmt.Errorf("profile picture download answered %s", resp.Status)	}	data, err := io.ReadAll(io.LimitReader(resp.Body, pictureMaxBytes+1))	if err != nil {		return 0, err	}	if len(data) > pictureMaxBytes {		return 0, fmt.Errorf("a profile picture of more than %d bytes", pictureMaxBytes)	}	if err := os.MkdirAll(filepath.Dir(dest), 0o700); err != nil {		return 0, err	}	tmp := dest + ".part"	if err := os.WriteFile(tmp, data, 0o600); err != nil {		return 0, err	}	return len(data), os.Rename(tmp, dest)}