bpi-rs 0.2.0

Bilibili API client library for Rust
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
#[cfg(test)]
use crate::fav::params::FavResourceIdsParams;
use crate::ids::MediaId;
use crate::{BpiError, BpiResult};
use serde::{Deserialize, Serialize};

// --- 获取收藏夹内容明细列表 ---

/// 收藏夹内容明细列表中的 UP 主信息
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FavListUpper {
    pub mid: u64,
    pub name: String,
    pub face: String,
    pub followed: Option<bool>,
    pub vip_type: Option<u8>,
    #[serde(alias = "vip_statue")]
    pub vip_status: Option<u8>,
}

/// 收藏夹内容明细列表中的状态数
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FavListCntInfo {
    /// 收藏
    pub collect: u64,
    /// 播放
    pub play: u64,

    /// 分享 (仅info)
    pub share: Option<u64>,
    /// 点赞 (仅info)
    pub thumb_up: Option<u64>,
    ///弹幕 (仅media)
    pub danmaku: Option<u64>,
    /// 播放文本 (仅media)
    pub view_text_1: Option<String>,
}

/// 收藏夹元数据
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FavListInfo {
    pub id: u64,
    pub fid: u64,
    pub mid: u64,
    pub attr: u32,
    pub title: String,
    pub cover: String,
    pub upper: FavListUpper,
    pub cover_type: u8,
    pub cnt_info: FavListCntInfo,
    #[serde(rename = "type")]
    pub type_name: u32,
    pub intro: String,
    pub ctime: u64,
    pub mtime: u64,
    pub state: u8,
    pub fav_state: u8,
    pub like_state: u8,
    pub media_count: u32,
}

/// 收藏夹中的单个内容
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FavListMedia {
    pub id: u64,
    #[serde(rename = "type")]
    pub type_name: u8,
    pub title: String,
    pub cover: String,
    pub intro: String,
    pub page: Option<u32>,
    pub duration: u32,
    pub upper: FavListUpper,
    pub attr: u8,
    pub cnt_info: FavListCntInfo,
    pub link: String,
    pub ctime: u64,
    pub pubtime: u64,
    pub fav_time: u64,
    pub bv_id: Option<String>,
    pub bvid: Option<String>,
    pub season: Option<serde_json::Value>,
}

/// 收藏夹内容明细列表数据
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FavListDetailData {
    pub info: FavListInfo,
    pub medias: Vec<FavListMedia>,
    pub has_more: bool,
    pub ttl: u64,
}

// --- 获取收藏夹全部内容id ---

/// 收藏夹全部内容ID列表中的单个ID
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FavResourceIdItem {
    pub id: u64,
    #[serde(rename = "type")]
    pub type_name: u8,
    pub bv_id: Option<String>,
    pub bvid: Option<String>,
}

/// Parameters for fetching a favorite folder's detailed resource list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FavListDetailParams {
    media_id: MediaId,
    tid: Option<u32>,
    keyword: Option<String>,
    order: Option<String>,
    typ: Option<u8>,
    ps: u32,
    pn: Option<u32>,
}

impl FavListDetailParams {
    /// Creates favorite-list detail parameters with the default page size.
    pub fn new(media_id: MediaId) -> Self {
        Self {
            media_id,
            tid: None,
            keyword: None,
            order: None,
            typ: None,
            ps: 20,
            pn: None,
        }
    }

    /// Sets the optional partition filter.
    pub fn tid(mut self, tid: u32) -> Self {
        self.tid = Some(tid);
        self
    }

    /// Sets the keyword filter.
    pub fn keyword(mut self, keyword: impl Into<String>) -> BpiResult<Self> {
        let keyword = keyword.into();
        validate_non_blank("keyword", &keyword)?;
        self.keyword = Some(keyword);
        Ok(self)
    }

    /// Sets the ordering key, such as `mtime`.
    pub fn order(mut self, order: impl Into<String>) -> BpiResult<Self> {
        let order = order.into();
        validate_non_blank("order", &order)?;
        self.order = Some(order);
        Ok(self)
    }

    /// Sets the content type filter.
    pub fn content_type(mut self, typ: u8) -> Self {
        self.typ = Some(typ);
        self
    }

