Skip to main content

fishpi_sdk/client/
article.rs

1use reqwest::Method;
2use serde::Serialize;
3use serde_json::{Value, json};
4
5use crate::client::core::FishPi;
6use crate::domain::article::{
7    ArticleDetail, ArticleDraftDetail, ArticleDraftSummary, ArticleList, ArticleListType,
8    ArticleType, Pagination,
9};
10use crate::ids::ArticleId;
11use crate::utils::build_http_path;
12use crate::utils::error::Error;
13use crate::wire::article::{
14    WireArticleDetail, WireArticleDraftEnvelope, WireArticleDraftList,
15    WireArticleDraftSummaryEnvelope, WireArticleList, WirePagination,
16};
17use crate::ws::{ParsedMessageHandler, RetryPolicy, WsConnection, WsLogHook, build_ws_url};
18use std::sync::Arc;
19
20type ArticleHandler = ParsedMessageHandler<ArticleEventKind, Value>;
21
22/// 文章频道事件类别(监听器键)。当前只有一类原始推送。
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
24pub enum ArticleEventKind {
25    Message,
26}
27
28fn parse_article_message(json: &Value) -> Result<(ArticleEventKind, Value), Error> {
29    Ok((ArticleEventKind::Message, json.clone()))
30}
31
32/// 发帖信息。
33#[derive(Clone, Debug, Serialize)]
34pub struct ArticlePost {
35    #[serde(rename = "articleTitle")]
36    pub title: String,
37    #[serde(rename = "articleContent")]
38    pub content: String,
39    #[serde(rename = "articleTags")]
40    pub tags: String,
41    #[serde(rename = "articleCommentable")]
42    pub commentable: bool,
43    #[serde(rename = "articleNotifyFollowers")]
44    pub notify_followers: bool,
45    #[serde(rename = "articleType")]
46    pub type_: ArticleType,
47    #[serde(rename = "articleShowInList")]
48    pub show_in_list: u32,
49    #[serde(
50        rename = "articleRewardContent",
51        skip_serializing_if = "Option::is_none"
52    )]
53    pub reward_content: Option<String>,
54    #[serde(rename = "articleRewardPoint", skip_serializing_if = "Option::is_none")]
55    pub reward_point: Option<String>,
56    #[serde(rename = "articleAnonymous", skip_serializing_if = "Option::is_none")]
57    pub anonymous: Option<bool>,
58    #[serde(
59        rename = "articleQnAOfferPoint",
60        skip_serializing_if = "Option::is_none"
61    )]
62    pub offer_point: Option<u32>,
63    #[serde(rename = "isGoodArticle", skip_serializing_if = "Option::is_none")]
64    pub is_good_article: Option<String>,
65}
66
67impl ArticlePost {
68    pub fn new(
69        title: impl Into<String>,
70        content: impl Into<String>,
71        tags: impl Into<String>,
72    ) -> Self {
73        Self {
74            title: title.into(),
75            content: content.into(),
76            tags: tags.into(),
77            commentable: true,
78            notify_followers: false,
79            type_: ArticleType::Normal,
80            show_in_list: 1,
81            reward_content: None,
82            reward_point: None,
83            anonymous: None,
84            offer_point: None,
85            is_good_article: None,
86        }
87    }
88}
89
90/// 文章草稿保存参数。
91#[derive(Clone, Debug, Serialize, Default)]
92pub struct ArticleDraftSave {
93    #[serde(rename = "articleDraftId", skip_serializing_if = "Option::is_none")]
94    pub draft_id: Option<String>,
95    #[serde(rename = "articleTitle")]
96    pub title: String,
97    #[serde(rename = "articleContent")]
98    pub content: String,
99    #[serde(rename = "articleDraftThoughtContent")]
100    pub thought_content: String,
101    #[serde(rename = "articleTags")]
102    pub tags: String,
103    #[serde(rename = "articleType")]
104    pub article_type: u32,
105    #[serde(rename = "columnId")]
106    pub column_id: String,
107    #[serde(rename = "columnTitle")]
108    pub column_title: String,
109    #[serde(rename = "chapterNo")]
110    pub chapter_no: String,
111    #[serde(rename = "articleRewardContent")]
112    pub reward_content: String,
113    #[serde(rename = "articleRewardPoint")]
114    pub reward_point: String,
115    #[serde(
116        rename = "articleQnAOfferPoint",
117        skip_serializing_if = "Option::is_none"
118    )]
119    pub qna_offer_point: Option<u32>,
120    #[serde(rename = "articleCommentable")]
121    pub commentable: bool,
122    #[serde(rename = "articleAnonymous")]
123    pub anonymous: bool,
124    #[serde(rename = "articleNotifyFollowers")]
125    pub notify_followers: bool,
126    #[serde(rename = "articleShowInList")]
127    pub show_in_list: u32,
128    #[serde(rename = "articleStatement")]
129    pub statement: u32,
130}
131
132/// 文章域访问器。
133pub struct ArticleApi(pub(crate) FishPi);
134
135impl FishPi {
136    /// 文章域。
137    pub fn article(&self) -> ArticleApi {
138        ArticleApi(self.clone())
139    }
140}
141
142impl ArticleApi {
143    /// 发布文章,返回文章 Id。
144    pub async fn post(&self, data: &ArticlePost) -> Result<ArticleId, Error> {
145        let rsp = self.0.post_raw("article", data).await?;
146        take_article_id(&rsp)
147    }
148
149    /// 更新文章,返回文章 Id。
150    pub async fn update(
151        &self,
152        id: impl Into<ArticleId>,
153        data: &ArticlePost,
154    ) -> Result<ArticleId, Error> {
155        let id = id.into();
156        let rsp = self.0.post_raw(&format!("article/{}", id), data).await?;
157        take_article_id(&rsp)
158    }
159
160    /// 查询文章列表。
161    pub async fn list(
162        &self,
163        type_: ArticleListType,
164        page: u32,
165        size: u32,
166        tag: Option<&str>,
167    ) -> Result<ArticleList, Error> {
168        let path = match (tag.map(str::trim).filter(|v| !v.is_empty()), type_) {
169            (Some(tag), ArticleListType::Long) => format!("api/articles/tag/{}", tag),
170            (Some(tag), _) => format!("api/articles/tag/{}{}", tag, type_.to_code()),
171            (None, ArticleListType::Perfect) => {
172                return Err(Error::business(
173                    -1,
174                    "优选帖子列表需要指定标签,请使用 /api/articles/tag/<标签URI>/perfect",
175                ));
176            }
177            (None, _) => format!("api/articles/recent{}", type_.to_code()),
178        };
179        let url = build_http_path(
180            &path,
181            &[
182                ("p", page.to_string()),
183                ("size", size.to_string()),
184                ("apiKey", self.0.api_key().to_string()),
185            ],
186        );
187        let wire: WireArticleList = self.0.get_data(&url).await?;
188        Ok(wire.into())
189    }
190
191    /// 查询指定用户的文章列表。
192    pub async fn list_by_user(
193        &self,
194        user: impl Into<String>,
195        page: u32,
196        size: u32,
197    ) -> Result<ArticleList, Error> {
198        let user = user.into();
199        let url = build_http_path(
200            &format!("api/user/{}/articles", user),
201            &[
202                ("p", page.to_string()),
203                ("size", size.to_string()),
204                ("apiKey", self.0.api_key().to_string()),
205            ],
206        );
207        let wire: WireArticleList = self.0.get_data(&url).await?;
208        Ok(wire.into())
209    }
210
211    /// 获取文章详情,`p` 为评论页码。
212    pub async fn detail(&self, id: impl Into<ArticleId>, p: u32) -> Result<ArticleDetail, Error> {
213        let id = id.into();
214        let url = build_http_path(
215            &format!("api/article/{}", id),
216            &[
217                ("p", p.to_string()),
218                ("apiKey", self.0.api_key().to_string()),
219            ],
220        );
221        let rsp = self.0.get_raw(&url).await?;
222        let data = &rsp["data"];
223        let wire: WireArticleDetail = serde_json::from_value(data["article"].clone())
224            .map_err(|e| Error::decode(e.to_string()))?;
225        let mut detail: ArticleDetail = wire.into();
226        let wire_pagination: WirePagination =
227            serde_json::from_value(data["pagination"].clone()).unwrap_or_default();
228        detail.pagination = Some(Pagination::from(wire_pagination));
229        Ok(detail)
230    }
231
232    /// 获取文章 Markdown 原文。
233    pub async fn markdown_source(&self, id: impl Into<ArticleId>) -> Result<String, Error> {
234        let id = id.into();
235        self.0
236            .get_text(&self.0.with_key(&format!("api/article/md/{}", id)))
237            .await
238    }
239}
240
241fn take_article_id(rsp: &Value) -> Result<ArticleId, Error> {
242    rsp["articleId"]
243        .as_str()
244        .map(ArticleId::from)
245        .ok_or_else(|| Error::decode("Missing articleId in response"))
246}
247
248impl ArticleApi {
249    /// 查询当前用户的文章草稿列表。
250    pub async fn list_drafts(&self) -> Result<Vec<ArticleDraftSummary>, Error> {
251        let url = build_http_path(
252            "api/article-drafts",
253            &[("apiKey", self.0.api_key().to_string())],
254        );
255        let wire: WireArticleDraftList = self.0.get_data(&url).await?;
256        Ok(wire
257            .drafts
258            .into_iter()
259            .map(ArticleDraftSummary::from)
260            .collect())
261    }
262
263    /// 新建或更新当前用户的文章草稿。
264    pub async fn save_draft(&self, data: &ArticleDraftSave) -> Result<ArticleDraftSummary, Error> {
265        let wire: WireArticleDraftSummaryEnvelope =
266            self.0.post_data("api/article-drafts", data).await?;
267        Ok(wire.draft.into())
268    }
269
270    /// 查询指定文章草稿详情。
271    pub async fn draft_detail(&self, id: impl Into<String>) -> Result<ArticleDraftDetail, Error> {
272        let id = id.into();
273        let url = build_http_path(
274            &format!("api/article-drafts/{}", id),
275            &[("apiKey", self.0.api_key().to_string())],
276        );
277        let wire: WireArticleDraftEnvelope = self.0.get_data(&url).await?;
278        Ok(wire.draft.into())
279    }
280
281    /// 删除指定文章草稿,返回被删除草稿 Id。
282    pub async fn delete_draft(&self, id: impl Into<String>) -> Result<String, Error> {
283        let id = id.into();
284        let url = build_http_path(
285            &format!("api/article-drafts/{}", id),
286            &[("apiKey", self.0.api_key().to_string())],
287        );
288        let rsp = self.0.send_raw(Method::DELETE, &url, None).await?;
289        if rsp.get("code").and_then(Value::as_i64).unwrap_or(-1) != 0 {
290            return Err(Error::business(
291                rsp.get("code").and_then(Value::as_i64).unwrap_or(-1),
292                rsp["msg"].as_str().unwrap_or("API error"),
293            ));
294        }
295        Ok(rsp["data"]["id"].as_str().unwrap_or(&id).to_string())
296    }
297
298    /// 点赞/点踩文章,返回是否点赞。
299    pub async fn vote(&self, id: impl Into<ArticleId>, like: bool) -> Result<bool, Error> {
300        let id = id.into();
301        let url = format!("vote/{}/article", if like { "up" } else { "down" });
302        let rsp = self
303            .0
304            .post_raw(&url, &json!({ "dataId": id.as_str() }))
305            .await?;
306        Ok(rsp.get("type").and_then(Value::as_i64) == Some(-1))
307    }
308
309    /// 感谢文章。
310    pub async fn thank(&self, id: impl Into<ArticleId>) -> Result<(), Error> {
311        let url = build_http_path("article/thank", &[("articleId", id.into().into_string())]);
312        self.0.post_raw(&url, &json!({})).await?;
313        Ok(())
314    }
315
316    /// 收藏文章。
317    pub async fn follow(&self, id: impl Into<ArticleId>) -> Result<(), Error> {
318        let id = id.into();
319        self.0
320            .post_raw("follow/article", &json!({ "followingId": id.as_str() }))
321            .await?;
322        Ok(())
323    }
324
325    /// 取消收藏文章。
326    pub async fn unfollow(&self, id: impl Into<ArticleId>) -> Result<(), Error> {
327        let id = id.into();
328        self.0
329            .post_raw("unfollow/article", &json!({ "followingId": id.as_str() }))
330            .await?;
331        Ok(())
332    }
333
334    /// 关注/取消关注文章。
335    pub async fn watch(&self, following_id: impl Into<ArticleId>) -> Result<(), Error> {
336        let following_id = following_id.into();
337        self.0
338            .post_raw(
339                "follow/article-watch",
340                &json!({ "followingId": following_id.as_str() }),
341            )
342            .await?;
343        Ok(())
344    }
345
346    /// 打赏文章。
347    pub async fn reward(&self, id: impl Into<ArticleId>) -> Result<(), Error> {
348        let url = build_http_path("article/reward", &[("articleId", id.into().into_string())]);
349        self.0.post_raw(&url, &json!({})).await?;
350        Ok(())
351    }
352
353    /// 获取文章在线人数。
354    pub async fn heat(&self, id: impl Into<ArticleId>) -> Result<u32, Error> {
355        let id = id.into();
356        let rsp = self
357            .0
358            .post_raw(&format!("api/article/heat/{}", id), &json!({}))
359            .await?;
360        let heat = rsp
361            .get("articleHeat")
362            .or_else(|| rsp.get("data").and_then(|d| d.get("articleHeat")))
363            .and_then(Value::as_u64)
364            .ok_or_else(|| Error::decode("Missing heat data in response"))?;
365        Ok(heat as u32)
366    }
367
368    /// 建立文章频道长连接(在线人数、评论等实时推送),返回连接句柄。
369    pub async fn connect(
370        &self,
371        id: impl Into<ArticleId>,
372        article_type: ArticleType,
373    ) -> Result<ArticleConnection, Error> {
374        let url = build_ws_url(
375            self.0.domain(),
376            "article-channel",
377            &[
378                ("articleId", id.into().into_string()),
379                ("articleType", (article_type as u8).to_string()),
380                ("apiKey", self.0.api_key().to_string()),
381            ],
382        )
383        .map_err(Error::from)?;
384        let handler = ArticleHandler::new(parse_article_message, None, "article");
385        let mut connection = WsConnection::new();
386        connection
387            .connect(false, &url, handler.clone())
388            .await
389            .map_err(Error::from)?;
390        Ok(ArticleConnection {
391            connection,
392            handler,
393            url,
394        })
395    }
396}
397
398/// 文章频道长连接:监听原始推送、断开重连。
399pub struct ArticleConnection {
400    connection: WsConnection,
401    handler: ArticleHandler,
402    url: String,
403}
404
405impl ArticleConnection {
406    /// 监听文章频道推送(原始 JSON)。
407    pub async fn on_message<F>(&self, listener: F)
408    where
409        F: Fn(Value) + Send + Sync + 'static,
410    {
411        self.handler
412            .get_emitter()
413            .add_listener(ArticleEventKind::Message, listener)
414            .await;
415    }
416
417    /// 重连。
418    pub async fn reconnect(&mut self) -> Result<(), Error> {
419        self.connection
420            .reconnect(&self.url, self.handler.clone())
421            .await
422            .map_err(Error::from)
423    }
424
425    /// 设置重连策略。
426    pub fn set_retry_policy(&mut self, policy: RetryPolicy) {
427        self.connection.set_retry_policy(policy);
428    }
429
430    /// 设置日志钩子。
431    pub fn set_log_hook<F>(&mut self, hook: F)
432    where
433        F: Fn(&str) + Send + Sync + 'static,
434    {
435        let hook = Arc::new(hook) as WsLogHook;
436        self.connection.set_log_hook_arc(hook.clone());
437        self.handler.set_log_hook_arc(hook);
438    }
439
440    /// 断开连接。
441    pub fn disconnect(&mut self) {
442        self.connection.disconnect();
443    }
444}