5
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2024-11-25 01:51:35 +00:00
matterbridge/vendor/go.mau.fi/whatsmeow/send.go

725 lines
24 KiB
Go
Raw Normal View History

2022-06-11 21:07:42 +00:00
// Copyright (c) 2022 Tulir Asokan
2022-01-30 23:27:37 +00:00
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package whatsmeow
import (
"context"
2022-01-30 23:27:37 +00:00
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"sort"
2022-06-11 21:07:42 +00:00
"strconv"
2022-01-30 23:27:37 +00:00
"strings"
"time"
2022-03-31 22:23:19 +00:00
"go.mau.fi/libsignal/signalerror"
2022-01-30 23:27:37 +00:00
"google.golang.org/protobuf/proto"
"go.mau.fi/libsignal/groups"
"go.mau.fi/libsignal/keys/prekey"
"go.mau.fi/libsignal/protocol"
"go.mau.fi/libsignal/session"
waBinary "go.mau.fi/whatsmeow/binary"
waProto "go.mau.fi/whatsmeow/binary/proto"
"go.mau.fi/whatsmeow/types"
)
// GenerateMessageID generates a random string that can be used as a message ID on WhatsApp.
2022-03-12 22:02:04 +00:00
//
2022-11-26 23:42:16 +00:00
// msgID := whatsmeow.GenerateMessageID()
2023-01-28 21:57:53 +00:00
// cli.SendMessage(context.Background(), targetJID, &waProto.Message{...}, whatsmeow.SendRequestExtra{ID: msgID})
2022-01-30 23:27:37 +00:00
func GenerateMessageID() types.MessageID {
2022-04-25 21:50:10 +00:00
id := make([]byte, 8)
2022-01-30 23:27:37 +00:00
_, err := rand.Read(id)
if err != nil {
// Out of entropy
panic(err)
}
2022-04-25 21:50:10 +00:00
return "3EB0" + strings.ToUpper(hex.EncodeToString(id))
2022-01-30 23:27:37 +00:00
}
type MessageDebugTimings struct {
Queue time.Duration
Marshal time.Duration
GetParticipants time.Duration
GetDevices time.Duration
GroupEncrypt time.Duration
PeerEncrypt time.Duration
Send time.Duration
Resp time.Duration
Retry time.Duration
}
type SendResponse struct {
// The message timestamp returned by the server
Timestamp time.Time
// The ID of the sent message
ID types.MessageID
// Message handling duration, used for debugging
DebugTimings MessageDebugTimings
}
2023-01-28 21:57:53 +00:00
// SendRequestExtra contains the optional parameters for SendMessage.
//
// By default, optional parameters don't have to be provided at all, e.g.
//
// cli.SendMessage(ctx, to, message)
//
// When providing optional parameters, add a single instance of this struct as the last parameter:
2022-01-30 23:27:37 +00:00
//
2023-01-28 21:57:53 +00:00
// cli.SendMessage(ctx, to, message, whatsmeow.SendRequestExtra{...})
//
// Trying to add multiple extra parameters will return an error.
type SendRequestExtra struct {
// The message ID to use when sending. If this is not provided, a random message ID will be generated
ID types.MessageID
// Should the message be sent as a peer message (protocol messages to your own devices, e.g. app state key requests)
Peer bool
}
// SendMessage sends the given message.
2022-01-30 23:27:37 +00:00
//
// This method will wait for the server to acknowledge the message before returning.
// The return value is the timestamp of the message from the server.
2022-03-12 22:02:04 +00:00
//
2023-01-28 21:57:53 +00:00
// Optional parameters like the message ID can be specified with the SendRequestExtra struct.
// Only one extra parameter is allowed, put all necessary parameters in the same struct.
//
2022-03-12 22:02:04 +00:00
// The message itself can contain anything you want (within the protobuf schema).
// e.g. for a simple text message, use the Conversation field:
2022-11-26 23:42:16 +00:00
//
2023-01-28 21:57:53 +00:00
// cli.SendMessage(context.Background(), targetJID, &waProto.Message{
2022-11-26 23:42:16 +00:00
// Conversation: proto.String("Hello, World!"),
// })
2022-03-12 22:02:04 +00:00
//
// Things like replies, mentioning users and the "forwarded" flag are stored in ContextInfo,
// which can be put in ExtendedTextMessage and any of the media message types.
//
// For uploading and sending media/attachments, see the Upload method.
//
// For other message types, you'll have to figure it out yourself. Looking at the protobuf schema
2023-01-28 21:57:53 +00:00
// in binary/proto/def.proto may be useful to find out all the allowed fields. Printing the RawMessage
// field in incoming message events to figure out what it contains is also a good way to learn how to
// send the same kind of message.
func (cli *Client) SendMessage(ctx context.Context, to types.JID, message *waProto.Message, extra ...SendRequestExtra) (resp SendResponse, err error) {
var req SendRequestExtra
if len(extra) > 1 {
err = errors.New("only one extra parameter may be provided to SendMessage")
return
} else if len(extra) == 1 {
req = extra[0]
}
if to.AD && !req.Peer {
err = ErrRecipientADJID
return
2022-01-30 23:27:37 +00:00
}
2023-01-28 21:57:53 +00:00
ownID := cli.getOwnID()
if ownID.IsEmpty() {
err = ErrNotLoggedIn
return
}
2022-01-30 23:27:37 +00:00
2023-01-28 21:57:53 +00:00
if len(req.ID) == 0 {
req.ID = GenerateMessageID()
2022-01-30 23:27:37 +00:00
}
2023-01-28 21:57:53 +00:00
resp.ID = req.ID
2022-01-30 23:27:37 +00:00
start := time.Now()
2022-06-11 21:07:42 +00:00
// Sending multiple messages at a time can cause weird issues and makes it harder to retry safely
cli.messageSendLock.Lock()
resp.DebugTimings.Queue = time.Since(start)
2022-06-11 21:07:42 +00:00
defer cli.messageSendLock.Unlock()
2022-05-09 21:00:23 +00:00
2023-01-28 21:57:53 +00:00
respChan := cli.waitResponse(req.ID)
2022-06-11 21:07:42 +00:00
// Peer message retries aren't implemented yet
2023-01-28 21:57:53 +00:00
if !req.Peer {
cli.addRecentMessage(to, req.ID, message)
2022-06-11 21:07:42 +00:00
}
2022-11-26 23:42:16 +00:00
if message.GetMessageContextInfo().GetMessageSecret() != nil {
2023-01-28 21:57:53 +00:00
err = cli.Store.MsgSecrets.PutMessageSecret(to, ownID, req.ID, message.GetMessageContextInfo().GetMessageSecret())
2022-11-26 23:42:16 +00:00
if err != nil {
2023-01-28 21:57:53 +00:00
cli.Log.Warnf("Failed to store message secret key for outgoing message %s: %v", req.ID, err)
2022-11-26 23:42:16 +00:00
} else {
2023-01-28 21:57:53 +00:00
cli.Log.Debugf("Stored message secret key for outgoing message %s", req.ID)
2022-11-26 23:42:16 +00:00
}
}
2022-01-30 23:27:37 +00:00
var phash string
2022-05-09 21:00:23 +00:00
var data []byte
2022-01-30 23:27:37 +00:00
switch to.Server {
2022-06-11 21:07:42 +00:00
case types.GroupServer, types.BroadcastServer:
2023-01-28 21:57:53 +00:00
phash, data, err = cli.sendGroup(ctx, to, ownID, req.ID, message, &resp.DebugTimings)
2022-01-30 23:27:37 +00:00
case types.DefaultUserServer:
2023-01-28 21:57:53 +00:00
if req.Peer {
data, err = cli.sendPeerMessage(to, req.ID, message, &resp.DebugTimings)
2022-06-11 21:07:42 +00:00
} else {
2023-01-28 21:57:53 +00:00
data, err = cli.sendDM(ctx, to, ownID, req.ID, message, &resp.DebugTimings)
2022-06-11 21:07:42 +00:00
}
2022-01-30 23:27:37 +00:00
default:
err = fmt.Errorf("%w %s", ErrUnknownServer, to.Server)
}
start = time.Now()
2022-01-30 23:27:37 +00:00
if err != nil {
2023-01-28 21:57:53 +00:00
cli.cancelResponse(req.ID, respChan)
return
}
var respNode *waBinary.Node
select {
case respNode = <-respChan:
case <-ctx.Done():
err = ctx.Err()
return
2022-01-30 23:27:37 +00:00
}
resp.DebugTimings.Resp = time.Since(start)
if isDisconnectNode(respNode) {
start = time.Now()
2023-01-28 21:57:53 +00:00
respNode, err = cli.retryFrame("message send", req.ID, data, respNode, ctx, 0)
resp.DebugTimings.Retry = time.Since(start)
2022-06-11 21:07:42 +00:00
if err != nil {
return
2022-05-09 21:00:23 +00:00
}
2022-01-30 23:27:37 +00:00
}
ag := respNode.AttrGetter()
resp.Timestamp = ag.UnixTime("t")
2023-01-28 21:57:53 +00:00
if errorCode := ag.Int("error"); errorCode != 0 {
err = fmt.Errorf("%w %d", ErrServerReturnedError, errorCode)
}
2022-01-30 23:27:37 +00:00
expectedPHash := ag.OptionalString("phash")
if len(expectedPHash) > 0 && phash != expectedPHash {
cli.Log.Warnf("Server returned different participant list hash when sending to %s. Some devices may not have received the message.", to)
// TODO also invalidate device list caches
cli.groupParticipantsCacheLock.Lock()
delete(cli.groupParticipantsCache, to)
cli.groupParticipantsCacheLock.Unlock()
}
return
2022-01-30 23:27:37 +00:00
}
// RevokeMessage deletes the given message from everyone in the chat.
//
// This method will wait for the server to acknowledge the revocation message before returning.
// The return value is the timestamp of the message from the server.
2022-11-26 23:42:16 +00:00
//
// Deprecated: This method is deprecated in favor of BuildRevoke
func (cli *Client) RevokeMessage(chat types.JID, id types.MessageID) (SendResponse, error) {
2023-01-28 21:57:53 +00:00
return cli.SendMessage(context.TODO(), chat, cli.BuildRevoke(chat, types.EmptyJID, id))
2022-11-26 23:42:16 +00:00
}
// BuildRevoke builds a message revocation message using the given variables.
// The built message can be sent normally using Client.SendMessage.
//
// To revoke your own messages, pass your JID or an empty JID as the second parameter (sender).
//
2023-01-28 21:57:53 +00:00
// resp, err := cli.SendMessage(context.Background(), chat, cli.BuildRevoke(chat, types.EmptyJID, originalMessageID)
2022-11-26 23:42:16 +00:00
//
// To revoke someone else's messages when you are group admin, pass the message sender's JID as the second parameter.
//
2023-01-28 21:57:53 +00:00
// resp, err := cli.SendMessage(context.Background(), chat, cli.BuildRevoke(chat, senderJID, originalMessageID)
2022-11-26 23:42:16 +00:00
func (cli *Client) BuildRevoke(chat, sender types.JID, id types.MessageID) *waProto.Message {
key := &waProto.MessageKey{
FromMe: proto.Bool(true),
Id: proto.String(id),
RemoteJid: proto.String(chat.String()),
}
2023-01-28 21:57:53 +00:00
if !sender.IsEmpty() && sender.User != cli.getOwnID().User {
2022-11-26 23:42:16 +00:00
key.FromMe = proto.Bool(false)
if chat.Server != types.DefaultUserServer {
key.Participant = proto.String(sender.ToNonAD().String())
}
}
return &waProto.Message{
2022-01-30 23:27:37 +00:00
ProtocolMessage: &waProto.ProtocolMessage{
Type: waProto.ProtocolMessage_REVOKE.Enum(),
2022-11-26 23:42:16 +00:00
Key: key,
},
}
}
// BuildEdit builds a message edit message using the given variables.
// The built message can be sent normally using Client.SendMessage.
//
2023-01-28 21:57:53 +00:00
// resp, err := cli.SendMessage(context.Background(), chat, cli.BuildEdit(chat, originalMessageID, &waProto.Message{
2022-11-26 23:42:16 +00:00
// Conversation: proto.String("edited message"),
// })
func (cli *Client) BuildEdit(chat types.JID, id types.MessageID, newContent *waProto.Message) *waProto.Message {
return &waProto.Message{
EditedMessage: &waProto.FutureProofMessage{
Message: &waProto.Message{
ProtocolMessage: &waProto.ProtocolMessage{
Key: &waProto.MessageKey{
FromMe: proto.Bool(true),
Id: proto.String(id),
RemoteJid: proto.String(chat.String()),
},
Type: waProto.ProtocolMessage_MESSAGE_EDIT.Enum(),
EditedMessage: newContent,
TimestampMs: proto.Int64(time.Now().UnixMilli()),
},
2022-01-30 23:27:37 +00:00
},
},
2022-11-26 23:42:16 +00:00
}
2022-01-30 23:27:37 +00:00
}
2022-06-11 21:07:42 +00:00
const (
DisappearingTimerOff = time.Duration(0)
DisappearingTimer24Hours = 24 * time.Hour
DisappearingTimer7Days = 7 * 24 * time.Hour
DisappearingTimer90Days = 90 * 24 * time.Hour
)
// ParseDisappearingTimerString parses common human-readable disappearing message timer strings into Duration values.
// If the string doesn't look like one of the allowed values (0, 24h, 7d, 90d), the second return value is false.
func ParseDisappearingTimerString(val string) (time.Duration, bool) {
switch strings.ReplaceAll(strings.ToLower(val), " ", "") {
case "0d", "0h", "0s", "0", "off":
return DisappearingTimerOff, true
case "1day", "day", "1d", "1", "24h", "24", "86400s", "86400":
return DisappearingTimer24Hours, true
case "1week", "week", "7d", "7", "168h", "168", "604800s", "604800":
return DisappearingTimer7Days, true
case "3months", "3m", "3mo", "90d", "90", "2160h", "2160", "7776000s", "7776000":
return DisappearingTimer90Days, true
default:
return 0, false
}
}
// SetDisappearingTimer sets the disappearing timer in a chat. Both private chats and groups are supported, but they're
// set with different methods.
//
// Note that while this function allows passing non-standard durations, official WhatsApp apps will ignore those,
// and in groups the server will just reject the change. You can use the DisappearingTimer<Duration> constants for convenience.
//
// In groups, the server will echo the change as a notification, so it'll show up as a *events.GroupInfo update.
func (cli *Client) SetDisappearingTimer(chat types.JID, timer time.Duration) (err error) {
switch chat.Server {
case types.DefaultUserServer:
2023-01-28 21:57:53 +00:00
_, err = cli.SendMessage(context.TODO(), chat, &waProto.Message{
2022-06-11 21:07:42 +00:00
ProtocolMessage: &waProto.ProtocolMessage{
Type: waProto.ProtocolMessage_EPHEMERAL_SETTING.Enum(),
EphemeralExpiration: proto.Uint32(uint32(timer.Seconds())),
},
})
case types.GroupServer:
if timer == 0 {
_, err = cli.sendGroupIQ(context.TODO(), iqSet, chat, waBinary.Node{Tag: "not_ephemeral"})
2022-06-11 21:07:42 +00:00
} else {
_, err = cli.sendGroupIQ(context.TODO(), iqSet, chat, waBinary.Node{
2022-06-11 21:07:42 +00:00
Tag: "ephemeral",
Attrs: waBinary.Attrs{
"expiration": strconv.Itoa(int(timer.Seconds())),
},
})
if errors.Is(err, ErrIQBadRequest) {
err = wrapIQError(ErrInvalidDisappearingTimer, err)
}
}
default:
err = fmt.Errorf("can't set disappearing time in a %s chat", chat.Server)
}
return
}
2022-01-30 23:27:37 +00:00
func participantListHashV2(participants []types.JID) string {
participantsStrings := make([]string, len(participants))
for i, part := range participants {
participantsStrings[i] = part.String()
}
sort.Strings(participantsStrings)
hash := sha256.Sum256([]byte(strings.Join(participantsStrings, "")))
return fmt.Sprintf("2:%s", base64.RawStdEncoding.EncodeToString(hash[:6]))
}
2023-01-28 21:57:53 +00:00
func (cli *Client) sendGroup(ctx context.Context, to, ownID types.JID, id types.MessageID, message *waProto.Message, timings *MessageDebugTimings) (string, []byte, error) {
2022-06-11 21:07:42 +00:00
var participants []types.JID
var err error
start := time.Now()
2022-06-11 21:07:42 +00:00
if to.Server == types.GroupServer {
participants, err = cli.getGroupMembers(ctx, to)
2022-06-11 21:07:42 +00:00
if err != nil {
return "", nil, fmt.Errorf("failed to get group members: %w", err)
}
} else {
// TODO use context
2022-06-11 21:07:42 +00:00
participants, err = cli.getBroadcastListParticipants(to)
if err != nil {
return "", nil, fmt.Errorf("failed to get broadcast list members: %w", err)
}
2022-01-30 23:27:37 +00:00
}
timings.GetParticipants = time.Since(start)
start = time.Now()
2022-01-30 23:27:37 +00:00
plaintext, _, err := marshalMessage(to, message)
timings.Marshal = time.Since(start)
2022-01-30 23:27:37 +00:00
if err != nil {
2022-05-09 21:00:23 +00:00
return "", nil, err
2022-01-30 23:27:37 +00:00
}
start = time.Now()
2022-01-30 23:27:37 +00:00
builder := groups.NewGroupSessionBuilder(cli.Store, pbSerializer)
2023-01-28 21:57:53 +00:00
senderKeyName := protocol.NewSenderKeyName(to.String(), ownID.SignalAddress())
2022-01-30 23:27:37 +00:00
signalSKDMessage, err := builder.Create(senderKeyName)
if err != nil {
2022-05-09 21:00:23 +00:00
return "", nil, fmt.Errorf("failed to create sender key distribution message to send %s to %s: %w", id, to, err)
2022-01-30 23:27:37 +00:00
}
skdMessage := &waProto.Message{
SenderKeyDistributionMessage: &waProto.SenderKeyDistributionMessage{
GroupId: proto.String(to.String()),
AxolotlSenderKeyDistributionMessage: signalSKDMessage.Serialize(),
},
}
skdPlaintext, err := proto.Marshal(skdMessage)
if err != nil {
2022-05-09 21:00:23 +00:00
return "", nil, fmt.Errorf("failed to marshal sender key distribution message to send %s to %s: %w", id, to, err)
2022-01-30 23:27:37 +00:00
}
cipher := groups.NewGroupCipher(builder, senderKeyName, cli.Store)
encrypted, err := cipher.Encrypt(padMessage(plaintext))
if err != nil {
2022-05-09 21:00:23 +00:00
return "", nil, fmt.Errorf("failed to encrypt group message to send %s to %s: %w", id, to, err)
2022-01-30 23:27:37 +00:00
}
ciphertext := encrypted.SignedSerialize()
timings.GroupEncrypt = time.Since(start)
2022-01-30 23:27:37 +00:00
2023-01-28 21:57:53 +00:00
node, allDevices, err := cli.prepareMessageNode(ctx, to, ownID, id, message, participants, skdPlaintext, nil, timings)
2022-01-30 23:27:37 +00:00
if err != nil {
2022-05-09 21:00:23 +00:00
return "", nil, err
2022-01-30 23:27:37 +00:00
}
phash := participantListHashV2(allDevices)
node.Attrs["phash"] = phash
node.Content = append(node.GetChildren(), waBinary.Node{
Tag: "enc",
Content: ciphertext,
Attrs: waBinary.Attrs{"v": "2", "type": "skmsg"},
})
start = time.Now()
2022-06-11 21:07:42 +00:00
data, err := cli.sendNodeAndGetData(*node)
timings.Send = time.Since(start)
2022-01-30 23:27:37 +00:00
if err != nil {
2022-05-09 21:00:23 +00:00
return "", nil, fmt.Errorf("failed to send message node: %w", err)
2022-01-30 23:27:37 +00:00
}
2022-05-09 21:00:23 +00:00
return phash, data, nil
2022-01-30 23:27:37 +00:00
}
func (cli *Client) sendPeerMessage(to types.JID, id types.MessageID, message *waProto.Message, timings *MessageDebugTimings) ([]byte, error) {
node, err := cli.preparePeerMessageNode(to, id, message, timings)
2022-06-11 21:07:42 +00:00
if err != nil {
return nil, err
}
start := time.Now()
2022-06-11 21:07:42 +00:00
data, err := cli.sendNodeAndGetData(*node)
timings.Send = time.Since(start)
2022-06-11 21:07:42 +00:00
if err != nil {
return nil, fmt.Errorf("failed to send message node: %w", err)
}
return data, nil
}
2023-01-28 21:57:53 +00:00
func (cli *Client) sendDM(ctx context.Context, to, ownID types.JID, id types.MessageID, message *waProto.Message, timings *MessageDebugTimings) ([]byte, error) {
start := time.Now()
2022-01-30 23:27:37 +00:00
messagePlaintext, deviceSentMessagePlaintext, err := marshalMessage(to, message)
timings.Marshal = time.Since(start)
2022-01-30 23:27:37 +00:00
if err != nil {
2022-05-09 21:00:23 +00:00
return nil, err
2022-01-30 23:27:37 +00:00
}
2023-01-28 21:57:53 +00:00
node, _, err := cli.prepareMessageNode(ctx, to, ownID, id, message, []types.JID{to, ownID.ToNonAD()}, messagePlaintext, deviceSentMessagePlaintext, timings)
2022-01-30 23:27:37 +00:00
if err != nil {
2022-05-09 21:00:23 +00:00
return nil, err
2022-01-30 23:27:37 +00:00
}
start = time.Now()
2022-06-11 21:07:42 +00:00
data, err := cli.sendNodeAndGetData(*node)
timings.Send = time.Since(start)
2022-01-30 23:27:37 +00:00
if err != nil {
2022-05-09 21:00:23 +00:00
return nil, fmt.Errorf("failed to send message node: %w", err)
2022-01-30 23:27:37 +00:00
}
2022-05-09 21:00:23 +00:00
return data, nil
2022-01-30 23:27:37 +00:00
}
2022-06-11 21:07:42 +00:00
func getTypeFromMessage(msg *waProto.Message) string {
switch {
case msg.ViewOnceMessage != nil:
return getTypeFromMessage(msg.ViewOnceMessage.Message)
2022-11-26 23:42:16 +00:00
case msg.ViewOnceMessageV2 != nil:
return getTypeFromMessage(msg.ViewOnceMessageV2.Message)
2022-06-11 21:07:42 +00:00
case msg.EphemeralMessage != nil:
return getTypeFromMessage(msg.EphemeralMessage.Message)
2022-11-26 23:42:16 +00:00
case msg.DocumentWithCaptionMessage != nil:
return getTypeFromMessage(msg.DocumentWithCaptionMessage.Message)
2022-06-11 21:07:42 +00:00
case msg.ReactionMessage != nil:
return "reaction"
2022-11-26 23:42:16 +00:00
case msg.PollCreationMessage != nil, msg.PollUpdateMessage != nil:
return "poll"
2022-06-11 21:07:42 +00:00
case msg.Conversation != nil, msg.ExtendedTextMessage != nil, msg.ProtocolMessage != nil:
return "text"
//TODO this requires setting mediatype in the enc nodes
//case msg.ImageMessage != nil, msg.DocumentMessage != nil, msg.AudioMessage != nil, msg.VideoMessage != nil:
// return "media"
default:
return "text"
}
}
2022-11-26 23:42:16 +00:00
const (
EditAttributeEmpty = ""
EditAttributeMessageEdit = "1"
EditAttributeSenderRevoke = "7"
EditAttributeAdminRevoke = "8"
)
const RemoveReactionText = ""
2022-06-11 21:07:42 +00:00
func getEditAttribute(msg *waProto.Message) string {
2022-11-26 23:42:16 +00:00
switch {
case msg.ProtocolMessage != nil && msg.ProtocolMessage.GetKey() != nil:
switch msg.ProtocolMessage.GetType() {
case waProto.ProtocolMessage_REVOKE:
if msg.ProtocolMessage.GetKey().GetFromMe() {
return EditAttributeSenderRevoke
} else {
return EditAttributeAdminRevoke
}
case waProto.ProtocolMessage_MESSAGE_EDIT:
if msg.EditedMessage != nil {
return EditAttributeMessageEdit
}
2022-06-11 21:07:42 +00:00
}
2022-11-26 23:42:16 +00:00
case msg.ReactionMessage != nil && msg.ReactionMessage.GetText() == RemoveReactionText:
return EditAttributeSenderRevoke
case msg.KeepInChatMessage != nil && msg.KeepInChatMessage.GetKey().GetFromMe() && msg.KeepInChatMessage.GetKeepType() == waProto.KeepType_UNDO_KEEP_FOR_ALL:
return EditAttributeSenderRevoke
2022-06-11 21:07:42 +00:00
}
2022-11-26 23:42:16 +00:00
return EditAttributeEmpty
2022-06-11 21:07:42 +00:00
}
func (cli *Client) preparePeerMessageNode(to types.JID, id types.MessageID, message *waProto.Message, timings *MessageDebugTimings) (*waBinary.Node, error) {
2022-06-11 21:07:42 +00:00
attrs := waBinary.Attrs{
"id": id,
"type": "text",
"category": "peer",
"to": to,
}
if message.GetProtocolMessage().GetType() == waProto.ProtocolMessage_APP_STATE_SYNC_KEY_REQUEST {
attrs["push_priority"] = "high"
}
start := time.Now()
2022-06-11 21:07:42 +00:00
plaintext, err := proto.Marshal(message)
timings.Marshal = time.Since(start)
2022-06-11 21:07:42 +00:00
if err != nil {
err = fmt.Errorf("failed to marshal message: %w", err)
return nil, err
}
start = time.Now()
2022-06-11 21:07:42 +00:00
encrypted, isPreKey, err := cli.encryptMessageForDevice(plaintext, to, nil)
timings.PeerEncrypt = time.Since(start)
2022-06-11 21:07:42 +00:00
if err != nil {
return nil, fmt.Errorf("failed to encrypt peer message for %s: %v", to, err)
}
content := []waBinary.Node{*encrypted}
if isPreKey {
content = append(content, cli.makeDeviceIdentityNode())
}
return &waBinary.Node{
Tag: "message",
Attrs: attrs,
Content: content,
}, nil
}
2023-01-28 21:57:53 +00:00
func (cli *Client) prepareMessageNode(ctx context.Context, to, ownID types.JID, id types.MessageID, message *waProto.Message, participants []types.JID, plaintext, dsmPlaintext []byte, timings *MessageDebugTimings) (*waBinary.Node, []types.JID, error) {
start := time.Now()
allDevices, err := cli.GetUserDevicesContext(ctx, participants)
timings.GetDevices = time.Since(start)
2022-01-30 23:27:37 +00:00
if err != nil {
return nil, nil, fmt.Errorf("failed to get device list: %w", err)
}
2022-06-11 21:07:42 +00:00
attrs := waBinary.Attrs{
"id": id,
"type": getTypeFromMessage(message),
"to": to,
}
if editAttr := getEditAttribute(message); editAttr != "" {
attrs["edit"] = editAttr
2022-01-30 23:27:37 +00:00
}
2022-06-11 21:07:42 +00:00
start = time.Now()
2023-01-28 21:57:53 +00:00
participantNodes, includeIdentity := cli.encryptMessageForDevices(ctx, allDevices, ownID, id, plaintext, dsmPlaintext)
timings.PeerEncrypt = time.Since(start)
2022-06-11 21:07:42 +00:00
content := []waBinary.Node{{
Tag: "participants",
Content: participantNodes,
}}
2022-01-30 23:27:37 +00:00
if includeIdentity {
2022-06-11 21:07:42 +00:00
content = append(content, cli.makeDeviceIdentityNode())
2022-01-30 23:27:37 +00:00
}
2022-11-26 23:42:16 +00:00
if attrs["type"] == "poll" {
pollType := "creation"
if message.PollUpdateMessage != nil {
pollType = "vote"
}
content = append(content, waBinary.Node{
Tag: "meta",
Attrs: waBinary.Attrs{
"polltype": pollType,
},
})
}
2022-06-11 21:07:42 +00:00
return &waBinary.Node{
Tag: "message",
Attrs: attrs,
Content: content,
}, allDevices, nil
2022-01-30 23:27:37 +00:00
}
func marshalMessage(to types.JID, message *waProto.Message) (plaintext, dsmPlaintext []byte, err error) {
plaintext, err = proto.Marshal(message)
if err != nil {
err = fmt.Errorf("failed to marshal message: %w", err)
return
}
if to.Server != types.GroupServer {
dsmPlaintext, err = proto.Marshal(&waProto.Message{
DeviceSentMessage: &waProto.DeviceSentMessage{
DestinationJid: proto.String(to.String()),
Message: message,
},
})
if err != nil {
err = fmt.Errorf("failed to marshal message (for own devices): %w", err)
return
}
}
return
}
2022-06-11 21:07:42 +00:00
func (cli *Client) makeDeviceIdentityNode() waBinary.Node {
2022-01-30 23:27:37 +00:00
deviceIdentity, err := proto.Marshal(cli.Store.Account)
if err != nil {
2022-06-11 21:07:42 +00:00
panic(fmt.Errorf("failed to marshal device identity: %w", err))
2022-01-30 23:27:37 +00:00
}
2022-06-11 21:07:42 +00:00
return waBinary.Node{
2022-01-30 23:27:37 +00:00
Tag: "device-identity",
Content: deviceIdentity,
2022-06-11 21:07:42 +00:00
}
2022-01-30 23:27:37 +00:00
}
2023-01-28 21:57:53 +00:00
func (cli *Client) encryptMessageForDevices(ctx context.Context, allDevices []types.JID, ownID types.JID, id string, msgPlaintext, dsmPlaintext []byte) ([]waBinary.Node, bool) {
2022-01-30 23:27:37 +00:00
includeIdentity := false
participantNodes := make([]waBinary.Node, 0, len(allDevices))
var retryDevices []types.JID
for _, jid := range allDevices {
plaintext := msgPlaintext
2023-01-28 21:57:53 +00:00
if jid.User == ownID.User && dsmPlaintext != nil {
if jid == ownID {
2022-01-30 23:27:37 +00:00
continue
}
plaintext = dsmPlaintext
}
encrypted, isPreKey, err := cli.encryptMessageForDeviceAndWrap(plaintext, jid, nil)
if errors.Is(err, ErrNoSession) {
retryDevices = append(retryDevices, jid)
continue
} else if err != nil {
cli.Log.Warnf("Failed to encrypt %s for %s: %v", id, jid, err)
continue
}
participantNodes = append(participantNodes, *encrypted)
if isPreKey {
includeIdentity = true
}
}
if len(retryDevices) > 0 {
bundles, err := cli.fetchPreKeys(ctx, retryDevices)
2022-01-30 23:27:37 +00:00
if err != nil {
2022-05-09 21:00:23 +00:00
cli.Log.Warnf("Failed to fetch prekeys for %v to retry encryption: %v", retryDevices, err)
2022-01-30 23:27:37 +00:00
} else {
for _, jid := range retryDevices {
resp := bundles[jid]
if resp.err != nil {
cli.Log.Warnf("Failed to fetch prekey for %s: %v", jid, resp.err)
continue
}
plaintext := msgPlaintext
2023-01-28 21:57:53 +00:00
if jid.User == ownID.User && dsmPlaintext != nil {
2022-01-30 23:27:37 +00:00
plaintext = dsmPlaintext
}
encrypted, isPreKey, err := cli.encryptMessageForDeviceAndWrap(plaintext, jid, resp.bundle)
if err != nil {
cli.Log.Warnf("Failed to encrypt %s for %s (retry): %v", id, jid, err)
continue
}
participantNodes = append(participantNodes, *encrypted)
if isPreKey {
includeIdentity = true
}
}
}
}
return participantNodes, includeIdentity
}
func (cli *Client) encryptMessageForDeviceAndWrap(plaintext []byte, to types.JID, bundle *prekey.Bundle) (*waBinary.Node, bool, error) {
node, includeDeviceIdentity, err := cli.encryptMessageForDevice(plaintext, to, bundle)
if err != nil {
return nil, false, err
}
return &waBinary.Node{
Tag: "to",
Attrs: waBinary.Attrs{"jid": to},
Content: []waBinary.Node{*node},
}, includeDeviceIdentity, nil
}
func (cli *Client) encryptMessageForDevice(plaintext []byte, to types.JID, bundle *prekey.Bundle) (*waBinary.Node, bool, error) {
builder := session.NewBuilderFromSignal(cli.Store, to.SignalAddress(), pbSerializer)
if bundle != nil {
cli.Log.Debugf("Processing prekey bundle for %s", to)
err := builder.ProcessBundle(bundle)
2022-03-31 22:23:19 +00:00
if cli.AutoTrustIdentity && errors.Is(err, signalerror.ErrUntrustedIdentity) {
cli.Log.Warnf("Got %v error while trying to process prekey bundle for %s, clearing stored identity and retrying", err, to)
cli.clearUntrustedIdentity(to)
err = builder.ProcessBundle(bundle)
}
2022-01-30 23:27:37 +00:00
if err != nil {
return nil, false, fmt.Errorf("failed to process prekey bundle: %w", err)
}
} else if !cli.Store.ContainsSession(to.SignalAddress()) {
return nil, false, ErrNoSession
}
cipher := session.NewCipher(builder, to.SignalAddress())
ciphertext, err := cipher.Encrypt(padMessage(plaintext))
if err != nil {
return nil, false, fmt.Errorf("cipher encryption failed: %w", err)
}
encType := "msg"
if ciphertext.Type() == protocol.PREKEY_TYPE {
encType = "pkmsg"
}
return &waBinary.Node{
Tag: "enc",
Attrs: waBinary.Attrs{
"v": "2",
"type": encType,
},
Content: ciphertext.Serialize(),
}, encType == "pkmsg", nil
}