Skip to main content

fishpi_sdk/client/
user.rs

1//! 用户域方法。
2
3use serde_json::{Value, json};
4
5use super::core::FishPi;
6use crate::domain::user::{AtUser, UserInfo, UserLite, UserPoint, UserVipInfo};
7use crate::ids::UserName;
8use crate::model::user::UserProfileUpdate;
9use crate::utils::error::Error;
10use crate::wire::user::{
11    WireAtUser, WireLiveness, WireUserInfo, WireUserLite, WireUserPoint, WireUserVipInfo,
12};
13
14/// 用户域访问器。
15pub struct UserApi(pub(crate) FishPi);
16
17impl FishPi {
18    /// 用户域。
19    pub fn user(&self) -> UserApi {
20        UserApi(self.clone())
21    }
22}
23
24impl UserApi {
25    /// 登录账户信息。
26    pub async fn info(&self) -> Result<UserInfo, Error> {
27        let wire: WireUserInfo = self.0.get_data(&self.0.with_key("api/user")).await?;
28        Ok(wire.into())
29    }
30
31    /// 获取其他用户信息。
32    pub async fn profile(&self, username: impl Into<UserName>) -> Result<UserInfo, Error> {
33        let username = username.into();
34        let path = self.0.with_key(&format!("user/{username}"));
35        let value = self.0.get_raw(&path).await?;
36        let wire: WireUserInfo =
37            serde_json::from_value(value).map_err(|e| Error::decode(e.to_string()))?;
38        Ok(wire.into())
39    }
40
41    /// 用户积分。
42    pub async fn points(&self, username: impl Into<UserName>) -> Result<UserPoint, Error> {
43        let username = username.into();
44        let wire: WireUserPoint = self.0.get_data(&format!("user/{username}/point")).await?;
45        Ok(wire.into())
46    }
47
48    /// 常用表情列表。
49    pub async fn emotions(&self) -> Result<Vec<String>, Error> {
50        let items: Vec<Value> = self.0.get_data(&self.0.with_key("users/emotions")).await?;
51        Ok(items
52            .into_iter()
53            .filter_map(|v| {
54                v.as_object()
55                    .and_then(|obj| obj.values().next())
56                    .and_then(Value::as_str)
57                    .map(str::to_string)
58            })
59            .collect())
60    }
61
62    /// 当前活跃度(请至少 10 分钟一次)。
63    pub async fn liveness(&self) -> Result<f64, Error> {
64        let wire: WireLiveness = {
65            let value = self.0.get_raw(&self.0.with_key("user/liveness")).await?;
66            serde_json::from_value(value).map_err(|e| Error::decode(e.to_string()))?
67        };
68        Ok(wire.liveness.max(0.0))
69    }
70
71    /// 是否已签到。
72    pub async fn is_checkin(&self) -> Result<bool, Error> {
73        let value = self.0.get_raw(&self.0.with_key("user/checkedIn")).await?;
74        Ok(value
75            .get("checkedIn")
76            .and_then(Value::as_bool)
77            .unwrap_or(false))
78    }
79
80    /// 是否已领取昨日活跃奖励。
81    pub async fn is_collected_liveness(&self) -> Result<bool, Error> {
82        let value = self
83            .0
84            .get_raw(&self.0.with_key("api/activity/is-collected-liveness"))
85            .await?;
86        value
87            .get("isCollectedYesterdayLivenessReward")
88            .and_then(Value::as_bool)
89            .ok_or_else(|| Error::decode("Missing isCollectedYesterdayLivenessReward"))
90    }
91
92    /// 领取昨日活跃度奖励,返回获得积分。
93    pub async fn reward_liveness(&self) -> Result<i32, Error> {
94        let value = self
95            .0
96            .get_raw(&self.0.with_key("activity/yesterday-liveness-reward-api"))
97            .await?;
98        value
99            .get("sum")
100            .and_then(Value::as_i64)
101            .map(|n| n as i32)
102            .ok_or_else(|| Error::decode("Missing liveness reward sum"))
103    }
104
105    /// 转账。
106    pub async fn transfer(
107        &self,
108        username: impl Into<UserName>,
109        amount: u32,
110        memo: impl Into<String>,
111    ) -> Result<(), Error> {
112        let body = json!({
113            "userName": username.into().as_str(),
114            "amount": amount,
115            "memo": memo.into(),
116            "apiKey": self.0.api_key().as_str(),
117        });
118        self.0.post_raw("point/transfer", &body).await?;
119        Ok(())
120    }
121
122    /// 关注用户。
123    pub async fn follow(&self, following_id: impl Into<UserName>) -> Result<(), Error> {
124        let body = json!({
125            "followingId": following_id.into().as_str(),
126            "apiKey": self.0.api_key().as_str(),
127        });
128        self.0.post_raw("follow/user", &body).await?;
129        Ok(())
130    }
131
132    /// 取消关注用户。
133    pub async fn unfollow(&self, following_id: impl Into<UserName>) -> Result<(), Error> {
134        let body = json!({
135            "followingId": following_id.into().as_str(),
136            "apiKey": self.0.api_key().as_str(),
137        });
138        self.0.post_raw("unfollow/user", &body).await?;
139        Ok(())
140    }
141
142    /// 获取用户勋章原始列表。
143    pub async fn medals(&self, username: impl Into<UserName>) -> Result<Value, Error> {
144        let body = json!({
145            "apiKey": self.0.api_key().as_str(),
146            "userName": username.into().as_str(),
147        });
148        let value = self.0.post_raw("api/medal/user/list", &body).await?;
149        Ok(value
150            .get("data")
151            .cloned()
152            .unwrap_or(Value::Array(Vec::new())))
153    }
154
155    /// 修改头像。
156    pub async fn update_avatar(&self, avatar_url: impl Into<String>) -> Result<(), Error> {
157        let body = json!({
158            "userAvatarURL": avatar_url.into(),
159            "apiKey": self.0.api_key().as_str(),
160        });
161        self.0.post_raw("api/settings/avatar", &body).await?;
162        Ok(())
163    }
164
165    /// 修改用户资料。
166    pub async fn update_profile(&self, params: impl Into<UserProfileUpdate>) -> Result<(), Error> {
167        let params = params.into();
168        let body = json!({
169            "userNickname": params.nickname,
170            "userURL": params.url,
171            "userIntro": params.intro,
172            "userTag": params.tags,
173            "mbti": params.mbti,
174            "apiKey": self.0.api_key().as_str(),
175        });
176        self.0.post_raw("api/settings/profiles", &body).await?;
177        Ok(())
178    }
179
180    /// 用户名联想。
181    pub async fn names(&self, name: impl Into<String>) -> Result<Vec<AtUser>, Error> {
182        let body = json!({ "name": name.into() });
183        let wire: Vec<WireAtUser> = self.0.post_data("users/names", &body).await?;
184        Ok(wire.into_iter().map(AtUser::from).collect())
185    }
186
187    /// 最近注册的 20 个用户。
188    pub async fn recent_register(&self) -> Result<Vec<UserLite>, Error> {
189        let wire: Vec<WireUserLite> = self.0.get_data("api/user/recentReg").await?;
190        Ok(wire.into_iter().map(UserLite::from).collect())
191    }
192
193    /// 用户 VIP 信息。
194    pub async fn vip_info(&self, user_id: impl AsRef<str>) -> Result<UserVipInfo, Error> {
195        let path = format!("api/membership/{}", user_id.as_ref());
196        let value = self.0.get_raw(&path).await?;
197        let assembled = assemble_vip(&value);
198        let wire: WireUserVipInfo =
199            serde_json::from_value(assembled).map_err(|e| Error::decode(e.to_string()))?;
200        Ok(wire.into())
201    }
202}
203
204/// 组装 `configJson` 与外层字段。
205fn assemble_vip(rsp: &Value) -> Value {
206    let data = match rsp.get("data").and_then(Value::as_object) {
207        Some(d) => d,
208        None => return json!({}),
209    };
210
211    let config_json_str = data
212        .get("configJson")
213        .and_then(Value::as_str)
214        .unwrap_or("null");
215    let mut assembled: Value = serde_json::from_str(config_json_str).unwrap_or_else(|_| json!({}));
216
217    if let Some(map) = assembled.as_object_mut() {
218        map.insert(
219            "state".to_string(),
220            data.get("state").cloned().unwrap_or(Value::Null),
221        );
222        if data.get("state").and_then(Value::as_i64).unwrap_or(0) == 1 {
223            for key in [
224                "oId",
225                "userId",
226                "lvCode",
227                "expiresAt",
228                "createdAt",
229                "updatedAt",
230            ] {
231                map.insert(
232                    key.to_string(),
233                    data.get(key).cloned().unwrap_or(Value::Null),
234                );
235            }
236        }
237    }
238    assembled
239}