fishpi-sdk 0.1.7

A Rust SDK for interacting with the FishPi community API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use crate::impl_str_enum;
use crate::model::reaction::ReactionSummaryItem;
use crate::model::user::{Metal, to_metal};
use crate::utils::error::Error;
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use std::str::FromStr;

#[derive(Clone, Debug)]
pub enum ClientType {
    /// 网页端
    Web,
    /// PC 端
    PC,
    /// 移动端聊天室
    Mobile,
    /// Windows 客户端
    Windows,
    /// macOS 客户端
    MacOs,
    /// Linux 客户端
    Linux,
    /// iOS 客户端
    Ios,
    /// Android 客户端
    Android,
    /// IDEA 插件
    Idea,
    /// Chrome 插件
    Chrome,
    /// Edge 插件
    Edge,
    /// VSCode 插件
    VSCode,
    /// Python 客户端
    Python,
    /// Golang 客户端
    Golang,
    /// Rust 客户端
    Rust,
    /// Harmony App
    Harmony,
    /// CLI 工具
    Cli,
    /// 鸽机器人
    Bird,
    /// 小冰机器人
    IceNet,
    /// 凌机器人
    ElvesOnline,
    /// 其他插件
    Other,
}

pub enum ChatContentType {
    Markdown,
    Html,
}

