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
use bytes::Bytes;

use crate::danmaku::action::{DanmakuAdvState, DanmakuAdvStateParams};
use crate::danmaku::danmaku_xml::{DanmakuXml, DanmakuXmlListParams, parse_deflate_danmaku_xml};
use crate::danmaku::history::DanmakuHistoryDatesParams;
use crate::danmaku::snapshot::DanmakuSnapshotParams;
use crate::danmaku::thumbup::{DanmakuThumbupStatsParams, ThumbupStatsMap};
use crate::danmaku::web::{DanmakuHistoryBytesParams, DanmakuSegmentParams, DanmakuWebViewParams};
use crate::{BilibiliRequest, BpiClient, BpiResult};

const HISTORY_DATES_ENDPOINT: &str = "https://api.bilibili.com/x/v2/dm/history/index";
const SNAPSHOT_ENDPOINT: &str = "https://api.bilibili.com/x/v2/dm/ajax";
const THUMBUP_STATS_ENDPOINT: &str = "https://api.bilibili.com/x/v2/dm/thumbup/stats";
const ADV_STATE_ENDPOINT: &str = "https://api.bilibili.com/x/dm/adv/state";
const WEB_SEG_ENDPOINT: &str = "https://api.bilibili.com/x/v2/dm/web/seg.so";
const WEB_SEG_WBI_ENDPOINT: &str = "https://api.bilibili.com/x/v2/dm/wbi/web/seg.so";
const WEB_VIEW_ENDPOINT: &str = "https://api.bilibili.com/x/v2/dm/web/view";
const MOBILE_SEG_ENDPOINT: &str = "https://api.bilibili.com/x/v2/dm/list/seg.so";
const WEB_HISTORY_SEG_ENDPOINT: &str = "https://api.bilibili.com/x/v2/dm/web/history/seg.so";
const HISTORY_XML_ENDPOINT: &str = "https://api.bilibili.com/x/v2/dm/history";
const XML_LIST_SO_ENDPOINT: &str = "https://api.bilibili.com/x/v1/dm/list.so";

/// Danmaku API client.
#[derive(Clone, Copy)]
pub struct DanmakuClient<'a> {
    pub(crate) client: &'a BpiClient,
}

impl<'a> DanmakuClient<'a> {
    pub(crate) fn new(client: &'a BpiClient) -> Self {
        Self { client }
    }

