Repository navigation
Expand file tree
/
Copy pathsend.rs
More file actions
2753 lines (2463 loc) · 104 KB
/
Copy pathsend.rs
File metadata and controls
2753 lines (2463 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::client::Client;
use crate::types::message::EditAttribute;
use anyhow::anyhow;
use log::debug;
use wacore::client::context::SendContextResolver;
use wacore::libsignal::protocol::SignalProtocolError;
use wacore::types::jid::JidExt;
use wacore::types::message::AddressingMode;
#[cfg(test)]
use wacore_binary::DeviceKey;
use wacore_binary::Node;
use wacore_binary::builder::NodeBuilder;
use wacore_binary::{Jid, JidExt as _, Server};
use waproto::whatsapp as wa;
/// Options for [`Client::send_message_with_options`].
#[derive(Debug, Clone, Default)]
pub struct SendOptions {
/// Override the auto-generated message ID.
/// Useful for resending a failed message with the same ID or idempotency.
pub message_id: Option<String>,
/// Extra XML child nodes on the message stanza.
pub extra_stanza_nodes: Vec<Node>,
/// Ephemeral duration in seconds. Sets `contextInfo.expiration` on the
/// message (WA Web `EProtoGenerator.js:183` parity).
/// Common values: 86400 (24h), 604800 (7d), 7776000 (90d).
pub ephemeral_expiration: Option<u32>,
}
/// Result of a successfully sent message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SendResult {
pub message_id: String,
pub to: Jid,
}
impl SendResult {
/// `participant` is `None` -- only valid for the sender's own messages.
pub fn message_key(&self) -> wa::MessageKey {
wa::MessageKey {
remote_jid: Some(self.to.to_string()),
from_me: Some(true),
id: Some(self.message_id.clone()),
participant: None,
}
}
}
/// Duration for pinned messages. Default is 7 days (matches WA Web).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum PinDuration {
Hours24,
#[default]
Days7,
Days30,
}
impl PinDuration {
fn as_secs(self) -> u32 {
match self {
Self::Hours24 => 86_400,
Self::Days7 => 604_800,
Self::Days30 => 2_592_000,
}
}
}
/// Specifies who is revoking (deleting) the message.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum RevokeType {
/// The message sender deleting their own message.
#[default]
Sender,
/// A group admin deleting another user's message.
/// `original_sender` is the JID of the user who sent the message being deleted.
Admin { original_sender: Jid },
}
/// Derive stanza-level edit attribute and meta node from message content.
fn infer_stanza_metadata(msg: &wa::Message) -> (Option<EditAttribute>, Option<Node>) {
if msg.pin_in_chat_message.is_some() {
return (Some(EditAttribute::PinInChat), None);
}
// Poll messages
if msg.poll_creation_message.is_some()
|| msg.poll_creation_message_v2.is_some()
|| msg.poll_creation_message_v3.is_some()
{
return (None, Some(meta_node("polltype", "creation")));
}
if let Some(ref poll_update) = msg.poll_update_message
&& poll_update.vote.is_some()
{
return (None, Some(meta_node("polltype", "vote")));
}
// TODO: polltype="result_snapshot" for poll_result_snapshot_message (gated behind AB flag)
// Event messages
if msg.event_message.is_some() {
return (None, Some(meta_node("event_type", "creation")));
}
if msg.enc_event_response_message.is_some() {
return (None, Some(meta_node("event_type", "response")));
}
if let Some(ref sec) = msg.secret_encrypted_message
&& sec.secret_enc_type
== Some(wa::message::secret_encrypted_message::SecretEncType::EventEdit as i32)
{
return (None, Some(meta_node("event_type", "edit")));
}
(None, None)
}
fn meta_node(key: &'static str, value: &'static str) -> Node {
NodeBuilder::new("meta").attr(key, value).build()
}
/// Derive the `<biz>` stanza child for native-flow interactive messages.
/// All native flow types use the same nested structure (confirmed via protocol capture).
fn infer_biz_node(msg: &wa::Message) -> Option<Node> {
let interactive = extract_interactive_message(msg)?;
let wa::message::interactive_message::InteractiveMessage::NativeFlowMessage(nf) =
interactive.interactive_message.as_ref()?
else {
return None;
};
let first_button_name = nf.buttons.first()?.name.as_deref()?;
let flow_name = button_name_to_flow_name(first_button_name);
Some(
NodeBuilder::new("biz")
.children([NodeBuilder::new("interactive")
.attr("type", "native_flow")
.attr("v", "1")
.children([NodeBuilder::new("native_flow")
.attr("name", flow_name)
.build()])
.build()])
.build(),
)
}
fn extract_interactive_message(msg: &wa::Message) -> Option<&wa::message::InteractiveMessage> {
// Only checks documentWithCaptionMessage wrapper (for media headers) and direct field.
// Does not use unwrap_message() since we need the InteractiveMessage specifically.
if let Some(ref doc) = msg.document_with_caption_message
&& let Some(ref inner) = doc.message
&& let Some(ref im) = inner.interactive_message
{
return Some(im);
}
msg.interactive_message.as_deref()
}
fn button_name_to_flow_name(button_name: &str) -> &str {
match button_name {
"review_and_pay" => "order_details",
"payment_info" => "payment_info",
"review_order" | "order_status" => "order_status",
"payment_status" => "payment_status",
"payment_method" => "payment_method",
"payment_reminder" => "payment_reminder",
"open_webview" => "message_with_link",
"message_with_link_status" => "message_with_link_status",
"cta_url" => "cta_url",
"cta_call" => "cta_call",
"cta_copy" => "cta_copy",
"cta_catalog" => "cta_catalog",
"catalog_message" => "catalog_message",
"quick_reply" => "quick_reply",
"galaxy_message" => "galaxy_message",
"booking_confirmation" => "booking_confirmation",
"call_permission_request" => "call_permission_request",
other => other,
}
}
fn build_revoke_message(
remote_jid: &Jid,
from_me: bool,
message_id: String,
participant: Option<String>,
) -> wa::Message {
wa::Message {
protocol_message: Some(Box::new(wa::message::ProtocolMessage {
key: Some(wa::MessageKey {
remote_jid: Some(remote_jid.to_string()),
from_me: Some(from_me),
id: Some(message_id),
participant,
}),
r#type: Some(wa::message::protocol_message::Type::Revoke as i32),
..Default::default()
})),
..Default::default()
}
}
impl Client {
/// Send a message to a user, group, or newsletter.
///
/// Newsletter messages are sent as plaintext (no E2E encryption).
/// For status/story updates use [`Client::status()`] instead.
pub async fn send_message(
&self,
to: Jid,
message: wa::Message,
) -> Result<SendResult, anyhow::Error> {
self.send_message_with_options(to, message, SendOptions::default())
.await
}
/// Send a message with additional options.
pub async fn send_message_with_options(
&self,
to: Jid,
mut message: wa::Message,
options: SendOptions,
) -> Result<SendResult, anyhow::Error> {
if let Some(exp) = options.ephemeral_expiration
&& exp > 0
{
use wacore::proto_helpers::MessageExt;
if !message.set_ephemeral_expiration(exp) {
// Bare `conversation` messages have no contextInfo field.
log::warn!("Could not set contextInfo.expiration on this message type");
}
}
let request_id = match options.message_id {
Some(id) => id,
None => self.generate_message_id().await,
};
// Both paths below consume `to` and `request_id`, so save copies for the result.
let result = SendResult {
message_id: request_id.clone(),
to: to.clone(),
};
// Newsletters are not E2E encrypted — send as plaintext via SMAX stanza.
// Matches WA Web's OutMessagePublishNewsletterRequest + ContentType mixins.
if to.is_newsletter() {
use prost::Message as _;
let stanza_type = wacore::send::stanza_type_from_message(&message);
let (_, meta_node) = infer_stanza_metadata(&message);
let mut plaintext_builder = NodeBuilder::new("plaintext");
if let Some(mt) = wacore::send::media_type_from_message(&message) {
plaintext_builder = plaintext_builder.attr("mediatype", mt);
}
let mut children = vec![plaintext_builder.bytes(message.encode_to_vec()).build()];
children.extend(meta_node);
children.extend(options.extra_stanza_nodes);
let stanza = NodeBuilder::new("message")
.attr("to", to)
.attr("type", stanza_type)
.attr("id", &request_id)
.children(children)
.build();
self.send_node(stanza).await?;
return Ok(result);
}
let (edit, inferred_meta) = infer_stanza_metadata(&message);
let inferred_biz = infer_biz_node(&message);
let extra_nodes = if inferred_meta.is_none() && inferred_biz.is_none() {
options.extra_stanza_nodes
} else {
let mut nodes = Vec::with_capacity(2 + options.extra_stanza_nodes.len());
nodes.extend(inferred_meta);
nodes.extend(inferred_biz);
nodes.extend(options.extra_stanza_nodes);
nodes
};
self.send_message_impl(
to,
&message,
Some(request_id),
false,
false,
edit,
extra_nodes,
)
.await?;
Ok(result)
}
/// Send a status/story update using sender-key encryption.
///
/// Status uses LID addressing (matches `WAWebEncryptAndSendStatusMsg`):
/// LID recipients pass through, PN recipients are resolved to LID via
/// `Client::get_lid_pn_entry` (cache-aside), and unresolvable recipients
/// are skipped silently. The resulting `GroupInfo` carries
/// `AddressingMode::Lid`; `prepare_group_stanza` signs with `own_lid`
/// and emits `addressing_mode="lid"` on the stanza. Errors only if no
/// recipient could be resolved.
pub(crate) async fn send_status_message(
&self,
message: wa::Message,
recipients: &[Jid],
options: crate::features::status::StatusSendOptions,
) -> Result<SendResult, anyhow::Error> {
use wacore::client::context::GroupInfo;
use wacore_binary::builder::NodeBuilder;
if recipients.is_empty() {
return Err(anyhow!("Cannot send status with no recipients"));
}
let to = Jid::status_broadcast();
let request_id = self.generate_message_id().await;
let mut device_snapshot = self.persistence_manager.get_device_snapshot().await;
let account_info = device_snapshot.account.take();
let own_jid = device_snapshot
.pn
.take()
.ok_or(crate::client::ClientError::NotLoggedIn)?;
// Status is LID-addressed (matches WA Web post-LID-migration). Without
// a real device LID we can't sign or fan out correctly; refuse rather
// than silently emit `addressing_mode="lid"` with a PN sender.
let own_lid = device_snapshot.lid.take().ok_or_else(|| {
anyhow!(
"Cannot send status: device has no LID yet. Finish pairing / LID \
migration before posting status."
)
})?;
// Fail fast for any JID that isn't a user (PN or LID). Mirrors WA
// Web's `asUserWidOrThrow` inside `toUserLid`: non-user inputs are a
// programming bug, not something to silently drop during resolution.
for jid in recipients {
if !(jid.is_pn() || jid.is_lid()) {
return Err(anyhow!(
"Invalid status recipient {}: must be a user JID (PN or LID), \
not a group/broadcast/newsletter/hosted/etc.",
jid
));
}
}
use std::collections::HashMap;
let mut resolved: Vec<Option<Jid>> = Vec::with_capacity(recipients.len());
let mut lid_to_pn_map: HashMap<wacore_binary::CompactString, Jid> =
HashMap::with_capacity(recipients.len() + 1);
for jid in recipients {
if let Some(lid_jid) = self.resolve_recipient_to_lid(jid).await {
if jid.is_pn() {
lid_to_pn_map.insert(lid_jid.user.clone(), jid.to_non_ad());
}
resolved.push(Some(lid_jid));
} else {
resolved.push(None);
}
}
lid_to_pn_map.insert(own_lid.user.clone(), own_jid.to_non_ad());
let participants = wacore::send::assemble_status_participants(resolved, &own_lid)?;
let mut group_info =
GroupInfo::with_lid_to_pn_map(participants, AddressingMode::Lid, lid_to_pn_map);
self.add_recent_message(&to, &request_id, &message).await;
let device_store_arc = self.persistence_manager.get_device_arc().await;
let to_str = to.to_string();
let force_skdm = {
use wacore::libsignal::store::sender_key_name::SenderKeyName;
// Sender key name tracks the addressing mode of the group stanza.
// Since status now uses LID addressing (see send_status_message
// header), the key is stored under own_lid, matching the address
// prepare_group_stanza derives internally.
let sender_address = own_lid.to_protocol_address();
let sender_key_name = SenderKeyName::from_parts(&to_str, sender_address.as_str());
let device_guard = device_store_arc.read().await;
let key_exists = self
.signal_cache
.get_sender_key(&sender_key_name, &*device_guard.backend)
.await?
.is_some();
!key_exists
};
let mut store_adapter = self.signal_adapter_from(device_store_arc.clone());
let mut stores = store_adapter.as_signal_stores();
// Determine which devices need SKDM using the unified per-device map
let skdm_target_devices: Option<Vec<Jid>> = if force_skdm {
None
} else {
self.resolve_skdm_targets(&to_str, &group_info, &own_lid)
.await
};
// `<meta status_setting>` describes the POSTER's privacy on their own
// status. Reactions go through WA Web's addon path and never visit
// `WAWebEncryptAndSendStatusMsg`; attaching the meta on a reaction
// gets the stanza NACK'd with 479 (SmaxInvalid). Revokes also skip it.
let extra_stanza_nodes = if wacore::send::status_carries_privacy_meta(&message) {
vec![
NodeBuilder::new("meta")
.attr("status_setting", options.privacy.as_str())
.build(),
]
} else {
vec![]
};
let prepared = match wacore::send::prepare_group_stanza(
&*self.runtime,
&mut stores,
self,
&mut group_info,
&own_jid,
&own_lid,
account_info.as_ref(),
to.clone(),
&message,
request_id.clone(),
force_skdm,
skdm_target_devices,
None,
&extra_stanza_nodes,
)
.await
{
Ok(prepared) => prepared,
Err(e) => {
if let Some(SignalProtocolError::NoSenderKeyState(_)) =
e.downcast_ref::<SignalProtocolError>()
{
log::warn!("No sender key for status broadcast, forcing distribution.");
if let Err(e) = self
.persistence_manager
.clear_sender_key_devices(&to_str)
.await
{
log::warn!(
"Failed to clear status SKDM recipients for {}: {:?}",
to_str,
e
);
}
self.sender_key_device_cache.invalidate(&to_str).await;
let mut store_adapter_retry =
self.signal_adapter_from(device_store_arc.clone());
let mut stores_retry = store_adapter_retry.as_signal_stores();
wacore::send::prepare_group_stanza(
&*self.runtime,
&mut stores_retry,
self,
&mut group_info,
&own_jid,
&own_lid,
account_info.as_ref(),
to.clone(),
&message,
request_id.clone(),
true,
None,
None,
&extra_stanza_nodes,
)
.await?
} else {
return Err(e);
}
}
};
let stanza = self
.ensure_status_participants(prepared.node, &group_info)
.await?;
let ack = if let Some(phash) = stanza
.attrs()
.optional_string("phash")
.map(|s| s.into_owned())
{
let rx = self.register_ack_waiter(&request_id).await;
Some((rx, phash))
} else {
None
};
if let Err(e) = self.send_node(stanza).await {
if ack.is_some() {
self.response_waiters.lock().await.remove(&request_id);
}
return Err(e.into());
}
if let Some((rx, phash)) = ack {
self.spawn_phash_validation(rx, phash, to.clone(), true, request_id.clone());
}
self.update_sender_key_devices(&to_str, &prepared.skdm_devices)
.await;
for user in &prepared.stale_device_users {
self.invalidate_device_cache(user).await;
}
self.flush_signal_cache_logged("send_status_message", None)
.await;
Ok(SendResult {
message_id: request_id,
to,
})
}
/// Resolve which devices need SKDM. Returns `None` for full distribution
/// (no cache data), or `Some(devices)` listing devices that need fresh SKDM.
///
/// For LID mode, uses `group_info.phone_jid_for_lid_user` to query devices
/// via PN when available (LID usync is unreliable for own JID), then
/// converts the result back to LID. Same fallback as `prepare_group_stanza`.
async fn resolve_skdm_targets(
&self,
group_jid: &str,
group_info: &wacore::client::context::GroupInfo,
own_sending_jid: &Jid,
) -> Option<Vec<Jid>> {
use crate::sender_key_device_cache::SenderKeyDeviceMap;
// Atomic get-or-init: if another task invalidated the cache during our
// DB read, get_or_init's single-flight guarantee means the stale data
// won't be inserted — the invalidation wins and the next caller re-inits.
let pm = self.persistence_manager.clone();
let cached_map = self
.sender_key_device_cache
.get_or_init(group_jid, async {
let db_rows = pm
.get_sender_key_devices(group_jid)
.await
.unwrap_or_else(|e| {
log::warn!(
"Failed to read sender key devices for {}: {:?}",
group_jid,
e
);
vec![]
});
std::sync::Arc::new(SenderKeyDeviceMap::from_db_rows(&db_rows))
})
.await;
// No empty-cache early-exit: WA Web iterates an empty `senderKey` Map
// as `false` per participant, so the filter below must run unconditionally.
let is_lid_mode = group_info.addressing_mode == wacore::types::message::AddressingMode::Lid;
let jids_to_resolve: Vec<Jid> = group_info
.participants
.iter()
.map(|jid| {
if is_lid_mode
&& jid.is_lid()
&& let Some(pn) = group_info.phone_jid_for_lid_user(&jid.user)
{
return pn.to_non_ad();
}
jid.to_non_ad()
})
.collect();
match SendContextResolver::resolve_devices(self, &jids_to_resolve).await {
Ok(all_devices) => {
let all_devices: Vec<Jid> = if is_lid_mode {
all_devices
.into_iter()
.map(|d| group_info.phone_device_jid_to_lid(&d))
.collect()
} else {
all_devices
};
let needs_skdm: Vec<Jid> = all_devices
.into_iter()
.filter(|device| {
if device.is_hosted() {
return false;
}
if device.user == own_sending_jid.user
&& device.device == own_sending_jid.device
{
return false;
}
// O(1) lookups into pre-indexed cache
!cached_map
.device_has_key(&device.user, device.device)
.unwrap_or(false)
|| cached_map.is_user_forgotten(&device.user)
})
.collect();
if needs_skdm.is_empty() {
Some(vec![])
} else {
log::debug!(
"Found {} devices needing SKDM for {}",
needs_skdm.len(),
group_jid
);
Some(needs_skdm)
}
}
Err(e) => {
log::warn!(
"Failed to resolve devices for SKDM check in {}: {:?}",
group_jid,
e
);
None
}
}
}
/// Update sender key device tracking after a successful group/status send.
///
/// Called AFTER `send_node()` succeeds (WA Web: `markHasSenderKey` after server ACK).
/// On full distribution, clears old state and marks the provided device list.
/// On partial, marks only the specific SKDM recipients.
///
/// The `all_resolved_devices` parameter carries the exact device list resolved
/// for the stanza, avoiding a redundant `resolve_devices` call and preventing
/// the clear-then-fail race where a transient resolver failure leaves the map empty.
/// Mark devices as `has_key=true` after successful SKDM distribution.
async fn update_sender_key_devices(&self, group_jid: &str, devices: &[Jid]) {
if devices.is_empty() {
return;
}
if let Err(e) = self
.set_sender_key_status_for_devices(group_jid, devices, true, false)
.await
{
log::warn!(
"Failed to update sender key devices for {}: {:?}",
group_jid,
e
);
}
self.sender_key_device_cache.invalidate(group_jid).await;
}
/// Spawn a background task to validate phash from server ack.
/// On mismatch, invalidates sender key device cache and group info cache.
fn spawn_phash_validation(
&self,
rx: futures::channel::oneshot::Receiver<std::sync::Arc<wacore_binary::OwnedNodeRef>>,
our_phash: String,
jid: Jid,
invalidate_group_cache: bool,
message_id: String,
) {
let Some(client) = self.self_weak.get().and_then(|w| w.upgrade()) else {
return;
};
self.runtime
.spawn(Box::pin(async move {
let ack = match wacore::runtime::timeout(
&*client.runtime,
std::time::Duration::from_secs(10),
rx,
)
.await
{
Ok(Ok(node)) => node,
_ => {
// Remove leaked waiter to prevent keepalive suppression
client.response_waiters.lock().await.remove(&message_id);
return;
}
};
if let Some(server) = ack.get().get_attr("phash").map(|v| v.as_str())
&& server != our_phash
{
log::warn!(
"Phash mismatch for {jid}: ours={our_phash}, server={server}. Invalidating caches."
);
// DM phash covers both recipient + own devices
// (WA Web: syncDeviceListJob([recipient, me]))
if !jid.is_group() && !jid.is_status_broadcast() {
client.invalidate_device_cache(&jid.user).await;
if let Some(own_pn) =
&client.persistence_manager.get_device_snapshot().await.pn
{
client.invalidate_device_cache(&own_pn.user).await;
}
}
let jid_str = jid.to_string();
// Cache-only invalidation re-reads the same stale rows on
// the next send. Drop the persisted state too so the next
// send takes the full-distribution path. If the clear
// fails, fall back to deleting the bot's own sender key
// for the chat — the next send will see `!key_exists`
// and force_skdm without depending on the tracker.
if jid.is_group() || jid.is_status_broadcast() {
let cleared = client
.persistence_manager
.clear_sender_key_devices(&jid_str)
.await;
if let Err(e) = cleared {
log::warn!(
"phash mismatch: clear_sender_key_devices failed: {e} — \
deleting own sender key as fallback to force redistribution"
);
use wacore::libsignal::store::sender_key_name::SenderKeyName;
use wacore::types::jid::JidExt;
let snapshot =
client.persistence_manager.get_device_snapshot().await;
for own in snapshot.lid.iter().chain(snapshot.pn.iter()) {
let sk =
SenderKeyName::from_parts(&jid_str, own.to_protocol_address().as_str());
client.signal_cache.delete_sender_key(sk.cache_key()).await;
}
let _ = client
.flush_signal_cache_logged("phash-mismatch-fallback", None)
.await;
}
}
client.sender_key_device_cache.invalidate(&jid_str).await;
if invalidate_group_cache {
client.get_group_cache().await.invalidate(&jid).await;
}
}
}))
.detach();
}
/// Ensure the status stanza has a <participants> node listing all recipient
/// user JIDs. WhatsApp Web's `participantList` uses bare USER JIDs (not
/// device JIDs) — `<to jid="user@s.whatsapp.net"/>` — to tell the server
/// which users should receive the skmsg. The SKDM distribution list
/// (already in <participants>) uses device JIDs with <enc> children.
async fn ensure_status_participants(
&self,
stanza: wacore_binary::Node,
group_info: &wacore::client::context::GroupInfo,
) -> Result<wacore_binary::Node, anyhow::Error> {
Ok(wacore::send::ensure_status_participants(stanza, group_info))
}
/// Delete a message for everyone in the chat (revoke).
///
/// This sends a revoke protocol message that removes the message for all participants.
/// The message will show as "This message was deleted" for recipients.
///
/// # Arguments
/// * `to` - The chat JID (DM or group)
/// * `message_id` - The ID of the message to delete
/// * `revoke_type` - Use `RevokeType::Sender` to delete your own message,
/// or `RevokeType::Admin { original_sender }` to delete another user's message as group admin
pub async fn revoke_message(
&self,
to: Jid,
message_id: impl Into<String>,
revoke_type: RevokeType,
) -> Result<(), anyhow::Error> {
let message_id = message_id.into();
self.require_pn().await?;
let (from_me, participant, edit_attr) = match &revoke_type {
RevokeType::Sender => {
// For sender revoke, participant is NOT set (from_me=true identifies it)
// This matches whatsmeow's BuildMessageKey behavior
(
true,
None,
crate::types::message::EditAttribute::SenderRevoke,
)
}
RevokeType::Admin { original_sender } => {
// Admin revoke requires group context
if !to.is_group() {
return Err(anyhow!("Admin revoke is only valid for group chats"));
}
// The protocolMessageKey.participant should match the original message's key exactly
// Do NOT convert LID to PN - pass through unchanged like WhatsApp Web does
let participant_str = original_sender.to_non_ad().to_string();
log::debug!(
"Admin revoke: using participant {} for MessageKey",
participant_str
);
(
false,
Some(participant_str),
crate::types::message::EditAttribute::AdminRevoke,
)
}
};
let revoke_message = build_revoke_message(&to, from_me, message_id, participant);
// The revoke message stanza needs a NEW unique ID, not the message ID being revoked
// The message_id being revoked is already in protocolMessage.key.id
// Passing None generates a fresh stanza ID
//
// For admin revokes, force SKDM distribution to get the proper message structure
// with phash, <participants>, and <device-identity> that WhatsApp Web uses
let force_skdm = matches!(revoke_type, RevokeType::Admin { .. });
self.send_message_impl(
to,
&revoke_message,
None,
false,
force_skdm,
Some(edit_attr),
vec![],
)
.await
}
/// Pin a message in a chat for all participants.
pub async fn pin_message(
&self,
chat: Jid,
key: wa::MessageKey,
duration: PinDuration,
) -> Result<(), anyhow::Error> {
self.send_pin(
chat,
key,
wa::message::pin_in_chat_message::Type::PinForAll,
duration.as_secs(),
)
.await
}
/// Unpin a previously pinned message.
pub async fn unpin_message(&self, chat: Jid, key: wa::MessageKey) -> Result<(), anyhow::Error> {
self.send_pin(
chat,
key,
wa::message::pin_in_chat_message::Type::UnpinForAll,
0,
)
.await
}
async fn send_pin(
&self,
chat: Jid,
key: wa::MessageKey,
pin_type: wa::message::pin_in_chat_message::Type,
duration_secs: u32,
) -> Result<(), anyhow::Error> {
let message = wa::Message {
pin_in_chat_message: Some(wa::message::PinInChatMessage {
key: Some(key),
r#type: Some(pin_type as i32),
sender_timestamp_ms: Some(wacore::time::now_millis()),
}),
message_context_info: Some(wa::MessageContextInfo {
message_add_on_duration_in_secs: Some(duration_secs),
..Default::default()
}),
..Default::default()
};
self.send_message_impl(
chat,
&message,
None,
false,
false,
Some(crate::types::message::EditAttribute::PinInChat),
vec![],
)
.await
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn send_message_impl(
&self,
to: Jid,
message: &wa::Message,
request_id_override: Option<String>,
peer: bool,
force_key_distribution: bool,
edit: Option<crate::types::message::EditAttribute>,
extra_stanza_nodes: Vec<Node>,
) -> Result<(), anyhow::Error> {
// status@broadcast reactions fan out pairwise to the author's devices;
// status posts keep going through send_status_message (owns recipients).
let (to, is_status_addon) = if to.is_status_broadcast() {
let author = message
.reaction_message
.as_ref()
.and_then(|rm| rm.key.as_ref())
.and_then(|k| k.participant.as_ref())
.and_then(|p| p.parse::<Jid>().ok())
.filter(|jid| jid.is_pn() || jid.is_lid())
.ok_or_else(|| {
anyhow!(
"send_message to status@broadcast requires \
reaction_message.key.participant = status author (user JID). \
Use client.status() for posting new statuses."
)
})?;
(author, true)
} else {
(to, false)
};
// Generate request ID early (doesn't need lock)
let request_id = match request_id_override {
Some(id) => id,
None => self.generate_message_id().await,
};
// SKDM update data — only populated for group sends, deferred until after send_node().
// This matches WhatsApp Web which only calls markHasSenderKey() after server ACK.
struct SkdmUpdate {
to_str: String,
devices: Vec<Jid>,
stale_users: Vec<String>,
}
let mut skdm_update: Option<SkdmUpdate> = None;
let mut should_issue_tc_token_after_send = false;
let mut used_cached_tc_token_key: Option<String> = None;
let tc_issue_target = to.clone();
let mut dm_phash: Option<String> = None;
let stanza_to_send: wacore_binary::Node = if peer && !to.is_group() {
// Peer messages are only valid for individual users, not groups
// Resolve encryption JID and acquire lock ONLY for encryption
let encryption_jid = self.resolve_encryption_jid(&to).await;
let signal_addr = encryption_jid.to_protocol_address();
let session_mutex = self.session_lock_for(signal_addr.as_str()).await;
let _session_guard = session_mutex.lock().await;
let mut store_adapter = self.signal_adapter().await;
wacore::send::prepare_peer_stanza(
&mut store_adapter.session_store,
&mut store_adapter.identity_store,
to,
&signal_addr,
message,
request_id,
)
.await?
} else if to.is_group() {
// Group messages: no client-level lock needed. The encrypt fan-out
// inside prepare_group_stanza touches a different Signal session
// per recipient device, so concurrent group sends to the same
// chat don't race on shared state.
let mut group_info = self.groups().query_info(&to).await?;
let mut device_snapshot = self.persistence_manager.get_device_snapshot().await;
let account_info = device_snapshot.account.take();
let own_jid = device_snapshot
.pn
.take()
.ok_or(crate::client::ClientError::NotLoggedIn)?;
let own_lid = device_snapshot
.lid
.take()
.ok_or_else(|| anyhow!("LID not set, cannot send to group"))?;
// Store serialized message bytes for retry (lightweight)
self.add_recent_message(&to, &request_id, message).await;
let device_store_arc = self.persistence_manager.get_device_arc().await;
let to_str = to.to_string();
let (own_sending_jid, _) = match group_info.addressing_mode {
crate::types::message::AddressingMode::Lid => (own_lid.clone(), "lid"),
crate::types::message::AddressingMode::Pn => (own_jid.clone(), "pn"),
};
if !group_info
.participants
.iter()
.any(|participant| participant.is_same_user_as(&own_sending_jid))
{
group_info.participants.push(own_sending_jid.to_non_ad());
}
let force_skdm = {
use wacore::libsignal::store::sender_key_name::SenderKeyName;
let sender_address = own_sending_jid.to_protocol_address();
let sender_key_name = SenderKeyName::from_parts(&to_str, sender_address.as_str());
let device_guard = device_store_arc.read().await;
let record = self
.signal_cache
.get_sender_key(&sender_key_name, &*device_guard.backend)