bark_rs 0.1.2

A feature-complete Rust client library for Bark push notification service with modular architecture
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
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
//! 异步 Bark 客户端模块
//!
//! 这个模块提供了异步的 Bark 推送客户端实现,使用 reqwest 的异步客户端。
//! 异步客户端需要在 tokio 运行时环境中使用,需要启用 `async` feature。
//!
//! # 特性
//!
//! - 基于 tokio 的异步 I/O
//! - 支持单个设备和批量推送
//! - 提供 Builder 模式的流畅 API
//! - 与同步版本完全兼容的 API
//!
//! # 示例
//!
//! ```rust,no_run
//! use bark_rs::{AsyncBarkClient, Level};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let client = AsyncBarkClient::with_device_key("https://api.day.app", "your_key");
//!
//!     let response = client
//!         .message()
//!         .title("异步测试")
//!         .body("异步消息")
//!         .level(Level::Critical)
//!         .send()
//!         .await?;
//!
//!     println!("发送成功: {}", response.message);
//!     Ok(())
//! }
//! ```
//!
//! # 注意
//!
//! 这个模块只在启用 `async` feature 时才可用。

#[cfg(feature = "async")]
use crate::{BarkError, BarkMessage, BarkMessageBuilder, BarkResponse, Result};
#[cfg(feature = "async")]
use reqwest::Client;
#[cfg(feature = "async")]
use std::collections::HashMap;

/// 异步 Bark 推送客户端
///
/// 使用 reqwest 的异步客户端实现,需要在 tokio 运行时环境中使用。
/// 支持单个设备推送和批量推送功能,与同步版本提供相同的 API。
///
/// # 创建客户端
///
/// ```rust,no_run
/// use bark_rs::AsyncBarkClient;
///
/// // 创建没有默认设备密钥的客户端
/// let client = AsyncBarkClient::new("https://api.day.app");
///
/// // 创建带有默认设备密钥的客户端
/// let client = AsyncBarkClient::with_device_key("https://api.day.app", "your_device_key");
/// ```
///
/// # 异步发送消息
///
/// ```rust,no_run
/// use bark_rs::{AsyncBarkClient, BarkMessage, Level};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = AsyncBarkClient::with_device_key("https://api.day.app", "your_key");
///
///     // 方式 1: 使用 message() 方法的 Builder 模式
///     let response = client
///         .message()
///         .title("标题")
///         .body("内容")
///         .level(Level::Active)
///         .send()
///         .await?;
///
///     // 方式 2: 先构建消息再发送
///     let message = BarkMessage::builder()
///         .title("标题")
///         .body("内容")
///         .build();
///
///     let response = client.send(&message).await?;
///     Ok(())
/// }
/// ```
#[cfg(feature = "async")]
pub struct AsyncBarkClient {
    /// 内部异步 HTTP 客户端
    client: Client,

    /// Bark 服务器的基础 URL
    pub(crate) base_url: String,

    /// 可选的默认设备密钥
    pub(crate) default_device_key: Option<String>,
}

#[cfg(feature = "async")]
impl AsyncBarkClient {
    /// 创建新的异步 Bark 客户端
    ///
    /// 创建一个没有默认设备密钥的客户端实例。发送消息时需要在消息中指定设备密钥,
    /// 或者使用 [`AsyncBarkClient::with_device_key`] 创建带默认密钥的客户端。
    ///
    /// # 参数
    ///
    /// * `base_url` - Bark 服务器的基础 URL(如 "https://api.day.app")
    ///
    /// # 示例
    ///
    /// ```rust
    /// use bark_rs::AsyncBarkClient;
    ///
    /// let client = AsyncBarkClient::new("https://api.day.app");
    /// ```
    pub fn new(base_url: &str) -> Self {
        Self {
            client: Client::new(),
            base_url: base_url.trim_end_matches('/').to_string(),
            default_device_key: None,
        }
    }

    /// 创建带有默认设备密钥的异步 Bark 客户端
    ///
    /// 创建一个具有默认设备密钥的客户端实例。如果消息中没有指定设备密钥,
    /// 将使用这里设置的默认密钥。消息中的密钥设置会覆盖默认密钥。
    ///
    /// # 参数
    ///
    /// * `base_url` - Bark 服务器的基础 URL
    /// * `device_key` - 默认的设备密钥
    ///
    /// # 示例
    ///
    /// ```rust
    /// use bark_rs::AsyncBarkClient;
    ///
    /// let client = AsyncBarkClient::with_device_key(
    ///     "https://api.day.app",
    ///     "your_device_key"
    /// );
    /// ```
    pub fn with_device_key(base_url: &str, device_key: &str) -> Self {
        Self {
            client: Client::new(),
            base_url: base_url.trim_end_matches('/').to_string(),
            default_device_key: Some(device_key.to_string()),
        }
    }