    #[cfg(test)]
    pub(crate) fn history_dates_endpoint(&self) -> &'static str {
        HISTORY_DATES_ENDPOINT
    }

    #[cfg(test)]
    pub(crate) fn snapshot_endpoint(&self) -> &'static str {
        SNAPSHOT_ENDPOINT
    }

    #[cfg(test)]
    pub(crate) fn thumbup_stats_endpoint(&self) -> &'static str {
        THUMBUP_STATS_ENDPOINT
    }

    #[cfg(test)]
    pub(crate) fn adv_state_endpoint(&self) -> &'static str {
        ADV_STATE_ENDPOINT
    }

    #[cfg(test)]
    pub(crate) fn web_seg_endpoint(&self) -> &'static str {
        WEB_SEG_ENDPOINT
    }

    #[cfg(test)]
    pub(crate) fn web_seg_wbi_endpoint(&self) -> &'static str {
        WEB_SEG_WBI_ENDPOINT
    }

    #[cfg(test)]
    pub(crate) fn web_view_endpoint(&self) -> &'static str {
        WEB_VIEW_ENDPOINT
    }

    #[cfg(test)]
    pub(crate) fn mobile_seg_endpoint(&self) -> &'static str {
        MOBILE_SEG_ENDPOINT
    }

    #[cfg(test)]
    pub(crate) fn web_history_seg_endpoint(&self) -> &'static str {
        WEB_HISTORY_SEG_ENDPOINT
    }

    #[cfg(test)]
    pub(crate) fn history_xml_endpoint(&self) -> &'static str {
        HISTORY_XML_ENDPOINT
    }

    #[cfg(test)]
    pub(crate) fn xml_list_so_endpoint(&self) -> &'static str {
        XML_LIST_SO_ENDPOINT
    }

    /// Queries the dates that have historical danmaku for a month.
    pub async fn history_dates(
        &self,
        params: DanmakuHistoryDatesParams,
    ) -> BpiResult<Option<Vec<String>>> {
        self.client
            .get(HISTORY_DATES_ENDPOINT)
            .query(&params.query_pairs())
            .send_bpi_optional_payload("danmaku.history.dates")
            .await
    }

    /// Gets recent danmaku snapshot lines for an archive.
    pub async fn snapshot(&self, params: DanmakuSnapshotParams) -> BpiResult<Vec<String>> {
        self.client
            .get(SNAPSHOT_ENDPOINT)
            .query(&params.query_pairs())
            .send_bpi_payload("danmaku.snapshot")
            .await
    }

    /// Queries like statistics for specific danmaku IDs.
    pub async fn thumbup_stats(
        &self,
        params: DanmakuThumbupStatsParams,
    ) -> BpiResult<ThumbupStatsMap> {
        self.client
            .get(THUMBUP_STATS_ENDPOINT)
            .query(&params.query_pairs())
            .send_bpi_payload("danmaku.thumbup.stats")
            .await
    }

    /// Checks advanced danmaku purchase/send state.
    pub async fn adv_state(&self, params: DanmakuAdvStateParams) -> BpiResult<DanmakuAdvState> {
        self.client
            .get(ADV_STATE_ENDPOINT)
            .query(&params.query_pairs())
            .send_bpi_payload("danmaku.adv.state")
            .await
    }

    /// Gets realtime web protobuf danmaku segment bytes.
    pub async fn web_seg_proto(&self, params: DanmakuSegmentParams) -> BpiResult<Bytes> {
        self.client
            .get(WEB_SEG_ENDPOINT)
            .with_bilibili_headers()
            .query(&params.query_pairs())
            .send_request("danmaku.web.seg")
            .await
    }

    /// Gets WBI-signed realtime web protobuf danmaku segment bytes.
    pub async fn web_seg_wbi_proto(&self, params: DanmakuSegmentParams) -> BpiResult<Bytes> {
        let signed = self.client.get_wbi_sign2(params.query_pairs()).await?;

        self.client
            .get(WEB_SEG_WBI_ENDPOINT)
            .with_bilibili_headers()
            .query(&signed)
            .send_request("danmaku.web.seg_wbi")
            .await
    }

    /// Gets protobuf danmaku web-view metadata bytes.
    pub async fn web_view_proto(&self, params: DanmakuWebViewParams) -> BpiResult<Bytes> {
        self.client
            .get(WEB_VIEW_ENDPOINT)
            .with_bilibili_headers()
            .query(&params.query_pairs())
            .send_request("danmaku.web.view")
            .await
    }

    /// Gets mobile protobuf danmaku segment bytes.
    pub async fn mobile_seg_proto(&self, params: DanmakuSegmentParams) -> BpiResult<Bytes> {
        self.client
            .get(MOBILE_SEG_ENDPOINT)
            .with_bilibili_headers()
            .query(&params.query_pairs())
            .send_request("danmaku.mobile.seg")
            .await
    }

    /// Gets dated historical protobuf danmaku segment bytes.
    pub async fn web_history_seg_proto(
        &self,
        params: DanmakuHistoryBytesParams,
    ) -> BpiResult<Bytes> {
        self.client
            .get(WEB_HISTORY_SEG_ENDPOINT)
            .with_bilibili_headers()
            .query(&params.query_pairs())
            .send_request("danmaku.web.history_seg")
            .await
    }

    /// Gets raw compressed dated historical XML danmaku bytes.
    pub async fn history_xml_bytes(&self, params: DanmakuHistoryBytesParams) -> BpiResult<Bytes> {
        self.client
            .get_without_response_decoding(HISTORY_XML_ENDPOINT)?
            .query(&params.query_pairs())
            .send_request("danmaku.history.xml")
            .await
    }

    /// Gets and parses realtime XML danmaku from `/x/v1/dm/list.so`.
    pub async fn xml_list_so(&self, params: DanmakuXmlListParams) -> BpiResult<DanmakuXml> {
        let response = self
            .client
            .get_without_response_decoding(XML_LIST_SO_ENDPOINT)?
            .query(&params.query_pairs())
            .send()
            .await?;
        let bytes = response.bytes().await?;

        parse_deflate_danmaku_xml(&bytes)
    }

    /// Gets and parses realtime XML danmaku from the comment host.
    pub async fn xml_list(&self, params: DanmakuXmlListParams) -> BpiResult<DanmakuXml> {
        let response = self
            .client
            .get_without_response_decoding(&params.comment_xml_url())?
            .send()
            .await?;
        let bytes = response.bytes().await?;

        parse_deflate_danmaku_xml(&bytes)
    }
}

