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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use serde::{Deserialize, Serialize};

/// 稿件私有笔记列表数据
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NoteListArchiveData {
    /// 笔记ID列表
    #[serde(rename = "noteIds")]
    pub note_ids: Option<Vec<String>>,
}

// --- 查询用户私有笔记 ---

/// 用户私有笔记的视频信息
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PrivateNoteArc {
    pub oid: u64,
    pub status: u8,
    pub oid_type: u8,
    pub aid: u64,

    // 老笔记没有以下内容
    pub bvid: Option<String>,
    pub pic: Option<String>,
    pub desc: Option<String>,
}

/// 用户私有笔记列表项
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PrivateNoteItem {
    pub title: String,
    pub summary: String,
    pub mtime: String,
    pub arc: PrivateNoteArc,
    pub note_id: u64,
    pub audit_status: u8,
    pub web_url: String,
    pub note_id_str: String,
    pub message: String,
    pub forbid_note_entrance: Option<bool>,
    pub likes: u64,
    pub has_like: bool,
}

/// 用户私有笔记列表数据
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PrivateNoteListData {
    pub list: Option<Vec<PrivateNoteItem>>,
    pub page: Option<NotePage>,
}

// --- 查询稿件公开笔记 ---

/// 稿件公开笔记列表项的作者信息
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PublicNoteAuthor {
    pub mid: u64,
    pub name: String,
    pub face: String,
    pub level: u8,
    pub vip_info: serde_json::Value,
    pub pendant: serde_json::Value,
}

/// 稿件公开笔记列表项
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PublicNoteItem {
    pub cvid: u64,
    pub title: String,
    pub summary: String,
    pub pubtime: String,
    pub web_url: String,
    pub message: String,
    pub author: PublicNoteAuthor,
    pub likes: u64,
    pub has_like: bool,
}

/// 稿件公开笔记分页信息
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NotePage {
    pub total: u32,
    pub size: u32,
    pub num: u32,
}

/// 稿件公开笔记列表数据
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PublicNoteListArchiveData {
    pub list: Option<Vec<PublicNoteItem>>,
    pub page: Option<NotePage>,
    pub show_public_note: bool,
    pub message: String,
}

// --- 查询用户公开笔记 ---

