fishpi_sdk/client/
notice.rs1use std::sync::Arc;
2
3use serde_json::Value;
4
5use crate::client::core::FishPi;
6use crate::domain::notice::{
7 NoticeCount, NoticeItem, NoticeList, NoticeMsg, NoticeMsgType, NoticeType,
8};
9use crate::utils::build_http_path;
10use crate::utils::error::Error;
11use crate::wire::notice::{
12 WireNoticeAt, WireNoticeComment, WireNoticeCount, WireNoticeFollow, WireNoticeMsg,
13 WireNoticePoint, WireNoticeReply, WireNoticeSystem,
14};
15use crate::ws::{ParsedMessageHandler, RetryPolicy, WsConnection, WsLogHook, build_ws_url};
16
17type NoticeHandler = ParsedMessageHandler<NoticeEventKind, NoticeMsg>;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub enum NoticeEventKind {
22 Refresh,
24 Broadcast,
26 All,
27}
28
29fn parse_notice_message(json: &Value) -> Result<(NoticeEventKind, NoticeMsg), Error> {
30 let payload = json
31 .get("data")
32 .filter(|v| v.get("command").is_some())
33 .unwrap_or(json);
34 let command = payload
35 .get("command")
36 .and_then(Value::as_str)
37 .ok_or_else(|| Error::decode("Missing command in notice message"))?;
38 let kind = match NoticeMsgType::from_command(command) {
39 Some(NoticeMsgType::Refresh) => NoticeEventKind::Refresh,
40 Some(NoticeMsgType::WarnBroadcast) => NoticeEventKind::Broadcast,
41 None => return Err(Error::decode(format!("Unknown notice command: {command}"))),
42 };
43 let wire: WireNoticeMsg =
44 serde_json::from_value(payload.clone()).map_err(|e| Error::decode(e.to_string()))?;
45 Ok((kind, wire.into()))
46}
47
48pub struct NoticeApi(pub(crate) FishPi);
50
51impl FishPi {
52 pub fn notice(&self) -> NoticeApi {
54 NoticeApi(self.clone())
55 }
56}
57
58impl NoticeApi {
59 pub async fn count(&self) -> Result<NoticeCount, Error> {
60 let wire: WireNoticeCount = self
61 .0
62 .get_data(&self.0.with_key("notifications/unread/count"))
63 .await?;
64 Ok(wire.into())
65 }
66
67 pub async fn list(&self, notice_type: NoticeType) -> Result<NoticeList, Error> {
68 let path = build_http_path(
69 "api/getNotifications",
70 &[
71 ("apiKey", self.0.api_key().to_string()),
72 ("type", notice_type.as_str().to_string()),
73 ],
74 );
75 let list = match notice_type {
76 NoticeType::Point => {
77 let wire: Vec<WireNoticePoint> = self.0.get_data(&path).await?;
78 wire.into_iter()
79 .map(|w| NoticeItem::Point(w.into()))
80 .collect()
81 }
82 NoticeType::Commented => {
83 let wire: Vec<WireNoticeComment> = self.0.get_data(&path).await?;
84 wire.into_iter()
85 .map(|w| NoticeItem::Comment(w.into()))
86 .collect()
87 }
88 NoticeType::Reply => {
89 let wire: Vec<WireNoticeReply> = self.0.get_data(&path).await?;
90 wire.into_iter()
91 .map(|w| NoticeItem::Reply(w.into()))
92 .collect()
93 }
94 NoticeType::At => {
95 let wire: Vec<WireNoticeAt> = self.0.get_data(&path).await?;
96 wire.into_iter().map(|w| NoticeItem::At(w.into())).collect()
97 }
98 NoticeType::Following => {
99 let wire: Vec<WireNoticeFollow> = self.0.get_data(&path).await?;
100 wire.into_iter()
101 .map(|w| NoticeItem::Follow(w.into()))
102 .collect()
103 }
104 NoticeType::System => {
105 let wire: Vec<WireNoticeSystem> = self.0.get_data(&path).await?;
106 wire.into_iter()
107 .map(|w| NoticeItem::System(w.into()))
108 .collect()
109 }
110 NoticeType::Broadcast => {
111 return Err(Error::decode("broadcast 通知不支持列表查询"));
112 }
113 };
114 Ok(list)
115 }
116
117 pub async fn make_read(&self, notice_type: NoticeType) -> Result<(), Error> {
118 let path = self
119 .0
120 .with_key(&format!("notifications/make-read/{}", notice_type.as_str()));
121 self.0.get_raw(&path).await?;
122 Ok(())
123 }
124
125 pub async fn read_all(&self) -> Result<(), Error> {
126 self.0
127 .get_raw(&self.0.with_key("notifications/all-read"))
128 .await?;
129 Ok(())
130 }
131
132 pub async fn connect(&self) -> Result<NoticeConnection, Error> {
134 let url = build_ws_url(
135 self.0.domain(),
136 "user-channel",
137 &[("apiKey", self.0.api_key().to_string())],
138 )
139 .map_err(Error::from)?;
140 let handler =
141 NoticeHandler::new(parse_notice_message, Some(NoticeEventKind::All), "notice");
142 let mut connection = WsConnection::new();
143 connection
144 .connect(false, &url, handler.clone())
145 .await
146 .map_err(Error::from)?;
147 Ok(NoticeConnection {
148 connection,
149 handler,
150 url,
151 })
152 }
153}
154
155pub struct NoticeConnection {
157 connection: WsConnection,
158 handler: NoticeHandler,
159 url: String,
160}
161
162impl NoticeConnection {
163 pub async fn on_refresh<F>(&self, listener: F)
165 where
166 F: Fn(NoticeMsg) + Send + Sync + 'static,
167 {
168 self.handler
169 .get_emitter()
170 .add_listener(NoticeEventKind::Refresh, listener)
171 .await;
172 }
173
174 pub async fn on_broadcast<F>(&self, listener: F)
176 where
177 F: Fn(NoticeMsg) + Send + Sync + 'static,
178 {
179 self.handler
180 .get_emitter()
181 .add_listener(NoticeEventKind::Broadcast, listener)
182 .await;
183 }
184
185 pub async fn on_all<F>(&self, listener: F)
187 where
188 F: Fn(NoticeMsg) + Send + Sync + 'static,
189 {
190 self.handler
191 .get_emitter()
192 .add_listener(NoticeEventKind::All, listener)
193 .await;
194 }
195
196 pub async fn off(&self, kind: NoticeEventKind) {
198 self.handler.get_emitter().remove_listener(Some(kind)).await;
199 }
200
201 pub async fn reconnect(&mut self) -> Result<(), Error> {
203 self.connection
204 .reconnect(&self.url, self.handler.clone())
205 .await
206 .map_err(Error::from)
207 }
208
209 pub fn set_retry_policy(&mut self, policy: RetryPolicy) {
211 self.connection.set_retry_policy(policy);
212 }
213
214 pub fn set_log_hook<F>(&mut self, hook: F)
216 where
217 F: Fn(&str) + Send + Sync + 'static,
218 {
219 let hook = Arc::new(hook) as WsLogHook;
220 self.connection.set_log_hook_arc(hook.clone());
221 self.handler.set_log_hook_arc(hook);
222 }
223
224 pub fn disconnect(&mut self) {
226 self.connection.disconnect();
227 }
228}