#[cfg(test)]
mod tests {
    use std::future::Future;

    use bytes::Bytes;

    use crate::danmaku::action::{DanmakuAdvState, DanmakuAdvStateParams};
    use crate::danmaku::danmaku_xml::{DanmakuXml, DanmakuXmlListParams};
    use crate::danmaku::history::DanmakuHistoryDatesParams;
    use crate::danmaku::snapshot::DanmakuSnapshotParams;
    use crate::danmaku::thumbup::{DanmakuThumbupStatsParams, ThumbupStatsMap};
    use crate::danmaku::web::{
        DanmakuHistoryBytesParams, DanmakuSegmentParams, DanmakuWebViewParams,
    };
    use crate::ids::{Aid, Bvid, Cid};
    use crate::probe::contract::HttpMethod;
    use crate::probe::endpoint_contract::EndpointContract;
    use crate::{BpiClient, BpiError, BpiResult};

    const TEST_AID: u64 = 170_001;
    const TEST_BVID: &str = "BV1fK4y1t741";
    const TEST_CID: u64 = 413_195_701;
    const TEST_DMID: u64 = 1_932_011_031_958_944_000;
    const TEST_OID: u64 = 16_546;

    fn assert_history_dates_future<F>(_future: F)
    where
        F: Future<Output = BpiResult<Option<Vec<String>>>>,
    {
    }

    fn assert_snapshot_future<F>(_future: F)
    where
        F: Future<Output = BpiResult<Vec<String>>>,
    {
    }

    fn assert_thumbup_stats_future<F>(_future: F)
    where
        F: Future<Output = BpiResult<ThumbupStatsMap>>,
    {
    }

    fn assert_adv_state_future<F>(_future: F)
    where
        F: Future<Output = BpiResult<DanmakuAdvState>>,
    {
    }

    fn assert_bytes_future<F>(_future: F)
    where
        F: Future<Output = BpiResult<Bytes>>,
    {
    }

    fn assert_xml_future<F>(_future: F)
    where
        F: Future<Output = BpiResult<DanmakuXml>>,
    {
    }

    fn contract(path: &str) -> BpiResult<EndpointContract> {
        let bytes = match path {
            "json-read/history-dates" => include_bytes!(
                "../../tests/contracts/danmaku/json-read/history-dates/contract.json"
            )
            .as_slice(),
            "json-read/snapshot" => {
                include_bytes!("../../tests/contracts/danmaku/json-read/snapshot/contract.json")
                    .as_slice()
            }
            "json-read/thumbup-stats" => include_bytes!(
                "../../tests/contracts/danmaku/json-read/thumbup-stats/contract.json"
            )
            .as_slice(),
            "json-read/adv-state" => {
                include_bytes!("../../tests/contracts/danmaku/json-read/adv-state/contract.json")
                    .as_slice()
            }
            "non-json-read/web-seg" => {
                include_bytes!("../../tests/contracts/danmaku/non-json-read/web-seg/contract.json")
                    .as_slice()
            }
            "non-json-read/web-seg-wbi" => include_bytes!(
                "../../tests/contracts/danmaku/non-json-read/web-seg-wbi/contract.json"
            )
            .as_slice(),
            "non-json-read/web-view" => {
                include_bytes!("../../tests/contracts/danmaku/non-json-read/web-view/contract.json")
                    .as_slice()
            }
            "non-json-read/mobile-seg" => include_bytes!(
                "../../tests/contracts/danmaku/non-json-read/mobile-seg/contract.json"
            )
            .as_slice(),
            "non-json-read/web-history-seg" => include_bytes!(
                "../../tests/contracts/danmaku/non-json-read/web-history-seg/contract.json"
            )
            .as_slice(),
            "history-xml" => {
                include_bytes!("../../tests/contracts/danmaku/history-xml/contract.json").as_slice()
            }
            "xml-read/list-so" => {
                include_bytes!("../../tests/contracts/danmaku/xml-read/list-so/contract.json")
                    .as_slice()
            }
            "xml-read/comment-xml" => {
                include_bytes!("../../tests/contracts/danmaku/xml-read/comment-xml/contract.json")
                    .as_slice()
            }
            _ => unreachable!("unknown danmaku contract"),
        };
        EndpointContract::from_slice(bytes)
    }

