fishpi-sdk 0.1.5

A Rust SDK for interacting with the FishPi community API
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
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
//! 聊天室 API 模块
//!
//! 这个模块提供了与聊天室相关的 API 操作,包括连接聊天室、发送消息、监听事件、获取历史消息、撤回消息、发送弹幕等功能。
//! 主要结构体是 `ChatRoom`,用于管理聊天室的 WebSocket 连接和事件监听。
//! 事件通过 `ChatRoomEventData` 枚举表示,支持多种消息类型(如普通消息、弹幕、红包等)。
//!
//! # 主要组件
//!
//! - [`ChatRoom`] - 聊天室客户端结构体,负责连接、发送消息和管理监听器。
//! - [`ChatRoomHandler`] - 聊天室消息处理器,实现 `MessageHandler` trait,处理 WebSocket 消息并发射事件。
//! - [`ChatRoomEventData`] - 聊天室事件数据枚举,包装所有消息类型(如在线用户、话题修改、普通消息等)。
//! - [`ChatRoomListener`] - 聊天室事件监听器类型别名,定义监听器函数的签名。
//! - [`ChatRoomNodeResponse`] 和 [`ChatRoomAvailableNode`] - 聊天室节点相关结构体,用于获取可用节点。
//!
//! # 方法列表
//!
//! - [`ChatRoom::new`] - 创建新的聊天室客户端实例。
//! - [`ChatRoom::get_node`] - 获取聊天室节点信息。
//! - [`ChatRoom::get_ws_url`] - 获取 WebSocket URL。
//! - [`ChatRoom::connect`] - 连接聊天室。
//! - [`ChatRoom::reconnect`] - 重连聊天室。
//! - [`ChatRoom::on_online`] - 监听在线用户更新事件。
//! - [`ChatRoom::on_discuss`] - 监听话题变更事件。
//! - [`ChatRoom::on_revoke`] - 监听消息撤回事件。
//! - [`ChatRoom::on_msg`] - 监听普通消息事件。
//! - [`ChatRoom::on_barrager`] - 监听弹幕消息事件。
//! - [`ChatRoom::on_redpacket`] - 监听红包消息事件。
//! - [`ChatRoom::on_redpacketstatus`] - 监听红包状态事件。
//! - [`ChatRoom::on_music`] - 监听音乐消息事件。
//! - [`ChatRoom::on_weather`] - 监听天气消息事件。
//! - [`ChatRoom::on_custom`] - 监听进出场消息事件。
//! - [`ChatRoom::off`] - 移除事件监听器。
//! - [`ChatRoom::disconnect`] - 断开连接。
//! - [`ChatRoom::send`] - 发送消息。
//! - [`ChatRoom::get_discuss`] - 获取当前话题。
//! - [`ChatRoom::set_discuss`] - 设置当前话题。
//! - [`ChatRoom::get_online_count`] - 获取在线人数。
//! - [`ChatRoom::set_api_key`] - 设置 API 密钥。
//! - [`ChatRoom::set_client_type`] - 设置客户端类型。
//! - [`ChatRoom::history`] - 查询历史消息。
//! - [`ChatRoom::get_msg_around`] - 获取指定消息附近的聊天室消息。
//! - [`ChatRoom::revoke`] - 撤回消息。
//! - [`ChatRoom::barrager`] - 发送弹幕。
//! - [`ChatRoom::barrage_cost`] - 获取弹幕花费。
//! - [`ChatRoom::mutes`] - 获取禁言成员列表。
//! - [`ChatRoom::get_raw_message`] - 获取消息原文。
//!
//! # 示例
//!
//! ```rust,no_run
//! use crate::api::chatroom::{ChatRoom, ChatRoomMsg, BarragerMsg};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let mut chatroom = ChatRoom::new("your_api_key".to_string());
//!
//!     // 监听普通消息(直接传递 ChatRoomMsg,无需 match)
//!     chatroom.on_msg(|msg: ChatRoomMsg| {
//!         println!("Received message: {}", msg.content);
//!     }).await;
//!
//!     // 监听弹幕消息
//!     chatroom.on_barrager(|barrager: BarragerMsg| {
//!         println!("Barrage: {}", barrager.content);
//!     }).await;
//!
//!     // 监听在线用户更新
//!     chatroom.on_online(|users: Vec<crate::model::chatroom::OnlineInfo>| {
//!         println!("Online users: {}", users.len());
//!     }).await;
//!
//!     // 连接聊天室
//!     chatroom.connect(false).await?;
//!
//!     // 发送消息
//!     chatroom.send("Hello, world!".to_string()).await?;
//!
//!     // 获取历史消息
//!     let history = chatroom.history(1, crate::model::chatroom::ChatContentType::Html).await?;
//!     for msg in history {
//!         println!("History: {}", msg.content);
//!     }
//!
//!     Ok(())
//! }
//! ```
//!
//! # 事件类型 [ChatRoomEventType]
//!
//! 聊天室支持以下事件类型(通过特定 `on_*` 方法监听):
//!
//! - `Online` - 在线用户更新。
//! - `DiscussChanged` - 话题修改。
//! - `Revoke` - 消息撤回。
//! - `Msg` - 普通消息。
//! - `Barrager` - 弹幕消息。
//! - `RedPacket` - 红包消息。
//! - `RedPacketStatus` - 红包状态。
//! - `Music` - 音乐消息。
//! - `Weather` - 天气消息。
//! - `Custom` - 进出场消息。
//! - `All` - 所有事件(除了自身)。

