1use std::sync::Arc;
2
3use serde_json::{Value, json};
4use tokio::sync::Mutex;
5use url::Url;
6
7use crate::client::core::FishPi;
8use crate::domain::chatroom::{
9 BarragerCost, BarragerMsg, ChatContentType, ChatReactionMsg, ChatRoomEvent, ChatRoomEventKind,
10 ChatRoomMessageMode, ChatRoomMsg, CustomMsg, MusicMsg, MuteItem, OnlineInfo,
11};
12use crate::domain::redpacket::RedPacketStatusMsg;
13use crate::ids::MessageId;
14use crate::utils::build_http_path;
15use crate::utils::error::Error;
16use crate::wire::chatroom::{
17 WireBarragerMsg, WireChatReactionMsg, WireChatRoomMsg, WireChatRoomNode, WireMuteItem,
18 WireOnlineInfo, payload_type,
19};
20use crate::wire::redpacket::WireRedPacketStatusMsg;
21use crate::ws::{ParsedMessageHandler, RetryPolicy, WsConnection, WsLogHook, build_ws_url};
22
23type ChatRoomHandler = ParsedMessageHandler<ChatRoomEventKind, ChatRoomEvent>;
24
25fn deser<T: serde::de::DeserializeOwned>(v: &Value) -> Result<T, Error> {
26 serde_json::from_value(v.clone()).map_err(|e| Error::decode(e.to_string()))
27}
28
29fn parse_chatroom_message(json: &Value) -> Result<(ChatRoomEventKind, ChatRoomEvent), Error> {
30 let type_str = json["type"]
31 .as_str()
32 .ok_or_else(|| Error::decode("Missing type in message"))?;
33
34 match type_str {
35 "online" => {
36 let users = json["users"]
37 .as_array()
38 .map(|arr| {
39 arr.iter()
40 .filter_map(|u| deser::<WireOnlineInfo>(u).ok())
41 .map(OnlineInfo::from)
42 .collect()
43 })
44 .unwrap_or_default();
45 let discussing = json["discussing"]
46 .as_str()
47 .map(|s| s.trim().to_string())
48 .filter(|s| !s.is_empty());
49 let online_chat_cnt = json["onlineChatCnt"]
50 .as_u64()
51 .or_else(|| json["onlineCnt"].as_u64())
52 .map(|n| n as usize);
53 Ok((
54 ChatRoomEventKind::Online,
55 ChatRoomEvent::Online {
56 users,
57 discussing,
58 online_chat_cnt,
59 },
60 ))
61 }
62 "discussChanged" => {
63 let d = json["newDiscuss"].as_str().unwrap_or_default().to_string();
64 Ok((
65 ChatRoomEventKind::DiscussChanged,
66 ChatRoomEvent::DiscussChanged(d),
67 ))
68 }
69 "revoke" => {
70 let id = json["oId"].as_str().unwrap_or_default().to_string();
71 Ok((ChatRoomEventKind::Revoke, ChatRoomEvent::Revoke(id)))
72 }
73 "msg" => {
74 let wire: WireChatRoomMsg = deser(json)?;
75 let kind = payload_type(&wire.content);
76 let msg = ChatRoomMsg::from(wire);
77 match kind.as_deref() {
78 Some(t) if t.eq_ignore_ascii_case("music") => Ok((
79 ChatRoomEventKind::Music,
80 ChatRoomEvent::Music(MusicMsg::from_base(msg)),
81 )),
82 Some(t) if t.eq_ignore_ascii_case("weather") => {
83 Ok((ChatRoomEventKind::Weather, ChatRoomEvent::Weather(msg)))
84 }
85 _ => Ok((ChatRoomEventKind::Msg, ChatRoomEvent::Msg(msg))),
86 }
87 }
88 "redPacket" => {
89 let wire: WireChatRoomMsg = deser(json)?;
90 Ok((
91 ChatRoomEventKind::RedPacket,
92 ChatRoomEvent::RedPacket(ChatRoomMsg::from(wire)),
93 ))
94 }
95 "redPacketStatus" => {
96 let wire: WireRedPacketStatusMsg = deser(json)?;
97 Ok((
98 ChatRoomEventKind::RedPacketStatus,
99 ChatRoomEvent::RedPacketStatus(RedPacketStatusMsg::from(wire)),
100 ))
101 }
102 "barrager" => {
103 let wire: WireBarragerMsg = deser(json)?;
104 Ok((
105 ChatRoomEventKind::Barrager,
106 ChatRoomEvent::Barrager(BarragerMsg::from(wire)),
107 ))
108 }
109 "customMessage" => {
110 let message = json["message"].as_str().unwrap_or_default().to_string();
111 Ok((
112 ChatRoomEventKind::Custom,
113 ChatRoomEvent::Custom(CustomMsg { message }),
114 ))
115 }
116 "chatreaction" => {
117 let wire: WireChatReactionMsg = deser(json)?;
118 Ok((
119 ChatRoomEventKind::ChatReaction,
120 ChatRoomEvent::ChatReaction(ChatReactionMsg::from(wire)),
121 ))
122 }
123 other => Err(Error::decode(format!("Unknown message type: {}", other))),
124 }
125}
126
127pub struct ChatRoomConnection {
129 connection: WsConnection,
130 handler: ChatRoomHandler,
131 url: String,
132 node_name: Option<String>,
133 discuss: Arc<Mutex<String>>,
134 onlines: Arc<Mutex<Vec<OnlineInfo>>>,
135}
136
137impl ChatRoomConnection {
138 pub async fn on_online<F>(&self, listener: F)
140 where
141 F: Fn(Vec<OnlineInfo>, Option<String>, Option<usize>) + Send + Sync + 'static,
142 {
143 let onlines = Arc::clone(&self.onlines);
144 let discuss = Arc::clone(&self.discuss);
145 self.add(ChatRoomEventKind::Online, move |e| {
146 if let ChatRoomEvent::Online {
147 users,
148 discussing,
149 online_chat_cnt,
150 } = e
151 {
152 if !users.is_empty()
153 && let Ok(mut g) = onlines.try_lock()
154 {
155 *g = users.clone();
156 }
157 if let Some(topic) = discussing.as_ref()
158 && let Ok(mut g) = discuss.try_lock()
159 {
160 *g = topic.clone();
161 }
162 listener(users, discussing, online_chat_cnt);
163 }
164 })
165 .await;
166 }
167
168 pub async fn on_discuss<F>(&self, listener: F)
170 where
171 F: Fn(String) + Send + Sync + 'static,
172 {
173 let discuss = Arc::clone(&self.discuss);
174 self.add(ChatRoomEventKind::DiscussChanged, move |e| {
175 if let ChatRoomEvent::DiscussChanged(topic) = e {
176 if let Ok(mut g) = discuss.try_lock() {
177 *g = topic.clone();
178 }
179 listener(topic);
180 }
181 })
182 .await;
183 }
184
185 pub async fn on_revoke<F>(&self, listener: F)
187 where
188 F: Fn(String) + Send + Sync + 'static,
189 {
190 self.add(ChatRoomEventKind::Revoke, move |e| {
191 if let ChatRoomEvent::Revoke(id) = e {
192 listener(id);
193 }
194 })
195 .await;
196 }
197
198 pub async fn on_msg<F>(&self, listener: F)
200 where
201 F: Fn(ChatRoomMsg) + Send + Sync + 'static,
202 {
203 self.add(ChatRoomEventKind::Msg, move |e| {
204 if let ChatRoomEvent::Msg(m) = e {
205 listener(m);
206 }
207 })
208 .await;
209 }
210
211 pub async fn on_barrager<F>(&self, listener: F)
213 where
214 F: Fn(BarragerMsg) + Send + Sync + 'static,
215 {
216 self.add(ChatRoomEventKind::Barrager, move |e| {
217 if let ChatRoomEvent::Barrager(b) = e {
218 listener(b);
219 }
220 })
221 .await;
222 }
223
224 pub async fn on_redpacket<F>(&self, listener: F)
226 where
227 F: Fn(ChatRoomMsg) + Send + Sync + 'static,
228 {
229 self.add(ChatRoomEventKind::RedPacket, move |e| {
230 if let ChatRoomEvent::RedPacket(m) = e {
231 listener(m);
232 }
233 })
234 .await;
235 }
236
237 pub async fn on_redpacket_status<F>(&self, listener: F)
239 where
240 F: Fn(RedPacketStatusMsg) + Send + Sync + 'static,
241 {
242 self.add(ChatRoomEventKind::RedPacketStatus, move |e| {
243 if let ChatRoomEvent::RedPacketStatus(s) = e {
244 listener(s);
245 }
246 })
247 .await;
248 }
249
250 pub async fn on_music<F>(&self, listener: F)
252 where
253 F: Fn(MusicMsg) + Send + Sync + 'static,
254 {
255 self.add(ChatRoomEventKind::Music, move |e| {
256 if let ChatRoomEvent::Music(m) = e {
257 listener(m);
258 }
259 })
260 .await;
261 }
262
263 pub async fn on_weather<F>(&self, listener: F)
265 where
266 F: Fn(ChatRoomMsg) + Send + Sync + 'static,
267 {
268 self.add(ChatRoomEventKind::Weather, move |e| {
269 if let ChatRoomEvent::Weather(m) = e {
270 listener(m);
271 }
272 })
273 .await;
274 }
275
276 pub async fn on_custom<F>(&self, listener: F)
278 where
279 F: Fn(CustomMsg) + Send + Sync + 'static,
280 {
281 self.add(ChatRoomEventKind::Custom, move |e| {
282 if let ChatRoomEvent::Custom(c) = e {
283 listener(c);
284 }
285 })
286 .await;
287 }
288
289 pub async fn on_chat_reaction<F>(&self, listener: F)
291 where
292 F: Fn(ChatReactionMsg) + Send + Sync + 'static,
293 {
294 self.add(ChatRoomEventKind::ChatReaction, move |e| {
295 if let ChatRoomEvent::ChatReaction(r) = e {
296 listener(r);
297 }
298 })
299 .await;
300 }
301
302 pub async fn on_all<F>(&self, listener: F)
304 where
305 F: Fn(ChatRoomEvent) + Send + Sync + 'static,
306 {
307 self.add(ChatRoomEventKind::All, listener).await;
308 }
309
310 async fn add<F>(&self, kind: ChatRoomEventKind, listener: F)
311 where
312 F: Fn(ChatRoomEvent) + Send + Sync + 'static,
313 {
314 self.handler
315 .get_emitter()
316 .add_listener(kind, listener)
317 .await;
318 }
319
320 pub async fn off(&self, kind: ChatRoomEventKind) {
322 self.handler.get_emitter().remove_listener(Some(kind)).await;
323 }
324
325 pub async fn discuss(&self) -> String {
327 self.discuss.lock().await.clone()
328 }
329
330 pub async fn online_count(&self) -> usize {
332 self.onlines.lock().await.len()
333 }
334
335 pub fn node_name(&self) -> Option<&str> {
337 self.node_name.as_deref()
338 }
339
340 pub async fn reconnect(&mut self) -> Result<(), Error> {
342 self.connection
343 .reconnect(&self.url, self.handler.clone())
344 .await
345 .map_err(Error::from)
346 }
347
348 pub fn set_retry_policy(&mut self, policy: RetryPolicy) {
350 self.connection.set_retry_policy(policy);
351 }
352
353 pub fn set_log_hook<F>(&mut self, hook: F)
355 where
356 F: Fn(&str) + Send + Sync + 'static,
357 {
358 let hook = Arc::new(hook) as WsLogHook;
359 self.connection.set_log_hook_arc(hook.clone());
360 self.handler.set_log_hook_arc(hook);
361 }
362
363 pub fn disconnect(&mut self) {
365 self.connection.disconnect();
366 }
367}
368
369pub struct ChatRoomApi(pub(crate) FishPi);
371
372impl FishPi {
373 pub fn chatroom(&self) -> ChatRoomApi {
375 ChatRoomApi(self.clone())
376 }
377}
378
379impl ChatRoomApi {
380 async fn chatroom_ws_url(&self) -> Result<(String, Option<String>), Error> {
382 let fallback = || {
383 build_ws_url(
384 self.0.domain(),
385 "chat-room-channel",
386 &[("apiKey", self.0.api_key().to_string())],
387 )
388 .map(|url| (url, None))
389 .map_err(Error::from)
390 };
391
392 let raw = match self.0.get_raw(&self.0.with_key("chat-room/node/get")).await {
393 Ok(v) => v,
394 Err(_) => return fallback(),
395 };
396 let node: WireChatRoomNode = match serde_json::from_value(raw) {
397 Ok(n) => n,
398 Err(_) => return fallback(),
399 };
400 let node_name = Some(node.msg.trim().to_string()).filter(|s| !s.is_empty());
401 match Url::parse(&node.data) {
402 Ok(mut parsed) => {
403 if parsed.path().is_empty() {
404 parsed.set_path("/");
405 }
406 Ok((parsed.to_string(), node_name))
407 }
408 Err(_) => fallback(),
409 }
410 }
411
412 pub async fn connect(&self) -> Result<ChatRoomConnection, Error> {
414 let (url, node_name) = self.chatroom_ws_url().await?;
415 let handler = ChatRoomHandler::new(
416 parse_chatroom_message,
417 Some(ChatRoomEventKind::All),
418 "chatroom",
419 );
420 let mut connection = WsConnection::new();
421 connection
422 .connect(false, &url, handler.clone())
423 .await
424 .map_err(Error::from)?;
425 Ok(ChatRoomConnection {
426 connection,
427 handler,
428 url,
429 node_name,
430 discuss: Arc::new(Mutex::new(String::new())),
431 onlines: Arc::new(Mutex::new(Vec::new())),
432 })
433 }
434
435 pub async fn send(&self, content: impl Into<String>) -> Result<(), Error> {
437 self.0
438 .post_raw(
439 "chat-room/send",
440 &json!({ "content": content.into(), "client": self.0.client_tag() }),
441 )
442 .await?;
443 Ok(())
444 }
445
446 pub async fn set_discuss(&self, discuss: impl Into<String>) -> Result<(), Error> {
448 self.send(format!("[setdiscuss]{}[/setdiscuss]", discuss.into()))
449 .await
450 }
451
452 pub async fn history(
454 &self,
455 page: u32,
456 content_type: ChatContentType,
457 ) -> Result<Vec<ChatRoomMsg>, Error> {
458 let url = build_http_path(
459 "chat-room/more",
460 &[
461 ("page", page.to_string()),
462 ("type", content_type.as_str().to_string()),
463 ("apiKey", self.0.api_key().to_string()),
464 ],
465 );
466 let rsp = self.0.get_raw(&url).await?;
467 Ok(collect_msgs(&rsp))
468 }
469
470 pub async fn msg_around(
472 &self,
473 msg_id: impl Into<MessageId>,
474 mode: ChatRoomMessageMode,
475 size: u32,
476 content_type: ChatContentType,
477 ) -> Result<Vec<ChatRoomMsg>, Error> {
478 let url = build_http_path(
479 "chat-room/getMessage",
480 &[
481 ("oId", msg_id.into().into_string()),
482 ("mode", mode.as_str().to_string()),
483 ("size", size.to_string()),
484 ("type", content_type.as_str().to_string()),
485 ("apiKey", self.0.api_key().to_string()),
486 ],
487 );
488 let rsp = self.0.get_raw(&url).await?;
489 Ok(collect_msgs(&rsp))
490 }
491
492 pub async fn revoke(&self, msg_id: impl Into<MessageId>) -> Result<String, Error> {
494 let rsp = self
495 .0
496 .delete_raw(&format!("chat-room/revoke/{}", msg_id.into()), &json!({}))
497 .await?;
498 Ok(rsp["msg"].as_str().unwrap_or_default().to_string())
499 }
500
501 pub async fn barrager(
503 &self,
504 content: impl Into<String>,
505 color: Option<&str>,
506 ) -> Result<String, Error> {
507 let color = color.unwrap_or("#ffffff");
508 let tag = format!(
509 "[barrager]{{\"color\":\"{}\",\"content\":\"{}\"}}[/barrager]",
510 color,
511 content.into()
512 );
513 let rsp = self
514 .0
515 .post_raw("chat-room/send", &json!({ "content": tag }))
516 .await?;
517 Ok(rsp["msg"].as_str().unwrap_or("弹幕发送成功").to_string())
518 }
519
520 pub async fn barrage_cost(&self) -> Result<BarragerCost, Error> {
522 let rsp = self
523 .0
524 .get_raw(&self.0.with_key("chat-room/barrager/get"))
525 .await?;
526 let text = rsp["data"].as_str().unwrap_or("5积分").trim();
527 let cost = text.trim_end_matches("积分").parse::<u32>().unwrap_or(0);
528 Ok(BarragerCost {
529 cost,
530 unit: "积分".to_string(),
531 })
532 }
533
534 pub async fn mutes(&self) -> Result<Vec<MuteItem>, Error> {
536 let rsp = self.0.get_raw("chat-room/si-guo-list").await?;
537 Ok(rsp["data"]
538 .as_array()
539 .map(|arr| {
540 arr.iter()
541 .filter_map(|v| serde_json::from_value::<WireMuteItem>(v.clone()).ok())
542 .map(MuteItem::from)
543 .collect()
544 })
545 .unwrap_or_default())
546 }
547
548 pub async fn raw_message(&self, msg_id: impl Into<MessageId>) -> Result<String, Error> {
550 let text = self
551 .0
552 .get_text(&format!("cr/raw/{}", msg_id.into()))
553 .await?;
554 Ok(text.split("<!--").next().unwrap_or("").trim().to_string())
555 }
556}
557
558fn collect_msgs(rsp: &Value) -> Vec<ChatRoomMsg> {
559 rsp["data"]
560 .as_array()
561 .map(|arr| {
562 arr.iter()
563 .filter_map(|v| serde_json::from_value::<WireChatRoomMsg>(v.clone()).ok())
564 .map(ChatRoomMsg::from)
565 .collect()
566 })
567 .unwrap_or_default()
568}