    /// Sets the page size.
    pub fn page_size(mut self, ps: u32) -> BpiResult<Self> {
        if ps == 0 {
            return Err(BpiError::invalid_parameter(
                "ps",
                "page size must be non-zero",
            ));
        }
        self.ps = ps;
        Ok(self)
    }

    /// Sets the page number.
    pub fn page(mut self, pn: u32) -> BpiResult<Self> {
        if pn == 0 {
            return Err(BpiError::invalid_parameter(
                "pn",
                "page number must be non-zero",
            ));
        }
        self.pn = Some(pn);
        Ok(self)
    }

    pub(crate) fn query_pairs(&self) -> Vec<(&'static str, String)> {
        let mut params = vec![
            ("media_id", self.media_id.to_string()),
            ("ps", self.ps.to_string()),
            ("platform", "web".to_string()),
        ];

        if let Some(tid) = self.tid {
            params.push(("tid", tid.to_string()));
        }
        if let Some(keyword) = self.keyword.as_ref() {
            params.push(("keyword", keyword.clone()));
        }
        if let Some(order) = self.order.as_ref() {
            params.push(("order", order.clone()));
        }
        if let Some(typ) = self.typ {
            params.push(("type", typ.to_string()));
        }
        if let Some(pn) = self.pn {
            params.push(("pn", pn.to_string()));
        }

        params
    }
}