use crate::api::ws::{MessageHandler, WebSocketClient, WebSocketError};
use crate::model::MuteItem;
use crate::model::chatroom::{
    BarragerCost, BarragerMsg, ChatContentType, ChatRoomMessageMode, ChatRoomMessageType,
    ChatRoomMsg, ClientType, CustomMsg, OnlineInfo, RevokeMsg,
};
use crate::model::redpacket::RedPacketStatusMsg;
use crate::utils::get_text;
use crate::utils::{delete, error::Error, get, post};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::sync::mpsc;
use url::Url;

#[derive(Debug, Clone, serde::Deserialize)]
#[allow(non_snake_case)]
pub struct ChatRoomNodeResponse {
    pub msg: String,
    pub code: i32,
    pub data: String,
    pub apiKey: String,
    pub avaliable: Vec<ChatRoomAvailableNode>,
}

#[derive(Debug, Clone, serde::Deserialize)]
pub struct ChatRoomAvailableNode {
    pub node: String,
    pub name: String,
    pub weight: u32,
    pub online: u32,
}

/// 聊天室事件数据(包装所有消息类型)
#[derive(Debug, Clone)]
pub enum ChatRoomEventData {
    /// 在线用户
    Online(Vec<OnlineInfo>),
    /// 话题修改
    DiscussChanged(String),
    /// 消息撤回
    Revoke(String),
    /// 普通消息
    Msg(ChatRoomMsg),
    /// 弹幕消息
    Barrager(BarragerMsg),
    /// 红包消息
    RedPacket(ChatRoomMsg<Value>),
    /// 红包状态
    RedPacketStatus(RedPacketStatusMsg),
    /// 音乐消息
    Music(ChatRoomMsg<Value>),
    /// 天气消息
    Weather(ChatRoomMsg<Value>),
    /// 进出场消息
    Custom(CustomMsg),
}

/// 聊天室事件类型枚举
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ChatRoomEventType {
    /// 在线用户更新
    Online,
    /// 话题修改
    DiscussChanged,
    /// 消息撤回
    Revoke,
    /// 普通消息
    Msg,
    /// 弹幕消息
    Barrager,
    /// 红包消息
    RedPacket,
    /// 红包状态
    RedPacketStatus,
    /// 音乐消息
    Music,
    /// 天气消息
    Weather,
    /// 进出场消息
    Custom,
    /// 所有事件(除了自身)
    All,
}

/// 聊天室事件监听器类型
pub type ChatRoomListener = Arc<dyn Fn(ChatRoomEventData) + Send + Sync + 'static>;

/// 聊天室消息处理器
pub struct ChatRoomHandler {
    emitter: Arc<Mutex<HashMap<ChatRoomEventType, Vec<ChatRoomListener>>>>,
}

impl Default for ChatRoomHandler {
    fn default() -> Self {
        Self {
            emitter: Arc::new(Mutex::new(HashMap::new())),
        }
    }
}

impl ChatRoomHandler {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn get_emitter(&self) -> Arc<Mutex<HashMap<ChatRoomEventType, Vec<ChatRoomListener>>>> {
        self.emitter.clone()
    }