/// 用户公开笔记列表数据
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PublicNoteListUserData {
    pub list: Option<Vec<PublicNoteItem>>,
    pub page: Option<NotePage>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ids::Aid;
    use crate::note::{
        NoteArchiveListParams, NotePublicArchiveListParams, NoteUserPrivateListParams,
        NoteUserPublicListParams,
    };
    use crate::probe::contract::HttpMethod;
    use crate::probe::endpoint_contract::EndpointContract;
    use crate::{ApiEnvelope, BpiClient, BpiError, BpiResult};
    use base64::{Engine as _, engine::general_purpose};
    use tracing::info;

    const TEST_PRIVATE_AID: u64 = 676_931_260;
    const TEST_PUBLIC_AID: u64 = 338_677_252;

    fn contract(endpoint: &str) -> BpiResult<EndpointContract> {
        let bytes = match endpoint {
            "archive-list" => {
                include_bytes!("../../tests/contracts/note/read/archive-list/contract.json")
                    .as_slice()
            }
            "user-private-list" => {
                include_bytes!("../../tests/contracts/note/read/user-private-list/contract.json")
                    .as_slice()
            }
            "public-archive-list" => {
                include_bytes!("../../tests/contracts/note/read/public-archive-list/contract.json")
                    .as_slice()
            }
            "user-public-list" => {
                include_bytes!("../../tests/contracts/note/read/user-public-list/contract.json")
                    .as_slice()
            }
            _ => {
                return Err(BpiError::invalid_parameter(
                    "endpoint",
                    "unknown note list contract",
                ));
            }
        };

        EndpointContract::from_slice(bytes)
    }

    #[ignore = "legacy live API test; requires explicit BPI_LIVE_TEST review"]
    #[tokio::test]
    async fn test_note_list_archive() {
        let bpi = BpiClient::new().expect("client should build");
        let resp = bpi
            .note()
            .archive_list(NoteArchiveListParams::new(
                Aid::new(TEST_PRIVATE_AID).expect("test aid should be valid"),
            ))
            .await;

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

        let data = resp.unwrap();
        info!("note ids: {:?}", data.note_ids);
    }

    #[ignore = "legacy live API test; requires explicit BPI_LIVE_TEST review"]
    #[tokio::test]
    async fn test_note_list_user_private() {
        let bpi = BpiClient::new().expect("client should build");
        let resp = bpi
            .note()
            .user_private_list(
                NoteUserPrivateListParams::new()
                    .with_page(1)
                    .expect("test page should be valid")
                    .with_page_size(10)
                    .expect("test page size should be valid"),
            )
            .await;

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

        let data = resp.unwrap();
        if let Some(list) = data.list.as_ref() {
            info!("first note item: {:?}", list.first());
        }
    }

    #[ignore = "legacy live API test; requires explicit BPI_LIVE_TEST review"]
    #[tokio::test]
    async fn test_note_list_public_archive() {
        let bpi = BpiClient::new().expect("client should build");
        let resp = bpi
            .note()
            .public_archive_list(
                NotePublicArchiveListParams::new(
                    Aid::new(TEST_PUBLIC_AID).expect("test aid should be valid"),
                )
                .with_page(1)
                .expect("test page should be valid")
                .with_page_size(10)
                .expect("test page size should be valid"),
            )
            .await;

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

        let data = resp.unwrap();
        info!("show_public_note: {}", data.show_public_note);
    }

    #[ignore = "legacy live API test; requires explicit BPI_LIVE_TEST review"]
    #[tokio::test]
    async fn test_note_list_public_user() {
        let bpi = BpiClient::new().expect("client should build");
        let resp = bpi
            .note()
            .user_public_list(
                NoteUserPublicListParams::new()
                    .with_page(1)
                    .expect("test page should be valid")
                    .with_page_size(10)
                    .expect("test page size should be valid"),
            )
            .await;

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

        let data = resp.unwrap();
        info!("total public notes: {}", data.page.as_ref().unwrap().total);
    }

    #[test]
    fn note_archive_list_params_serializes_aid() -> Result<(), BpiError> {
        let params = NoteArchiveListParams::new(Aid::new(TEST_PRIVATE_AID)?);

        assert_eq!(
            params.query_pairs(),
            vec![
                ("oid", TEST_PRIVATE_AID.to_string()),
                ("oid_type", "0".to_string()),
            ]
        );
        Ok(())
    }

    #[test]
    fn note_user_private_list_params_rejects_zero_page() {
        let err = NoteUserPrivateListParams::new().with_page(0).unwrap_err();

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

    #[test]
    fn note_public_archive_list_params_serializes_query() -> Result<(), BpiError> {
        let params = NotePublicArchiveListParams::new(Aid::new(TEST_PUBLIC_AID)?)
            .with_page(1)?
            .with_page_size(10)?;

        assert_eq!(
            params.query_pairs(),
            vec![
                ("oid", TEST_PUBLIC_AID.to_string()),
                ("oid_type", "0".to_string()),
                ("pn", "1".to_string()),
                ("ps", "10".to_string()),
            ]
        );
        Ok(())
    }

    #[test]
    fn note_list_contracts_match_endpoint_requests() -> BpiResult<()> {
        let archive_list = contract("archive-list")?;
        assert_eq!(archive_list.name, "note.archive_list");
        assert_eq!(archive_list.request.method, HttpMethod::Get);
        assert_eq!(
            archive_list.request.url.as_str(),
            "https://api.bilibili.com/x/note/list/archive"
        );
        assert_eq!(
            archive_list.request.query.get("oid").map(String::as_str),
            Some("676931260")
        );
        assert_eq!(archive_list.cases[0].response.api_code, Some(-101));
        assert_eq!(
            archive_list.cases[1].response.rust_model.as_deref(),
            Some("NoteListArchiveData")
        );

        let user_private = contract("user-private-list")?;
        assert_eq!(user_private.name, "note.user_private_list");
        assert_eq!(
            user_private.request.url.as_str(),
            "https://api.bilibili.com/x/note/list"
        );
        assert_eq!(
            user_private.request.query.get("pn").map(String::as_str),
            Some("1")
        );
        assert_eq!(
            user_private.cases[1].response.rust_model.as_deref(),
            Some("PrivateNoteListData")
        );

        let public_archive = contract("public-archive-list")?;
        assert_eq!(public_archive.name, "note.public_archive_list");
        assert_eq!(
            public_archive.request.url.as_str(),
            "https://api.bilibili.com/x/note/publish/list/archive"
        );
        assert_eq!(
            public_archive.cases[0].response.rust_model.as_deref(),
            Some("PublicNoteListArchiveData")
        );

        let user_public = contract("user-public-list")?;
        assert_eq!(user_public.name, "note.user_public_list");
        assert_eq!(
            user_public.request.url.as_str(),
            "https://api.bilibili.com/x/note/publish/list/user"
        );
        assert_eq!(user_public.cases[0].response.http_status, Some(200));
        assert_eq!(
            user_public.cases[0].response.error.as_deref(),
            Some("requires_login")
        );
        assert_eq!(
            user_public.cases[1].response.rust_model.as_deref(),
            Some("PublicNoteListUserData")
        );
        Ok(())
    }

    #[test]
    fn note_list_response_fixtures_parse_declared_models() -> BpiResult<()> {
        let err = ApiEnvelope::<serde_json::Value>::from_slice(include_bytes!(
            "../../tests/contracts/note/read/archive-list/responses/anonymous.requires_login.json"
        ))
        .and_then(ApiEnvelope::ensure_success)
        .unwrap_err();
        assert!(err.requires_login());

        let archive = ApiEnvelope::<NoteListArchiveData>::from_slice(include_bytes!(
            "../../tests/contracts/note/read/archive-list/responses/authenticated.success.json"
        ))?
        .into_payload()?;
        assert_eq!(
            archive
                .note_ids
                .as_ref()
                .and_then(|note_ids| note_ids.first())
                .map(String::as_str),
            Some("1")
        );

        let private_list = ApiEnvelope::<PrivateNoteListData>::from_slice(include_bytes!(
            "../../tests/contracts/note/read/user-private-list/responses/authenticated.success.json"
        ))?
        .into_payload()?;
        assert_eq!(
            private_list
                .list
                .as_ref()
                .and_then(|items| items.first())
                .map(|item| item.title.as_str()),
            Some("sanitized private note title")
        );

        let public_archive = ApiEnvelope::<PublicNoteListArchiveData>::from_slice(include_bytes!(
            "../../tests/contracts/note/read/public-archive-list/responses/closed.success.json"
        ))?
        .into_payload()?;
        assert!(!public_archive.show_public_note);

        let binary: serde_json::Value = serde_json::from_slice(include_bytes!(
            "../../tests/contracts/note/read/user-public-list/responses/anonymous.requires_login.binary.json"
        ))?;
        assert_eq!(binary["kind"], "binary");
        let decoded = general_purpose::STANDARD
            .decode(
                binary["body_base64"]
                    .as_str()
                    .ok_or_else(|| BpiError::unsupported_response("missing binary body"))?,
            )
            .map_err(|err| BpiError::parse(err.to_string()))?;
        let decoded_text =
            String::from_utf8(decoded).map_err(|err| BpiError::parse(err.to_string()))?;
        assert!(decoded_text.contains("\"code\":-101"));

        let public_user = ApiEnvelope::<PublicNoteListUserData>::from_slice(include_bytes!(
            "../../tests/contracts/note/read/user-public-list/responses/authenticated.success.json"
        ))?
        .into_payload()?;
        assert_eq!(public_user.page.as_ref().map(|page| page.total), Some(0));
        assert!(public_user.list.is_none());
        Ok(())
    }

    fn local_probe_body(endpoint: &str, profile: &str) -> Option<serde_json::Value> {
        let path = format!("target/bpi-probe-runs/note/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 note_list_models_match_local_probe_outputs_when_available() -> BpiResult<()> {
        for profile in ["anonymous", "normal", "vip"] {
            let Some(body) = local_probe_body("archive-list", profile) else {
                continue;
            };
            if profile == "anonymous" {
                let err = serde_json::from_value::<ApiEnvelope<serde_json::Value>>(body)?
                    .ensure_success()
                    .unwrap_err();
                assert!(err.requires_login());
                continue;
            }
            serde_json::from_value::<ApiEnvelope<NoteListArchiveData>>(body)?.into_payload()?;
        }

        for profile in ["anonymous", "normal", "vip"] {
            let Some(body) = local_probe_body("user-private-list", profile) else {
                continue;
            };
            if profile == "anonymous" {
                let err = serde_json::from_value::<ApiEnvelope<serde_json::Value>>(body)?
                    .ensure_success()
                    .unwrap_err();
                assert!(err.requires_login());
                continue;
            }
            serde_json::from_value::<ApiEnvelope<PrivateNoteListData>>(body)?.into_payload()?;
        }

        for profile in ["anonymous", "normal", "vip"] {
            let Some(body) = local_probe_body("public-archive-list", profile) else {
                continue;
            };
            serde_json::from_value::<ApiEnvelope<PublicNoteListArchiveData>>(body)?
                .into_payload()?;
        }

        for profile in ["anonymous", "normal", "vip"] {
            let Some(body) = local_probe_body("user-public-list", profile) else {
                continue;
            };
            if profile == "anonymous" {
                assert_eq!(body["kind"], "binary");
                continue;
            }
            serde_json::from_value::<ApiEnvelope<PublicNoteListUserData>>(body)?.into_payload()?;
        }
        Ok(())
    }
}