initial commit
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
target
|
||||
.git
|
||||
*.log
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
# Cargo 构建产物
|
||||
/target/
|
||||
|
||||
# Rust 工具与覆盖率产物
|
||||
**/*.rs.bk
|
||||
*.profraw
|
||||
*.profdata
|
||||
/lcov.info
|
||||
|
||||
# 本地环境与凭据(包括直播 Cookie)
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
/cookie.txt
|
||||
/cookies.txt
|
||||
/secrets/
|
||||
|
||||
# 本地抓包可能包含用户内容或标识信息
|
||||
/frames.jsonl
|
||||
/captures/
|
||||
|
||||
# 日志与编辑器临时文件
|
||||
*.log
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# IDE 与操作系统生成的元数据
|
||||
/.idea/
|
||||
/.vscode/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
Generated
+1595
File diff suppressed because it is too large
Load Diff
+42
@@ -0,0 +1,42 @@
|
||||
[package]
|
||||
name = "libilibili"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.81"
|
||||
description = "An async Bilibili Web and Live API client with Cookie, CSRF, WBI, and live WebSocket support."
|
||||
license = "GPL-3.0-only"
|
||||
repository = "https://github.com/feliscafra/libilibili"
|
||||
keywords = ["bilibili", "live", "api", "wbi"]
|
||||
categories = ["api-bindings", "web-programming::http-client"]
|
||||
|
||||
[features]
|
||||
default = ["websocket"]
|
||||
websocket = ["dep:tokio", "dep:tokio-tungstenite", "dep:futures-util", "dep:flate2", "dep:brotli"]
|
||||
|
||||
[[bin]]
|
||||
name = "libilibili-capture"
|
||||
path = "src/bin/libilibili-capture.rs"
|
||||
required-features = ["websocket"]
|
||||
|
||||
[[bin]]
|
||||
name = "libilibili-analyze"
|
||||
path = "src/bin/libilibili-analyze.rs"
|
||||
required-features = ["websocket"]
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22"
|
||||
md-5 = "0.10"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
thiserror = "2"
|
||||
url = "2"
|
||||
|
||||
brotli = { version = "7", optional = true }
|
||||
flate2 = { version = "1", optional = true }
|
||||
futures-util = { version = "0.3", optional = true }
|
||||
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "time"], optional = true }
|
||||
tokio-tungstenite = { version = "0.26", features = ["rustls-tls-webpki-roots"], optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||
@@ -0,0 +1,675 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# libilibili
|
||||
|
||||
异步 Rust Bilibili Web/直播 API 库,依据 [feliscafra/Bilibili-Live-API](https://github.com/feliscafra/Bilibili-Live-API) 的接口、鉴权与 WebSocket 文档实现。
|
||||
|
||||
## 功能
|
||||
|
||||
- 公开 GET、WBI GET、Cookie GET、带 CSRF 的 Cookie POST,以及 WBI+POST。
|
||||
- 从 `/x/web-interface/nav` 自动刷新和缓存 WBI key;参数排序、清洗、percent-encode、MD5 签名均在库内完成。
|
||||
- 登录 Cookie 存在内存;状态变更请求自动写入 `csrf` 与 `csrf_token`(取自 `bili_jct`)。
|
||||
- 高层分组:直播间/分区/播放/礼物/勋章、视频、空间与关系、评论、搜索。
|
||||
- 默认 `websocket` feature:直播弹幕认证、心跳和 JSON/zlib/brotli 协议包解析,并只连接 `*.chat.bilibili.com`。
|
||||
- 使用通用请求方法覆盖参考文档中尚未提供快捷封装的低频或易变端点。
|
||||
|
||||
## 使用
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
libilibili = "0.1"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||
```
|
||||
|
||||
```rust,no_run
|
||||
use libilibili::{Client, Credentials};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), libilibili::Error> {
|
||||
let anonymous = Client::anonymous()?;
|
||||
let room = anonymous.live().room_detail(5050).await?; // 自动 WBI
|
||||
println!("{room:#}");
|
||||
|
||||
let auth = Credentials::from_cookie_header("SESSDATA=...; bili_jct=...");
|
||||
let client = Client::with_credentials(auth)?;
|
||||
client.video().like(170001, true).await?; // 自动 csrf + csrf_token
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
不需要 WebSocket:
|
||||
|
||||
```toml
|
||||
libilibili = { version = "0.1", default-features = false }
|
||||
```
|
||||
|
||||
## 通用端点调用与鉴权
|
||||
|
||||
| 鉴权类型 | 方法 |
|
||||
| --- | --- |
|
||||
| Public GET | `client.get(url, query)` |
|
||||
| WBI GET | `client.get_wbi(url, query)` |
|
||||
| Cookie POST | `client.post_form(url, form)` |
|
||||
| Cookie + WBI POST | `client.post_form_wbi(url, query, form)` |
|
||||
|
||||
`query`/`form` 是 `Vec<(String, String)>`;响应的 `data` 为泛型,快捷方法默认保留为 `serde_json::Value`,防止上游新增字段时信息丢失。
|
||||
|
||||
```rust,no_run
|
||||
# use libilibili::Client;
|
||||
# async fn example(client: Client) -> Result<(), libilibili::Error> {
|
||||
let history: serde_json::Value = client.get(
|
||||
"https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory",
|
||||
vec![("roomid".into(), "5050".into()), ("room_type".into(), "0".into())],
|
||||
).await?;
|
||||
# Ok(()) }
|
||||
```
|
||||
|
||||
## 弹幕 WebSocket
|
||||
|
||||
```rust,no_run
|
||||
use libilibili::{Client, Credentials, websocket::LiveWebSocket};
|
||||
|
||||
# async fn example() -> Result<(), libilibili::Error> {
|
||||
let credentials = Credentials::from_cookie_header("SESSDATA=...; bili_jct=...; buvid3=...");
|
||||
let client = Client::with_credentials(credentials)?;
|
||||
let mut ws = LiveWebSocket::connect(&client, 5050).await?;
|
||||
ws.heartbeat().await?; // 应约每 30 秒调用
|
||||
while let Some(event) = ws.next_event().await? { println!("{event:?}"); }
|
||||
# Ok(()) }
|
||||
```
|
||||
|
||||
## 原始帧抓取
|
||||
|
||||
`libilibili-capture` 可连接一个已登录的直播间,并将收到的**原始 WebSocket 二进制帧**
|
||||
写为 stdout 的 JSON Lines;连接状态与心跳日志只写入 stderr。每条输出含完整
|
||||
`frame_base64`,以及未解压协议包的版本、操作码和 `body_base64`,便于离线复现协议
|
||||
解析。
|
||||
|
||||
```sh
|
||||
cargo run --bin libilibili-capture -- \
|
||||
--cookie 'SESSDATA=...; bili_jct=...; buvid3=...' \
|
||||
--room-id 5050 \
|
||||
--seconds 120 \
|
||||
> frames.jsonl
|
||||
```
|
||||
|
||||
更安全的方式是通过标准输入提供 Cookie:
|
||||
|
||||
```sh
|
||||
printf '%s' "$BILI_COOKIE" | cargo run --bin libilibili-capture -- \
|
||||
--cookie-stdin --room-id 5050 --seconds 120 > frames.jsonl
|
||||
```
|
||||
|
||||
Cookie 不会被工具输出,但命令行参数可能被同机其他用户读取;在共享机器上应使用
|
||||
`--cookie-stdin`、受限权限的启动器或 secret 管理器注入 Cookie。
|
||||
|
||||
## 安全边界
|
||||
|
||||
本库不自动化密码、验证码、二维码或 OAuth 登录,也不尝试绕过风控。通过 Bilibili 正常登录取得会话后,使用环境变量或 secret store 注入 `SESSDATA`/`bili_jct`;绝不要提交或记录这些值。`-352` 代表风控/上下文限制,不等价于接口下线。
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// 浏览器会话凭据。
|
||||
///
|
||||
/// 凭据仅保存在内存中,且不会通过本 crate 的 `Debug` 输出泄露。
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Credentials {
|
||||
cookies: BTreeMap<String, String>,
|
||||
csrf: Option<String>,
|
||||
access_key: Option<String>,
|
||||
}
|
||||
|
||||
impl Credentials {
|
||||
/// 创建凭据构建器。
|
||||
pub fn builder() -> CredentialsBuilder {
|
||||
CredentialsBuilder::default()
|
||||
}
|
||||
|
||||
/// 从 `Cookie` 请求头文本解析凭据。
|
||||
///
|
||||
/// 若其中含有 `bili_jct`,它会同时被用作 CSRF token。
|
||||
pub fn from_cookie_header(header: impl AsRef<str>) -> Self {
|
||||
let mut result = Self::default();
|
||||
for pair in header.as_ref().split(';') {
|
||||
if let Some((name, value)) = pair.trim().split_once('=') {
|
||||
if !name.is_empty() {
|
||||
result.cookies.insert(name.to_owned(), value.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
result.csrf = result.cookies.get("bili_jct").cloned();
|
||||
result
|
||||
}
|
||||
|
||||
/// 生成可直接写入 HTTP `Cookie` 请求头的值;没有 Cookie 时返回 `None`。
|
||||
pub fn cookie_header(&self) -> Option<String> {
|
||||
(!self.cookies.is_empty()).then(|| {
|
||||
self.cookies
|
||||
.iter()
|
||||
.map(|(name, value)| format!("{name}={value}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ")
|
||||
})
|
||||
}
|
||||
/// 获取 CSRF token,通常等于 Cookie 中的 `bili_jct`。
|
||||
pub fn csrf(&self) -> Option<&str> {
|
||||
self.csrf.as_deref()
|
||||
}
|
||||
/// 获取 APP 接口使用的 `access_key`。
|
||||
pub fn access_key(&self) -> Option<&str> {
|
||||
self.access_key.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Credentials`] 的链式构建器。
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct CredentialsBuilder(Credentials);
|
||||
|
||||
impl CredentialsBuilder {
|
||||
/// 添加任意名称的 Cookie。
|
||||
pub fn cookie(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
self.0.cookies.insert(name.into(), value.into());
|
||||
self
|
||||
}
|
||||
/// 设置登录会话 Cookie `SESSDATA`。
|
||||
pub fn sessdata(self, value: impl Into<String>) -> Self {
|
||||
self.cookie("SESSDATA", value)
|
||||
}
|
||||
/// 显式设置 CSRF token;未设置时会尝试使用 `bili_jct` Cookie。
|
||||
pub fn csrf(mut self, value: impl Into<String>) -> Self {
|
||||
self.0.csrf = Some(value.into());
|
||||
self
|
||||
}
|
||||
/// 设置移动端接口使用的 `access_key`。
|
||||
pub fn access_key(mut self, value: impl Into<String>) -> Self {
|
||||
self.0.access_key = Some(value.into());
|
||||
self
|
||||
}
|
||||
/// 构建凭据。
|
||||
pub fn build(mut self) -> Credentials {
|
||||
if self.0.csrf.is_none() {
|
||||
self.0.csrf = self.0.cookies.get("bili_jct").cloned();
|
||||
}
|
||||
self.0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
//! `libilibili-capture` 产生的 JSONL 文件的离线类型分发统计工具。
|
||||
//!
|
||||
//! 工具只输出事件类型、未知命令和解析错误数量,不输出弹幕、昵称或其他业务内容。
|
||||
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use libilibili::{
|
||||
websocket::{decode_events, LiveCommand, LiveEvent},
|
||||
Error, Result,
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{collections::BTreeMap, env, fs};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let path = env::args().nth(1).ok_or_else(|| {
|
||||
Error::InvalidPacket(
|
||||
"用法:libilibili-analyze <libilibili-capture 输出的 JSONL 文件>".into(),
|
||||
)
|
||||
})?;
|
||||
let input = fs::read_to_string(path)?;
|
||||
let mut counts = BTreeMap::<String, u64>::new();
|
||||
let mut frames = 0_u64;
|
||||
let mut decode_errors = 0_u64;
|
||||
|
||||
for line in input.lines().filter(|line| !line.trim().is_empty()) {
|
||||
let record: Value = serde_json::from_str(line)?;
|
||||
let Some(frame_base64) = record.get("frame_base64").and_then(Value::as_str) else {
|
||||
decode_errors += 1;
|
||||
continue;
|
||||
};
|
||||
frames += 1;
|
||||
match STANDARD
|
||||
.decode(frame_base64)
|
||||
.ok()
|
||||
.and_then(|frame| decode_events(&frame).ok())
|
||||
{
|
||||
Some(events) => {
|
||||
for event in events {
|
||||
*counts.entry(event_name(&event)).or_default() += 1;
|
||||
}
|
||||
}
|
||||
None => decode_errors += 1,
|
||||
}
|
||||
}
|
||||
|
||||
println!("frames={frames}");
|
||||
println!("decode_errors={decode_errors}");
|
||||
for (name, count) in counts {
|
||||
println!("{name}={count}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn event_name(event: &LiveEvent) -> String {
|
||||
match event {
|
||||
LiveEvent::Popularity(_) => "Popularity".into(),
|
||||
LiveEvent::Auth(_) => "Auth".into(),
|
||||
LiveEvent::Unknown(_) => "PacketUnknown".into(),
|
||||
LiveEvent::Command(command) => match command.as_ref() {
|
||||
LiveCommand::Danmu(_) => "Danmu".into(),
|
||||
LiveCommand::Gift(_) => "Gift".into(),
|
||||
LiveCommand::ComboSend(_) => "ComboSend".into(),
|
||||
LiveCommand::LikeClick(_) => "LikeClick".into(),
|
||||
LiveCommand::LikeUpdate(_) => "LikeUpdate".into(),
|
||||
LiveCommand::LikeNotice(_) => "LikeNotice".into(),
|
||||
LiveCommand::OnlineRankCount(_) => "OnlineRankCount".into(),
|
||||
LiveCommand::WatchedChange(_) => "WatchedChange".into(),
|
||||
LiveCommand::StopLiveRoomList(_) => "StopLiveRoomList".into(),
|
||||
LiveCommand::GiftStarProcess(_) => "GiftStarProcess".into(),
|
||||
LiveCommand::OnlineRankV3(_) => "OnlineRankV3".into(),
|
||||
LiveCommand::InteractWordV2(_) => "InteractWordV2".into(),
|
||||
LiveCommand::GuardBuy(_) => "GuardBuy".into(),
|
||||
LiveCommand::SuperChat(_) => "SuperChat".into(),
|
||||
LiveCommand::InteractWord(_) => "InteractWord".into(),
|
||||
LiveCommand::RoomChange(_) => "RoomChange".into(),
|
||||
LiveCommand::Live(_) => "Live".into(),
|
||||
LiveCommand::Preparing(_) => "Preparing".into(),
|
||||
LiveCommand::Unknown { command, .. } => {
|
||||
format!("Unknown:{}", command.as_deref().unwrap_or("<missing>"))
|
||||
}
|
||||
LiveCommand::Invalid { command, .. } => {
|
||||
format!("Invalid:{}", command.as_deref().unwrap_or("<missing>"))
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! 直播弹幕 WebSocket 原始帧抓取工具。
|
||||
//!
|
||||
//! stderr 仅记录运行状态;stdout 输出 JSON Lines,每一行都是一个收到的原始
|
||||
//! WebSocket 二进制帧及其可选的协议包头摘要。Cookie 永远不会被输出。
|
||||
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use libilibili::{
|
||||
websocket::{decode_packets, LiveWebSocket},
|
||||
Client, Credentials, Error, Result,
|
||||
};
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
env,
|
||||
io::{self, Read, Write},
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
struct Config {
|
||||
cookie: String,
|
||||
room_id: u64,
|
||||
duration: Duration,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let Some(config) = parse_args()? else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// Cookie 仅传给客户端;日志刻意不打印其值或长度。
|
||||
let client = Client::with_credentials(Credentials::from_cookie_header(&config.cookie))?;
|
||||
eprintln!(
|
||||
"正在连接直播间 {},抓取时长 {} 秒。",
|
||||
config.room_id,
|
||||
config.duration.as_secs()
|
||||
);
|
||||
let mut socket = LiveWebSocket::connect(&client, config.room_id).await?;
|
||||
eprintln!("WebSocket 已认证。原始帧将以 JSON Lines 输出到 stdout。");
|
||||
|
||||
let end = Instant::now() + config.duration;
|
||||
let mut next_heartbeat = Instant::now() + Duration::from_secs(30);
|
||||
let mut sequence = 0_u64;
|
||||
let stdout = io::stdout();
|
||||
let mut output = io::BufWriter::new(stdout.lock());
|
||||
|
||||
while Instant::now() < end {
|
||||
let now = Instant::now();
|
||||
if now >= next_heartbeat {
|
||||
socket.heartbeat().await?;
|
||||
next_heartbeat = now + Duration::from_secs(30);
|
||||
eprintln!("已发送心跳。");
|
||||
}
|
||||
|
||||
let deadline = end.min(next_heartbeat);
|
||||
let timeout = deadline.saturating_duration_since(Instant::now());
|
||||
match tokio::time::timeout(timeout, socket.next_raw_frame()).await {
|
||||
Err(_) => continue,
|
||||
Ok(Ok(None)) => {
|
||||
eprintln!("服务器已关闭 WebSocket 连接。");
|
||||
break;
|
||||
}
|
||||
Ok(Err(error)) => return Err(error),
|
||||
Ok(Ok(Some(frame))) => {
|
||||
sequence += 1;
|
||||
let record = frame_record(sequence, &frame);
|
||||
serde_json::to_writer(&mut output, &record)?;
|
||||
output.write_all(b"\n")?;
|
||||
output.flush()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("抓取结束,共输出 {sequence} 个 WebSocket 帧。");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn frame_record(sequence: u64, frame: &[u8]) -> Value {
|
||||
let received_at_ms = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis();
|
||||
match decode_packets(frame) {
|
||||
Ok(packets) => json!({
|
||||
"sequence": sequence,
|
||||
"received_at_ms": received_at_ms,
|
||||
"frame_base64": STANDARD.encode(frame),
|
||||
"packets": packets.into_iter().map(|packet| json!({
|
||||
"version": packet.version,
|
||||
"operation": packet.operation,
|
||||
"body_base64": STANDARD.encode(packet.body),
|
||||
})).collect::<Vec<_>>(),
|
||||
}),
|
||||
Err(error) => json!({
|
||||
"sequence": sequence,
|
||||
"received_at_ms": received_at_ms,
|
||||
"frame_base64": STANDARD.encode(frame),
|
||||
"decode_error": error.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Option<Config>> {
|
||||
let mut cookie = None;
|
||||
let mut cookie_stdin = false;
|
||||
let mut room_id = None;
|
||||
let mut seconds = 60_u64;
|
||||
let mut args = env::args().skip(1);
|
||||
|
||||
while let Some(argument) = args.next() {
|
||||
match argument.as_str() {
|
||||
"--cookie" => cookie = Some(next_value(&mut args, "--cookie")?),
|
||||
"--cookie-stdin" => cookie_stdin = true,
|
||||
"--room-id" | "-r" => {
|
||||
room_id = Some(
|
||||
next_value(&mut args, "--room-id")?
|
||||
.parse()
|
||||
.map_err(|_| Error::InvalidPacket("直播间 ID 必须是无符号整数".into()))?,
|
||||
)
|
||||
}
|
||||
"--seconds" | "-s" => {
|
||||
seconds = next_value(&mut args, "--seconds")?
|
||||
.parse()
|
||||
.map_err(|_| Error::InvalidPacket("抓取秒数必须是无符号整数".into()))?
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
print_usage();
|
||||
return Ok(None);
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::InvalidPacket(format!(
|
||||
"未知参数:{argument};使用 --help 查看帮助"
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if cookie.is_some() && cookie_stdin {
|
||||
return Err(Error::InvalidPacket(
|
||||
"--cookie 与 --cookie-stdin 不能同时使用".into(),
|
||||
));
|
||||
}
|
||||
let cookie = match (cookie, cookie_stdin) {
|
||||
(Some(cookie), false) => cookie,
|
||||
(None, true) => {
|
||||
let mut input = String::new();
|
||||
io::stdin().read_to_string(&mut input)?;
|
||||
let cookie = input.trim().to_owned();
|
||||
if cookie.is_empty() {
|
||||
return Err(Error::InvalidPacket("标准输入中的 Cookie 为空".into()));
|
||||
}
|
||||
cookie
|
||||
}
|
||||
(None, false) => {
|
||||
return Err(Error::InvalidPacket(
|
||||
"缺少 --cookie 或 --cookie-stdin 参数".into(),
|
||||
))
|
||||
}
|
||||
(Some(_), true) => unreachable!("前置条件已检查"),
|
||||
};
|
||||
let room_id = room_id.ok_or_else(|| Error::InvalidPacket("缺少 --room-id 参数".into()))?;
|
||||
Ok(Some(Config {
|
||||
cookie,
|
||||
room_id,
|
||||
duration: Duration::from_secs(seconds),
|
||||
}))
|
||||
}
|
||||
|
||||
fn next_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<String> {
|
||||
args.next()
|
||||
.ok_or_else(|| Error::InvalidPacket(format!("{name} 需要一个值")))
|
||||
}
|
||||
|
||||
fn print_usage() {
|
||||
eprintln!(
|
||||
"\
|
||||
用法:
|
||||
libilibili-capture --cookie 'SESSDATA=...; bili_jct=...; buvid3=...' --room-id 5050 [--seconds 60]
|
||||
|
||||
选项:
|
||||
-r, --room-id <ID> 要监听的直播间 ID
|
||||
-s, --seconds <秒> 抓取时长,默认 60 秒
|
||||
--cookie <文本> 完整 Cookie 请求头文本
|
||||
--cookie-stdin 从标准输入读取完整 Cookie(更安全)
|
||||
-h, --help 显示本帮助
|
||||
|
||||
stdout 为 JSON Lines,包含原始帧和包体的 Base64。运行状态仅写入 stderr。
|
||||
注意:命令行参数可能被同机其他用户读取;优先使用 --cookie-stdin 或 secret 管理器注入 Cookie。"
|
||||
);
|
||||
}
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
use crate::{wbi, ApiError, Credentials, Error, Result, WbiKey};
|
||||
use reqwest::{
|
||||
header::{
|
||||
HeaderMap, HeaderValue, ACCEPT, ACCEPT_LANGUAGE, COOKIE, ORIGIN, REFERER, USER_AGENT,
|
||||
},
|
||||
Method,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
const WEB_ORIGIN: &str = "https://www.bilibili.com";
|
||||
const LIVE_ORIGIN: &str = "https://live.bilibili.com";
|
||||
|
||||
/// Bilibili HTTP API 客户端。
|
||||
///
|
||||
/// 客户端可廉价克隆,克隆后共享连接池与已缓存的 WBI key。
|
||||
#[derive(Clone)]
|
||||
pub struct Client {
|
||||
pub(crate) http: reqwest::Client,
|
||||
pub(crate) credentials: Credentials,
|
||||
wbi_key: Arc<RwLock<Option<WbiKey>>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Client {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Client")
|
||||
.field("credentials", &"[redacted]")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Client`] 的构建器,用于设置凭据和 User-Agent。
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ClientBuilder {
|
||||
credentials: Credentials,
|
||||
user_agent: String,
|
||||
}
|
||||
|
||||
impl Default for ClientBuilder {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
credentials: Credentials::default(),
|
||||
user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientBuilder {
|
||||
/// 设置客户端使用的浏览器会话凭据。
|
||||
pub fn credentials(mut self, credentials: Credentials) -> Self {
|
||||
self.credentials = credentials;
|
||||
self
|
||||
}
|
||||
/// 设置请求的 User-Agent。
|
||||
pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
|
||||
self.user_agent = user_agent.into();
|
||||
self
|
||||
}
|
||||
/// 创建客户端及其 HTTP 连接池。
|
||||
pub fn build(self) -> Result<Client> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
USER_AGENT,
|
||||
HeaderValue::from_str(&self.user_agent)
|
||||
.map_err(|_| Error::InvalidPacket("invalid user agent".into()))?,
|
||||
);
|
||||
headers.insert(ORIGIN, HeaderValue::from_static(WEB_ORIGIN));
|
||||
headers.insert(
|
||||
ACCEPT,
|
||||
HeaderValue::from_static("application/json, text/plain, */*"),
|
||||
);
|
||||
headers.insert(
|
||||
ACCEPT_LANGUAGE,
|
||||
HeaderValue::from_static("zh-CN,zh;q=0.9,en;q=0.8"),
|
||||
);
|
||||
headers.insert(
|
||||
REFERER,
|
||||
HeaderValue::from_static("https://www.bilibili.com/"),
|
||||
);
|
||||
if let Some(cookie) = self.credentials.cookie_header() {
|
||||
headers.insert(
|
||||
COOKIE,
|
||||
HeaderValue::from_str(&cookie)
|
||||
.map_err(|_| Error::InvalidPacket("invalid cookie header".into()))?,
|
||||
);
|
||||
}
|
||||
Ok(Client {
|
||||
http: reqwest::Client::builder()
|
||||
.default_headers(headers)
|
||||
.build()?,
|
||||
credentials: self.credentials,
|
||||
wbi_key: Arc::new(RwLock::new(None)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Bilibili 常见的 JSON 响应包裹结构。
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Response<T> {
|
||||
/// 业务状态码;`0` 表示成功。
|
||||
pub code: i64,
|
||||
/// 业务错误消息。
|
||||
#[serde(default, alias = "msg")]
|
||||
pub message: String,
|
||||
/// Bilibili 缓存控制字段。
|
||||
#[serde(default)]
|
||||
pub ttl: i64,
|
||||
/// 实际业务数据。
|
||||
///
|
||||
/// 非成功响应通常不包含该字段。
|
||||
#[serde(default)]
|
||||
pub data: Option<T>,
|
||||
}
|
||||
|
||||
impl<T> Response<T> {
|
||||
/// 在 `code == 0` 时取出 `data`,否则转换为 [`ApiError`]。
|
||||
pub fn into_data(self) -> Result<T> {
|
||||
if self.code == 0 {
|
||||
self.data.ok_or_else(|| {
|
||||
ApiError {
|
||||
code: self.code,
|
||||
message: if self.message.is_empty() {
|
||||
"成功响应缺少 data 字段".into()
|
||||
} else {
|
||||
self.message
|
||||
},
|
||||
}
|
||||
.into()
|
||||
})
|
||||
} else {
|
||||
Err(ApiError {
|
||||
code: self.code,
|
||||
message: self.message,
|
||||
}
|
||||
.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// 创建客户端构建器。
|
||||
pub fn builder() -> ClientBuilder {
|
||||
ClientBuilder::default()
|
||||
}
|
||||
/// 创建不含登录凭据的匿名客户端。
|
||||
pub fn anonymous() -> Result<Self> {
|
||||
Self::builder().build()
|
||||
}
|
||||
/// 使用给定凭据创建客户端。
|
||||
pub fn with_credentials(credentials: Credentials) -> Result<Self> {
|
||||
Self::builder().credentials(credentials).build()
|
||||
}
|
||||
/// 获取客户端保存的凭据引用。
|
||||
pub fn credentials(&self) -> &Credentials {
|
||||
&self.credentials
|
||||
}
|
||||
/// 访问直播相关接口。
|
||||
pub fn live(&self) -> crate::LiveApi<'_> {
|
||||
crate::LiveApi::new(self)
|
||||
}
|
||||
/// 访问视频相关接口。
|
||||
pub fn video(&self) -> crate::VideoApi<'_> {
|
||||
crate::VideoApi::new(self)
|
||||
}
|
||||
/// 访问用户、空间和关系接口。
|
||||
pub fn user(&self) -> crate::UserApi<'_> {
|
||||
crate::UserApi::new(self)
|
||||
}
|
||||
/// 访问评论接口。
|
||||
pub fn comments(&self) -> crate::CommentApi<'_> {
|
||||
crate::CommentApi::new(self)
|
||||
}
|
||||
/// 访问搜索接口。
|
||||
pub fn search(&self) -> crate::SearchApi<'_> {
|
||||
crate::SearchApi::new(self)
|
||||
}
|
||||
|
||||
/// 调用任意公开 GET 端点并返回响应中的 `data`。
|
||||
pub async fn get<T: DeserializeOwned>(
|
||||
&self,
|
||||
url: &str,
|
||||
query: Vec<(String, String)>,
|
||||
) -> Result<T> {
|
||||
self.send(Method::GET, url, query, None, false).await
|
||||
}
|
||||
/// 调用需要 WBI 签名的 GET 端点。
|
||||
///
|
||||
/// 会在首次调用时获取并缓存当前 WBI key。
|
||||
pub async fn get_wbi<T: DeserializeOwned>(
|
||||
&self,
|
||||
url: &str,
|
||||
query: Vec<(String, String)>,
|
||||
) -> Result<T> {
|
||||
let key = self.wbi_key().await?;
|
||||
let signed = key.sign(query);
|
||||
self.send(
|
||||
Method::GET,
|
||||
&signed_url(url, &signed),
|
||||
Vec::new(),
|
||||
None,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 发送需要登录态的表单 POST 请求。
|
||||
///
|
||||
/// 自动补充 `csrf` 与 `csrf_token`;缺少 `bili_jct` 时返回 [`Error::MissingCsrf`]。
|
||||
pub async fn post_form<T: DeserializeOwned>(
|
||||
&self,
|
||||
url: &str,
|
||||
mut form: Vec<(String, String)>,
|
||||
) -> Result<T> {
|
||||
let csrf = self.credentials.csrf().ok_or(Error::MissingCsrf)?;
|
||||
if !form.iter().any(|(k, _)| k == "csrf") {
|
||||
form.push(("csrf".into(), csrf.into()));
|
||||
}
|
||||
if !form.iter().any(|(k, _)| k == "csrf_token") {
|
||||
form.push(("csrf_token".into(), csrf.into()));
|
||||
}
|
||||
self.send(Method::POST, url, Vec::new(), Some(form), true)
|
||||
.await
|
||||
}
|
||||
/// 发送同时需要 Cookie/CSRF 和 WBI 查询签名的表单 POST 请求。
|
||||
pub async fn post_form_wbi<T: DeserializeOwned>(
|
||||
&self,
|
||||
url: &str,
|
||||
query: Vec<(String, String)>,
|
||||
form: Vec<(String, String)>,
|
||||
) -> Result<T> {
|
||||
let csrf = self.credentials.csrf().ok_or(Error::MissingCsrf)?;
|
||||
let mut form = form;
|
||||
if !form.iter().any(|(k, _)| k == "csrf") {
|
||||
form.push(("csrf".into(), csrf.into()));
|
||||
}
|
||||
if !form.iter().any(|(k, _)| k == "csrf_token") {
|
||||
form.push(("csrf_token".into(), csrf.into()));
|
||||
}
|
||||
let key = self.wbi_key().await?;
|
||||
let signed = key.sign(query);
|
||||
self.send(
|
||||
Method::POST,
|
||||
&signed_url(url, &signed),
|
||||
Vec::new(),
|
||||
Some(form),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn send<T: DeserializeOwned>(
|
||||
&self,
|
||||
method: Method,
|
||||
url: &str,
|
||||
query: Vec<(String, String)>,
|
||||
form: Option<Vec<(String, String)>>,
|
||||
live: bool,
|
||||
) -> Result<T> {
|
||||
let mut request = self.http.request(method, url).query(&query);
|
||||
if live {
|
||||
request = request
|
||||
.header(ORIGIN, LIVE_ORIGIN)
|
||||
.header(REFERER, "https://live.bilibili.com/");
|
||||
}
|
||||
if let Some(form) = form {
|
||||
request = request.form(&form);
|
||||
}
|
||||
let envelope: Response<Value> = request.send().await?.error_for_status()?.json().await?;
|
||||
envelope
|
||||
.into_data()
|
||||
.and_then(|data| Ok(serde_json::from_value(data)?))
|
||||
}
|
||||
|
||||
async fn wbi_key(&self) -> Result<WbiKey> {
|
||||
if let Some(key) = self.wbi_key.read().expect("WBI key lock poisoned").clone() {
|
||||
return Ok(key);
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Nav {
|
||||
wbi_img: Option<WbiImage>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct WbiImage {
|
||||
img_url: String,
|
||||
sub_url: String,
|
||||
}
|
||||
let nav: Nav = self
|
||||
.get("https://api.bilibili.com/x/web-interface/nav", Vec::new())
|
||||
.await?;
|
||||
let image = nav.wbi_img.ok_or(Error::MissingWbiKey)?;
|
||||
let key = WbiKey::from_image_urls(&image.img_url, &image.sub_url)?;
|
||||
*self.wbi_key.write().expect("WBI key lock poisoned") = Some(key.clone());
|
||||
Ok(key)
|
||||
}
|
||||
}
|
||||
|
||||
fn signed_url(url: &str, params: &[(String, String)]) -> String {
|
||||
let separator = if url.contains('?') { "&" } else { "?" };
|
||||
format!(
|
||||
"{url}{separator}{}",
|
||||
wbi::encode(
|
||||
params
|
||||
.iter()
|
||||
.map(|(key, value)| (key.as_str(), value.as_str()))
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,628 @@
|
||||
//! 高层接口分组。
|
||||
//!
|
||||
//! 所有快捷方法均返回 `serde_json::Value`:Bilibili 的响应字段变化频繁,这能在无需
|
||||
//! 发布新版本时保留新增字段。尚未提供快捷方法的端点可使用 [`crate::Client::get`]、
|
||||
//! [`crate::Client::get_wbi`] 与 [`crate::Client::post_form`] 调用。
|
||||
|
||||
use crate::{Client, Result};
|
||||
use serde_json::Value;
|
||||
|
||||
fn q(items: impl IntoIterator<Item = (&'static str, String)>) -> Vec<(String, String)> {
|
||||
items
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.to_owned(), value))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 直播间、分区、礼物与粉丝勋章接口组。
|
||||
pub struct LiveApi<'a> {
|
||||
client: &'a Client,
|
||||
}
|
||||
impl<'a> LiveApi<'a> {
|
||||
pub(crate) fn new(client: &'a Client) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
/// 解析直播间 ID,并返回真实房间号、主播 UID 与开播状态。
|
||||
pub async fn room_init(&self, room_id: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/room/v1/Room/room_init",
|
||||
q([("id", room_id.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取直播间基础信息。
|
||||
pub async fn room_info(&self, room_id: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/room/v1/Room/get_info",
|
||||
q([("room_id", room_id.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 根据主播 UID 查询其直播间信息。
|
||||
pub async fn room_info_by_uid(&self, uid: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/room/v1/Room/getRoomInfoOld",
|
||||
q([("mid", uid.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 批量获取直播间基础信息。
|
||||
pub async fn room_base_info(&self, room_ids: &[u64]) -> Result<Value> {
|
||||
let ids = room_ids
|
||||
.iter()
|
||||
.map(u64::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/xlive/web-room/v1/index/getRoomBaseInfo",
|
||||
q([("room_ids", ids), ("req_biz", "web_room_componet".into())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 通过 WBI 签名获取直播间聚合详情。
|
||||
pub async fn room_detail(&self, room_id: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get_wbi(
|
||||
"https://api.live.bilibili.com/xlive/web-room/v1/index/getInfoByRoom",
|
||||
q([
|
||||
("room_id", room_id.to_string()),
|
||||
("web_location", "444.8".into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取弹幕 WebSocket 的 token 和可用服务器列表。
|
||||
pub async fn danmu_info(&self, room_id: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get_wbi(
|
||||
"https://api.live.bilibili.com/xlive/web-room/v1/index/getDanmuInfo",
|
||||
q([
|
||||
("id", room_id.to_string()),
|
||||
("type", "0".into()),
|
||||
("web_location", "444.8".into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取直播流播放信息与 CDN 候选地址。
|
||||
///
|
||||
/// `quality` 是期望清晰度,例如 `10000` 表示原画。
|
||||
pub async fn play_info(&self, room_id: u64, quality: u32) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo",
|
||||
q([
|
||||
("room_id", room_id.to_string()),
|
||||
("protocol", "0,1".into()),
|
||||
("format", "0,1,2".into()),
|
||||
("codec", "0,1,2".into()),
|
||||
("qn", quality.to_string()),
|
||||
("platform", "web".into()),
|
||||
("ptype", "8".into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取全部直播分区。
|
||||
pub async fn areas(&self) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/xlive/web-interface/v1/index/getWebAreaList",
|
||||
q([("source_id", "2".into())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取指定直播分区内的房间分页列表。
|
||||
pub async fn area_rooms(
|
||||
&self,
|
||||
parent_area_id: u64,
|
||||
area_id: u64,
|
||||
page: u32,
|
||||
page_size: u32,
|
||||
) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/room/v3/area/getRoomList",
|
||||
q([
|
||||
("parent_area_id", parent_area_id.to_string()),
|
||||
("area_id", area_id.to_string()),
|
||||
("page", page.to_string()),
|
||||
("page_size", page_size.to_string()),
|
||||
("platform", "web".into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取直播首页推荐列表。
|
||||
pub async fn homepage(&self) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/xlive/web-interface/v1/webMain/getList",
|
||||
q([("platform", "web".into())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取直播间礼物面板配置。
|
||||
pub async fn room_gift_config(&self, room_id: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/xlive/web-room/v1/giftPanel/roomGiftConfig",
|
||||
q([
|
||||
("room_id", room_id.to_string()),
|
||||
("platform", "pc".into()),
|
||||
("source", "live".into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取直播间可展示的礼物列表。
|
||||
pub async fn room_gifts(&self, room_id: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/xlive/web-room/v1/giftPanel/roomGiftList",
|
||||
q([("room_id", room_id.to_string()), ("platform", "pc".into())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取直播间贡献榜或在线榜。
|
||||
pub async fn contribution_rank(
|
||||
&self,
|
||||
room_id: u64,
|
||||
anchor_uid: u64,
|
||||
page: u32,
|
||||
page_size: u32,
|
||||
) -> Result<Value> {
|
||||
self.client.get("https://api.live.bilibili.com/xlive/general-interface/v1/rank/queryContributionRank", q([
|
||||
("room_id", room_id.to_string()), ("ruid", anchor_uid.to_string()), ("page", page.to_string()),
|
||||
("page_size", page_size.to_string()), ("type", "online_rank".into()),
|
||||
])).await
|
||||
}
|
||||
/// 获取直播间历史弹幕。
|
||||
pub async fn danmu_history(&self, room_id: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory",
|
||||
q([("roomid", room_id.to_string()), ("room_type", "0".into())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取直播间主播资料面板。
|
||||
pub async fn anchor_in_room(&self, room_id: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/live_user/v1/UserInfo/get_anchor_in_room",
|
||||
q([("roomid", room_id.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取当前登录用户的粉丝勋章列表。
|
||||
pub async fn my_medals(&self, page: u32, page_size: u32) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.live.bilibili.com/xlive/app-ucenter/v1/user/GetMyMedals",
|
||||
q([
|
||||
("page", page.to_string()),
|
||||
("page_size", page_size.to_string()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 佩戴指定粉丝勋章。
|
||||
///
|
||||
/// 此操作会改变账号状态,需要登录 Cookie 与 CSRF token。
|
||||
pub async fn wear_medal(&self, medal_id: u64) -> Result<Value> {
|
||||
self.client
|
||||
.post_form(
|
||||
"https://api.live.bilibili.com/xlive/web-room/v1/fansMedal/wear",
|
||||
q([("medal_id", medal_id.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 卸下当前佩戴的粉丝勋章。
|
||||
///
|
||||
/// 此操作会改变账号状态,需要登录 Cookie 与 CSRF token。
|
||||
pub async fn take_off_medal(&self) -> Result<Value> {
|
||||
self.client
|
||||
.post_form(
|
||||
"https://api.live.bilibili.com/xlive/web-room/v1/fansMedal/take_off",
|
||||
Vec::new(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 向直播间发送弹幕。
|
||||
///
|
||||
/// 此操作会改变账号状态,需要登录 Cookie 与 CSRF token。
|
||||
pub async fn send_danmu(&self, room_id: u64, message: impl Into<String>) -> Result<Value> {
|
||||
self.client
|
||||
.post_form(
|
||||
"https://api.live.bilibili.com/msg/send",
|
||||
q([
|
||||
("roomid", room_id.to_string()),
|
||||
("msg", message.into()),
|
||||
("color", "16777215".into()),
|
||||
("fontsize", "25".into()),
|
||||
("mode", "1".into()),
|
||||
(
|
||||
"rnd",
|
||||
(std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs())
|
||||
.to_string(),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// 视频详情、播放辅助与互动接口组。
|
||||
pub struct VideoApi<'a> {
|
||||
client: &'a Client,
|
||||
}
|
||||
impl<'a> VideoApi<'a> {
|
||||
pub(crate) fn new(client: &'a Client) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
/// 根据 BV 号获取视频详情。
|
||||
pub async fn view_by_bvid(&self, bvid: impl Into<String>) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/web-interface/view",
|
||||
q([("bvid", bvid.into())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 根据 AV 号获取视频详情。
|
||||
pub async fn view_by_aid(&self, aid: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/web-interface/view",
|
||||
q([("aid", aid.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取视频的分 P 列表。
|
||||
pub async fn pages(&self, bvid: impl Into<String>) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/player/pagelist",
|
||||
q([("bvid", bvid.into())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取视频当前在线观看人数。
|
||||
pub async fn online_total(&self, aid: u64, cid: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/player/online/total",
|
||||
q([("aid", aid.to_string()), ("cid", cid.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取当前用户与视频的互动关系,例如点赞和收藏状态。
|
||||
pub async fn archive_relation(&self, aid: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/web-interface/archive/relation",
|
||||
q([("aid", aid.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取视频标签。
|
||||
pub async fn tags(&self, aid: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/tag/archive/tags",
|
||||
q([("aid", aid.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取指定分 P 的字幕元数据。
|
||||
pub async fn subtitles(&self, aid: u64, cid: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/v2/subtitle/web/view",
|
||||
q([("aid", aid.to_string()), ("cid", cid.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 点赞或取消点赞视频。
|
||||
///
|
||||
/// `like` 为 `true` 时点赞,为 `false` 时取消点赞;需要登录 Cookie 与 CSRF token。
|
||||
pub async fn like(&self, aid: u64, like: bool) -> Result<Value> {
|
||||
self.client
|
||||
.post_form(
|
||||
"https://api.bilibili.com/x/web-interface/archive/like",
|
||||
q([
|
||||
("aid", aid.to_string()),
|
||||
("like", if like { "1" } else { "2" }.into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 为视频投币。
|
||||
///
|
||||
/// `count` 为投币数量,`select_like` 表示是否同时点赞;需要登录 Cookie 与 CSRF token。
|
||||
pub async fn coin(&self, aid: u64, count: u8, select_like: bool) -> Result<Value> {
|
||||
self.client
|
||||
.post_form(
|
||||
"https://api.bilibili.com/x/web-interface/coin/add",
|
||||
q([
|
||||
("aid", aid.to_string()),
|
||||
("multiply", count.to_string()),
|
||||
("select_like", if select_like { "1" } else { "0" }.into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 修改视频收藏夹归属。
|
||||
///
|
||||
/// 两个 ID 参数均使用逗号分隔的收藏夹 ID;需要登录 Cookie 与 CSRF token。
|
||||
pub async fn favourite(
|
||||
&self,
|
||||
aid: u64,
|
||||
add_media_ids: impl Into<String>,
|
||||
del_media_ids: impl Into<String>,
|
||||
) -> Result<Value> {
|
||||
self.client
|
||||
.post_form(
|
||||
"https://api.bilibili.com/x/v3/fav/resource/deal",
|
||||
q([
|
||||
("rid", aid.to_string()),
|
||||
("type", "2".into()),
|
||||
("add_media_ids", add_media_ids.into()),
|
||||
("del_media_ids", del_media_ids.into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// 用户资料、空间、关系和动态接口组。
|
||||
pub struct UserApi<'a> {
|
||||
client: &'a Client,
|
||||
}
|
||||
impl<'a> UserApi<'a> {
|
||||
pub(crate) fn new(client: &'a Client) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
/// 获取当前登录状态及导航栏用户信息。
|
||||
pub async fn nav(&self) -> Result<Value> {
|
||||
self.client
|
||||
.get("https://api.bilibili.com/x/web-interface/nav", Vec::new())
|
||||
.await
|
||||
}
|
||||
/// 获取用户基础资料。
|
||||
pub async fn profile(&self, uid: u64) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/space/acc/info",
|
||||
q([("mid", uid.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 通过 WBI 签名获取用户空间投稿列表。
|
||||
pub async fn space_videos(&self, uid: u64, page: u32, page_size: u32) -> Result<Value> {
|
||||
self.client
|
||||
.get_wbi(
|
||||
"https://api.bilibili.com/x/space/wbi/arc/search",
|
||||
q([
|
||||
("mid", uid.to_string()),
|
||||
("pn", page.to_string()),
|
||||
("ps", page_size.to_string()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取用户关注列表。
|
||||
pub async fn following(&self, uid: u64, page: u32, page_size: u32) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/relation/followings",
|
||||
q([
|
||||
("vmid", uid.to_string()),
|
||||
("pn", page.to_string()),
|
||||
("ps", page_size.to_string()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取用户粉丝列表。
|
||||
pub async fn followers(&self, uid: u64, page: u32, page_size: u32) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/relation/fans",
|
||||
q([
|
||||
("vmid", uid.to_string()),
|
||||
("pn", page.to_string()),
|
||||
("ps", page_size.to_string()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 修改与用户的关系。
|
||||
///
|
||||
/// `act` 的具体含义由 Bilibili 接口定义;需要登录 Cookie 与 CSRF token。
|
||||
pub async fn modify_relation(&self, uid: u64, act: u8) -> Result<Value> {
|
||||
self.client
|
||||
.post_form(
|
||||
"https://api.bilibili.com/x/relation/modify",
|
||||
q([("fid", uid.to_string()), ("act", act.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取用户空间动态列表。
|
||||
///
|
||||
/// `offset` 应使用上一次响应给出的分页游标;首次查询可传空字符串。
|
||||
pub async fn dynamic_space(&self, uid: u64, offset: impl Into<String>) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space",
|
||||
q([
|
||||
("host_mid", uid.to_string()),
|
||||
("offset", offset.into()),
|
||||
("timezone_offset", "-480".into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取单条动态详情。
|
||||
pub async fn dynamic_detail(&self, dynamic_id: impl Into<String>) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/polymer/web-dynamic/v1/detail",
|
||||
q([
|
||||
("id", dynamic_id.into()),
|
||||
("timezone_offset", "-480".into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// 视频评论与评论互动接口组。
|
||||
pub struct CommentApi<'a> {
|
||||
client: &'a Client,
|
||||
}
|
||||
impl<'a> CommentApi<'a> {
|
||||
pub(crate) fn new(client: &'a Client) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
/// 获取视频评论分页列表。
|
||||
///
|
||||
/// `oid` 为视频 AV 号,`sort` 使用 Bilibili 定义的排序值。
|
||||
pub async fn list(&self, oid: u64, page: u32, page_size: u32, sort: u8) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/v2/reply",
|
||||
q([
|
||||
("type", "1".into()),
|
||||
("oid", oid.to_string()),
|
||||
("pn", page.to_string()),
|
||||
("ps", page_size.to_string()),
|
||||
("sort", sort.to_string()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 通过 WBI 签名获取新版评论主楼列表。
|
||||
pub async fn list_wbi(&self, oid: u64, mode: u8) -> Result<Value> {
|
||||
self.client
|
||||
.get_wbi(
|
||||
"https://api.bilibili.com/x/v2/reply/wbi/main",
|
||||
q([
|
||||
("type", "1".into()),
|
||||
("oid", oid.to_string()),
|
||||
("mode", mode.to_string()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取某条主评论下的回复列表。
|
||||
pub async fn replies(&self, oid: u64, root_reply_id: u64, page: u32) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/v2/reply/reply",
|
||||
q([
|
||||
("type", "1".into()),
|
||||
("oid", oid.to_string()),
|
||||
("root", root_reply_id.to_string()),
|
||||
("pn", page.to_string()),
|
||||
("ps", "20".into()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 发布评论或回复。
|
||||
///
|
||||
/// 传入 `root_reply_id` 时发布回复;需要登录 Cookie 与 CSRF token。
|
||||
pub async fn add(
|
||||
&self,
|
||||
oid: u64,
|
||||
message: impl Into<String>,
|
||||
root_reply_id: Option<u64>,
|
||||
) -> Result<Value> {
|
||||
let mut form = q([
|
||||
("type", "1".into()),
|
||||
("oid", oid.to_string()),
|
||||
("message", message.into()),
|
||||
]);
|
||||
if let Some(root) = root_reply_id {
|
||||
form.push(("root".into(), root.to_string()));
|
||||
}
|
||||
self.client
|
||||
.post_form("https://api.bilibili.com/x/v2/reply/add", form)
|
||||
.await
|
||||
}
|
||||
/// 对评论执行点赞或取消点赞等动作。
|
||||
///
|
||||
/// `action` 的具体含义由 Bilibili 接口定义;需要登录 Cookie 与 CSRF token。
|
||||
pub async fn action(&self, oid: u64, reply_id: u64, action: u8) -> Result<Value> {
|
||||
self.client
|
||||
.post_form(
|
||||
"https://api.bilibili.com/x/v2/reply/action",
|
||||
q([
|
||||
("type", "1".into()),
|
||||
("oid", oid.to_string()),
|
||||
("rpid", reply_id.to_string()),
|
||||
("action", action.to_string()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// 全站搜索和搜索建议接口组。
|
||||
pub struct SearchApi<'a> {
|
||||
client: &'a Client,
|
||||
}
|
||||
impl<'a> SearchApi<'a> {
|
||||
pub(crate) fn new(client: &'a Client) -> Self {
|
||||
Self { client }
|
||||
}
|
||||
/// 通过 WBI 签名进行综合搜索。
|
||||
pub async fn all(&self, keyword: impl Into<String>, page: u32) -> Result<Value> {
|
||||
self.client
|
||||
.get_wbi(
|
||||
"https://api.bilibili.com/x/web-interface/wbi/search/all/v2",
|
||||
q([("keyword", keyword.into()), ("page", page.to_string())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 通过 WBI 签名搜索视频。
|
||||
pub async fn video(&self, keyword: impl Into<String>, page: u32) -> Result<Value> {
|
||||
self.client
|
||||
.get_wbi(
|
||||
"https://api.bilibili.com/x/web-interface/wbi/search/type",
|
||||
q([
|
||||
("search_type", "video".into()),
|
||||
("keyword", keyword.into()),
|
||||
("page", page.to_string()),
|
||||
]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 获取关键词联想建议。
|
||||
pub async fn suggest(&self, keyword: impl Into<String>) -> Result<Value> {
|
||||
self.client
|
||||
.get(
|
||||
"https://api.bilibili.com/x/web-interface/suggest",
|
||||
q([("term", keyword.into())]),
|
||||
)
|
||||
.await
|
||||
}
|
||||
/// 通过 WBI 签名获取搜索默认词。
|
||||
pub async fn default_word(&self) -> Result<Value> {
|
||||
self.client
|
||||
.get_wbi(
|
||||
"https://api.bilibili.com/x/web-interface/wbi/search/default",
|
||||
Vec::new(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
use thiserror::Error;
|
||||
|
||||
/// crate 内所有可恢复操作使用的结果类型。
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Bilibili 返回了非零业务状态码时的错误信息。
|
||||
#[derive(Debug, Clone, Error, PartialEq, Eq)]
|
||||
#[error("Bilibili API returned code {code}: {message}")]
|
||||
pub struct ApiError {
|
||||
/// Bilibili 响应中的 `code`。
|
||||
pub code: i64,
|
||||
/// Bilibili 响应中的 `message` 或 `msg`。
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// 调用 API、签名或解析协议时可能发生的错误。
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
/// HTTP 传输或状态码错误。
|
||||
#[error(transparent)]
|
||||
Http(#[from] reqwest::Error),
|
||||
/// URL 解析错误。
|
||||
#[error(transparent)]
|
||||
Url(#[from] url::ParseError),
|
||||
/// JSON 编码或解码错误。
|
||||
#[error(transparent)]
|
||||
Json(#[from] serde_json::Error),
|
||||
/// Bilibili 返回的业务错误。
|
||||
#[error(transparent)]
|
||||
Api(#[from] ApiError),
|
||||
/// 状态变更请求缺少 `bili_jct` CSRF token。
|
||||
#[error("this request requires credentials with a bili_jct CSRF token")]
|
||||
MissingCsrf,
|
||||
/// `/x/web-interface/nav` 未返回 WBI 图片 key。
|
||||
#[error("WBI key was absent from /x/web-interface/nav")]
|
||||
MissingWbiKey,
|
||||
/// WBI 图片 URL 不符合预期格式。
|
||||
#[error("invalid WBI image URL: {0}")]
|
||||
InvalidWbiImageUrl(String),
|
||||
/// 直播 WebSocket 数据包格式无效。
|
||||
#[error("invalid WebSocket packet: {0}")]
|
||||
InvalidPacket(String),
|
||||
/// WebSocket 建连或读写错误。
|
||||
#[cfg(feature = "websocket")]
|
||||
#[error(transparent)]
|
||||
WebSocket(Box<tokio_tungstenite::tungstenite::Error>),
|
||||
/// WebSocket 压缩数据解压时发生的 I/O 错误。
|
||||
#[cfg(feature = "websocket")]
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
|
||||
#[cfg(feature = "websocket")]
|
||||
impl Error {
|
||||
pub(crate) fn websocket(error: tokio_tungstenite::tungstenite::Error) -> Self {
|
||||
Self::WebSocket(Box::new(error))
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
//! Bilibili Web 与直播接口的异步客户端。
|
||||
//!
|
||||
//! 本 crate 不实现密码、二维码、验证码或 OAuth 登录流程。请通过 Bilibili 的正常登录页面
|
||||
//! 获得会话,再将 `SESSDATA` 和 `bili_jct` 传给 [`Credentials`]。会改变账号状态的
|
||||
//! Cookie 请求会自动携带 `csrf` 和 `csrf_token`。
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use libilibili::Client;
|
||||
//!
|
||||
//! # async fn example() -> Result<(), libilibili::Error> {
|
||||
//! let client = Client::anonymous()?;
|
||||
//! let room = client.live().room_init(5050).await?;
|
||||
//! println!("{room:#}");
|
||||
//! # Ok(()) }
|
||||
//! ```
|
||||
|
||||
mod auth;
|
||||
mod client;
|
||||
mod endpoints;
|
||||
mod error;
|
||||
mod wbi;
|
||||
|
||||
#[cfg(feature = "websocket")]
|
||||
pub mod websocket;
|
||||
|
||||
pub use auth::{Credentials, CredentialsBuilder};
|
||||
pub use client::{Client, ClientBuilder, Response};
|
||||
pub use endpoints::{CommentApi, LiveApi, SearchApi, UserApi, VideoApi};
|
||||
pub use error::{ApiError, Error, Result};
|
||||
pub use wbi::{WbiKey, WBI_MIXIN_TABLE};
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
use crate::{Error, Result};
|
||||
use md5::{Digest, Md5};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use url::Url;
|
||||
|
||||
/// 推导 Bilibili 短期 WBI mixin key 使用的公开置换表。
|
||||
///
|
||||
/// 导出该常量便于调用方离线复现签名。
|
||||
pub const WBI_MIXIN_TABLE: [usize; 64] = [
|
||||
46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49, 33, 9, 42, 19, 29,
|
||||
28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40, 61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25,
|
||||
54, 21, 56, 59, 6, 63, 57, 62, 11, 36, 20, 34, 44, 52,
|
||||
];
|
||||
|
||||
/// 从 `/x/web-interface/nav` 的 `data.wbi_img` 推导出的 WBI mixin key。
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WbiKey(String);
|
||||
|
||||
impl WbiKey {
|
||||
/// 根据两张 WBI 图片的 URL 推导 mixin key。
|
||||
pub fn from_image_urls(img_url: &str, sub_url: &str) -> Result<Self> {
|
||||
let source = format!("{}{}", image_stem(img_url)?, image_stem(sub_url)?);
|
||||
let mixed: String = WBI_MIXIN_TABLE
|
||||
.iter()
|
||||
.filter_map(|&index| source.chars().nth(index))
|
||||
.collect();
|
||||
Ok(Self(mixed.chars().take(32).collect()))
|
||||
}
|
||||
/// 以字符串形式返回 mixin key。
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// 为参数加入 `wts` 与 `w_rid` 签名。
|
||||
///
|
||||
/// 已存在的 `wts` 和 `w_rid` 会被替换;业务参数按键名排序,且会移除
|
||||
/// WBI 规则中不参与签名的字符。
|
||||
pub fn sign(
|
||||
&self,
|
||||
parameters: impl IntoIterator<Item = (String, String)>,
|
||||
) -> Vec<(String, String)> {
|
||||
let mut params: BTreeMap<String, String> = parameters
|
||||
.into_iter()
|
||||
.filter(|(key, _)| key != "wts" && key != "w_rid")
|
||||
.map(|(key, value)| (key, clean_value(&value)))
|
||||
.collect();
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs()
|
||||
.to_string();
|
||||
params.insert("wts".to_owned(), now);
|
||||
let query = encode(
|
||||
params
|
||||
.iter()
|
||||
.map(|(key, value)| (key.as_str(), value.as_str())),
|
||||
);
|
||||
let mut hasher = Md5::new();
|
||||
hasher.update(query.as_bytes());
|
||||
hasher.update(self.0.as_bytes());
|
||||
params.insert("w_rid".to_owned(), format!("{:x}", hasher.finalize()));
|
||||
params.into_iter().collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn image_stem(image_url: &str) -> Result<String> {
|
||||
let url = Url::parse(image_url).map_err(|_| Error::InvalidWbiImageUrl(image_url.to_owned()))?;
|
||||
let filename = url
|
||||
.path_segments()
|
||||
.and_then(Iterator::last)
|
||||
.and_then(|name| name.split('.').next())
|
||||
.filter(|name| !name.is_empty())
|
||||
.ok_or_else(|| Error::InvalidWbiImageUrl(image_url.to_owned()))?;
|
||||
Ok(filename.to_owned())
|
||||
}
|
||||
|
||||
fn clean_value(value: &str) -> String {
|
||||
value.chars().filter(|ch| !"!'()*".contains(*ch)).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn encode<'a>(params: impl IntoIterator<Item = (&'a str, &'a str)>) -> String {
|
||||
params
|
||||
.into_iter()
|
||||
.map(|(key, value)| format!("{}={}", percent_encode(key), percent_encode(value)))
|
||||
.collect::<Vec<_>>()
|
||||
.join("&")
|
||||
}
|
||||
|
||||
fn percent_encode(value: &str) -> String {
|
||||
value
|
||||
.bytes()
|
||||
.flat_map(|byte| match byte {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
vec![byte as char]
|
||||
}
|
||||
_ => format!("%{byte:02X}").chars().collect(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn derives_the_published_mixin_key() {
|
||||
let key = WbiKey::from_image_urls(
|
||||
"https://i0.hdslb.com/bfs/wbi/7cd084941338484aae1ad9425b84077c.png",
|
||||
"https://i0.hdslb.com/bfs/wbi/4932caff0ff746eab6f01bf08b70ac45.png",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(key.as_str(), "ea1db124af3c7062474693fa704f4ff8");
|
||||
}
|
||||
#[test]
|
||||
fn signing_sorts_and_cleans_values() {
|
||||
let key = WbiKey("01234567890123456789012345678901".into());
|
||||
let signed = key.sign([
|
||||
(String::from("z"), String::from("a!b")),
|
||||
(String::from("a"), String::from("x")),
|
||||
]);
|
||||
assert_eq!(signed[0], ("a".into(), "x".into()));
|
||||
assert_eq!(
|
||||
signed.iter().find(|(key, _)| key == "z"),
|
||||
Some(&("z".into(), "ab".into()))
|
||||
);
|
||||
assert!(signed.iter().any(|(k, _)| k == "w_rid"));
|
||||
}
|
||||
}
|
||||
+1935
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user