    /// 发射事件
    async fn emit_event(
        emitter: &Arc<Mutex<HashMap<ChatRoomEventType, Vec<ChatRoomListener>>>>,
        event_type: ChatRoomEventType,
        event: ChatRoomEventData,
    ) {
        let listeners: Vec<ChatRoomListener> = {
            let guard = emitter.lock().await;
            guard.get(&event_type).cloned().unwrap_or_default()
        };
        for listener in listeners {
            let event = event.clone();
            tokio::spawn(async move { listener(event) });
        }
        // 处理 "all" 事件
        if event_type != ChatRoomEventType::All {
            let all_listeners: Vec<ChatRoomListener> = {
                let guard = emitter.lock().await;
                guard
                    .get(&ChatRoomEventType::All)
                    .cloned()
                    .unwrap_or_default()
            };
            for listener in all_listeners {
                let event = event.clone();
                tokio::spawn(async move { listener(event) });
            }
        }
    }
}

impl MessageHandler for ChatRoomHandler {
    fn handle_message(&self, text: String) {
        if let Ok(json) = serde_json::from_str::<Value>(&text) {
            let emitter = self.get_emitter();
            tokio::spawn(async move {
                match parse_chatroom_message(&json) {
                    Ok((event_type, event)) => {
                        Self::emit_event(&emitter, event_type, event).await;
                    }
                    Err(e) => {
                        eprintln!("解析聊天室消息失败: {}", e);
                    }
                }
            });
        }
    }
}

/// 解析聊天室消息,返回 (事件类型, 事件数据)
#[allow(non_snake_case)]
fn parse_chatroom_message(json: &Value) -> Result<(ChatRoomEventType, ChatRoomEventData), Error> {
    let type_str = json["type"]
        .as_str()
        .ok_or_else(|| Error::Parse("Missing type in message".to_string()))?;
    let r#type = ChatRoomMessageType::from_str(type_str)
        .map_err(|_| Error::Parse(format!("Unknown message type: {}", type_str)))?;

    match r#type {
        ChatRoomMessageType::Online => {
            if let Some(users) = json["users"].as_array() {
                let online_info: Vec<OnlineInfo> = users
                    .iter()
                    .filter_map(|u| {
                        Some(OnlineInfo {
                            homePage: u["homePage"].as_str()?.to_string(),
                            userAvatarURL: u["userAvatarURL"].as_str()?.to_string(),
                            userName: u["userName"].as_str()?.to_string(),
                        })
                    })
                    .collect();
                Ok((
                    ChatRoomEventType::Online,
                    ChatRoomEventData::Online(online_info),
                ))
            } else {
                Err(Error::Parse("Missing users in online message".to_string()))
            }
        }
        ChatRoomMessageType::DiscussChanged => {
            let new_discuss = json["newDiscuss"]
                .as_str()
                .ok_or_else(|| Error::Parse("Missing newDiscuss".to_string()))?
                .to_string();
            Ok((
                ChatRoomEventType::DiscussChanged,
                ChatRoomEventData::DiscussChanged(new_discuss),
            ))
        }
        ChatRoomMessageType::Revoke => {
            let o_id = json["oId"]
                .as_str()
                .ok_or_else(|| Error::Parse("Missing oId in revoke".to_string()))?
                .to_string();
            Ok((ChatRoomEventType::Revoke, ChatRoomEventData::Revoke(o_id)))
        }
        ChatRoomMessageType::Msg => {
            let chat_msg = ChatRoomMsg::from_value(json)?;

            // 检查 content 是否为 music 或 weather
            if let Value::Object(ref obj) = chat_msg.content {
                if obj.get("msgType").and_then(|v| v.as_str()) == Some("music") {
                    Ok((ChatRoomEventType::Music, ChatRoomEventData::Music(chat_msg)))
                } else if obj.get("msgType").and_then(|v| v.as_str()) == Some("weather") {
                    Ok((
                        ChatRoomEventType::Weather,
                        ChatRoomEventData::Weather(chat_msg),
                    ))
                } else {
                    Ok((ChatRoomEventType::Msg, ChatRoomEventData::Msg(chat_msg)))
                }
            } else {
                Ok((ChatRoomEventType::Msg, ChatRoomEventData::Msg(chat_msg)))
            }
        }
        ChatRoomMessageType::RedPacket => {
            let redpacket_msg = ChatRoomMsg::from_value(json)?;
            Ok((
                ChatRoomEventType::RedPacket,
                ChatRoomEventData::RedPacket(redpacket_msg),
            ))
        }
        ChatRoomMessageType::Barrager => {
            let barrager = BarragerMsg::from_value(json)?;
            Ok((
                ChatRoomEventType::Barrager,
                ChatRoomEventData::Barrager(barrager),
            ))
        }
        ChatRoomMessageType::Custom => {
            let message = json["message"]
                .as_str()
                .ok_or_else(|| Error::Parse("Missing message in custom".to_string()))?
                .to_string();
            Ok((
                ChatRoomEventType::Custom,
                ChatRoomEventData::Custom(CustomMsg { message }),
            ))
        }
        ChatRoomMessageType::RedPacketStatus => {
            let redpacket_status = RedPacketStatusMsg::from_value(json)?;
            Ok((
                ChatRoomEventType::RedPacketStatus,
                ChatRoomEventData::RedPacketStatus(redpacket_status),
            ))
        }
    }
}