    /// 创建异步消息构建器
    ///
    /// 返回一个与此客户端关联的异步消息构建器,支持链式调用来构建和发送消息。
    ///
    /// # 返回值
    ///
    /// 返回 [`AsyncBarkMessageBuilder`] 实例
    ///
    /// # 示例
    ///
    /// ```rust,no_run
    /// use bark_rs::{AsyncBarkClient, Level};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = AsyncBarkClient::with_device_key("https://api.day.app", "key");
    ///
    ///     let response = client
    ///         .message()
    ///         .title("标题")
    ///         .body("内容")
    ///         .level(Level::Active)
    ///         .send()
    ///         .await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn message(&self) -> AsyncBarkMessageBuilder {
        AsyncBarkMessageBuilder::new(self)
    }

    /// 异步发送 Bark 推送消息
    ///
    /// 根据消息是否包含多个设备密钥自动选择单个发送或批量发送。
    /// 如果消息和客户端都没有设备密钥,将返回错误。
    ///
    /// # 参数
    ///
    /// * `message` - 要发送的消息
    ///
    /// # 返回值
    ///
    /// 成功时返回 [`BarkResponse`],失败时返回 [`BarkError`]
    ///
    /// # 错误
    ///
    /// * [`BarkError::MissingDeviceKey`] - 缺少设备密钥
    /// * [`BarkError::RequestError`] - 网络请求错误
    /// * [`BarkError::SerializationError`] - 序列化错误
    ///
    /// # 示例
    ///
    /// ```rust,no_run
    /// use bark_rs::{AsyncBarkClient, BarkMessage};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = AsyncBarkClient::with_device_key("https://api.day.app", "key");
    ///     let message = BarkMessage::builder()
    ///         .body("测试消息")
    ///         .build();
    ///
    ///     let response = client.send(&message).await?;
    ///     println!("发送成功: {}", response.message);
    ///     Ok(())
    /// }
    /// ```
    pub async fn send(&self, message: &BarkMessage) -> Result<BarkResponse> {
        if message.device_keys.is_some() {
            self.send_batch(message).await
        } else {
            self.send_single(message).await
        }
    }

    /// 获取有效的设备密钥
    ///
    /// 优先使用消息中的设备密钥,如果没有则使用客户端的默认密钥。
    /// 如果都没有,则返回错误。
    fn get_device_key(&self, message: &BarkMessage) -> Result<String> {
        if let Some(key) = &message.device_key {
            Ok(key.clone())
        } else if let Some(key) = &self.default_device_key {
            Ok(key.clone())
        } else {
            Err(BarkError::MissingDeviceKey)
        }
    }

    /// 异步发送单个设备的推送消息
    async fn send_single(&self, message: &BarkMessage) -> Result<BarkResponse> {
        let device_key = self.get_device_key(message)?;
        let url = format!("{}/push", self.base_url);

        let mut payload = self.build_json_payload(message)?;
        payload.insert(
            "device_key".to_string(),
            serde_json::Value::String(device_key),
        );

        let response = self.client.post(&url).json(&payload).send().await?;
        let bark_response: BarkResponse = response.json().await?;
        Ok(bark_response)
    }

    /// 异步发送批量推送消息(多个设备)
    async fn send_batch(&self, message: &BarkMessage) -> Result<BarkResponse> {
        let url = format!("{}/push", self.base_url);
        let payload = self.build_json_payload(message)?;

        let response = self.client.post(&url).json(&payload).send().await?;
        let bark_response: BarkResponse = response.json().await?;
        Ok(bark_response)
    }

    /// 构建发送给 Bark API 的 JSON 负载
    ///
    /// 将 BarkMessage 转换为 Bark API 期望的 JSON 格式
    fn build_json_payload(
        &self,
        message: &BarkMessage,
    ) -> Result<HashMap<String, serde_json::Value>> {
        let mut payload = HashMap::new();

        payload.insert(
            "body".to_string(),
            serde_json::Value::String(message.body.clone()),
        );

        if let Some(title) = &message.title {
            payload.insert(
                "title".to_string(),
                serde_json::Value::String(title.clone()),
            );
        }

        if let Some(subtitle) = &message.subtitle {
            payload.insert(
                "subtitle".to_string(),
                serde_json::Value::String(subtitle.clone()),
            );
        }

        if let Some(device_keys) = &message.device_keys {
            payload.insert(
                "device_keys".to_string(),
                serde_json::to_value(device_keys)?,
            );
        }

        if let Some(level) = &message.level {
            payload.insert(
                "level".to_string(),
                serde_json::Value::String(level.as_str().to_string()),
            );
        }

        if let Some(volume) = message.volume {
            if volume <= 10 {
                payload.insert(
                    "volume".to_string(),
                    serde_json::Value::Number(volume.into()),
                );
            }
        }

        if let Some(badge) = message.badge {
            payload.insert("badge".to_string(), serde_json::Value::Number(badge.into()));
        }

        if let Some(call) = message.call {
            payload.insert(
                "call".to_string(),
                serde_json::Value::String(if call { "1" } else { "0" }.to_string()),
            );
        }

        if let Some(auto_copy) = message.auto_copy {
            payload.insert(
                "autoCopy".to_string(),
                serde_json::Value::String(if auto_copy { "1" } else { "0" }.to_string()),
            );
        }

        if let Some(copy) = &message.copy {
            payload.insert("copy".to_string(), serde_json::Value::String(copy.clone()));
        }

        if let Some(sound) = &message.sound {
            payload.insert(
                "sound".to_string(),
                serde_json::Value::String(sound.clone()),
            );
        }

        if let Some(icon) = &message.icon {
            payload.insert("icon".to_string(), serde_json::Value::String(icon.clone()));
        }

        if let Some(group) = &message.group {
            payload.insert(
                "group".to_string(),
                serde_json::Value::String(group.clone()),
            );
        }

        if let Some(ciphertext) = &message.ciphertext {
            payload.insert(
                "ciphertext".to_string(),
                serde_json::Value::String(ciphertext.clone()),
            );
        }

        if let Some(is_archive) = message.is_archive {
            payload.insert(
                "isArchive".to_string(),
                serde_json::Value::String(if is_archive { "1" } else { "0" }.to_string()),
            );
        }

        if let Some(url) = &message.url {
            payload.insert("url".to_string(), serde_json::Value::String(url.clone()));
        }

        if let Some(action) = &message.action {
            payload.insert(
                "action".to_string(),
                serde_json::Value::String(action.clone()),
            );
        }

        if let Some(id) = &message.id {
            payload.insert("id".to_string(), serde_json::Value::String(id.clone()));
        }

        if let Some(delete) = message.delete {
            payload.insert(
                "delete".to_string(),
                serde_json::Value::String(if delete { "1" } else { "0" }.to_string()),
            );
        }

        Ok(payload)
    }
}