    #[test]
    fn danmaku_methods_return_read_futures() -> Result<(), BpiError> {
        let client = BpiClient::new()?;
        let danmaku = client.danmaku();
        let cid = Cid::new(TEST_CID)?;
        let xml_cid = Cid::new(TEST_OID)?;
        let bvid = Bvid::new(TEST_BVID)?;

        assert_history_dates_future(
            danmaku.history_dates(DanmakuHistoryDatesParams::new(cid, "2022-01")?),
        );
        assert_snapshot_future(danmaku.snapshot(DanmakuSnapshotParams::from_bvid(bvid)));
        assert_snapshot_future(
            danmaku.snapshot(DanmakuSnapshotParams::from_aid(Aid::new(TEST_AID)?)),
        );
        assert_thumbup_stats_future(danmaku.thumbup_stats(DanmakuThumbupStatsParams::new(
            Cid::new(TEST_CID)?,
            [TEST_DMID],
        )?));
        assert_adv_state_future(danmaku.adv_state(DanmakuAdvStateParams::new(Cid::new(TEST_CID)?)));
        assert_bytes_future(danmaku.web_seg_proto(DanmakuSegmentParams::new(1, TEST_OID, 1)?));
        assert_bytes_future(danmaku.web_seg_wbi_proto(DanmakuSegmentParams::new(1, TEST_OID, 1)?));
        assert_bytes_future(danmaku.web_view_proto(DanmakuWebViewParams::new(1, TEST_OID)?));
        assert_bytes_future(danmaku.mobile_seg_proto(DanmakuSegmentParams::new(1, TEST_OID, 1)?));
        assert_bytes_future(
            danmaku.web_history_seg_proto(DanmakuHistoryBytesParams::new(
                1,
                TEST_OID,
                "2022-01-01",
            )?),
        );
        assert_bytes_future(danmaku.history_xml_bytes(DanmakuHistoryBytesParams::new(
            1,
            TEST_OID,
            "2022-01-01",
        )?));
        assert_xml_future(danmaku.xml_list_so(DanmakuXmlListParams::new(xml_cid)));
        assert_xml_future(danmaku.xml_list(DanmakuXmlListParams::new(xml_cid)));
        Ok(())
    }

    #[test]
    fn danmaku_contracts_match_module_client_endpoints() -> BpiResult<()> {
        let client = BpiClient::new()?;
        let danmaku = client.danmaku();
        let cases = [
            (
                "json-read/history-dates",
                "danmaku.history.dates",
                danmaku.history_dates_endpoint(),
            ),
            (
                "json-read/snapshot",
                "danmaku.snapshot",
                danmaku.snapshot_endpoint(),
            ),
            (
                "json-read/thumbup-stats",
                "danmaku.thumbup.stats",
                danmaku.thumbup_stats_endpoint(),
            ),
            (
                "json-read/adv-state",
                "danmaku.adv.state",
                danmaku.adv_state_endpoint(),
            ),
            (
                "non-json-read/web-seg",
                "danmaku.web.seg",
                danmaku.web_seg_endpoint(),
            ),
            (
                "non-json-read/web-seg-wbi",
                "danmaku.web.seg_wbi",
                danmaku.web_seg_wbi_endpoint(),
            ),
            (
                "non-json-read/web-view",
                "danmaku.web.view",
                danmaku.web_view_endpoint(),
            ),
            (
                "non-json-read/mobile-seg",
                "danmaku.mobile.seg",
                danmaku.mobile_seg_endpoint(),
            ),
            (
                "non-json-read/web-history-seg",
                "danmaku.web.history_seg",
                danmaku.web_history_seg_endpoint(),
            ),
            (
                "history-xml",
                "danmaku.history.xml",
                danmaku.history_xml_endpoint(),
            ),
            (
                "xml-read/list-so",
                "danmaku.xml.list_so",
                danmaku.xml_list_so_endpoint(),
            ),
        ];

        for (path, name, endpoint) in cases {
            let contract = contract(path)?;
            assert_eq!(contract.name, name);
            assert_eq!(contract.request.method, HttpMethod::Get);
            assert_eq!(contract.request.url.as_str(), endpoint);
        }

        let comment_xml = contract("xml-read/comment-xml")?;
        let params = DanmakuXmlListParams::new(Cid::new(TEST_OID)?);
        assert_eq!(comment_xml.name, "danmaku.xml.comment_xml");
        assert_eq!(comment_xml.request.method, HttpMethod::Get);
        assert_eq!(comment_xml.request.url.as_str(), params.comment_xml_url());
        Ok(())
    }
}