impl Clone for ChatRoomHandler {
    fn clone(&self) -> Self {
        Self {
            emitter: self.emitter.clone(),
        }
    }
}

/// 聊天室客户端
pub struct ChatRoom {
    ws: Option<WebSocketClient>,
    handler: ChatRoomHandler,
    sender: Option<mpsc::UnboundedSender<String>>,
    api_key: String,
    discuss: Arc<Mutex<String>>,
    onlines: Arc<Mutex<Vec<OnlineInfo>>>,
    client: ClientType,
    version: String,
}

impl ChatRoom {
    pub fn new(api_key: String) -> Self {
        Self {
            ws: None,
            handler: ChatRoomHandler::new(),
            sender: None,
            api_key,
            discuss: Arc::new(Mutex::new(String::new())),
            onlines: Arc::new(Mutex::new(Vec::new())),
            client: ClientType::Rust,
            version: env!("CARGO_PKG_VERSION").to_string(),
        }
    }

    pub async fn get_node(&self) -> Result<ChatRoomNodeResponse, WebSocketError> {
        let url = format!("chat-room/node/get?apiKey={}", self.api_key);

        let response: Value = get(&url)
            .await
            .map_err(|e| WebSocketError::Other(format!("请求失败:{}", e)))?;

        let code = response["code"].as_i64().unwrap_or(-1) as i32;
        if code != 0 {
            let msg = response["msg"].as_str().unwrap_or("未知错误");
            return Err(WebSocketError::Other(format!("获取节点失败:{}", msg)));
        }

        let node_response: ChatRoomNodeResponse = serde_json::from_value(response)
            .map_err(|e| WebSocketError::Other(format!("解析节点信息失败:{}", e)))?;
        Ok(node_response)
    }

    /// 获取 WebSocket URL
    pub async fn get_ws_url(&self) -> Result<String, WebSocketError> {
        match self.get_node().await {
            Ok(node_response) => {
                let mut parsed = Url::parse(&node_response.data)
                    .map_err(|e| WebSocketError::Other(format!("URL parse error: {}", e)))?;
                if parsed.path() == "" {
                    parsed.set_path("/");
                }
                Ok(parsed.to_string())
            }
            Err(_) => Ok(format!(
                "wss://fishpi.cn/chat-room-channel?apiKey={}",
                self.api_key
            )),
        }
    }

    /// 连接聊天室
    ///
    /// # 参数
    /// * `reload` - 是否重新连接
    pub async fn connect(&mut self, reload: bool) -> Result<(), WebSocketError> {
        if self.ws.is_some() && !reload {
            return Ok(());
        }

        let url = self.get_ws_url().await?;

        // 创建发送通道
        let (tx_send, _) = mpsc::unbounded_channel::<String>();
        self.sender = Some(tx_send);

        // 连接 WebSocket
        let ws = WebSocketClient::connect(&url, self.handler.clone()).await?;

        self.ws = Some(ws);
        Ok(())
    }

    /// 重连
    pub async fn reconnect(&mut self) -> Result<(), WebSocketError> {
        self.connect(true).await
    }