/// 异步 Bark 消息构建器
///
/// 与 [`AsyncBarkClient`] 关联的异步消息构建器,提供流畅的 API 来构建和直接发送消息。
/// 它包装了通用的 [`BarkMessageBuilder`] 并添加了异步的 [`send()`](Self::send) 方法。
///
/// # 特性
///
/// - 支持所有 [`BarkMessageBuilder`] 的方法
/// - 提供异步的 [`send()`](Self::send) 方法直接发送消息
/// - 支持 [`build()`](Self::build) 方法构建消息对象
///
/// # 示例
///
/// ```rust,no_run
/// use bark_rs::{AsyncBarkClient, Level};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = AsyncBarkClient::with_device_key("https://api.day.app", "key");
///
///     // 构建并发送
///     let response = client
///         .message()
///         .title("标题")
///         .body("内容")
///         .level(Level::Active)
///         .send()
///         .await?;
///
///     // 或者只构建
///     let message = client
///         .message()
///         .body("内容")
///         .build();
///     Ok(())
/// }
/// ```
#[cfg(feature = "async")]
pub struct AsyncBarkMessageBuilder<'a> {
    /// 关联的异步客户端
    client: &'a AsyncBarkClient,
    /// 内部的消息构建器
    builder: BarkMessageBuilder,
}

#[cfg(feature = "async")]
impl<'a> AsyncBarkMessageBuilder<'a> {
    /// 创建新的异步消息构建器实例
    fn new(client: &'a AsyncBarkClient) -> Self {
        Self {
            client,
            builder: BarkMessageBuilder::new(),
        }
    }

