Skip to main content

fishpi_sdk/domain/
user.rs

1//! 用户相关的干净对外类型。
2
3use chrono::{DateTime, Utc};
4
5use crate::ids::{UserId, UserName};
6use crate::wire::user::{
7    WireAtUser, WireMetal, WireUserInfo, WireUserLite, WireUserPoint, WireUserVipInfo,
8};
9
10const DOMAIN: &str = "fishpi.cn";
11
12/// 用户 App 角色。
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
14pub enum UserAppRole {
15    /// 黑客
16    #[default]
17    Hack,
18    /// 画家
19    Artist,
20}
21
22impl From<&str> for UserAppRole {
23    fn from(value: &str) -> Self {
24        match value.trim() {
25            "1" => UserAppRole::Artist,
26            _ => UserAppRole::Hack,
27        }
28    }
29}
30
31/// 勋章 attr。
32#[derive(Clone, Debug)]
33pub enum MetalAttr {
34    Attr {
35        url: String,
36        backcolor: String,
37        fontcolor: String,
38        ver: f32,
39        scale: f32,
40    },
41    Raw(String),
42}
43
44/// 一枚勋章。
45#[derive(Clone, Debug)]
46pub struct Metal {
47    pub attr: MetalAttr,
48    pub name: String,
49    pub description: String,
50    pub data: String,
51    /// 完整徽章地址(含文字)
52    pub url: String,
53    /// 徽章地址(不含文字)
54    pub icon: String,
55    /// 是否佩戴
56    pub enabled: bool,
57}
58
59fn analyze_metal_attr(attr_str: &str) -> MetalAttr {
60    if attr_str.is_empty() {
61        return MetalAttr::Raw(String::new());
62    }
63    let mut url = String::new();
64    let mut backcolor = String::new();
65    let mut fontcolor = String::new();
66    let mut ver = 1.0_f32;
67    let mut scale = 0.79_f32;
68    for pair in attr_str.split('&') {
69        let mut parts = pair.split('=');
70        if let (Some(key), Some(value)) = (parts.next(), parts.next()) {
71            match key {
72                "url" => url = value.to_string(),
73                "backcolor" => backcolor = value.to_string(),
74                "fontcolor" => fontcolor = value.to_string(),
75                "ver" => ver = value.parse().unwrap_or(1.0),
76                "scale" => scale = value.parse().unwrap_or(0.79),
77                _ => {}
78            }
79        }
80    }
81    if url.is_empty() && backcolor.is_empty() && fontcolor.is_empty() {
82        MetalAttr::Raw(attr_str.to_string())
83    } else {
84        MetalAttr::Attr {
85            url,
86            backcolor,
87            fontcolor,
88            ver,
89            scale,
90        }
91    }
92}
93
94fn metal_url(attr: &MetalAttr, name: &str, include_text: bool) -> String {
95    let attr_str = match attr {
96        MetalAttr::Attr {
97            backcolor,
98            fontcolor,
99            ver,
100            scale,
101            ..
102        } => format!("ver={ver}&scale={scale}&backcolor={backcolor}&fontcolor={fontcolor}"),
103        MetalAttr::Raw(s) => s.clone(),
104    };
105    let text = if include_text { name } else { "" };
106    format!("https://{DOMAIN}/gen?txt={text}&{attr_str}")
107}
108
109impl From<WireMetal> for Metal {
110    fn from(w: WireMetal) -> Self {
111        let attr = analyze_metal_attr(&w.attr);
112        let url = metal_url(&attr, &w.name, true);
113        let icon = metal_url(&attr, &w.name, false);
114        Metal {
115            attr,
116            name: w.name,
117            description: w.description,
118            data: w.data,
119            url,
120            icon,
121            enabled: w.enabled,
122        }
123    }
124}
125
126/// 用户信息。
127#[derive(Clone, Debug)]
128#[non_exhaustive]
129pub struct UserInfo {
130    /// 用户 ID(`oId`)
131    pub id: UserId,
132    /// 用户编号
133    pub user_no: String,
134    /// 用户名
135    pub username: UserName,
136    /// 用户昵称
137    pub nickname: String,
138    /// 首页地址
139    pub url: String,
140    /// 所在城市
141    pub city: String,
142    /// 签名
143    pub intro: String,
144    /// 是否在线
145    pub online: bool,
146    /// 用户积分
147    pub points: i32,
148    /// 用户组
149    pub role: String,
150    /// App 角色
151    pub app_role: UserAppRole,
152    /// 头像地址
153    pub avatar: String,
154    /// 卡片背景
155    pub card_bg: String,
156    /// 关注数
157    pub following: i32,
158    /// 粉丝数
159    pub follower: i32,
160    /// 在线时长(分钟)
161    pub online_minutes: i32,
162    /// 是否可关注(`no`=已关注,未登录可能 `hide`)
163    pub can_follow: String,
164    /// 佩戴/持有的勋章
165    pub metals: Vec<Metal>,
166}
167
168impl UserInfo {
169    /// 展示名:优先昵称,空则用户名。
170    pub fn display_name(&self) -> &str {
171        if self.nickname.is_empty() {
172            self.username.as_str()
173        } else {
174            &self.nickname
175        }
176    }
177}
178
179impl From<WireUserInfo> for UserInfo {
180    fn from(w: WireUserInfo) -> Self {
181        UserInfo {
182            id: UserId::new(w.o_id),
183            user_no: w.user_no,
184            username: UserName::new(w.user_name),
185            nickname: w.user_nickname,
186            url: w.user_url,
187            city: w.user_city,
188            intro: w.user_intro,
189            online: w.user_online_flag,
190            points: w.user_point,
191            role: w.user_role,
192            app_role: UserAppRole::from(w.user_app_role.as_str()),
193            avatar: w.user_avatar_url,
194            card_bg: w.card_bg,
195            following: w.following_user_count,
196            follower: w.follower_count,
197            online_minutes: w.online_minute,
198            can_follow: w.can_follow,
199            metals: w.sys_metal.into_iter().map(Metal::from).collect(),
200        }
201    }
202}
203
204/// 用户名联想项。
205#[derive(Clone, Debug)]
206pub struct AtUser {
207    pub username: UserName,
208    pub avatar: String,
209    pub username_lower: String,
210}
211
212impl From<WireAtUser> for AtUser {
213    fn from(w: WireAtUser) -> Self {
214        AtUser {
215            username: UserName::new(w.user_name),
216            avatar: w.user_avatar_url,
217            username_lower: w.user_name_lower_case,
218        }
219    }
220}
221
222/// 用户积分。
223#[derive(Clone, Debug)]
224pub struct UserPoint {
225    pub username: UserName,
226    pub point: u32,
227}
228
229impl From<WireUserPoint> for UserPoint {
230    fn from(w: WireUserPoint) -> Self {
231        UserPoint {
232            username: UserName::new(w.user_name),
233            point: w.user_point,
234        }
235    }
236}
237
238/// 最近注册用户。
239#[derive(Clone, Debug)]
240pub struct UserLite {
241    pub username: UserName,
242    pub nickname: String,
243}
244
245impl From<WireUserLite> for UserLite {
246    fn from(w: WireUserLite) -> Self {
247        UserLite {
248            username: UserName::new(w.user_name),
249            nickname: w.user_nickname,
250        }
251    }
252}
253
254/// 用户 VIP 信息。
255#[derive(Clone, Debug)]
256#[non_exhaustive]
257pub struct UserVipInfo {
258    pub joint_vip: bool,
259    pub color: String,
260    pub underline: bool,
261    pub metal: bool,
262    pub auto_checkin: u32,
263    pub bold: bool,
264    pub o_id: UserId,
265    pub state: bool,
266    pub user_id: UserId,
267    pub lv_code: String,
268    pub expires_at: u64,
269    pub created_at: u64,
270    pub updated_at: u64,
271}
272
273impl UserVipInfo {
274    /// 是否为 VIP。
275    pub fn is_vip(&self) -> bool {
276        self.state
277    }
278
279    /// 过期日期。
280    pub fn expires_date(&self) -> DateTime<Utc> {
281        DateTime::from_timestamp_millis(self.expires_at as i64).unwrap_or_default()
282    }
283
284    /// 创建日期。
285    pub fn created_date(&self) -> DateTime<Utc> {
286        DateTime::from_timestamp_millis(self.created_at as i64).unwrap_or_default()
287    }
288
289    /// 更新日期。
290    pub fn updated_date(&self) -> DateTime<Utc> {
291        DateTime::from_timestamp_millis(self.updated_at as i64).unwrap_or_default()
292    }
293
294    /// VIP 名称。
295    pub fn vip_name(&self) -> String {
296        self.lv_code
297            .replace("_YEAR", "(包年)")
298            .replace("_MONTH", "(包月)")
299    }
300}
301
302impl From<WireUserVipInfo> for UserVipInfo {
303    fn from(w: WireUserVipInfo) -> Self {
304        UserVipInfo {
305            joint_vip: w.joint_vip,
306            color: w.color,
307            underline: w.underline,
308            metal: w.metal,
309            auto_checkin: w.auto_checkin,
310            bold: w.bold,
311            o_id: w.o_id.into(),
312            state: w.state,
313            user_id: w.user_id.into(),
314            lv_code: w.lv_code,
315            expires_at: w.expires_at,
316            created_at: w.created_at,
317            updated_at: w.updated_at,
318        }
319    }
320}