    /// 监听在线用户更新事件
    pub async fn on_online<F>(&self, listener: F)
    where
        F: Fn(Vec<OnlineInfo>) + Send + Sync + 'static,
    {
        let onlines = Arc::clone(&self.onlines);
        let wrapped_listener: ChatRoomListener = Arc::new(move |event: ChatRoomEventData| {
            if let ChatRoomEventData::Online(users) = event {
                // 更新状态
                if let Ok(mut onlines_guard) = onlines.try_lock() {
                    *onlines_guard = users.clone();
                }
                listener(users);
            }
        });
        let mut emitter = self.handler.emitter.lock().await;
        emitter
            .entry(ChatRoomEventType::Online)
            .or_insert_with(Vec::new)
            .push(wrapped_listener);
    }

    /// 监听话题变更事件
    pub async fn on_discuss<F>(&self, listener: F)
    where
        F: Fn(String) + Send + Sync + 'static,
    {
        let discuss = Arc::clone(&self.discuss);
        let wrapped_listener: ChatRoomListener = Arc::new(move |event: ChatRoomEventData| {
            if let ChatRoomEventData::DiscussChanged(topic) = event {
                // 更新状态
                if let Ok(mut discuss_guard) = discuss.try_lock() {
                    *discuss_guard = topic.clone();
                }
                listener(topic);
            }
        });
        let mut emitter = self.handler.emitter.lock().await;
        emitter
            .entry(ChatRoomEventType::DiscussChanged)
            .or_insert_with(Vec::new)
            .push(wrapped_listener);
    }

    /// 监听消息撤回事件
    pub async fn on_revoke<F>(&self, listener: F)
    where
        F: Fn(String) + Send + Sync + 'static,
    {
        self.add_listener(
            ChatRoomEventType::Revoke,
            move |event: ChatRoomEventData| {
                if let ChatRoomEventData::Revoke(msg_id) = event {
                    listener(msg_id);
                }
            },
        )
        .await;
    }

    /// 监听普通消息事件
    pub async fn on_msg<F>(&self, listener: F)
    where
        F: Fn(ChatRoomMsg) + Send + Sync + 'static,
    {
        self.add_listener(ChatRoomEventType::Msg, move |event: ChatRoomEventData| {
            if let ChatRoomEventData::Msg(msg) = event {
                listener(msg);
            }
        })
        .await;
    }

    /// 监听弹幕消息事件
    pub async fn on_barrager<F>(&self, listener: F)
    where
        F: Fn(BarragerMsg) + Send + Sync + 'static,
    {
        self.add_listener(
            ChatRoomEventType::Barrager,
            move |event: ChatRoomEventData| {
                if let ChatRoomEventData::Barrager(barrager) = event {
                    listener(barrager);
                }
            },
        )
        .await;
    }

    /// 监听红包消息事件
    pub async fn on_redpacket<F>(&self, listener: F)
    where
        F: Fn(ChatRoomMsg<Value>) + Send + Sync + 'static,
    {
        self.add_listener(
            ChatRoomEventType::RedPacket,
            move |event: ChatRoomEventData| {
                if let ChatRoomEventData::RedPacket(red_packet) = event {
                    listener(red_packet);
                }
            },
        )
        .await;
    }

    /// 监听红包状态事件
    pub async fn on_redpacketstatus<F>(&self, listener: F)
    where
        F: Fn(RedPacketStatusMsg) + Send + Sync + 'static,
    {
        self.add_listener(
            ChatRoomEventType::RedPacketStatus,
            move |event: ChatRoomEventData| {
                if let ChatRoomEventData::RedPacketStatus(status) = event {
                    listener(status);
                }
            },
        )
        .await;
    }

    /// 监听音乐消息事件
    pub async fn on_music<F>(&self, listener: F)
    where
        F: Fn(ChatRoomMsg<Value>) + Send + Sync + 'static,
    {
        self.add_listener(ChatRoomEventType::Music, move |event: ChatRoomEventData| {
            if let ChatRoomEventData::Music(music) = event {
                listener(music);
            }
        })
        .await;
    }

    /// 监听天气消息事件
    pub async fn on_weather<F>(&self, listener: F)
    where
        F: Fn(ChatRoomMsg<Value>) + Send + Sync + 'static,
    {
        self.add_listener(
            ChatRoomEventType::Weather,
            move |event: ChatRoomEventData| {
                if let ChatRoomEventData::Weather(weather) = event {
                    listener(weather);
                }
            },
        )
        .await;
    }