/// chatroom get 接口获取 oId 的相关消息类型
#[repr(u8)]
pub enum ChatRoomMessageMode {
    ///前后消息
    Context = 0,
    /// 前面的消息
    Before = 1,
    /// 后面的消息
    After = 2,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ChatRoomMessageType {
    /// 在线用户
    Online,
    /// 话题修改
    DiscussChanged,
    /// 消息撤回
    Revoke,
    /// 消息
    Msg,
    /// 红包
    RedPacket,
    /// 红包状态
    RedPacketStatus,
    /// 弹幕
    Barrager,
    /// 进出场消息
    Custom,
    /// 聊天室表态/反应
    ChatReaction,
}

#[derive(Clone, Debug)]
pub struct CustomMsg {
    pub message: String,
}
pub struct DiscussMsg;

#[derive(Clone, Debug)]
pub struct RevokeMsg {
    pub msg: String,
}

#[derive(Clone, Debug, Default, Deserialize)]
#[allow(non_snake_case)]
pub struct ChatReactionMsg {
    /// 目标聊天室消息 ID。
    #[serde(default)]
    pub oId: String,
    /// 目标类型。
    #[serde(default)]
    pub targetType: String,
    /// Reaction 分组。
    #[serde(default)]
    pub groupType: String,
    /// 该聊天消息最新的表情汇总。
    #[serde(default)]
    pub summary: Vec<ReactionSummaryItem>,
    /// 本次触发操作的用户 id。
    #[serde(default)]
    pub actorUserId: String,
    /// 该用户本次操作后最终选中的表情值。
    #[serde(default)]
    pub actorReaction: String,
    /// 保留原始数据,方便服务端字段扩展时客户端不丢信息。
    #[serde(skip)]
    pub raw: Value,
}

impl ChatReactionMsg {
    pub fn from_value(value: &Value) -> Result<Self, Error> {
        let mut msg: Self = serde_json::from_value(value.clone())
            .map_err(|e| Error::Parse(format!("Failed to parse ChatReactionMsg: {}", e)))?;
        msg.raw = value.clone();
        Ok(msg)
    }
}

#[derive(Clone, Debug)]
pub struct BarragerCost {
    pub cost: u32,
    pub unit: String,
}

// /// 聊天天气消息
// pub struct WeatherMessage {
//     city: String,
//     description: String,
//     data: WeatherData,
// }

/// 聊天天气消息详情
pub struct WeatherData {
    pub date: String,
    pub code: WeatherCode,
    pub min: String,
    pub max: String,
}

/// 消息来源
pub struct ChatRoomSource {
    pub client: String,
    pub version: String,
}

#[derive(Clone, Debug)]
pub enum WeatherCode {
    ClearDay,
    ClearNight,
    Cloudy,
    Dust,
    Fog,
    HeavyHaze,
    HeavyRain,
    HeavySnow,
    LightHaze,
    LightRain,
    LightSnow,
    ModerateHaze,
    ModerateRain,
    ModerateSnow,
    PartlyCloudyDay,
    PartlyCloudyNight,
    Sand,
    StormRain,
    StormSnow,
    Wind,
}

/// 聊天消息
#[derive(Clone, Debug)]
#[allow(non_snake_case)]
pub struct ChatRoomMsg<T = Value> {
    pub r#type: ChatRoomMessageType,
    pub oId: String,
    pub time: String,
    pub userOId: String,
    pub userName: String,
    pub userNickname: String,
    pub userAvatarURL: String,
    pub sysMetal: Vec<Metal>,
    pub content: T,
    pub md: String,
    pub client: String,
    pub via: ClientType,
    pub reactionSummary: Vec<ReactionSummaryItem>,
    pub currentUserReaction: String,
}

#[derive(Clone, Debug, Deserialize)]
#[allow(non_snake_case)]
pub struct BarragerMsg {
    /// 用户名
    pub userName: String,
    /// 用户昵称
    pub userNickname: String,
    /// 弹幕消息
    pub barragerContent: String,
    /// 弹幕颜色
    pub barragerColor: String,
    /// 用户头像地址
    pub userAvatarURL: String,
    /// 头像地址20x20
    pub userAvatarURL200: String,
    /// 头像地址48x48
    pub userAvatarURL48: String,
    /// 头像地址100x100
    pub userAvatarURL210: String,
}

/// 在线用户信息
#[derive(Clone, Debug)]
#[allow(non_snake_case)]
pub struct OnlineInfo {
    /// 用户首页
    pub homePage: String,
    /// 用户头像
    pub userAvatarURL: String,
    /// 用户名
    pub userName: String,
}

impl_str_enum!(ClientType {
    Web => "Web",
    PC => "PC",
    Mobile => "Mobile",
    Windows => "Windows",
    MacOs => "macOS",
    Linux => "Linux",
    Ios => "iOS",
    Android => "Android",
    Idea => "IDEA",
    Chrome => "Chrome",
    Edge => "Edge",
    VSCode => "VSCode",
    Python => "Python",
    Golang => "Golang",
    Rust => "Rust",
    Harmony => "Harmony",
    Cli => "CLI",
    Bird => "Bird",
    IceNet => "IceNet",
    ElvesOnline => "ElvesOnline",
    Other => "Other",
});

impl_str_enum!(ChatContentType {
    Markdown => "Markdown",
    Html => "Html",
});

impl_str_enum!(ChatRoomMessageType {
    Online => "online",
    DiscussChanged => "discussChanged",
    Revoke => "revoke",
    Msg => "msg",
    RedPacket => "redPacket",
    RedPacketStatus => "redPacketStatus",
    Barrager => "barrager",
    Custom => "customMessage",
    ChatReaction => "chatreaction",
});

impl_str_enum!(WeatherCode {
    ClearDay => "CLEAR_DAY",
    ClearNight => "CLEAR_NIGHT",
    Cloudy => "CLOUDY",
    Dust => "DUST",
    Fog => "FOG",
    HeavyHaze => "HEAVY_HAZE",
    HeavyRain => "HEAVY_RAIN",
    HeavySnow => "HEAVY_SNOW",
    LightHaze => "LIGHT_HAZE",
    LightRain => "LIGHT_RAIN",
    LightSnow => "LIGHT_SNOW",
    ModerateHaze => "MODERATE_HAZE",
    ModerateRain => "MODERATE_RAIN",
    ModerateSnow => "MODERATE_SNOW",
    PartlyCloudyDay => "PARTLY_CLOUDY_DAY",
    PartlyCloudyNight => "PARTLY_CLOUDY_NIGHT",
    Sand => "SAND",
    StormRain => "STORM_RAIN",
    StormSnow => "STORM_SNOW",
    Wind => "WIND",
});

impl_str_enum!(ChatRoomMessageMode{
    Context => "0",
    Before => "1",
    After => "2",
});

impl Default for ChatRoomSource {
    fn default() -> Self {
        Self {
            client: "Other".to_string(),
            version: "latest".to_string(),
        }
    }
}

impl ChatRoomMsg {
    pub fn from_value(value: &Value) -> Result<Self, Error> {
        serde_json::from_value(value.clone())
            .map_err(|e| Error::Parse(format!("Failed to parse ChatRoomMsg: {}", e)))
    }

