Cotton code
312 lines · 13.0 KB · GoRaw
package mainimport (	"context"	"errors"	"fmt"	"os"	"os/exec"	"strings"	"time"	"go.mau.fi/whatsmeow"	"go.mau.fi/whatsmeow/proto/waE2E"	"go.mau.fi/whatsmeow/types"	"google.golang.org/protobuf/proto")// Sends beyond a text (owner, FEEDBACK-3, 23 Nov 2026: he uses WhatsApp from inside Comms). The same rules as a text:// the owner's own tap, the message id Cotton fixed at the tap (WhatsApp keeps one), and the sent message kept as the// owner's so Cotton lands it once. This file and send.go are the only ones that send (readonly_test.go).// The largest file the helper sends: WhatsApp's own limit for a document is 2 GB, but the helper reads it whole.const maxSendBytes = 100 << 20func sendTimeout(kind string) time.Duration {	switch kind {	case "picture", "video", "voice", "document":		return 10 * time.Minute	}	return 30 * time.Second}var sendMedia = map[string]whatsmeow.MediaType{"picture": whatsmeow.MediaImage, "video": whatsmeow.MediaVideo, "voice": whatsmeow.MediaAudio, "audio": whatsmeow.MediaAudio, "document": whatsmeow.MediaDocument}// SendKind sends one picture, video, voice note, document, reaction, edit, delete, poll or vote.func (h *Hub) SendKind(ctx context.Context, req *Request) (map[string]any, error) {	if strings.TrimSpace(req.MessageID) == "" {		return nil, errors.New("send needs a message_id")	}	jid, err := types.ParseJID(req.Chat)	if err != nil || jid.User == "" {		return nil, fmt.Errorf("send needs a chat jid, got %q", req.Chat)	}	if !h.mu.TryLock() {		return nil, errors.New("busy")	}	held := h.held[req.Account]	h.mu.Unlock()	if held {		return nil, errors.New("busy")	}	cli, err := h.client(req.Account)	if err != nil {		return nil, err	}	var msg *waE2E.Message	var media *MediaPointer	switch req.Kind {	case "picture", "video", "voice", "audio", "document":		jid, err = recipient(ctx, jid, cli.IsOnWhatsApp)		if err != nil {			return nil, err		}		// A picture WhatsApp does not show (HEIC and the like) goes as a JPEG; a video as MP4.		path, mimetype, cleanup, err := shown(ctx, req.Kind, req.Path, req.Mimetype)		if err != nil {			return nil, err		}		defer cleanup()		req.Path, req.Mimetype = path, mimetype		if req.Kind == "voice" {			// WhatsApp plays a voice note only as Ogg Opus; a phone's recording (AAC) is turned into one here.			path, cleanup, err := asVoiceNote(ctx, req.Path, req.Mimetype)			if err != nil {				return nil, err			}			defer cleanup()			req.Path, req.Mimetype = path, voiceMimetype		}		data, err := readSendable(req.Path)		if err != nil {			return nil, err		}		req.takeShapeOf(data)		up, err := cli.Upload(ctx, data, sendMedia[req.Kind])		if err != nil {			return nil, fmt.Errorf("the file did not go up to WhatsApp: %w", err)		}		msg, media = mediaMessage(req, up)	case "poll":		jid, err = recipient(ctx, jid, cli.IsOnWhatsApp)		if err != nil {			return nil, err		}		if strings.TrimSpace(req.Text) == "" || len(req.Options) < 2 {			return nil, errors.New("a poll needs a question and two options")		}		msg = cli.BuildPollCreation(req.Text, req.Options, req.Selectable)	case "reaction", "edit", "delete", "poll_vote":		if req.Target == "" {			return nil, fmt.Errorf("%s needs the message it acts on", req.Kind)		}		target := types.MessageID(req.Target)		sender := ownJID(cli)		if !req.TargetFromMe {			if sender, err = types.ParseJID(req.TargetSender); err != nil || sender.User == "" {				if jid.Server == types.GroupServer {					return nil, fmt.Errorf("%s in a group needs the sender of the message it acts on", req.Kind)				}				sender = jid			}		}		switch req.Kind {		case "reaction":			msg = cli.BuildReaction(jid, sender, target, req.Emoji)		case "edit":			if !req.TargetFromMe || strings.TrimSpace(req.Text) == "" {				return nil, errors.New("only your own message can be edited, with new words")			}			msg = cli.BuildEdit(jid, target, &waE2E.Message{Conversation: proto.String(req.Text)})		case "delete":			msg = cli.BuildRevoke(jid, sender, target)		case "poll_vote":			info := &types.MessageInfo{ID: target, MessageSource: types.MessageSource{Chat: jid, Sender: sender, IsFromMe: req.TargetFromMe, IsGroup: jid.Server == types.GroupServer}}			if msg, err = cli.BuildPollVote(ctx, info, req.Options); err != nil {				return nil, fmt.Errorf("the vote could not be made: %w", err)			}		}	default:		return nil, fmt.Errorf("unknown send kind %q", req.Kind)	}	resp, err := cli.SendMessage(ctx, jid, msg, whatsmeow.SendRequestExtra{ID: types.MessageID(req.MessageID)})	if err != nil {		return nil, err	}	if h.outbox != nil {		if ev := sentKindEvent(req, jid, string(resp.ID), resp.Timestamp.Unix(), media); ev != nil {			h.durable(ev)		}	}	return map[string]any{"id": string(resp.ID), "ts": resp.Timestamp.Unix()}, nil}const voiceMimetype = "audio/ogg; codecs=opus"// asVoiceNote answers an Ogg Opus file of the recording at path: the file itself when it is one already, else one// macOS's own afconvert writes beside it (removed by cleanup).func asVoiceNote(ctx context.Context, path, mimetype string) (string, func(), error) {	lower := strings.ToLower(mimetype)	if strings.Contains(lower, "ogg") || strings.Contains(lower, "opus") {		return path, func() {}, nil	}	// afconvert writes Opus into CAF only; the packets then move into Ogg unchanged (oggopus.go).	caf, out := path+".voice.caf", path+".voice.ogg"	cleanup := func() { _ = os.Remove(caf); _ = os.Remove(out) }	cmd := exec.CommandContext(ctx, "/usr/bin/afconvert", "-f", "caff", "-d", "opus@48000", "-c", "1", path, caf)	if said, err := cmd.CombinedOutput(); err != nil {		cleanup()		return "", nil, fmt.Errorf("%s (the voice note: %v %s)", CouldNotOpen, err, strings.TrimSpace(string(said)))	}	if err := cafToOgg(caf, out); err != nil {		cleanup()		return "", nil, fmt.Errorf("%s (the voice note: %w)", CouldNotOpen, err)	}	_ = os.Remove(caf)	return out, cleanup, nil}// size is a picture's or video's side for WhatsApp, or nothing when the phone did not say.func size(side uint32) *uint32 {	if side == 0 {		return nil	}	return proto.Uint32(side)}// shown answers a file WhatsApp shows: a picture as JPEG, PNG or WebP as given, any other picture (HEIC and the// like) turned into a JPEG by macOS's own sips; a video as MP4 as given, any other (a phone's QuickTime) turned into// MP4 by macOS's own avconvert. Other kinds go as they are. cleanup removes what was written.func shown(ctx context.Context, kind, path, mimetype string) (string, string, func(), error) {	lower := strings.ToLower(mimetype)	none := func() {}	switch {	case kind == "picture" && !(strings.Contains(lower, "jpeg") || strings.Contains(lower, "jpg") || strings.Contains(lower, "png") || strings.Contains(lower, "webp")):		out := path + ".shown.jpg"		cmd := exec.CommandContext(ctx, "/usr/bin/sips", "-s", "format", "jpeg", path, "--out", out)		if said, err := cmd.CombinedOutput(); err != nil {			_ = os.Remove(out)			return "", "", nil, fmt.Errorf("%s (%v %s)", CouldNotOpen, err, strings.TrimSpace(string(said)))		}		return out, "image/jpeg", func() { _ = os.Remove(out) }, nil	case kind == "video" && !strings.Contains(lower, "mp4"):		out := path + ".shown.mp4"		cmd := exec.CommandContext(ctx, "/usr/bin/avconvert", "--preset", "PresetHighestQuality", "--source", path, "--output", out, "--replace")		if said, err := cmd.CombinedOutput(); err != nil {			_ = os.Remove(out)			return "", "", nil, fmt.Errorf("%s (%v %s)", CouldNotOpen, err, strings.TrimSpace(string(said)))		}		return out, "video/mp4", func() { _ = os.Remove(out) }, nil	}	return path, mimetype, none, nil}// takeShapeOf sets a picture's width, height and thumbnail from the file that goes (pictureShape), over what the// phone's row said; a file Go cannot read keeps the row's.func (req *Request) takeShapeOf(data []byte) {	if req.Kind != "picture" {		return	}	if w, h, thumb, ok := pictureShape(data); ok {		req.Width, req.Height = w, h		if thumb != nil {			req.Preview = thumb		}	}}// TooLarge starts the refusal for a file over what WhatsApp from Cotton sends.const TooLarge = "too_large"// CouldNotOpen starts the refusal for a file the Mac could not turn into one WhatsApp shows.const CouldNotOpen = "could_not_open"func ownJID(cli *whatsmeow.Client) types.JID {	if cli.Store != nil && cli.Store.ID != nil {		return cli.Store.ID.ToNonAD()	}	return types.EmptyJID}func readSendable(path string) ([]byte, error) {	info, err := os.Stat(path)	if err != nil {		return nil, fmt.Errorf("the file to send is not on this Mac: %w", err)	}	if info.Size() > maxSendBytes {		return nil, fmt.Errorf("%s (%d MB; up to %d MB)", TooLarge, info.Size()>>20, maxSendBytes>>20)	}	return os.ReadFile(path)}// mediaMessage is the message for a file WhatsApp now holds, with the caption and the quote of a reply, and the// pointer Cotton lands the sent message with.func mediaMessage(req *Request, up whatsmeow.UploadResponse) (*waE2E.Message, *MediaPointer) {	ctx := quoteOf(req).context()	p := &MediaPointer{Mimetype: req.Mimetype, FileName: req.FileName, DirectPath: up.DirectPath, MediaKey: up.MediaKey, FileSHA256: up.FileSHA256, FileEncSHA256: up.FileEncSHA256, FileLength: up.FileLength}	caption := proto.String(req.Text)	if req.Text == "" {		caption = nil	}	switch req.Kind {	case "picture":		p.Type = "image"		return &waE2E.Message{ImageMessage: &waE2E.ImageMessage{URL: proto.String(up.URL), DirectPath: proto.String(up.DirectPath), MediaKey: up.MediaKey, Mimetype: proto.String(req.Mimetype), FileEncSHA256: up.FileEncSHA256, FileSHA256: up.FileSHA256, FileLength: proto.Uint64(up.FileLength), Caption: caption, Width: size(req.Width), Height: size(req.Height), JPEGThumbnail: req.Preview, ContextInfo: ctx}}, p	case "video":		p.Type = "video"		return &waE2E.Message{VideoMessage: &waE2E.VideoMessage{URL: proto.String(up.URL), DirectPath: proto.String(up.DirectPath), MediaKey: up.MediaKey, Mimetype: proto.String(req.Mimetype), FileEncSHA256: up.FileEncSHA256, FileSHA256: up.FileSHA256, FileLength: proto.Uint64(up.FileLength), Seconds: proto.Uint32(req.Seconds), Caption: caption, Width: size(req.Width), Height: size(req.Height), JPEGThumbnail: req.Preview, ContextInfo: ctx}}, p	case "voice", "audio":		p.Type = "audio"		voice := req.Kind == "voice"		var waveform []byte		if voice {			waveform = req.Waveform		}		return &waE2E.Message{AudioMessage: &waE2E.AudioMessage{URL: proto.String(up.URL), DirectPath: proto.String(up.DirectPath), MediaKey: up.MediaKey, Mimetype: proto.String(req.Mimetype), FileEncSHA256: up.FileEncSHA256, FileSHA256: up.FileSHA256, FileLength: proto.Uint64(up.FileLength), Seconds: proto.Uint32(req.Seconds), PTT: proto.Bool(voice), Waveform: waveform, ContextInfo: ctx}}, p	default:		p.Type = "document"		name := req.FileName		if name == "" {			name = "file"		}		return &waE2E.Message{DocumentMessage: &waE2E.DocumentMessage{URL: proto.String(up.URL), DirectPath: proto.String(up.DirectPath), MediaKey: up.MediaKey, Mimetype: proto.String(req.Mimetype), FileEncSHA256: up.FileEncSHA256, FileSHA256: up.FileSHA256, FileLength: proto.Uint64(up.FileLength), FileName: proto.String(name), Title: proto.String(name), Caption: caption, ContextInfo: ctx}}, p	}}// sentKindEvent is what the helper keeps of a send so Cotton lands it as the owner's (WhatsApp never echoes this// device's own sends): a file as a message with its pointer, a poll with its options, a reaction, an edit, a delete// and a vote as the same events a received one makes.func sentKindEvent(req *Request, chat types.JID, id string, ts int64, media *MediaPointer) *Event {	chat = chat.ToNonAD()	m := &Message{ID: id, Chat: chat.String(), FromMe: true, IsGroup: chat.Server == types.GroupServer, Timestamp: ts, Text: req.Text, QuotedID: req.QuotedID, Origin: "live"}	switch req.Kind {	case "picture", "video", "voice", "audio", "document":		m.Kind = map[string]string{"picture": "image", "video": "video", "voice": "voice", "audio": "audio", "document": "document"}[req.Kind]		if len(req.Landed) > 0 {			// His own copy is already in Cotton: the message lands with it, never fetched back from WhatsApp.			m.Landed = req.Landed			return &Event{Event: "message", Message: m}		}		if media != nil {			media.MessageID, media.Chat, media.FromMe, media.IsGroup = id, chat.String(), true, m.IsGroup		}		m.Media = media		return &Event{Event: "message", Message: m}	case "poll":		m.Kind, m.Poll = "poll", &Poll{Options: req.Options, Selectable: uint32(req.Selectable)}		return &Event{Event: "message", Message: m}	case "reaction":		m.Kind, m.Text, m.ReactionTo, m.QuotedID = "reaction", req.Emoji, req.Target, ""		return &Event{Event: "message", Message: m}	case "edit":		m.Kind, m.EditOf, m.QuotedID = "text", req.Target, ""		return &Event{Event: "message", Message: m}	case "delete":		m.Text, m.QuotedID = "", ""		return &Event{Event: "revoke", Chat: m.Chat, Target: req.Target, Message: m}	case "poll_vote":		m.Kind, m.Text, m.QuotedID = "poll_vote", "", ""		return &Event{Event: "poll_vote", Chat: m.Chat, Target: req.Target, Votes: hashesHex(whatsmeow.HashPollOptions(req.Options)), Message: m}	}	return nil}