    /// 监听进出场消息事件
    pub async fn on_custom<F>(&self, listener: F)
    where
        F: Fn(CustomMsg) + Send + Sync + 'static,
    {
        self.add_listener(
            ChatRoomEventType::Custom,
            move |event: ChatRoomEventData| {
                if let ChatRoomEventData::Custom(custom) = event {
                    listener(custom);
                }
            },
        )
        .await;
    }

    pub async fn on_all<F>(&self, listener: F)
    where
        F: Fn(ChatRoomEventData) + Send + Sync + 'static,
    {
        self.add_listener(ChatRoomEventType::All, listener).await;
    }

    async fn add_listener<F>(&self, event: ChatRoomEventType, listener: F)
    where
        F: Fn(ChatRoomEventData) + Send + Sync + 'static,
    {
        let wrapped_listener: ChatRoomListener = Arc::new(listener);
        let mut emitter = self.handler.emitter.lock().await;
        emitter
            .entry(event)
            .or_insert_with(Vec::new)
            .push(wrapped_listener);
    }

    /// 移除监听
    pub async fn off(&self, event: ChatRoomEventType) {
        let mut emitter = self.handler.emitter.lock().await;
        emitter.remove(&event);
    }

    /// 断开连接
    pub fn disconnect(&mut self) {
        if let Some(ws) = &self.ws {
            ws.disconnect();
        }
        self.ws = None;
        self.sender = None;
    }

    /// 发送消息
    ///
    /// # 参数
    /// * `msg` - 消息内容
    pub async fn send(&self, msg: String) -> Result<(), Error> {
        let client = format!("{}/{}", self.client.as_str(), self.version);

        let data = json!({
            "content": msg,
            "client": client,
            "apiKey": self.api_key,
        });

        let resp = post("chat-room/send", Some(data)).await?;

        if let Some(code) = resp["code"].as_i64()
            && code != 0
        {
            return Err(Error::Api(
                resp["msg"].as_str().unwrap_or("发送失败").to_string(),
            ));
        }

        Ok(())
    }

    /// 当前话题
    pub async fn get_discuss(&self) -> String {
        let discuss_guard = self.discuss.lock().await;
        discuss_guard.clone()
    }

    /// 设置当前话题
    ///
    /// # 参数
    /// * `discuss` - 新话题
    pub async fn set_discuss(&self, discuss: String) {
        self.send(format!("[setdiscuss]{}[/setdiscuss]", discuss))
            .await
            .ok();
    }

    /// 当前在线人数
    pub async fn get_online_count(&self) -> usize {
        let onlines_guard = self.onlines.lock().await;
        onlines_guard.len()
    }

    /// 重新设置apiKey
    pub fn set_api_key(&mut self, api_key: String) {
        self.api_key = api_key;
    }

    /// 设置客户端类型
    ///
    /// #### 参数
    /// * `client` - 客户端类型 [ClientType]
    /// * `version` - 版本号
    pub fn set_client_type(&mut self, client: ClientType, version: Option<String>) {
        self.client = client;
        self.version = version.unwrap_or_else(|| "last".to_string());
    }

    /// 查询聊天室历史消息
    ///
    /// #参数
    /// `page` - 页码
    /// `type_` - 内容类型 [ChatContentType]
    pub async fn history(
        &self,
        page: u32,
        type_: ChatContentType,
    ) -> Result<Vec<ChatRoomMsg>, Error> {
        let resp = get(&format!(
            "chat-room/more?page={}&type={}&apiKey={}",
            page,
            type_.as_str(),
            self.api_key
        ))
        .await?;

        if let Some(code) = resp["code"].as_i64()
            && code != 0
        {
            return Err(Error::Api(
                resp["msg"].as_str().unwrap_or("Api error").to_string(),
            ));
        }

        let messages: Vec<ChatRoomMsg> = resp["data"]
            .as_array()
            .ok_or_else(|| Error::Api("Data is not an array".to_string()))?
            .iter()
            .map(ChatRoomMsg::from_value)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(messages)
    }

