Cotton code
67 lines · 2.7 KB · GoRaw
package mainimport (	"context"	"encoding/hex"	"go.mau.fi/whatsmeow"	"go.mau.fi/whatsmeow/proto/waWeb"	"go.mau.fi/whatsmeow/types"	"go.mau.fi/whatsmeow/types/events")// Votes on a poll (owner, FEEDBACK-3, 23 Nov 2026: who voted for what and the counts, updating as votes arrive).// WhatsApp sends each vote encrypted with the poll's own secret, as the voter's whole choice so far; the helper opens// it and hands Cotton a poll_vote event naming the poll, the voter and the options picked, as hashes of the// options' words (Cotton holds the words, from the poll itself).func hashesHex(selected [][]byte) []string {	out := make([]string, 0, len(selected))	for _, h := range selected {		out = append(out, hex.EncodeToString(h))	}	return out}// liveVote is a poll vote that just came, opened with the poll's secret; nil when it is not a vote or does not open// (a poll from before this Mac was linked carries a secret the helper never saw).func liveVote(ctx context.Context, cli *whatsmeow.Client, evt *events.Message, resolve PNResolver) *Event {	update := evt.Message.GetPollUpdateMessage()	if update == nil {		return nil	}	vote, err := cli.DecryptPollVote(ctx, evt)	if err != nil {		return nil	}	chat, _ := normalize(evt.Info.Chat, resolve)	sender, _ := normalize(evt.Info.Sender, resolve)	m := &Message{ID: string(evt.Info.ID), Chat: chat.String(), FromMe: evt.Info.IsFromMe, IsGroup: evt.Info.IsGroup, Timestamp: evt.Info.Timestamp.Unix(), Kind: "poll_vote", Origin: "live"}	if !evt.Info.IsFromMe {		m.Sender = sender.String()	}	return &Event{Event: "poll_vote", Chat: m.Chat, Target: update.GetPollCreationMessageKey().GetID(), Votes: hashesHex(vote.GetSelectedOptions()), Message: m}}// historyVotes are the votes a poll in WhatsApp's history carries beside it, already opened by the phone: one// poll_vote each, after the poll itself.func historyVotes(web *waWeb.WebMessageInfo, chat types.JID, resolve PNResolver) []*Event {	var out []*Event	normChat, _ := normalize(chat, resolve)	for _, u := range web.GetPollUpdates() {		key := u.GetPollUpdateMessageKey()		m := &Message{ID: key.GetID(), Chat: normChat.String(), FromMe: key.GetFromMe(), IsGroup: chat.Server == types.GroupServer, Timestamp: u.GetSenderTimestampMS() / 1000, Kind: "poll_vote", Origin: "history"}		if !key.GetFromMe() {			voter := key.GetParticipant()			if voter == "" {				voter = key.GetRemoteJID()			}			if j, err := types.ParseJID(voter); err == nil {				pn, _ := normalize(j, resolve)				m.Sender = pn.String()			}		}		out = append(out, &Event{Event: "poll_vote", Chat: m.Chat, Target: web.GetKey().GetID(), Votes: hashesHex(u.GetVote().GetSelectedOptions()), Message: m})	}	return out}