whatsapp-rust 0.5.0

Rust client for WhatsApp Web
Documentation
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
use crate::client::Client;
use log::{debug, warn};
use thiserror::Error;
use wacore::StringEnum;
use wacore::iq::tctoken::build_tc_token_node;
use wacore_binary::builder::NodeBuilder;
use wacore_binary::jid::Jid;
use wacore_binary::node::Node;

#[derive(Debug, Error)]
pub enum PresenceError {
    #[error("cannot send presence without a push name set")]
    PushNameEmpty,
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

/// Presence status for online/offline state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, StringEnum)]
pub enum PresenceStatus {
    #[str = "available"]
    Available,
    #[str = "unavailable"]
    Unavailable,
}

impl From<crate::types::presence::Presence> for PresenceStatus {
    fn from(p: crate::types::presence::Presence) -> Self {
        match p {
            crate::types::presence::Presence::Available => PresenceStatus::Available,
            crate::types::presence::Presence::Unavailable => PresenceStatus::Unavailable,
        }
    }
}

/// Feature handle for presence operations.
pub struct Presence<'a> {
    client: &'a Client,
}

impl<'a> Presence<'a> {
    pub(crate) fn new(client: &'a Client) -> Self {
        Self { client }
    }

    async fn build_subscription_node(&self, jid: &Jid) -> Node {
        let mut builder = NodeBuilder::new("presence")
            .attr("type", "subscribe")
            .attr("to", jid.clone());

        // Include tctoken if available (no t attribute, matching WhatsApp Web)
        if let Some(token) = self.client.lookup_tc_token_for_jid(jid).await {
            builder = builder.children([build_tc_token_node(&token)]);
        }

        builder.build()
    }

    fn build_unsubscription_node(&self, jid: &Jid) -> Node {
        NodeBuilder::new("presence")
            .attr("type", "unsubscribe")
            .attr("to", jid.clone())
            .build()
    }

    /// Set the presence status.
    pub async fn set(&self, status: PresenceStatus) -> Result<(), PresenceError> {
        let device_snapshot = self
            .client
            .persistence_manager()
            .get_device_snapshot()
            .await;

        debug!(
            "send_presence called with push_name: '{}'",
            device_snapshot.push_name
        );

        if device_snapshot.push_name.is_empty() {
            warn!("Cannot send presence: push_name is empty!");
            return Err(PresenceError::PushNameEmpty);
        }

        if status == PresenceStatus::Available {
            self.client.send_unified_session().await;
        }

        let presence_type = status.as_str();

        let node = NodeBuilder::new("presence")
            .attr("type", presence_type)
            .attr("name", &device_snapshot.push_name)
            .build();

        debug!(
            "Sending presence stanza: <presence type=\"{}\" name=\"{}\"/>",
            presence_type,
            node.attrs
                .get("name")
                .map(|s| s.as_str())
                .as_deref()
                .unwrap_or("")
        );

        self.client
            .send_node(node)
            .await
            .map_err(|e| PresenceError::Other(anyhow::Error::from(e)))
    }

    /// Set presence to available (online).
    pub async fn set_available(&self) -> Result<(), PresenceError> {
        self.set(PresenceStatus::Available).await
    }

    /// Set presence to unavailable (offline).
    pub async fn set_unavailable(&self) -> Result<(), PresenceError> {
        self.set(PresenceStatus::Unavailable).await
    }

    /// Subscribe to a contact's presence updates.
    ///
    /// Sends a `<presence type="subscribe">` stanza to the target JID.
    /// If a valid tctoken exists for the contact, it is included as a child node.
    ///
    /// ## Wire Format
    /// ```xml
    /// <presence type="subscribe" to="user@s.whatsapp.net">
    ///   <tctoken><!-- raw token bytes --></tctoken>
    /// </presence>
    /// ```
    pub async fn subscribe(&self, jid: &Jid) -> Result<(), anyhow::Error> {
        debug!("presence subscribe: subscribing to {}", jid);
        let node = self.build_subscription_node(jid).await;
        self.client
            .send_node(node)
            .await
            .map_err(anyhow::Error::from)?;
        self.client.track_presence_subscription(jid.clone()).await;
        Ok(())
    }

    /// Unsubscribe from a contact's presence updates.
    ///
    /// Sends a `<presence type="unsubscribe">` stanza to the target JID.
    ///
    /// ## Wire Format
    /// ```xml
    /// <presence type="unsubscribe" to="user@s.whatsapp.net"/>
    /// ```
    pub async fn unsubscribe(&self, jid: &Jid) -> Result<(), anyhow::Error> {
        debug!("presence unsubscribe: unsubscribing from {}", jid);
        let node = self.build_unsubscription_node(jid);
        self.client
            .send_node(node)
            .await
            .map_err(anyhow::Error::from)?;
        self.client.untrack_presence_subscription(jid).await;
        Ok(())
    }
}