    /// 获取指定消息附近的聊天室消息
    ///
    /// # 参数
    /// * `o_id` - 消息 Id
    /// * `mode` - 获取模式,context 上下文模式,after 之后模式 [ChatRoomMessageMode]
    /// * `size` - 获取消息数量,默认 25,最大 100
    /// * `type_` - 获取消息类型,默认 HTML [ChatContentType]
    /// * 返回 [ChatRoomMsg] 消息列表
    pub async fn get_msg_around(
        &self,
        o_id: &str,
        mode: ChatRoomMessageMode,
        size: u32,
        type_: ChatContentType,
    ) -> Result<Vec<ChatRoomMsg>, Error> {
        let resp = get(&format!(
            "chat-room/getMessage?oId={}&mode={}&size={}&type={}&apiKey={}",
            o_id, mode, size, type_, self.api_key
        ))
        .await?;

        if let Some(code) = resp["code"].as_i64()
            && code != 0
        {
            return Err(Error::Api(
                resp["msg"].as_str().unwrap_or("Api error").to_string(),
            ));
        }

        let messages: Vec<ChatRoomMsg> = resp["data"]
            .as_array()
            .ok_or_else(|| Error::Api("Data is not an array".to_string()))?
            .iter()
            .map(ChatRoomMsg::from_value)
            .collect::<Result<Vec<_>, _>>()?;

        Ok(messages)
    }

    /// 撤回消息
    ///
    /// #### 参数
    /// * `o_id` - 消息 ID
    /// #### 返回 [RevokeMsg]
    pub async fn revoke(&self, o_id: &str) -> Result<RevokeMsg, Error> {
        let data = json!({
            "apiKey": self.api_key,
        });
        let resp = delete(&format!("chat-room/revoke/{}", o_id), Some(data)).await?;

        if let Some(code) = resp["code"].as_i64()
            && code != 0
        {
            return Err(Error::Api(
                resp["msg"].as_str().unwrap_or("Api error").to_string(),
            ));
        }

        Ok(RevokeMsg {
            msg: resp["msg"].as_str().unwrap_or("").to_string(),
        })
    }

    /// 发送弹幕
    ///
    /// #### 参数
    /// * `msg` - 弹幕内容
    /// * `color` - 颜色(可选)
    pub async fn barrager(&self, msg: String, color: Option<String>) -> Result<String, Error> {
        let color = color.unwrap_or("#ffffff".to_string());

        let data = json!({
            "content": format!("[barrager]{{\"color\":\"{}\",\"content\":\"{}\"}}[/barrager]",color, msg),
            "apiKey": self.api_key,
        });

        let resp = post("chat-room/send", Some(data)).await?;

        if let Some(code) = resp["code"].as_i64()
            && code != 0
        {
            return Err(Error::Api(
                resp["msg"].as_str().unwrap_or("弹幕发送失败").to_string(),
            ));
        }

        Ok(resp["msg"].as_str().unwrap_or("弹幕发送成功").to_string())
    }

    /// 获取弹幕花费
    /// #### 返回 [BarragerCost]
    pub async fn barrage_cost(&self) -> Result<BarragerCost, Error> {
        let resp = get(&format!("chat-room/barrager/get?apiKey={}", self.api_key)).await?;

        if let Some(code) = resp["code"].as_i64()
            && code != 0
        {
            return Err(Error::Api(
                resp["msg"]
                    .as_str()
                    .unwrap_or("获取弹幕花费失败")
                    .to_string(),
            ));
        }

        Ok(BarragerCost::from_value(&resp["data"]))
    }

    /// 获取禁言中成员列表(思过崖)
    ///
    /// 返回禁言中成员列表 [MuteItem]
    pub async fn mutes(&self) -> Result<Vec<MuteItem>, Error> {
        let resp = get("chat-room/si-guo-list").await?;

        if let Some(code) = resp["code"].as_i64()
            && code != 0
        {
            return Err(Error::Api(
                resp["msg"]
                    .as_str()
                    .unwrap_or("获取禁言成员列表失败")
                    .to_string(),
            ));
        }

        let messages: Vec<MuteItem> = resp["data"]
            .as_array()
            .ok_or_else(|| Error::Api("Data is not an array".to_string()))?
            .iter()
            .map(MuteItem::from_value)
            .collect::<Result<Vec<_>, _>>()?;

        Ok(messages)
    }

    /// 获取消息原文(比如 Markdown)
    ///
    /// #### 参数
    /// * `o_id` - 消息 ID
    pub async fn get_raw_message(&self, o_id: &str) -> Result<String, Error> {
        let resp = get_text(&format!("cr/raw/{}", o_id,)).await?;

        let raw_message = resp.split("<!--").next().unwrap_or("").trim().to_string();

        Ok(raw_message)
    }
}