Skip to content

Commit

Permalink
优化代码
Browse files Browse the repository at this point in the history
  • Loading branch information
CuteReimu committed Mar 24, 2024
1 parent 0198354 commit 7c6c44a
Show file tree
Hide file tree
Showing 15 changed files with 331 additions and 390 deletions.
55 changes: 39 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ go get -u github.com/CuteReimu/bilibili/v2
```go
import "github.com/CuteReimu/bilibili/v2"

func main() {
client := bilibili.New()
}
var client = bilibili.New()
```

### 首次登录
Expand All @@ -63,8 +61,10 @@ img, _ := png.Decode(buf) // 或者写入文件 os.WriteFile("qrcode.png", buf,
扫码并确认成功后,发送登录请求:

```go
err := client.LoginWithQRCode(qrCode)
if err == nil {
result, err := client.LoginWithQRCode(bilibili.LoginWithQRCodeParam{
QrcodeKey: qrCode.QrcodeKey,
})
if err == nil && result.Code == 0 {
log.Println("登录成功")
}
```
Expand All @@ -80,8 +80,15 @@ captchaResult, _ := client.Captcha()
`captchaResult`中的`gt``challenge`值保存下来,自行使用 [手动验证器](https://kuresaru.github.io/geetest-validator/) 进行人机验证,并获得`validate``seccode`。然后使用账号密码进行登录即可:

```go
err := client.LoginWithPassword(userName, password, captchaResult, validate, seccode)
if err == nil {
result, err := client.LoginWithPassword(bilibili.LoginWithPasswordParam{
Username: userName,
Password: password,
Token: captchaResult.Token,
Challenge: captchaResult.Geetest.Challenge,
Validate: validate,
Seccode: seccode,
})
if err == nil && result.Status == 0 {
log.Println("登录成功")
}
```
Expand All @@ -91,22 +98,36 @@ if err == nil {
首先用上述方法二相同的方式获取人机验证参数并进行人机验证。然后获取国际地区代码:

```go
common, others, _ := client.ListCountry()
countryCrown, others, _ := client.GetCountryCrown()
```

当然,如果你已经确定`cid`的值,这一步可以跳过。中国大陆的`cid`就是1
当然,如果你已经确定`cid`的值,这一步可以跳过。中国大陆的`cid`就是86

然后发送短信验证码:
然后发送短信验证码:*[这个接口大概率返回86103错误](https://github.com/SocialSisterYi/bilibili-API-collect/issues/756)*

```go
captchaKey, _ := client.SendSMS(tel, cid, captchaResult, validate, seccode)
sendSMSResult, _ := client.SendSMS(bilibili.SendSMSParam{
Cid: cid,
Tel: tel,
Source: "main_web",
Token: captchaResult.Token,
Challenge: captchaResult.Geetest.Challenge,
Validate: validate,
Seccode: seccode,
})
```

然后就可以使用手机验证码登录了:

```go
err := client.LoginWithSMS(tel, cid, code, captchaKey) // 其中code是短信验证码
if err == nil {
result, err := client.LoginWithSMS(bilibili.LoginWithSMSParam{
Cid: cid,
Tel: tel,
Code: 123456, // 短信验证码
Source: "main_web",
CaptchaKey: sendSMSResult.CaptchaKey,
})
if err == nil && result.Status == 0 {
log.Println("登录成功")
}
```
Expand All @@ -123,11 +144,13 @@ cookiesString := client.GetCookiesString()
client.SetCookiesString(cookiesString)
```

### 设置超时时间和logger
### 设置*resty.Client的一些参数

调用`client.Resty()`就可以获取到`*resty.Client`,然后自行操作即可。**但是不要做一些离谱的操作**~~(比如把Cookies删了)~~

```go
client.SetTimeout(20 * time.Second) // 设置超时时间
client.SetLogger(logger) // 自定义logger
client.Resty().SetTimeout(20 * time.Second) // 设置超时时间
client.Resty().SetLogger(logger) // 自定义logger
```

## 进度
Expand Down
2 changes: 1 addition & 1 deletion account.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type AccountInformation struct {

// GetAccountInformation 获取我的信息 无参数
func (c *Client) GetAccountInformation() (*AccountInformation, error) {
request := c.resty().R().SetHeader("Content-Type", "application/x-www-form-urlencoded").SetQueryParam("version", "1")
request := c.resty.R().SetQueryParam("version", "1")

var accountInfo AccountInformation

Expand Down
14 changes: 7 additions & 7 deletions article.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ type ArticlesInfo struct {

// GetArticlesInfo 获取文集基本信息
func (c *Client) GetArticlesInfo(id int) (*ArticlesInfo, error) {
resp, err := c.resty().R().SetHeader("Content-Type", "application/x-www-form-urlencoded").
resp, err := c.resty.R().
SetQueryParam("id", strconv.Itoa(id)).Get("https://api.bilibili.com/x/article/list/web/articles")
if err != nil {
return nil, errors.WithStack(err)
Expand Down Expand Up @@ -123,7 +123,7 @@ type ArticleViewInfo struct {

// GetArticleViewInfo 获取专栏文章基本信息
func (c *Client) GetArticleViewInfo(id int) (*ArticleViewInfo, error) {
resp, err := c.resty().R().SetHeader("Content-Type", "application/x-www-form-urlencoded").
resp, err := c.resty.R().
SetQueryParam("id", strconv.Itoa(id)).Get("https://api.bilibili.com/x/article/viewinfo")
if err != nil {
return nil, errors.WithStack(err)
Expand All @@ -149,7 +149,7 @@ func (c *Client) LikeArticle(id int, like bool) error {
} else {
typeNum = "2"
}
resp, err := c.resty().R().SetHeader("Content-Type", "application/x-www-form-urlencoded").SetQueryParams(map[string]string{
resp, err := c.resty.R().SetQueryParams(map[string]string{
"id": strconv.Itoa(id),
"type": typeNum,
"csrf": biliJct,
Expand All @@ -167,7 +167,7 @@ func (c *Client) CoinArticle(id, upid, multiply int) (bool, error) {
if len(biliJct) == 0 {
return false, errors.New("B站登录过期")
}
resp, err := c.resty().R().SetHeader("Content-Type", "application/x-www-form-urlencoded").SetQueryParams(map[string]string{
resp, err := c.resty.R().SetQueryParams(map[string]string{
"aid": strconv.Itoa(id),
"upid": strconv.Itoa(upid),
"multiply": strconv.Itoa(multiply),
Expand All @@ -190,7 +190,7 @@ func (c *Client) FavourArticle(id int) error {
if len(biliJct) == 0 {
return errors.New("B站登录过期")
}
resp, err := c.resty().R().SetHeader("Content-Type", "application/x-www-form-urlencoded").SetQueryParams(map[string]string{
resp, err := c.resty.R().SetQueryParams(map[string]string{
"id": strconv.Itoa(id),
"csrf": biliJct,
}).Post("https://api.bilibili.com/x/article/favorites/add")
Expand Down Expand Up @@ -305,7 +305,7 @@ func (c *Client) GetUserArticleList(mid, pn, ps int, sort string) (*UserArticleL
if len(sort) == 0 {
sort = "publish_time"
}
resp, err := c.resty().R().SetHeader("Content-Type", "application/x-www-form-urlencoded").SetQueryParams(map[string]string{
resp, err := c.resty.R().SetQueryParams(map[string]string{
"mid": strconv.Itoa(mid),
"pn": strconv.Itoa(pn),
"ps": strconv.Itoa(ps),
Expand Down Expand Up @@ -346,7 +346,7 @@ type UserArticlesList struct {

// GetUserArticlesList 获取用户专栏文集列表。sort可选值,0:最近更新,1:最多阅读。
func (c *Client) GetUserArticlesList(mid, sort int) (*UserArticlesList, error) {
resp, err := c.resty().R().SetHeader("Content-Type", "application/x-www-form-urlencoded").SetQueryParams(map[string]string{
resp, err := c.resty.R().SetQueryParams(map[string]string{
"mid": strconv.Itoa(mid),
"sort": strconv.Itoa(sort),
}).Get("https://api.bilibili.com/x/article/up/lists")
Expand Down
90 changes: 27 additions & 63 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,90 +11,54 @@ import (
)

type Client struct {
cookies []*http.Cookie
cookiesString string
timeout time.Duration
logger resty.Logger
resty *resty.Client
}

// New 返回一个 bilibili.Client
// New 返回一个默认的 bilibili.Client
func New() *Client {
return &Client{}
restyClient := resty.New().
SetTimeout(20*time.Second).
SetHeader("Accept", "application/json").
SetHeader("Accept-Language", "zh-CN,zh;q=0.9").
SetHeader("Content-Type", "application/x-www-form-urlencoded").
SetHeader("Origin", "https://www.bilibili.com").
SetHeader("Referer", "https://www.bilibili.com/").
SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0")
return NewWithClient(restyClient)
}

func Default() *Client {
return &Client{timeout: 20 * time.Second}
// NewWithClient 接收一个自定义的*resty.Client为参数
func NewWithClient(restyClient *resty.Client) *Client {
return &Client{resty: restyClient}
}

// SetTimeout 设置http请求超时时间
func (c *Client) SetTimeout(timeout time.Duration) {
c.timeout = timeout
}

// GetTimeout 获取http请求超时时间,默认20秒
func (c *Client) GetTimeout() time.Duration {
if c.timeout == 0 {
return time.Second * 20
}
return c.timeout
}

// SetLogger 设置logger
func (c *Client) SetLogger(logger resty.Logger) {
c.logger = logger
}

// GetLogger 获取logger,默认使用resty默认的logger
func (c *Client) GetLogger() resty.Logger {
return c.logger
func (c *Client) Resty() *resty.Client {
return c.resty
}

// GetCookiesString 获取字符串格式的cookies,方便自行存储后下次使用。配合下面的 SetCookiesString 使用。
func (c *Client) GetCookiesString() string {
return c.cookiesString
}

// SetCookiesString 设置Cookies,但是是字符串格式,配合 GetCookiesString 使用。有些功能必须登录或设置Cookies后才能使用。

func (c *Client) SetCookiesString(cookiesString string) {
c.cookiesString = cookiesString
c.cookies = (&resty.Response{RawResponse: &http.Response{Header: http.Header{
"Set-Cookie": strings.Split(cookiesString, "\n"),
}}}).Cookies()
}

// GetCookies 获取Cookies。配合下面的SetCookies使用。
func (c *Client) GetCookies() []*http.Cookie {
return c.cookies
}

// SetCookies 设置Cookies。有些功能必须登录之后才能使用,设置Cookies可以代替登录。
func (c *Client) SetCookies(cookies []*http.Cookie) {
c.cookies = cookies
cookies := c.resty.Cookies
cookieStrings := make([]string, 0, len(cookies))
for _, cookie := range c.cookies {
for _, cookie := range c.resty.Cookies {
cookieStrings = append(cookieStrings, cookie.String())
}
c.cookiesString = strings.Join(cookieStrings, "\n")
return strings.Join(cookieStrings, "\n")
}

// 获取resty的一个request
func (c *Client) resty() *resty.Client {
client := resty.New().SetTimeout(c.GetTimeout()).SetHeader("user-agent", "go")
if c.logger != nil {
client.SetLogger(c.logger)
}
if c.cookies != nil {
client.SetCookies(c.cookies)
}
return client
// SetCookiesString 设置Cookies,但是是字符串格式,配合 GetCookiesString 使用。有些功能必须登录或设置Cookies后才能使用。
func (c *Client) SetCookiesString(cookiesString string) {
c.resty.SetCookies((&resty.Response{RawResponse: &http.Response{Header: http.Header{
"Set-Cookie": strings.Split(cookiesString, "\n"),
}}}).Cookies())
}

// 根据key获取指定的cookie值
func (c *Client) getCookie(name string) string {
now := time.Now()
for _, cookie := range c.cookies {
if cookie.Name == name && now.Before(cookie.Expires) {
// 查找指定name的cookie
for _, cookie := range c.resty.Cookies {
if cookie.Name == name && (cookie.Expires.IsZero() || cookie.Expires.After(now)) {
return cookie.Value
}
}
Expand Down
2 changes: 1 addition & 1 deletion comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ func (c *Client) GetVideoComment(oidType, oid, sort, root int) (*HotReply, error
}

// 发送 HTTP GET 请求
resp, err := c.resty().R().SetHeader("Content-Type", "application/x-www-form-urlencoded").SetQueryParams(params).Get(url)
resp, err := c.resty.R().SetQueryParams(params).Get(url)
if err != nil {
// 返回错误
return nil, errors.WithStack(err)
Expand Down
Loading

0 comments on commit 7c6c44a

Please sign in to comment.