    /// 设置推送内容(必需)
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::body`]。
    pub fn body(mut self, body: &str) -> Self {
        self.builder = self.builder.body(body);
        self
    }

    /// 设置推送标题
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::title`]。
    pub fn title(mut self, title: &str) -> Self {
        self.builder = self.builder.title(title);
        self
    }

    /// 设置推送副标题
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::subtitle`]。
    pub fn subtitle(mut self, subtitle: &str) -> Self {
        self.builder = self.builder.subtitle(subtitle);
        self
    }

    /// 设置单个设备密钥
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::device_key`]。
    pub fn device_key(mut self, device_key: &str) -> Self {
        self.builder = self.builder.device_key(device_key);
        self
    }

    /// 设置多个设备密钥(批量推送)
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::device_keys`]。
    pub fn device_keys(mut self, device_keys: Vec<String>) -> Self {
        self.builder = self.builder.device_keys(device_keys);
        self
    }

    /// 设置推送级别
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::level`]。
    pub fn level(mut self, level: crate::Level) -> Self {
        self.builder = self.builder.level(level);
        self
    }

    /// 设置铃声音量 (1-10)
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::volume`]。
    pub fn volume(mut self, volume: u8) -> Self {
        self.builder = self.builder.volume(volume);
        self
    }

    /// 设置应用角标数字
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::badge`]。
    pub fn badge(mut self, badge: u32) -> Self {
        self.builder = self.builder.badge(badge);
        self
    }

    /// 设置是否重复播放铃声
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::call`]。
    pub fn call(mut self, call: bool) -> Self {
        self.builder = self.builder.call(call);
        self
    }

    /// 设置是否自动复制推送内容
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::auto_copy`]。
    pub fn auto_copy(mut self, auto_copy: bool) -> Self {
        self.builder = self.builder.auto_copy(auto_copy);
        self
    }

    /// 设置自定义复制内容
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::copy`]。
    pub fn copy(mut self, copy: &str) -> Self {
        self.builder = self.builder.copy(copy);
        self
    }

    /// 设置铃声名称
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::sound`]。
    pub fn sound(mut self, sound: &str) -> Self {
        self.builder = self.builder.sound(sound);
        self
    }

    /// 设置自定义图标
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::icon`]。
    pub fn icon(mut self, icon: &str) -> Self {
        self.builder = self.builder.icon(icon);
        self
    }

    /// 设置消息分组
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::group`]。
    pub fn group(mut self, group: &str) -> Self {
        self.builder = self.builder.group(group);
        self
    }

    /// 设置加密文本
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::ciphertext`]。
    pub fn ciphertext(mut self, ciphertext: &str) -> Self {
        self.builder = self.builder.ciphertext(ciphertext);
        self
    }

    /// 设置是否保存到历史
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::is_archive`]。
    pub fn is_archive(mut self, is_archive: bool) -> Self {
        self.builder = self.builder.is_archive(is_archive);
        self
    }

    /// 设置点击跳转 URL
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::url`]。
    pub fn url(mut self, url: &str) -> Self {
        self.builder = self.builder.url(url);
        self
    }

    /// 设置动作类型
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::action`]。
    pub fn action(mut self, action: &str) -> Self {
        self.builder = self.builder.action(action);
        self
    }

    /// 设置消息唯一标识
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::id`]。
    pub fn id(mut self, id: &str) -> Self {
        self.builder = self.builder.id(id);
        self
    }

    /// 设置是否删除消息
    ///
    /// 详细说明请参见 [`BarkMessageBuilder::delete`]。
    pub fn delete(mut self, delete: bool) -> Self {
        self.builder = self.builder.delete(delete);
        self
    }

    /// 构建并立即异步发送消息
    ///
    /// 这是一个便捷方法,相当于先调用 [`build()`](Self::build) 再调用 [`AsyncBarkClient::send`]。
    ///
    /// # 返回值
    ///
    /// 成功时返回 [`BarkResponse`],失败时返回 [`BarkError`]
    ///
    /// # 错误
    ///
    /// 可能返回的错误类型与 [`AsyncBarkClient::send`] 相同。
    ///
    /// # 示例
    ///
    /// ```rust,no_run
    /// use bark_rs::{AsyncBarkClient, Level};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = AsyncBarkClient::with_device_key("https://api.day.app", "key");
    ///
    ///     let response = client
    ///         .message()
    ///         .body("测试消息")
    ///         .title("测试")
    ///         .level(Level::Active)
    ///         .send()
    ///         .await?;
    ///
    ///     println!("发送成功: {}", response.message);
    ///     Ok(())
    /// }
    /// ```
    pub async fn send(self) -> Result<BarkResponse> {
        let message = self.builder.build();
        self.client.send(&message).await
    }

    /// 构建消息对象而不发送
    ///
    /// 如果您需要先构建消息再由其他客户端发送,或者需要复用消息,可以使用这个方法。
    ///
    /// # 返回值
    ///
    /// 返回构建完成的 [`BarkMessage`]
    ///
    /// # 示例
    ///
    /// ```rust
    /// use bark_rs::AsyncBarkClient;
    ///
    /// let client = AsyncBarkClient::new("https://api.day.app");
    ///
    /// let message = client
    ///     .message()
    ///     .body("消息内容")
    ///     .title("消息标题")
    ///     .build();
    ///
    /// // 现在可以用不同的客户端发送这个消息
    /// ```
    pub fn build(self) -> BarkMessage {
        self.builder.build()
    }
}