Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions appstate.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (cli *Client) fetchAppState(ctx context.Context, name appstate.WAPatchName,
wantSnapshot := fullSync
var eventsToDispatch []any
eventsToDispatchPtr := &eventsToDispatch
if fullSync && !cli.EmitAppStateEventsOnFullSync && !cli.EmitLabelEventsOnFullSync && !cli.EmitQuickReplyEventsOnFullSync {
if fullSync && !cli.EmitAppStateEventsOnFullSync && !cli.EmitLabelEventsOnFullSync && !cli.EmitQuickReplyEventsOnFullSync && !cli.EmitStickerEventsOnFullSync {
eventsToDispatchPtr = nil
}
for hasMore {
Expand Down Expand Up @@ -118,7 +118,7 @@ func (cli *Client) handleAppStateRecovery(
}
var eventsToDispatch []any
eventsToDispatchPtr := &eventsToDispatch
if !cli.EmitAppStateEventsOnFullSync && !cli.EmitLabelEventsOnFullSync && !cli.EmitQuickReplyEventsOnFullSync {
if !cli.EmitAppStateEventsOnFullSync && !cli.EmitLabelEventsOnFullSync && !cli.EmitQuickReplyEventsOnFullSync && !cli.EmitStickerEventsOnFullSync {
eventsToDispatchPtr = nil
}
snapshot, err := appstate.ParseRecovery(result[0].GetSyncdSnapshotFatalRecoveryResponse())
Expand Down Expand Up @@ -215,6 +215,9 @@ func (cli *Client) shouldEmitFullSyncMutation(index []string) bool {
if len(index) == 0 {
return false
}
if cli.EmitStickerEventsOnFullSync && (index[0] == appstate.IndexFavoriteSticker || index[0] == appstate.IndexRemoveRecentSticker) {
return true
}
if cli.EmitQuickReplyEventsOnFullSync && index[0] == appstate.IndexQuickReply {
return true
}
Expand Down Expand Up @@ -304,6 +307,16 @@ func (cli *Client) dispatchAppState(ctx context.Context, name appstate.WAPatchNa

var storeUpdateError error
switch mutation.Index[0] {
case appstate.IndexFavoriteSticker:
if len(mutation.Index) != 2 || mutation.Index[1] == "" || (mutation.Action.GetStickerAction() == nil || mutation.Action.GetStickerAction().IsFavorite == nil) {
return
}
eventToDispatch = &events.FavoriteSticker{FileSHA256: mutation.Index[1], Timestamp: ts, Action: mutation.Action.GetStickerAction(), FromFullSync: fullSync}
case appstate.IndexRemoveRecentSticker:
if len(mutation.Index) != 2 || mutation.Index[1] == "" || mutation.Action.GetRemoveRecentStickerAction() == nil {
return
}
eventToDispatch = &events.RemoveRecentSticker{FileSHA256: mutation.Index[1], Timestamp: ts, Action: mutation.Action.GetRemoveRecentStickerAction(), FromFullSync: fullSync}
case appstate.IndexMute:
act := mutation.Action.GetMuteAction()
eventToDispatch = &events.Mute{JID: jid, Timestamp: ts, Action: act, FromFullSync: fullSync}
Expand Down
33 changes: 33 additions & 0 deletions appstate/sticker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package appstate

import (
"encoding/base64"
"fmt"

"google.golang.org/protobuf/proto"

"github.com/polymorfa/hypermeow/proto/waSyncAction"
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// BuildFavoriteSticker builds a regular_low v7 favorite/unfavorite mutation.
// The hash is the plaintext SHA-256. Favoriting requires downloadable media details.
// Evidence: WAWebStickersFavoriteSyncAction, whatsapp-1053201649, lines 20-25, 81-99.
func BuildFavoriteSticker(hash []byte, action *waSyncAction.StickerAction) (PatchInfo, error) {
if len(hash) != 32 || action == nil || action.IsFavorite == nil {
return PatchInfo{}, fmt.Errorf("sticker hash and favorite state are required")
}
if action.GetIsFavorite() && (len(action.MediaKey) != 32 || len(action.FileEncSHA256) != 32 || action.GetDirectPath() == "" || action.GetMimetype() == "") {
return PatchInfo{}, fmt.Errorf("favorite sticker requires media details")
}
return PatchInfo{Type: WAPatchRegularLow, Mutations: []MutationInfo{{Index: []string{IndexFavoriteSticker, base64.StdEncoding.EncodeToString(hash)}, Version: 7, Value: &waSyncAction.SyncActionValue{StickerAction: proto.Clone(action).(*waSyncAction.StickerAction)}}}}, nil
}

// BuildRemoveRecentSticker removes a recent sticker up to lastSentTimestampMS.
// The timestamp guard preserves a sticker sent again after the removal was made.
// Evidence: WAWebStickersRemoveRecentSyncAction, whatsapp-1053201649, lines 16-21, 35-38, 46-55.
func BuildRemoveRecentSticker(hash []byte, lastSentTimestampMS int64) (PatchInfo, error) {
if len(hash) != 32 || lastSentTimestampMS < 0 {
return PatchInfo{}, fmt.Errorf("valid sticker hash and last sent timestamp are required")
}
return PatchInfo{Type: WAPatchRegularLow, Mutations: []MutationInfo{{Index: []string{IndexRemoveRecentSticker, base64.StdEncoding.EncodeToString(hash)}, Version: 7, Value: &waSyncAction.SyncActionValue{RemoveRecentStickerAction: &waSyncAction.RemoveRecentStickerAction{LastStickerSentTS: proto.Int64(lastSentTimestampMS)}}}}}, nil
}
34 changes: 34 additions & 0 deletions appstate/sticker_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package appstate

import (
"bytes"
"testing"

"google.golang.org/protobuf/proto"

"github.com/polymorfa/hypermeow/proto/waSyncAction"
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

func TestStickerPatches(t *testing.T) {
hash := bytes.Repeat([]byte{1}, 32)
p, err := BuildFavoriteSticker(hash, &waSyncAction.StickerAction{IsFavorite: proto.Bool(false)})
if err != nil {
t.Fatal(err)
}
if p.Type != WAPatchRegularLow || p.Mutations[0].Version != 7 || p.Mutations[0].Index[0] != IndexFavoriteSticker {
t.Fatal("wrong favorite patch")
}
if _, err = BuildFavoriteSticker(hash, &waSyncAction.StickerAction{IsFavorite: proto.Bool(true)}); err == nil {
t.Fatal("favorite without media accepted")
}
p, err = BuildRemoveRecentSticker(hash, 123)
if err != nil {
t.Fatal(err)
}
if p.Mutations[0].Value.GetRemoveRecentStickerAction().GetLastStickerSentTS() != 123 || p.Mutations[0].Version != 7 {
t.Fatal("missing timestamp")
}
if _, err = BuildRemoveRecentSticker(nil, 123); err == nil {
t.Fatal("missing hash accepted")
}
}
5 changes: 4 additions & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,10 @@ type Client struct {
EmitAppStateEventsOnFullSync bool
EmitLabelEventsOnFullSync bool
EmitQuickReplyEventsOnFullSync bool
AppStateDebugLogs bool

// EmitStickerEventsOnFullSync emits favorite and recent-removal snapshot events.
EmitStickerEventsOnFullSync bool
AppStateDebugLogs bool

AutomaticMessageRerequestFromPhone bool
pendingPhoneRerequests map[types.MessageID]context.CancelFunc
Expand Down
14 changes: 10 additions & 4 deletions download.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ const (
MediaHistory MediaType = "WhatsApp History Keys"
MediaAppState MediaType = "WhatsApp App State Keys"

MediaStickerPack MediaType = "WhatsApp Sticker Pack Keys"
MediaLinkThumbnail MediaType = "WhatsApp Link Thumbnail Keys"
MediaStickerPackThumbnail MediaType = "WhatsApp Sticker Pack Thumbnail Keys"
MediaStickerPack MediaType = "WhatsApp Sticker Pack Keys"
MediaLinkThumbnail MediaType = "WhatsApp Link Thumbnail Keys"
)

// DownloadableMessage represents a protobuf message that contains attachment info.
Expand Down Expand Up @@ -89,6 +90,7 @@ var (
_ DownloadableMessage = (*waE2E.HistorySyncNotification)(nil)
_ DownloadableMessage = (*waServerSync.ExternalBlobReference)(nil)
_ DownloadableThumbnail = (*waE2E.ExtendedTextMessage)(nil)
_ DownloadableThumbnail = (*waE2E.StickerPackMessage)(nil)
_ DownloadableMessage = (*types.StickerPackItem)(nil)
)

Expand All @@ -107,6 +109,7 @@ var classToMediaType = map[protoreflect.Name]MediaType{

var classToThumbnailMediaType = map[protoreflect.Name]MediaType{
"ExtendedTextMessage": MediaLinkThumbnail,
"StickerPackMessage": MediaStickerPackThumbnail,
}

var mediaTypeToMMSType = map[MediaType]string{
Expand All @@ -117,8 +120,9 @@ var mediaTypeToMMSType = map[MediaType]string{
MediaHistory: "md-msg-hist",
MediaAppState: "md-app-state",

MediaStickerPack: "sticker-pack",
MediaLinkThumbnail: "thumbnail-link",
MediaStickerPack: "sticker-pack",
MediaLinkThumbnail: "thumbnail-link",
MediaStickerPackThumbnail: "thumbnail-sticker-pack",
}

// DownloadAny loops through the downloadable parts of the given message and downloads the first non-nil item.
Expand All @@ -139,6 +143,8 @@ func (cli *Client) DownloadAny(ctx context.Context, msg *waE2E.Message) (data []
return cli.Download(ctx, msg.DocumentMessage)
case msg.StickerMessage != nil:
return cli.Download(ctx, msg.StickerMessage)
case msg.StickerPackMessage != nil:
return cli.Download(ctx, msg.StickerPackMessage)
default:
return nil, ErrNothingDownloadableFound
}
Expand Down
29 changes: 24 additions & 5 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -1016,6 +1016,13 @@ func (cli *Client) handlePlaceholderResendResponse(msg *waE2E.PeerDataOperationR
}

func (cli *Client) handleProtocolMessage(ctx context.Context, info *types.MessageInfo, msg *waE2E.Message) (ok bool) {
ok, _ = handleProtocolMessageResult(cli, ctx, info, msg)
return
}

// Keep the legacy internal hook's bool result while the decrypt path carries
// handler failure independently from ordinary Message-event suppression.
func handleProtocolMessageResult(cli *Client, ctx context.Context, info *types.MessageInfo, msg *waE2E.Message) (ok, handlerFailed bool) {
ok = true
protoMsg := msg.GetProtocolMessage()

Expand Down Expand Up @@ -1044,9 +1051,11 @@ func (cli *Client) handleProtocolMessage(ctx context.Context, info *types.Messag
cli.storeLIDSyncMessage(ctx, protoMsg.GetLidMigrationMappingSyncMessage().GetEncodedMappingPayload())
}

if info.Sender.Device == 0 {
peerResp := protoMsg.GetPeerDataOperationRequestResponseMessage()
if peerResp := protoMsg.GetPeerDataOperationRequestResponseMessage(); info.Sender.Device == 0 && peerResp != nil {
switch peerResp.GetPeerDataOperationRequestType() {
case waE2E.PeerDataOperationRequestType_UPLOAD_STICKER:
handlerFailed = cli.dispatchEvent(&events.StickerReupload{RequestID: peerResp.GetStanzaID(), Results: peerResp.GetPeerDataOperationResult()})
ok = false
case waE2E.PeerDataOperationRequestType_PLACEHOLDER_MESSAGE_RESEND:
ok = cli.handlePlaceholderResendResponse(peerResp) && ok
case waE2E.PeerDataOperationRequestType_COMPANION_SYNCD_SNAPSHOT_FATAL_RECOVERY:
Expand All @@ -1058,7 +1067,7 @@ func (cli *Client) handleProtocolMessage(ctx context.Context, info *types.Messag
go cli.handleAppStateSyncKeyShare(context.WithoutCancel(ctx), protoMsg.AppStateSyncKeyShare)
}

if info.Category == "peer" {
if info.Category == "peer" && !handlerFailed {
go func() {
err := cli.SendProtocolMessageReceipt(ctx, info.ID, types.ReceiptTypePeerMsg)
if err != nil {
Expand Down Expand Up @@ -1086,6 +1095,11 @@ func (cli *Client) shouldStoreHistorySyncNonce() bool {
}

func (cli *Client) processProtocolParts(ctx context.Context, info *types.MessageInfo, msg *waE2E.Message) (ok bool) {
ok, _ = processProtocolPartsResult(cli, ctx, info, msg)
return
}

func processProtocolPartsResult(cli *Client, ctx context.Context, info *types.MessageInfo, msg *waE2E.Message) (ok, handlerFailed bool) {
ok = true
cli.storeMessageSecret(ctx, info, msg)
// Hopefully sender key distribution messages and protocol messages can't be inside ephemeral messages
Expand All @@ -1106,7 +1120,9 @@ func (cli *Client) processProtocolParts(ctx context.Context, info *types.Message
// N.B. Edits are protocol messages, but they're also wrapped inside EditedMessage,
// which is only unwrapped after processProtocolParts, so this won't trigger for edits.
if msg.GetProtocolMessage() != nil {
ok = cli.handleProtocolMessage(ctx, info, msg) && ok
protocolOK, failed := handleProtocolMessageResult(cli, ctx, info, msg)
ok = protocolOK && ok
handlerFailed = failed
}
return
}
Expand Down Expand Up @@ -1338,7 +1354,10 @@ func (cli *Client) storeHistoricalPNLIDMappings(ctx context.Context, mappings []
}

func (cli *Client) handleDecryptedMessage(ctx context.Context, info *types.MessageInfo, msg *waE2E.Message, retryCount int) (handlerFailed bool) {
ok := cli.processProtocolParts(ctx, info, msg)
ok, failed := processProtocolPartsResult(cli, ctx, info, msg)
if failed {
return true
}
if !ok {
return false
}
Expand Down
2 changes: 2 additions & 0 deletions send.go
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,8 @@ func getMediaTypeFromMessage(msg *waE2E.Message) string {
return "image"
case msg.StickerMessage != nil:
return "sticker"
case msg.StickerPackMessage != nil:
return "sticker_pack"
case msg.DocumentMessage != nil:
return "document"
case msg.AudioMessage != nil:
Expand Down
38 changes: 38 additions & 0 deletions sticker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package whatsmeow

import (
"encoding/base64"
"fmt"

"google.golang.org/protobuf/proto"

"github.com/polymorfa/hypermeow/proto/waE2E"
)

// BuildStickerReuploadRequest requests fresh media details from the primary device.
// Send it with SendPeerMessage. Acceptance of the request does not mean the phone
// found or uploaded the stickers; results arrive in events.StickerReupload.
func (cli *Client) BuildStickerReuploadRequest(hashes [][]byte) (*waE2E.Message, error) {
if len(hashes) == 0 {
return nil, fmt.Errorf("at least one sticker hash is required")
}
req := &waE2E.PeerDataOperationRequestMessage{PeerDataOperationRequestType: waE2E.PeerDataOperationRequestType_UPLOAD_STICKER.Enum()}
seen := make(map[string]bool)
for _, hash := range hashes {
if len(hash) != 32 {
return nil, fmt.Errorf("sticker hashes must contain 32 bytes")
}
key := base64.StdEncoding.EncodeToString(hash)
if !seen[key] {
req.RequestStickerReupload = append(req.RequestStickerReupload, &waE2E.PeerDataOperationRequestMessage_RequestStickerReupload{FileSHA256: proto.String(key)})
seen[key] = true
}
}
return &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{Type: waE2E.ProtocolMessage_PEER_DATA_OPERATION_REQUEST_MESSAGE.Enum(), PeerDataOperationRequestMessage: req}}, nil
}

// BuildRecentStickerBootstrapRequest requests recents in a later history sync.
// Send with SendPeerMessage. The primary device must be available to respond.
func (cli *Client) BuildRecentStickerBootstrapRequest() *waE2E.Message {
return &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{Type: waE2E.ProtocolMessage_PEER_DATA_OPERATION_REQUEST_MESSAGE.Enum(), PeerDataOperationRequestMessage: &waE2E.PeerDataOperationRequestMessage{PeerDataOperationRequestType: waE2E.PeerDataOperationRequestType_SEND_RECENT_STICKER_BOOTSTRAP.Enum()}}}
}
48 changes: 48 additions & 0 deletions sticker_delivery_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package whatsmeow

import (
"context"
"testing"

"google.golang.org/protobuf/proto"

"github.com/polymorfa/hypermeow/proto/waE2E"
"github.com/polymorfa/hypermeow/store"
"github.com/polymorfa/hypermeow/types"
"github.com/polymorfa/hypermeow/types/events"
waLog "github.com/polymorfa/hypermeow/util/log"
)

func TestStickerResultPreservesHandlerFailureAndSuppressesMessage(t *testing.T) {
for _, wrapped := range []bool{false, true} {
for _, success := range []bool{false, true} {
cli := NewClient(&store.Device{}, waLog.Noop)
results, messages := 0, 0
cli.AddEventHandlerWithSuccessStatus(func(event any) bool {
switch e := event.(type) {
case *events.StickerReupload:
results++
if e.RequestID != "request" {
t.Errorf("request identity lost: %s", e.RequestID)
}
return success
case *events.Message:
messages++
}
return true
})
msg := &waE2E.Message{ProtocolMessage: &waE2E.ProtocolMessage{PeerDataOperationRequestResponseMessage: &waE2E.PeerDataOperationRequestResponseMessage{PeerDataOperationRequestType: waE2E.PeerDataOperationRequestType_UPLOAD_STICKER.Enum(), StanzaID: proto.String("request")}}}
if wrapped {
msg = &waE2E.Message{DeviceSentMessage: &waE2E.DeviceSentMessage{Message: msg}}
}
info := &types.MessageInfo{MessageSource: types.MessageSource{IsFromMe: true, Sender: types.JID{User: "fixture", Server: types.DefaultUserServer}}}
failed := cli.handleDecryptedMessage(context.Background(), info, msg, 0)
if failed == success {
t.Errorf("wrapped=%t success=%t: handler failure=%t", wrapped, success, failed)
}
if results != 1 || messages != 0 {
t.Errorf("wrapped=%t success=%t: results=%d ordinary messages=%d", wrapped, success, results, messages)
}
}
}
}
Loading
Loading