    pub fn name(&self) -> &str {
        if self.userNickname.is_empty() {
            &self.userName
        } else {
            &self.userNickname
        }
    }
}

impl BarragerMsg {
    pub fn from_value(value: &Value) -> Result<Self, Error> {
        serde_json::from_value(value.clone())
            .map_err(|e| Error::Parse(format!("Failed to parse BarragerMsg: {}", e)))
    }
}

fn parse_content(content: &str) -> (ChatRoomMessageType, Value) {
    if let Ok(data) = serde_json::from_str::<Value>(content) {
        if let Some(msg_type_str) = data["msgType"].as_str() {
            match msg_type_str {
                "redPacket" => (ChatRoomMessageType::RedPacket, data),
                "music" => (ChatRoomMessageType::Msg, data),
                "weather" => (ChatRoomMessageType::Msg, data),
                _ => (ChatRoomMessageType::Msg, Value::String(content.to_string())),
            }
        } else {
            (ChatRoomMessageType::Msg, Value::String(content.to_string()))
        }
    } else {
        (ChatRoomMessageType::Msg, Value::String(content.to_string()))
    }
}

impl<'de> Deserialize<'de> for ChatRoomMsg<Value> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[allow(non_snake_case)]
        struct Raw {
            oId: String,
            time: String,
            userOId: Value,
            userName: String,
            userNickname: String,
            userAvatarURL: String,
            sysMetal: Option<Value>,
            content: String,
            md: Option<String>,
            client: Option<String>,
            #[serde(default)]
            reactionSummary: Option<Vec<ReactionSummaryItem>>,
            #[serde(default)]
            currentUserReaction: Option<String>,
        }

        let raw = Raw::deserialize(deserializer)?;

        let (r#type, content) = parse_content(&raw.content);

        let via = raw
            .client
            .as_ref()
            .and_then(|s| ClientType::from_str(s).ok())
            .unwrap_or(ClientType::Other);
        let client = raw.client.unwrap_or(ClientType::Rust.as_str().to_string());

        let sys_metal = raw
            .sysMetal
            .as_ref()
            .and_then(|v| v.as_str())
            .map(|s| to_metal(s))
            .unwrap_or(Ok(vec![]))
            .unwrap_or(vec![]);

        Ok(ChatRoomMsg {
            r#type,
            oId: raw.oId,
            time: raw.time,
            userOId: raw.userOId.to_string(),
            userName: raw.userName,
            userNickname: raw.userNickname,
            userAvatarURL: raw.userAvatarURL,
            sysMetal: sys_metal,
            content,
            md: raw.md.unwrap_or("".to_string()),
            client,
            via,
            reactionSummary: raw.reactionSummary.unwrap_or_default(),
            currentUserReaction: raw.currentUserReaction.unwrap_or_default(),
        })
    }
}

impl BarragerCost {
    pub fn from_value(value: &Value) -> Self {
        let content = value
            .get("data")
            .and_then(|v| v.as_str())
            .unwrap_or("5积分");
        let mut parts = content
            .split(|c: char| !c.is_alphanumeric())
            .filter(|s| !s.is_empty());
        let cost = parts
            .next()
            .and_then(|s| s.parse::<u32>().ok())
            .unwrap_or(0);
        let unit = parts.next().unwrap_or("积分").to_string();

        Self { cost, unit }
    }
}