impl Client {
    pub(crate) async fn track_presence_subscription(&self, jid: Jid) {
        self.presence_subscriptions.lock().await.insert(jid);
    }

    pub(crate) async fn untrack_presence_subscription(&self, jid: &Jid) {
        self.presence_subscriptions.lock().await.remove(jid);
    }

    pub(crate) async fn tracked_presence_subscriptions(&self) -> Vec<Jid> {
        self.presence_subscriptions
            .lock()
            .await
            .iter()
            .cloned()
            .collect()
    }

    pub(crate) async fn resubscribe_presence_subscriptions(&self, expected_generation: u64) {
        let subscribed_jids = self.tracked_presence_subscriptions().await;
        if subscribed_jids.is_empty() {
            return;
        }

        debug!(
            "Re-subscribing to {} tracked presence subscriptions",
            subscribed_jids.len()
        );

        for jid in subscribed_jids {
            if self
                .connection_generation
                .load(std::sync::atomic::Ordering::SeqCst)
                != expected_generation
            {
                debug!("Stopping presence re-subscribe: connection generation changed");
                return;
            }

            if !self.is_connected() {
                debug!("Stopping presence re-subscribe: connection closed");
                return;
            }

            // Check membership before re-subscribing — a concurrent unsubscribe()
            // call may have removed this JID while we were iterating.
            if !self.presence_subscriptions.lock().await.contains(&jid) {
                debug!("Skipping re-subscribe for {jid}: unsubscribed during iteration");
                continue;
            }

            if let Err(err) = self.presence().subscribe(&jid).await {
                warn!("Failed to re-subscribe to presence for {jid}: {err:?}");
            }
        }
    }

