1use std::sync::Arc;
2
3use serde_json::Value;
4
5use crate::client::core::FishPi;
6use crate::domain::chat::{ChatData, ChatEvent, ChatEventKind, ChatNotice, ChatRevoke};
7use crate::ids::MessageId;
8use crate::utils::build_http_path;
9use crate::utils::error::Error;
10use crate::wire::chat::{WireChatData, WireChatNotice};
11use crate::ws::{ParsedMessageHandler, RetryPolicy, WsConnection, WsLogHook, build_ws_url};
12
13type ChatHandler = ParsedMessageHandler<ChatEventKind, ChatEvent>;
14
15fn parse_chat_message(json: &Value) -> Result<(ChatEventKind, ChatEvent), Error> {
16 let kind = detect_kind(json)?;
17 let payload = json.get("data").filter(|v| !v.is_null()).unwrap_or(json);
18 match kind {
19 ChatEventKind::Notice => {
20 let wire: WireChatNotice = deser(payload).or_else(|_| deser(json))?;
21 Ok((kind, ChatEvent::Notice(ChatNotice::from(wire))))
22 }
23 ChatEventKind::Data => {
24 let wire: WireChatData = deser(payload).or_else(|_| deser(json))?;
25 Ok((kind, ChatEvent::Data(ChatData::from(wire))))
26 }
27 ChatEventKind::Revoke => {
28 let id = payload
29 .get("data")
30 .and_then(Value::as_str)
31 .or_else(|| json.get("data").and_then(Value::as_str))
32 .unwrap_or_default()
33 .to_string();
34 Ok((kind, ChatEvent::Revoke(ChatRevoke { id })))
35 }
36 }
37}
38
39fn deser<T: serde::de::DeserializeOwned>(v: &Value) -> Result<T, Error> {
40 serde_json::from_value(v.clone()).map_err(|e| Error::decode(e.to_string()))
41}
42
43fn detect_kind(json: &Value) -> Result<ChatEventKind, Error> {
44 let candidates = [
45 json.get("type"),
46 json.get("command"),
47 json.get("data").and_then(|v| v.get("type")),
48 json.get("data").and_then(|v| v.get("command")),
49 ];
50 for c in candidates {
51 match c.and_then(Value::as_str) {
52 Some("notice") => return Ok(ChatEventKind::Notice),
53 Some("data") => return Ok(ChatEventKind::Data),
54 Some("revoke") => return Ok(ChatEventKind::Revoke),
55 _ => {}
56 }
57 }
58 let payload = json.get("data").filter(|v| v.is_object()).unwrap_or(json);
59 if payload.get("senderUserName").is_some() && payload.get("receiverUserName").is_some() {
60 return Ok(ChatEventKind::Data);
61 }
62 if payload.get("userId").is_some() && payload.get("preview").is_some() {
63 return Ok(ChatEventKind::Notice);
64 }
65 if payload.get("data").and_then(Value::as_str).is_some() {
66 return Ok(ChatEventKind::Revoke);
67 }
68 Err(Error::decode("Missing type/command field"))
69}
70
71pub struct ChatConnection {
73 connection: WsConnection,
74 handler: ChatHandler,
75 url: String,
76}
77
78impl ChatConnection {
79 pub async fn on_data<F>(&self, listener: F)
81 where
82 F: Fn(ChatData) + Send + Sync + 'static,
83 {
84 self.add(ChatEventKind::Data, move |e| {
85 if let ChatEvent::Data(d) = e {
86 listener(d);
87 }
88 })
89 .await;
90 }
91
92 pub async fn on_notice<F>(&self, listener: F)
94 where
95 F: Fn(ChatNotice) + Send + Sync + 'static,
96 {
97 self.add(ChatEventKind::Notice, move |e| {
98 if let ChatEvent::Notice(n) = e {
99 listener(n);
100 }
101 })
102 .await;
103 }
104
105 pub async fn on_revoke<F>(&self, listener: F)
107 where
108 F: Fn(ChatRevoke) + Send + Sync + 'static,
109 {
110 self.add(ChatEventKind::Revoke, move |e| {
111 if let ChatEvent::Revoke(r) = e {
112 listener(r);
113 }
114 })
115 .await;
116 }
117
118 async fn add<F>(&self, kind: ChatEventKind, listener: F)
119 where
120 F: Fn(ChatEvent) + Send + Sync + 'static,
121 {
122 self.handler
123 .get_emitter()
124 .add_listener(kind, listener)
125 .await;
126 }
127
128 pub async fn off(&self, kind: ChatEventKind) {
130 self.handler.get_emitter().remove_listener(Some(kind)).await;
131 }
132
133 pub fn send(&self, content: &str) -> Result<(), Error> {
135 self.connection.send_text(content).map_err(Error::from)
136 }
137
138 pub async fn reconnect(&mut self) -> Result<(), Error> {
140 self.connection
141 .reconnect(&self.url, self.handler.clone())
142 .await
143 .map_err(Error::from)
144 }
145
146 pub fn set_retry_policy(&mut self, policy: RetryPolicy) {
148 self.connection.set_retry_policy(policy);
149 }
150
151 pub fn set_log_hook<F>(&mut self, hook: F)
153 where
154 F: Fn(&str) + Send + Sync + 'static,
155 {
156 let hook = Arc::new(hook) as WsLogHook;
157 self.connection.set_log_hook_arc(hook.clone());
158 self.handler.set_log_hook_arc(hook);
159 }
160
161 pub fn disconnect(&mut self) {
163 self.connection.disconnect();
164 }
165}
166
167pub struct ChatApi(pub(crate) FishPi);
169
170impl FishPi {
171 pub fn chat(&self) -> ChatApi {
173 ChatApi(self.clone())
174 }
175}
176
177impl ChatApi {
178 pub async fn connect(&self, user: Option<&str>) -> Result<ChatConnection, Error> {
180 let mut params = vec![("apiKey", self.0.api_key().to_string())];
181 let path = match user {
182 Some(u) => {
183 params.push(("toUser", u.to_string()));
184 "chat-channel"
185 }
186 None => "user-channel",
187 };
188 let url = build_ws_url(self.0.domain(), path, ¶ms).map_err(Error::from)?;
189 let handler = ChatHandler::new(parse_chat_message, None, "chat");
190 let mut connection = WsConnection::new();
191 connection
192 .connect(false, &url, handler.clone())
193 .await
194 .map_err(Error::from)?;
195 Ok(ChatConnection {
196 connection,
197 handler,
198 url,
199 })
200 }
201
202 pub async fn list(&self) -> Result<Vec<ChatData>, Error> {
204 let rsp = self.0.get_raw(&self.0.with_key("chat/get-list")).await?;
205 Ok(collect_chat_data(&rsp))
206 }
207
208 pub async fn history(
210 &self,
211 user: impl Into<String>,
212 page: u32,
213 size: u32,
214 autoread: bool,
215 ) -> Result<Vec<ChatData>, Error> {
216 let user = user.into();
217 let url = build_http_path(
218 "chat/get-message",
219 &[
220 ("apiKey", self.0.api_key().to_string()),
221 ("page", page.to_string()),
222 ("pageSize", size.to_string()),
223 ("toUser", user.clone()),
224 ],
225 );
226 let rsp = self.0.get_raw(&url).await?;
227 if !result_ok(&rsp) {
228 return Err(Error::decode(
229 rsp["msg"].as_str().unwrap_or("API error").to_string(),
230 ));
231 }
232 let list = collect_chat_data(&rsp);
233 if autoread {
234 self.mark_as_read(user).await?;
235 }
236 Ok(list)
237 }
238
239 pub async fn mark_as_read(&self, user: impl Into<String>) -> Result<bool, Error> {
241 let user = user.into();
242 let by_to = build_http_path(
243 "chat/mark-as-read",
244 &[
245 ("toUser", user.clone()),
246 ("apiKey", self.0.api_key().to_string()),
247 ],
248 );
249 match self.0.get_raw(&by_to).await {
250 Ok(rsp) if result_ok(&rsp) => Ok(true),
251 other => {
252 let text = match &other {
253 Ok(rsp) => rsp["msg"].as_str().unwrap_or("").to_string(),
254 Err(e) => e.to_string(),
255 };
256 if !(text.contains("fromUserJSON") || text.contains("Cannot invoke")) {
257 other?;
258 return Ok(false);
259 }
260 let by_from = build_http_path(
261 "chat/mark-as-read",
262 &[("fromUser", user), ("apiKey", self.0.api_key().to_string())],
263 );
264 let rsp = self.0.get_raw(&by_from).await?;
265 if !result_ok(&rsp) {
266 return Err(Error::decode(
267 rsp["msg"].as_str().unwrap_or("API error").to_string(),
268 ));
269 }
270 Ok(true)
271 }
272 }
273 }
274
275 pub async fn unread(&self) -> Result<Vec<ChatData>, Error> {
277 let rsp = self.0.get_raw(&self.0.with_key("chat/has-unread")).await?;
278 if rsp["result"].as_i64().unwrap_or(0) == 0 {
279 return Ok(Vec::new());
280 }
281 Ok(collect_chat_data(&rsp))
282 }
283
284 pub async fn revoke(&self, msg_id: impl Into<MessageId>) -> Result<bool, Error> {
286 let url = build_http_path(
287 "chat/revoke",
288 &[
289 ("apiKey", self.0.api_key().to_string()),
290 ("oId", msg_id.into().into_string()),
291 ],
292 );
293 let rsp = self.0.get_raw(&url).await?;
294 if !result_ok(&rsp) {
295 return Err(Error::decode(
296 rsp["msg"].as_str().unwrap_or("API error").to_string(),
297 ));
298 }
299 Ok(true)
300 }
301}
302
303fn result_ok(rsp: &Value) -> bool {
304 rsp.get("result").and_then(Value::as_i64).unwrap_or(0) == 0
305}
306
307fn collect_chat_data(rsp: &Value) -> Vec<ChatData> {
308 rsp["data"]
309 .as_array()
310 .map(|list| {
311 list.iter()
312 .filter_map(|v| serde_json::from_value::<WireChatData>(v.clone()).ok())
313 .map(ChatData::from)
314 .collect()
315 })
316 .unwrap_or_default()
317}