fn validate_non_blank(field: &'static str, value: &str) -> BpiResult<()> {
    if value.trim().is_empty() {
        return Err(BpiError::invalid_parameter(field, "value cannot be blank"));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ids::MediaId;
    use crate::probe::contract::HttpMethod;
    use crate::probe::endpoint_contract::EndpointContract;
    use crate::{ApiEnvelope, BpiClient, BpiResult};
    use tracing::info;

    fn contract(endpoint: &str) -> BpiResult<EndpointContract> {
        let bytes = match endpoint {
            "list-detail" => {
                include_bytes!("../../tests/contracts/fav/read/list-detail/contract.json")
                    .as_slice()
            }
            "resource-ids" => {
                include_bytes!("../../tests/contracts/fav/read/resource-ids/contract.json")
                    .as_slice()
            }
            _ => unreachable!("unknown fav list contract endpoint"),
        };

        EndpointContract::from_slice(bytes)
    }

    #[ignore = "legacy live API test; requires explicit BPI_LIVE_TEST review"]
    #[tokio::test]
    async fn test_get_fav_list_detail() {
        let bpi = BpiClient::new().expect("client should build");
        let media_id = 1052622027;
        let params = FavListDetailParams::new(MediaId::new(media_id).expect("media id is valid"))
            .order("mtime")
            .expect("order is valid")
            .content_type(0)
            .page_size(5)
            .expect("page size is valid")
            .page(1)
            .expect("page is valid");
        let resp = bpi.fav().list_detail(params).await;

        info!("{:?}", resp);
        assert!(resp.is_ok());

        let data = resp.unwrap();
        info!("has_more: {}", data.has_more);
        info!("total media count: {}", data.info.media_count);
        info!("retrieved media count: {}", data.medias.len());
        info!("first media item: {:?}", data.medias.first());
    }

    #[ignore = "legacy live API test; requires explicit BPI_LIVE_TEST review"]
    #[tokio::test]
    async fn test_get_fav_resource_ids() {
        let bpi = BpiClient::new().expect("client should build");
        let params = FavResourceIdsParams::new(
            MediaId::new(1052622027).expect("fixture media id should be valid"),
        );
        let resp = bpi.fav().resource_ids(params).await;

        info!("{:?}", resp);
        assert!(resp.is_ok());

        let data = resp.unwrap();
        info!("total IDs retrieved: {}", data.len());
        info!("first ID item: {:?}", data.first());
    }

    #[test]
    fn fav_list_detail_params_serializes_required_query() -> Result<(), BpiError> {
        let params = FavListDetailParams::new(MediaId::new(1052622027)?);

        assert_eq!(
            params.query_pairs(),
            vec![
                ("media_id", "1052622027".to_string()),
                ("ps", "20".to_string()),
                ("platform", "web".to_string())
            ]
        );
        Ok(())
    }

    #[test]
    fn fav_list_detail_params_serializes_optional_query() -> Result<(), BpiError> {
        let params = FavListDetailParams::new(MediaId::new(1052622027)?)
            .tid(3)
            .keyword("rust")?
            .order("mtime")?
            .content_type(0)
            .page_size(5)?
            .page(1)?;

        assert_eq!(
            params.query_pairs(),
            vec![
                ("media_id", "1052622027".to_string()),
                ("ps", "5".to_string()),
                ("platform", "web".to_string()),
                ("tid", "3".to_string()),
                ("keyword", "rust".to_string()),
                ("order", "mtime".to_string()),
                ("type", "0".to_string()),
                ("pn", "1".to_string())
            ]
        );
        Ok(())
    }

    #[test]
    fn fav_list_detail_params_rejects_zero_page_size() {
        let err = FavListDetailParams::new(MediaId::new(1052622027).expect("media id is valid"))
            .page_size(0)
            .unwrap_err();

        assert!(matches!(
            err,
            BpiError::InvalidParameter { field: "ps", .. }
        ));
    }

    #[test]
    fn fav_list_detail_contract_matches_endpoint_request() -> BpiResult<()> {
        let contract = contract("list-detail")?;

        assert_eq!(contract.name, "fav.list_detail");
        assert_eq!(contract.request.method, HttpMethod::Get);
        assert_eq!(
            contract.request.url.as_str(),
            "https://api.bilibili.com/x/v3/fav/resource/list"
        );
        assert_eq!(
            contract.request.query.get("media_id").map(String::as_str),
            Some("1052622027")
        );
        assert_eq!(
            contract.request.query.get("platform").map(String::as_str),
            Some("web")
        );
        assert_eq!(contract.cases.len(), 3);
        assert_eq!(
            contract.cases[0].response.rust_model.as_deref(),
            Some("FavListDetailData")
        );
        Ok(())
    }

    #[test]
    fn fav_resource_ids_contract_matches_endpoint_request() -> BpiResult<()> {
        let contract = contract("resource-ids")?;

        assert_eq!(contract.name, "fav.resource_ids");
        assert_eq!(contract.request.method, HttpMethod::Get);
        assert_eq!(
            contract.request.url.as_str(),
            "https://api.bilibili.com/x/v3/fav/resource/ids"
        );
        assert_eq!(
            contract.request.query.get("media_id").map(String::as_str),
            Some("1052622027")
        );
        assert_eq!(contract.cases.len(), 3);
        assert_eq!(
            contract.cases[0].response.rust_model.as_deref(),
            Some("Vec<FavResourceIdItem>")
        );
        Ok(())
    }

    #[test]
    fn fav_list_response_fixtures_parse_declared_models() -> BpiResult<()> {
        let detail = ApiEnvelope::<FavListDetailData>::from_slice(include_bytes!(
            "../../tests/contracts/fav/read/list-detail/responses/success.json"
        ))?
        .into_payload()?;
        assert_eq!(detail.medias.len(), 1);

        let ids = ApiEnvelope::<Vec<FavResourceIdItem>>::from_slice(include_bytes!(
            "../../tests/contracts/fav/read/resource-ids/responses/success.json"
        ))?
        .into_payload()?;
        assert_eq!(ids.len(), 1);
        Ok(())
    }

    fn local_probe_body(endpoint: &str, profile: &str) -> Option<serde_json::Value> {
        let path = format!("target/bpi-probe-runs/fav/read/{endpoint}/{profile}.response.json");
        let bytes = std::fs::read(path).ok()?;
        let value: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
        value
            .get("response")
            .and_then(|response| response.get("body"))
            .cloned()
    }

    #[test]
    fn fav_list_models_match_local_probe_outputs_when_available() -> BpiResult<()> {
        for profile in ["anonymous", "normal", "vip"] {
            if let Some(body) = local_probe_body("list-detail", profile) {
                let payload = serde_json::from_value::<ApiEnvelope<FavListDetailData>>(body)?
                    .into_payload()?;
                assert!(payload.info.media_count >= payload.medias.len() as u32);
            }

            if let Some(body) = local_probe_body("resource-ids", profile) {
                let payload = serde_json::from_value::<ApiEnvelope<Vec<FavResourceIdItem>>>(body)?
                    .into_payload()?;
                assert!(!payload.is_empty());
            }
        }
        Ok(())
    }
}