    /// Access presence operations.
    #[allow(clippy::wrong_self_convention)]
    pub fn presence(&self) -> Presence<'_> {
        Presence::new(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::TokioRuntime;
    use crate::bot::Bot;
    use crate::http::{HttpClient, HttpRequest, HttpResponse};
    use crate::store::SqliteStore;
    use crate::store::commands::DeviceCommand;
    use anyhow::Result;
    use std::str::FromStr;
    use std::sync::Arc;
    use wacore::store::traits::Backend;
    use whatsapp_rust_tokio_transport::TokioWebSocketTransportFactory;

    // Mock HTTP client for testing
    #[derive(Debug, Clone)]
    struct MockHttpClient;

    #[async_trait::async_trait]
    impl HttpClient for MockHttpClient {
        async fn execute(&self, _request: HttpRequest) -> Result<HttpResponse> {
            Ok(HttpResponse {
                status_code: 200,
                body: br#"self.__swData=JSON.parse(/*BTDS*/"{\"dynamic_data\":{\"SiteData\":{\"server_revision\":1026131876,\"client_revision\":1026131876}}}");"#.to_vec(),
            })
        }
    }

    async fn create_test_backend() -> Arc<dyn Backend> {
        let temp_db = format!(
            "file:memdb_presence_{}?mode=memory&cache=shared",
            uuid::Uuid::new_v4()
        );
        Arc::new(
            SqliteStore::new(&temp_db)
                .await
                .expect("Failed to create test SqliteStore"),
        ) as Arc<dyn Backend>
    }

    /// Verifies WhatsApp Web behavior: presence deferred until pushname available.
    #[tokio::test]
    async fn test_presence_rejected_when_pushname_empty() {
        let backend = create_test_backend().await;
        let transport = TokioWebSocketTransportFactory::new();

        let bot = Bot::builder()
            .with_backend(backend)
            .with_transport_factory(transport)
            .with_http_client(MockHttpClient)
            .with_runtime(TokioRuntime)
            .build()
            .await
            .expect("Failed to build bot");

        let client = bot.client();

        let snapshot = client.persistence_manager().get_device_snapshot().await;
        assert!(
            snapshot.push_name.is_empty(),
            "Pushname should be empty on fresh device"
        );

        let result = client.presence().set(PresenceStatus::Available).await;

        assert!(
            result.is_err(),
            "Presence should fail when pushname is empty"
        );
        assert!(
            matches!(result.unwrap_err(), PresenceError::PushNameEmpty),
            "Error should be PushNameEmpty"
        );
    }

    /// Simulates pushname arriving from app state sync (setting_pushName mutation).
    #[tokio::test]
    async fn test_presence_succeeds_after_pushname_set() {
        let backend = create_test_backend().await;
        let transport = TokioWebSocketTransportFactory::new();

        let bot = Bot::builder()
            .with_backend(backend)
            .with_transport_factory(transport)
            .with_http_client(MockHttpClient)
            .with_runtime(TokioRuntime)
            .build()
            .await
            .expect("Failed to build bot");

        let client = bot.client();

        client
            .persistence_manager()
            .process_command(DeviceCommand::SetPushName("Test User".to_string()))
            .await;

        let snapshot = client.persistence_manager().get_device_snapshot().await;
        assert_eq!(snapshot.push_name, "Test User");

        // Validation passes; error should be connection-related, not pushname
        let result = client.presence().set(PresenceStatus::Available).await;

        if let Err(e) = result {
            assert!(
                !matches!(e, PresenceError::PushNameEmpty),
                "Should not fail due to pushname, got: {}",
                e
            );
            assert!(
                matches!(e, PresenceError::Other(_)),
                "Expected connection error (Other), got: {}",
                e
            );
        }
    }

    /// Matches WAWebPushNameSync.js: fresh pairing -> app state sync -> presence.
    #[tokio::test]
    async fn test_pushname_presence_flow_matches_whatsapp_web() {
        let backend = create_test_backend().await;
        let transport = TokioWebSocketTransportFactory::new();

        let bot = Bot::builder()
            .with_backend(backend)
            .with_transport_factory(transport)
            .with_http_client(MockHttpClient)
            .with_runtime(TokioRuntime)
            .build()
            .await
            .expect("Failed to build bot");

        let client = bot.client();

        // Fresh device has empty pushname
        let snapshot = client.persistence_manager().get_device_snapshot().await;
        assert!(snapshot.push_name.is_empty());

        // Presence deferred when pushname empty
        let result = client.presence().set(PresenceStatus::Available).await;
        assert!(matches!(result, Err(PresenceError::PushNameEmpty)));

        // Pushname arrives via app state sync
        client
            .persistence_manager()
            .process_command(DeviceCommand::SetPushName("WhatsApp User".to_string()))
            .await;

        // Now presence validation passes
        let result = client.presence().set(PresenceStatus::Available).await;

        if let Err(e) = result {
            assert!(
                !matches!(e, PresenceError::PushNameEmpty),
                "Error should be connection-related: {}",
                e
            );
        }
    }

    #[tokio::test]
    async fn test_presence_subscription_tracking_is_deduplicated() {
        let backend = create_test_backend().await;
        let transport = TokioWebSocketTransportFactory::new();

        let bot = Bot::builder()
            .with_backend(backend)
            .with_transport_factory(transport)
            .with_http_client(MockHttpClient)
            .with_runtime(TokioRuntime)
            .build()
            .await
            .expect("Failed to build bot");

        let client = bot.client();
        let jid = Jid::from_str("1234567890@s.whatsapp.net").expect("valid jid");

        client.track_presence_subscription(jid.clone()).await;
        client.track_presence_subscription(jid.clone()).await;

        let tracked = client.tracked_presence_subscriptions().await;
        assert_eq!(tracked, vec![jid]);
    }

    #[tokio::test]
    async fn test_presence_unsubscription_removes_tracked_jid() {
        let backend = create_test_backend().await;
        let transport = TokioWebSocketTransportFactory::new();

        let bot = Bot::builder()
            .with_backend(backend)
            .with_transport_factory(transport)
            .with_http_client(MockHttpClient)
            .with_runtime(TokioRuntime)
            .build()
            .await
            .expect("Failed to build bot");

        let client = bot.client();
        let jid = Jid::from_str("1234567890@s.whatsapp.net").expect("valid jid");

        client.track_presence_subscription(jid.clone()).await;
        client.untrack_presence_subscription(&jid).await;

        assert!(
            client.tracked_presence_subscriptions().await.is_empty(),
            "unsubscribe tracking should remove the jid"
        );
    }

    #[tokio::test]
    async fn test_unsubscribe_builds_expected_presence_stanza() {
        let jid = Jid::from_str("1234567890@s.whatsapp.net").expect("valid jid");
        let backend = create_test_backend().await;
        let transport = TokioWebSocketTransportFactory::new();

        let bot = Bot::builder()
            .with_backend(backend)
            .with_transport_factory(transport)
            .with_http_client(MockHttpClient)
            .with_runtime(TokioRuntime)
            .build()
            .await
            .expect("Failed to build bot");

        let client = bot.client();
        let node = client.presence().build_unsubscription_node(&jid);

        assert_eq!(node.tag, "presence");
        assert!(node.attrs.get("type").is_some_and(|v| v == "unsubscribe"));
        assert_eq!(
            node.attrs.get("to").map(ToString::to_string),
            Some(jid.to_string())
        );
        assert!(
            node.content.is_none(),
            "unsubscribe stanza should not have children"
        );
    }
}