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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
use crate::cache_config::CacheConfig;
use crate::client::Client;
use crate::pair_code::PairCodeOptions;
use crate::store::commands::DeviceCommand;
use crate::store::persistence_manager::PersistenceManager;
use crate::store::traits::Backend;
use crate::types::enc_handler::EncHandler;
use crate::types::events::{Event, EventHandler};
use crate::types::message::MessageInfo;
use anyhow::Result;
use log::{info, warn};
use std::collections::HashMap;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use thiserror::Error;
use wacore::runtime::Runtime;
use waproto::whatsapp as wa;
/// Typestate marker: a required builder field has not been provided yet.
pub struct Missing;
/// Typestate marker: a required builder field has been provided.
pub struct Provided;
#[derive(Debug, Error)]
pub enum BotBuilderError {
#[error(transparent)]
Other(#[from] anyhow::Error),
}
pub struct MessageContext {
pub message: Box<wa::Message>,
pub info: MessageInfo,
pub client: Arc<Client>,
}
impl MessageContext {
pub async fn send_message(&self, message: wa::Message) -> Result<String, anyhow::Error> {
self.client
.send_message(self.info.source.chat.clone(), message)
.await
}
/// Build a quote context for this message.
///
/// Handles:
/// - Correct stanza_id/participant (newsletters + group status)
/// - Stripping nested mentions to avoid accidental tags
/// - Preserving bot quote chains (matches WhatsApp Web)
///
/// Use this when you need manual control but want correct quoting behavior.
pub fn build_quote_context(&self) -> wa::ContextInfo {
// Use the standalone function from wacore with full message info
// This handles newsletter/group status participant resolution
wacore::proto_helpers::build_quote_context_with_info(
&self.info.id,
&self.info.source.sender,
&self.info.source.chat,
&self.message,
)
}
pub async fn edit_message(
&self,
original_message_id: impl Into<String>,
new_message: wa::Message,
) -> Result<String, anyhow::Error> {
self.client
.edit_message(
self.info.source.chat.clone(),
original_message_id,
new_message,
)
.await
}
/// Delete a message for everyone in the chat.
pub async fn revoke_message(
&self,
message_id: String,
revoke_type: crate::send::RevokeType,
) -> Result<(), anyhow::Error> {
self.client
.revoke_message(self.info.source.chat.clone(), message_id, revoke_type)
.await
}
}
type EventHandlerCallback =
Arc<dyn Fn(Event, Arc<Client>) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
struct BotEventHandler {
client: Arc<Client>,
event_handler: Option<EventHandlerCallback>,
}
impl EventHandler for BotEventHandler {
fn handle_event(&self, event: &Event) {
if let Some(handler) = &self.event_handler {
let handler_clone = handler.clone();
let event_clone = event.clone();
let client_clone = self.client.clone();
self.client
.runtime
.spawn(Box::pin(async move {
handler_clone(event_clone, client_clone).await;
}))
.detach();
}
}
}
/// Handle returned by [`Bot::run`] that can be awaited to wait for the
/// client's run loop to finish.
pub struct BotHandle {
done_rx: futures::channel::oneshot::Receiver<()>,
_abort_handle: wacore::runtime::AbortHandle,
}
impl BotHandle {
/// Abort the bot's run task.
pub fn abort(&self) {
self._abort_handle.abort();
}
}
impl std::future::Future for BotHandle {
type Output = Result<(), futures::channel::oneshot::Canceled>;
fn poll(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
Pin::new(&mut self.done_rx).poll(cx)
}
}
pub struct Bot {
client: Arc<Client>,
sync_task_receiver: Option<async_channel::Receiver<crate::sync_task::MajorSyncTask>>,
event_handler: Option<EventHandlerCallback>,
pair_code_options: Option<PairCodeOptions>,
}
impl std::fmt::Debug for Bot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Bot")
.field("client", &"<Client>")
.field("sync_task_receiver", &self.sync_task_receiver.is_some())
.field("event_handler", &self.event_handler.is_some())
.field("pair_code_options", &self.pair_code_options.is_some())
.finish()
}
}
impl Bot {
pub fn builder() -> BotBuilder<Missing, Missing, Missing, Missing> {
BotBuilder::new()
}
pub fn client(&self) -> Arc<Client> {
self.client.clone()
}
pub async fn run(&mut self) -> Result<BotHandle> {
if let Some(receiver) = self.sync_task_receiver.take() {
let worker_client = Arc::downgrade(&self.client);
self.client
.runtime
.spawn(Box::pin(async move {
while let Ok(task) = receiver.recv().await {
let Some(worker_client) = worker_client.upgrade() else {
break;
};
worker_client.process_sync_task(task).await;
}
info!("Sync worker shutting down.");
}))
.detach();
}
let handler = Arc::new(BotEventHandler {
client: self.client.clone(),
event_handler: self.event_handler.take(),
});
self.client.core.event_bus.add_handler(handler);
// If pair code options are set, spawn a task to request pair code after socket is ready
if let Some(options) = self.pair_code_options.take() {
let client_for_pair = self.client.clone();
self.client.runtime.spawn(Box::pin(async move {
// Wait for socket to be ready (before login) with 30 second timeout
if let Err(e) = client_for_pair
.wait_for_socket(std::time::Duration::from_secs(30))
.await
{
warn!(target: "Bot/PairCode", "Timeout waiting for socket: {}", e);
return;
}
// Check if already logged in (paired via QR or existing session)
if client_for_pair.is_logged_in() {
info!(target: "Bot/PairCode", "Already logged in, skipping pair code request");
return;
}
// Request pair code
match client_for_pair.pair_with_code(options).await {
Ok(code) => {
info!(target: "Bot/PairCode", "Pair code generated: {}", code);
}
Err(e) => {
warn!(target: "Bot/PairCode", "Failed to request pair code: {}", e);
}
}
})).detach();
}
let client_for_run = self.client.clone();
let (done_tx, done_rx) = futures::channel::oneshot::channel::<()>();
let abort_handle = self.client.runtime.spawn(Box::pin(async move {
client_for_run.run().await;
let _ = done_tx.send(());
}));
Ok(BotHandle {
done_rx,
_abort_handle: abort_handle,
})
}
}
/// Builder for [`Bot`] using the typestate pattern.
///
/// The four type parameters (`B`, `T`, `H`, `R`) track whether the required
/// fields (backend, transport_factory, http_client, runtime) have been
/// provided. The `build()` method is only available when all four are
/// [`Provided`], turning missing-field errors into compile-time errors.
pub struct BotBuilder<B = Missing, T = Missing, H = Missing, R = Missing> {
// Required fields (guaranteed present when B/T/H/R = Provided)
backend: Option<Arc<dyn Backend>>,
transport_factory: Option<Arc<dyn crate::transport::TransportFactory>>,
http_client: Option<Arc<dyn crate::http::HttpClient>>,
runtime: Option<Arc<dyn Runtime>>,
// Optional fields
event_handler: Option<EventHandlerCallback>,
custom_enc_handlers: HashMap<String, Arc<dyn EncHandler>>,
override_version: Option<(u32, u32, u32)>,
os_info: Option<(
Option<String>,
Option<wa::device_props::AppVersion>,
Option<wa::device_props::PlatformType>,
)>,
pair_code_options: Option<PairCodeOptions>,
skip_history_sync: bool,
initial_push_name: Option<String>,
cache_config: CacheConfig,
_marker: PhantomData<(B, T, H, R)>,
}
impl BotBuilder<Missing, Missing, Missing, Missing> {
fn new() -> Self {
Self {
backend: None,
transport_factory: None,
http_client: None,
runtime: None,
event_handler: None,
custom_enc_handlers: HashMap::new(),
override_version: None,
os_info: None,
pair_code_options: None,
skip_history_sync: false,
initial_push_name: None,
cache_config: CacheConfig::default(),
_marker: PhantomData,
}
}
}
// ── Required-field setters (each transitions one type parameter) ──────────
impl<T, H, R> BotBuilder<Missing, T, H, R> {
/// Use a backend implementation for storage.
/// This is the only way to configure storage - there are no defaults.
///
/// # Arguments
/// * `backend` - The backend implementation that provides all storage operations
///
/// # Example
/// ```rust,ignore
/// let backend = Arc::new(SqliteStore::new("whatsapp.db").await?);
/// let bot = Bot::builder()
/// .with_backend(backend)
/// .build()
/// .await?;
/// ```
pub fn with_backend(self, backend: Arc<dyn Backend>) -> BotBuilder<Provided, T, H, R> {
BotBuilder {
backend: Some(backend),
transport_factory: self.transport_factory,
http_client: self.http_client,
runtime: self.runtime,
event_handler: self.event_handler,
custom_enc_handlers: self.custom_enc_handlers,
override_version: self.override_version,
os_info: self.os_info,
pair_code_options: self.pair_code_options,
skip_history_sync: self.skip_history_sync,
initial_push_name: self.initial_push_name,
cache_config: self.cache_config,
_marker: PhantomData,
}
}
}
impl<B, H, R> BotBuilder<B, Missing, H, R> {
/// Set the transport factory for creating network connections.
/// This is required to build a bot.
///
/// # Arguments
/// * `factory` - The transport factory implementation
///
/// # Example
/// ```rust,ignore
/// use whatsapp_rust_tokio_transport::TokioWebSocketTransportFactory;
///
/// let bot = Bot::builder()
/// .with_backend(backend)
/// .with_transport_factory(TokioWebSocketTransportFactory::new())
/// .build()
/// .await?;
/// ```
pub fn with_transport_factory<F>(self, factory: F) -> BotBuilder<B, Provided, H, R>
where
F: crate::transport::TransportFactory + 'static,
{
BotBuilder {
backend: self.backend,
transport_factory: Some(Arc::new(factory)),
http_client: self.http_client,
runtime: self.runtime,
event_handler: self.event_handler,
custom_enc_handlers: self.custom_enc_handlers,
override_version: self.override_version,
os_info: self.os_info,
pair_code_options: self.pair_code_options,
skip_history_sync: self.skip_history_sync,
initial_push_name: self.initial_push_name,
cache_config: self.cache_config,
_marker: PhantomData,
}
}
}
impl<B, T, R> BotBuilder<B, T, Missing, R> {
/// Configure the HTTP client used for media operations and version fetching.
///
/// # Arguments
/// * `client` - The HTTP client implementation
///
/// # Example
/// ```rust,ignore
/// use whatsapp_rust_ureq_http_client::UreqHttpClient;
///
/// let bot = Bot::builder()
/// .with_backend(backend)
/// .with_http_client(UreqHttpClient::new())
/// .build()
/// .await?;
/// ```
pub fn with_http_client<C>(self, client: C) -> BotBuilder<B, T, Provided, R>
where
C: crate::http::HttpClient + 'static,
{
BotBuilder {
backend: self.backend,
transport_factory: self.transport_factory,
http_client: Some(Arc::new(client)),
runtime: self.runtime,
event_handler: self.event_handler,
custom_enc_handlers: self.custom_enc_handlers,
override_version: self.override_version,
os_info: self.os_info,
pair_code_options: self.pair_code_options,
skip_history_sync: self.skip_history_sync,
initial_push_name: self.initial_push_name,
cache_config: self.cache_config,
_marker: PhantomData,
}
}
}
impl<B, T, H> BotBuilder<B, T, H, Missing> {
/// Set the async runtime implementation to use.
///
/// This is required to build a bot.
pub fn with_runtime<Rt: Runtime>(self, runtime: Rt) -> BotBuilder<B, T, H, Provided> {
BotBuilder {
backend: self.backend,
transport_factory: self.transport_factory,
http_client: self.http_client,
runtime: Some(Arc::new(runtime)),
event_handler: self.event_handler,
custom_enc_handlers: self.custom_enc_handlers,
override_version: self.override_version,
os_info: self.os_info,
pair_code_options: self.pair_code_options,
skip_history_sync: self.skip_history_sync,
initial_push_name: self.initial_push_name,
cache_config: self.cache_config,
_marker: PhantomData,
}
}
}
// ── Optional-field setters (available in any state) ──────────────────────
impl<B, T, H, R> BotBuilder<B, T, H, R> {
pub fn on_event<F, Fut>(mut self, handler: F) -> Self
where
F: Fn(Event, Arc<Client>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
self.event_handler = Some(Arc::new(move |event, client| {
Box::pin(handler(event, client))
}));
self
}
/// Register a custom handler for a specific encrypted message type
///
/// # Arguments
/// * `enc_type` - The encrypted message type (e.g., "frskmsg")
/// * `handler` - The handler implementation for this type
///
/// # Returns
/// The updated BotBuilder
pub fn with_enc_handler<Eh>(mut self, enc_type: impl Into<String>, handler: Eh) -> Self
where
Eh: EncHandler + 'static,
{
self.custom_enc_handlers
.insert(enc_type.into(), Arc::new(handler));
self
}
/// Override the WhatsApp version used by the client.
///
/// By default, the client will automatically fetch the latest version from WhatsApp's servers.
/// Use this method to force a specific version instead.
///
/// # Arguments
/// * `version` - A tuple of (primary, secondary, tertiary) version numbers
///
/// # Example
/// ```rust,ignore
/// let bot = Bot::builder()
/// .with_backend(backend)
/// .with_version((2, 3000, 1027868167))
/// .build()
/// .await?;
/// ```
pub fn with_version(mut self, version: (u32, u32, u32)) -> Self {
self.override_version = Some(version);
self
}
/// Override the device properties sent to WhatsApp servers.
/// This allows customizing how your device appears on the linked devices list.
///
/// # Arguments
/// * `os_name` - Optional OS name (e.g., "macOS", "Windows", "Linux")
/// * `version` - Optional app version as AppVersion struct
/// * `platform_type` - Optional platform type that determines the device name shown
/// on the phone's linked devices list (e.g., Chrome, Firefox, Safari, Desktop)
///
/// **Important**: The `platform_type` determines what device name is shown on the phone.
/// Common values: `Chrome`, `Firefox`, `Safari`, `Edge`, `Desktop`, `Ipad`, etc.
/// If not set, defaults to `Unknown` which shows as "Unknown device".
///
/// You can pass `None` for any parameter to keep the default value.
///
/// # Example
/// ```rust,ignore
/// use waproto::whatsapp::device_props::{self, PlatformType};
///
/// // Show as "Chrome" on linked devices
/// let bot = Bot::builder()
/// .with_backend(backend)
/// .with_device_props(
/// Some("macOS".to_string()),
/// Some(device_props::AppVersion {
/// primary: Some(2),
/// secondary: Some(0),
/// tertiary: Some(0),
/// ..Default::default()
/// }),
/// Some(PlatformType::Chrome),
/// )
/// .build()
/// .await?;
///
/// // Show as "Desktop" on linked devices
/// let bot = Bot::builder()
/// .with_backend(backend)
/// .with_device_props(None, None, Some(PlatformType::Desktop))
/// .build()
/// .await?;
/// ```
pub fn with_device_props(
mut self,
os_name: Option<String>,
version: Option<wa::device_props::AppVersion>,
platform_type: Option<wa::device_props::PlatformType>,
) -> Self {
self.os_info = Some((os_name, version, platform_type));
self
}
/// Configure pair code authentication to run automatically after connecting.
///
/// When set, the pair code request will be sent automatically after establishing
/// a connection, and the pairing code will be dispatched via `Event::PairingCode`.
/// This runs concurrently with QR code pairing - whichever completes first wins.
///
/// # Arguments
/// * `options` - Configuration for pair code authentication
///
/// # Example
/// ```rust,ignore
/// use whatsapp_rust::pair_code::{PairCodeOptions, PlatformId};
///
/// let bot = Bot::builder()
/// .with_backend(backend)
/// .with_transport_factory(transport)
/// .with_http_client(http_client)
/// .with_pair_code(PairCodeOptions {
/// phone_number: "15551234567".to_string(),
/// show_push_notification: true,
/// custom_code: Some("ABCD1234".to_string()),
/// platform_id: PlatformId::Chrome,
/// platform_display: "Chrome (Linux)".to_string(),
/// })
/// .on_event(|event, client| async move {
/// match event {
/// Event::PairingCode { code, timeout } => {
/// println!("Enter this code on your phone: {}", code);
/// }
/// _ => {}
/// }
/// })
/// .build()
/// .await?;
/// ```
pub fn with_pair_code(mut self, options: PairCodeOptions) -> Self {
self.pair_code_options = Some(options);
self
}
/// Skip processing of history sync notifications from the phone.
///
/// When enabled, the client will acknowledge all incoming history sync
/// notifications (so the phone considers them delivered) but will not
/// download or process any historical data (INITIAL_BOOTSTRAP, RECENT,
/// FULL, PUSH_NAME, etc.). A debug log entry is emitted for each skipped
/// notification. This is useful for bot use cases where message history
/// is not needed.
///
/// Default: `false` (history sync is processed normally).
///
/// # Example
/// ```rust,ignore
/// let bot = Bot::builder()
/// .with_backend(backend)
/// .with_transport_factory(transport)
/// .with_http_client(http_client)
/// .skip_history_sync()
/// .build()
/// .await?;
/// ```
pub fn skip_history_sync(mut self) -> Self {
self.skip_history_sync = true;
self
}
/// Set an initial push name on the device before connecting.
///
/// This is included in the `ClientPayload` during registration, allowing the
/// mock server to deterministically assign phone numbers based on push name
/// (same push name = same phone, enabling multi-device testing).
pub fn with_push_name(mut self, name: impl Into<String>) -> Self {
self.initial_push_name = Some(name.into());
self
}
/// Configure cache TTL and capacity settings.
///
/// By default, all caches match WhatsApp Web behavior. Use this method
/// to customize cache durations for your use case.
///
/// # Example
/// ```rust,ignore
/// use whatsapp_rust::{CacheConfig, CacheEntryConfig};
///
/// // Disable TTL for group and device caches (good for bots with few groups)
/// let bot = Bot::builder()
/// .with_backend(backend)
/// .with_transport_factory(transport)
/// .with_http_client(http_client)
/// .with_cache_config(CacheConfig {
/// group_cache: CacheEntryConfig::new(None, 1_000),
/// device_cache: CacheEntryConfig::new(None, 5_000),
/// ..Default::default()
/// })
/// .build()
/// .await?;
/// ```
pub fn with_cache_config(mut self, config: CacheConfig) -> Self {
self.cache_config = config;
self
}
}
// ── build() — only available when all 4 required fields are Provided ─────
impl BotBuilder<Provided, Provided, Provided, Provided> {
pub async fn build(self) -> std::result::Result<Bot, BotBuilderError> {
// Destructure to extract required fields — typestate guarantees all are Some.
let (Some(runtime), Some(backend), Some(transport_factory), Some(http_client)) = (
self.runtime,
self.backend,
self.transport_factory,
self.http_client,
) else {
unreachable!("typestate guarantees all required fields are Provided")
};
// Note: For multi-account mode, create the backend with SqliteStore::new_for_device()
// before passing it to with_backend()
let persistence_manager = Arc::new(
PersistenceManager::new(backend)
.await
.map_err(|e| anyhow::anyhow!("Failed to create persistence manager: {}", e))?,
);
persistence_manager
.clone()
.run_background_saver(runtime.clone(), std::time::Duration::from_secs(30));
// Apply initial push name if specified (for deterministic mock server phone assignment)
if let Some(name) = self.initial_push_name {
persistence_manager
.process_command(DeviceCommand::SetPushName(name))
.await;
}
// Apply device props override if specified
if let Some((os_name, version, platform_type)) = self.os_info {
info!(
"Applying device props override: os={:?}, version={:?}, platform_type={:?}",
os_name, version, platform_type
);
persistence_manager
.process_command(DeviceCommand::SetDeviceProps(
os_name,
version,
platform_type,
))
.await;
}
info!("Creating client...");
let (client, sync_task_receiver) = Client::new_with_cache_config(
runtime,
persistence_manager.clone(),
transport_factory,
http_client,
self.override_version,
self.cache_config,
)
.await;
// Register custom enc handlers
for (enc_type, handler) in self.custom_enc_handlers {
client
.custom_enc_handlers
.write()
.await
.insert(enc_type, handler);
}
if self.skip_history_sync {
client.set_skip_history_sync(true);
}
Ok(Bot {
client,
sync_task_receiver: Some(sync_task_receiver),
event_handler: self.event_handler,
pair_code_options: self.pair_code_options,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::TokioRuntime;
use crate::http::{HttpClient, HttpRequest, HttpResponse};
use crate::store::SqliteStore;
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> {
// Return a mock response for version fetching
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_sqlite_backend() -> Arc<dyn Backend> {
let temp_db = format!(
"file:memdb_bot_{}?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>
}
async fn create_test_sqlite_backend_for_device(device_id: i32) -> Arc<dyn Backend> {
let temp_db = format!(
"file:memdb_bot_{}?mode=memory&cache=shared",
uuid::Uuid::new_v4()
);
Arc::new(
SqliteStore::new_for_device(&temp_db, device_id)
.await
.expect("Failed to create test SqliteStore"),
) as Arc<dyn Backend>
}
#[tokio::test]
async fn test_bot_builder_single_device() {
let backend = create_test_sqlite_backend().await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
let bot = Bot::builder()
.with_backend(backend)
.with_transport_factory(transport)
.with_http_client(http_client)
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot");
// Verify bot was created successfully
let _client = bot.client();
}
#[tokio::test]
async fn test_bot_builder_multi_device() {
// Create a backend configured for device ID 42
let backend = create_test_sqlite_backend_for_device(42).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");
// Verify bot was created successfully
let _client = bot.client();
}
#[tokio::test]
async fn test_bot_builder_with_custom_backend() {
// Create an in-memory backend for testing
let backend = create_test_sqlite_backend().await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
let bot = Bot::builder()
.with_backend(backend)
.with_transport_factory(transport)
.with_http_client(http_client)
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot with custom backend");
// Verify the bot was created successfully
let _client = bot.client();
}
#[tokio::test]
async fn test_bot_builder_with_custom_backend_specific_device() {
// Create a backend configured for device ID 100
let backend = create_test_sqlite_backend_for_device(100).await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
// Build a bot with the custom backend
let bot = Bot::builder()
.with_backend(backend)
.with_http_client(http_client)
.with_transport_factory(transport)
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot with custom backend for specific device");
// Verify the bot was created successfully
let _client = bot.client();
}
// NOTE: test_bot_builder_missing_backend, test_bot_builder_missing_transport,
// and test_bot_builder_missing_http_client have been removed because the
// typestate pattern now makes those cases compile-time errors instead of
// runtime errors.
#[tokio::test]
async fn test_bot_builder_with_version_override() {
let backend = create_test_sqlite_backend().await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
let bot = Bot::builder()
.with_backend(backend)
.with_transport_factory(transport)
.with_http_client(http_client)
.with_version((2, 3000, 123456789))
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot with version override");
// Verify the bot was created successfully
let client = bot.client();
// Check that the override version is stored in the client
assert_eq!(client.override_version, Some((2, 3000, 123456789)));
}
#[tokio::test]
async fn test_bot_builder_with_device_props_override() {
let backend = create_test_sqlite_backend().await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
let custom_os = "CustomOS".to_string();
let custom_version = wa::device_props::AppVersion {
primary: Some(99),
secondary: Some(88),
tertiary: Some(77),
..Default::default()
};
let bot = Bot::builder()
.with_backend(backend)
.with_transport_factory(transport)
.with_http_client(http_client)
.with_device_props(Some(custom_os.clone()), Some(custom_version), None)
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot with device props override");
let client = bot.client();
let persistence_manager = client.persistence_manager();
let device = persistence_manager.get_device_snapshot().await;
// Verify the device props were overridden
assert_eq!(device.device_props.os, Some(custom_os));
assert_eq!(device.device_props.version, Some(custom_version));
}
#[tokio::test]
async fn test_bot_builder_with_os_only_override() {
let backend = create_test_sqlite_backend().await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
let custom_os = "CustomOS".to_string();
let bot = Bot::builder()
.with_backend(backend)
.with_transport_factory(transport)
.with_http_client(http_client)
.with_device_props(Some(custom_os.clone()), None, None)
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot with OS only override");
let client = bot.client();
let persistence_manager = client.persistence_manager();
let device = persistence_manager.get_device_snapshot().await;
// Verify only OS was overridden, version should be default
assert_eq!(device.device_props.os, Some(custom_os));
// Version should be the default since we didn't override it
assert_eq!(
device.device_props.version,
Some(wacore::store::Device::default_device_props_version())
);
}
#[tokio::test]
async fn test_bot_builder_with_version_only_override() {
let backend = create_test_sqlite_backend().await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
let custom_version = wa::device_props::AppVersion {
primary: Some(99),
secondary: Some(88),
tertiary: Some(77),
..Default::default()
};
let bot = Bot::builder()
.with_backend(backend)
.with_http_client(http_client)
.with_transport_factory(transport)
.with_device_props(None, Some(custom_version), None)
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot with version only override");
let client = bot.client();
let persistence_manager = client.persistence_manager();
let device = persistence_manager.get_device_snapshot().await;
// Verify only version was overridden, OS should be default ("rust")
assert_eq!(device.device_props.version, Some(custom_version));
// OS should be the default since we didn't override it
assert_eq!(
device.device_props.os,
Some(wacore::store::Device::default_os().to_string())
);
}
#[tokio::test]
async fn test_bot_builder_with_platform_type_override() {
let backend = create_test_sqlite_backend().await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
let bot = Bot::builder()
.with_backend(backend)
.with_transport_factory(transport)
.with_http_client(http_client)
.with_device_props(None, None, Some(wa::device_props::PlatformType::Chrome))
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot with platform type override");
let client = bot.client();
let persistence_manager = client.persistence_manager();
let device = persistence_manager.get_device_snapshot().await;
// Verify platform type was set to Chrome
assert_eq!(
device.device_props.platform_type,
Some(wa::device_props::PlatformType::Chrome as i32)
);
// OS and version should remain default
assert_eq!(
device.device_props.os,
Some(wacore::store::Device::default_os().to_string())
);
assert_eq!(
device.device_props.version,
Some(wacore::store::Device::default_device_props_version())
);
}
#[tokio::test]
async fn test_bot_builder_with_full_device_props_override() {
let backend = create_test_sqlite_backend().await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
let custom_os = "macOS".to_string();
let custom_version = wa::device_props::AppVersion {
primary: Some(2),
secondary: Some(0),
tertiary: Some(0),
..Default::default()
};
let custom_platform = wa::device_props::PlatformType::Safari;
let bot = Bot::builder()
.with_backend(backend)
.with_transport_factory(transport)
.with_http_client(http_client)
.with_device_props(
Some(custom_os.clone()),
Some(custom_version),
Some(custom_platform),
)
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot with full device props override");
let client = bot.client();
let persistence_manager = client.persistence_manager();
let device = persistence_manager.get_device_snapshot().await;
// Verify all device props were overridden
assert_eq!(device.device_props.os, Some(custom_os));
assert_eq!(device.device_props.version, Some(custom_version));
assert_eq!(
device.device_props.platform_type,
Some(custom_platform as i32)
);
}
#[tokio::test]
async fn test_bot_builder_skip_history_sync() {
let backend = create_test_sqlite_backend().await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
let bot = Bot::builder()
.with_backend(backend)
.with_transport_factory(transport)
.with_http_client(http_client)
.skip_history_sync()
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot with skip_history_sync");
assert!(bot.client().skip_history_sync_enabled());
}
#[tokio::test]
async fn test_bot_builder_default_history_sync_enabled() {
let backend = create_test_sqlite_backend().await;
let transport = TokioWebSocketTransportFactory::new();
let http_client = MockHttpClient;
let bot = Bot::builder()
.with_backend(backend)
.with_transport_factory(transport)
.with_http_client(http_client)
.with_runtime(TokioRuntime)
.build()
.await
.expect("Failed to build bot");
assert!(!bot.client().skip_history_sync_enabled());
}
}