Skip to main content

whatsapp_rust/handlers/
basic.rs

1use super::traits::StanzaHandler;
2use crate::client::Client;
3use async_trait::async_trait;
4use std::sync::Arc;
5use wacore_binary::node::Node;
6
7/// Handler for `<success>` stanzas.
8///
9/// Processes successful authentication/connection events.
10#[derive(Default)]
11pub struct SuccessHandler;
12
13#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
14#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
15impl StanzaHandler for SuccessHandler {
16    fn tag(&self) -> &'static str {
17        "success"
18    }
19
20    async fn handle(&self, client: Arc<Client>, node: Arc<Node>, _cancelled: &mut bool) -> bool {
21        client.handle_success(&node).await;
22        true
23    }
24}
25
26/// Handler for `<failure>` stanzas.
27///
28/// Processes connection or authentication failures.
29#[derive(Default)]
30pub struct FailureHandler;
31
32#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
33#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
34impl StanzaHandler for FailureHandler {
35    fn tag(&self) -> &'static str {
36        "failure"
37    }
38
39    async fn handle(&self, client: Arc<Client>, node: Arc<Node>, _cancelled: &mut bool) -> bool {
40        client.handle_connect_failure(&node).await;
41        true
42    }
43}
44
45/// Handler for `<stream:error>` stanzas.
46///
47/// Processes stream-level errors that may require connection reset.
48#[derive(Default)]
49pub struct StreamErrorHandler;
50
51#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
52#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
53impl StanzaHandler for StreamErrorHandler {
54    fn tag(&self) -> &'static str {
55        "stream:error"
56    }
57
58    async fn handle(&self, client: Arc<Client>, node: Arc<Node>, _cancelled: &mut bool) -> bool {
59        client.handle_stream_error(&node).await;
60        true
61    }
62}
63
64/// Handler for `<ack>` stanzas.
65///
66/// Processes acknowledgment messages.
67#[derive(Default)]
68pub struct AckHandler;
69
70#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
71#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
72impl StanzaHandler for AckHandler {
73    fn tag(&self) -> &'static str {
74        "ack"
75    }
76
77    async fn handle(&self, client: Arc<Client>, node: Arc<Node>, _cancelled: &mut bool) -> bool {
78        // Delegate to the client to check if any task is waiting for this ack.
79        // The client will resolve pending response waiters if the ID matches.
80        // Try to unwrap Arc or clone Node if there are other references
81        let owned_node = Arc::try_unwrap(node).unwrap_or_else(|arc| (*arc).clone());
82        client.handle_ack_response(owned_node).await;
83        // We return `true` because this handler's purpose is to consume all <ack> stanzas.
84        true
85    }
86}