-
Notifications
You must be signed in to change notification settings - Fork 0
/
Wbi.go
275 lines (257 loc) · 8.06 KB
/
Wbi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package Wbi
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"sync"
"time"
)
var (
mixinKeyEncTab = [64]int{
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,
}
cache sync.Map
lastUpdateTime time.Time
)
// Sign 为链接签名
func Sign(url string) (string, error) {
return signAndGenerateURL(url)
}
// GetWbiKeysCached 获取缓存的imgKey和subKey
func GetWbiKeysCached() (imgKey string, subKey string) {
return getWbiKeysCached()
}
// GetWbiKeys 获取最新的imgKey和subKey
func GetWbiKeys() (imgKey string, subKey string) {
return getWbiKeys()
}
func signAndGenerateURL(urlStr string) (string, error) {
urlObj, err := url.Parse(urlStr)
if err != nil {
return "", err
}
imgKey, subKey := getWbiKeysCached()
query := urlObj.Query()
params := map[string]string{}
for k, v := range query {
params[k] = v[0]
}
newParams := encWbi(params, imgKey, subKey)
for k, v := range newParams {
query.Set(k, v)
}
urlObj.RawQuery = query.Encode()
newUrlStr := urlObj.String()
return newUrlStr, nil
}
func encWbi(params map[string]string, imgKey, subKey string) map[string]string {
mixinKey := getMixinKey(imgKey + subKey)
currTime := strconv.FormatInt(time.Now().Unix(), 10)
params["wts"] = currTime
// Sort keys
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
// Remove unwanted characters
for k, v := range params {
v = sanitizeString(v)
params[k] = v
}
// Build URL parameters
query := url.Values{}
for _, k := range keys {
query.Set(k, params[k])
}
queryStr := query.Encode()
// Calculate w_rid
hash := md5.Sum([]byte(queryStr + mixinKey))
params["w_rid"] = hex.EncodeToString(hash[:])
return params
}
func getMixinKey(orig string) string {
var str strings.Builder
for _, v := range mixinKeyEncTab {
if v < len(orig) {
str.WriteByte(orig[v])
}
}
return str.String()[:32]
}
func sanitizeString(s string) string {
unwantedChars := []string{"!", "'", "(", ")", "*"}
for _, char := range unwantedChars {
s = strings.ReplaceAll(s, char, "")
}
return s
}
func updateCache() {
if time.Since(lastUpdateTime).Minutes() < 10 {
return
}
imgKey, subKey := getWbiKeys()
cache.Store("imgKey", imgKey)
cache.Store("subKey", subKey)
lastUpdateTime = time.Now()
}
func getWbiKeysCached() (imgKey string, subKey string) {
updateCache()
imgKeyI, _ := cache.Load("imgKey")
subKeyI, _ := cache.Load("subKey")
return imgKeyI.(string), subKeyI.(string)
}
func getWbiKeys() (imgKey string, subKey string) {
resp, err := http.Get("https://api.bilibili.com/x/web-interface/nav")
if err != nil {
fmt.Printf("Error: %s", err)
return "", ""
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error: %s", err)
return "", ""
}
n := &navCut{}
err = json.Unmarshal(body, n)
if err != nil {
fmt.Printf("Error: %s", err)
return "", ""
}
// imgURL := gjson.Get(json, "data.wbi_img.img_url").String()
imgURL := n.Data.WbiImg.ImgUrl
// subURL := gjson.Get(json, "data.wbi_img.sub_url").String()
subURL := n.Data.WbiImg.SubUrl
imgKey = strings.Split(strings.Split(imgURL, "/")[len(strings.Split(imgURL, "/"))-1], ".")[0]
subKey = strings.Split(strings.Split(subURL, "/")[len(strings.Split(subURL, "/"))-1], ".")[0]
return imgKey, subKey
}
type navCut struct {
Code int `json:"code"`
Message string `json:"message"`
Ttl int `json:"ttl"`
Data struct {
WbiImg struct {
ImgUrl string `json:"img_url"`
SubUrl string `json:"sub_url"`
} `json:"wbi_img"`
}
}
type nav struct {
Code int `json:"code"`
Message string `json:"message"`
Ttl int `json:"ttl"`
Data struct {
IsLogin bool `json:"isLogin"`
EmailVerified int `json:"email_verified"`
Face string `json:"face"`
FaceNft int `json:"face_nft"`
FaceNftType int `json:"face_nft_type"`
LevelInfo struct {
CurrentLevel int `json:"current_level"`
CurrentMin int `json:"current_min"`
CurrentExp int `json:"current_exp"`
NextExp string `json:"next_exp"`
} `json:"level_info"`
Mid int `json:"mid"`
MobileVerified int `json:"mobile_verified"`
Money float64 `json:"money"`
Moral int `json:"moral"`
Official struct {
Role int `json:"role"`
Title string `json:"title"`
Desc string `json:"desc"`
Type int `json:"type"`
} `json:"official"`
OfficialVerify struct {
Type int `json:"type"`
Desc string `json:"desc"`
} `json:"officialVerify"`
Pendant struct {
Pid int `json:"pid"`
Name string `json:"name"`
Image string `json:"image"`
Expire int `json:"expire"`
ImageEnhance string `json:"image_enhance"`
ImageEnhanceFrame string `json:"image_enhance_frame"`
NPid int `json:"n_pid"`
} `json:"pendant"`
Scores int `json:"scores"`
Uname string `json:"uname"`
VipDueDate int64 `json:"vipDueDate"`
VipStatus int `json:"vipStatus"`
VipType int `json:"vipType"`
VipPayType int `json:"vip_pay_type"`
VipThemeType int `json:"vip_theme_type"`
VipLabel struct {
Path string `json:"path"`
Text string `json:"text"`
LabelTheme string `json:"label_theme"`
TextColor string `json:"text_color"`
BgStyle int `json:"bg_style"`
BgColor string `json:"bg_color"`
BorderColor string `json:"border_color"`
UseImgLabel bool `json:"use_img_label"`
ImgLabelUriHans string `json:"img_label_uri_hans"`
ImgLabelUriHant string `json:"img_label_uri_hant"`
ImgLabelUriHansStatic string `json:"img_label_uri_hans_static"`
ImgLabelUriHantStatic string `json:"img_label_uri_hant_static"`
} `json:"vip_label"`
VipAvatarSubscript int `json:"vip_avatar_subscript"`
VipNicknameColor string `json:"vip_nickname_color"`
Vip struct {
Type int `json:"type"`
Status int `json:"status"`
DueDate int64 `json:"due_date"`
VipPayType int `json:"vip_pay_type"`
ThemeType int `json:"theme_type"`
Label struct {
Path string `json:"path"`
Text string `json:"text"`
LabelTheme string `json:"label_theme"`
TextColor string `json:"text_color"`
BgStyle int `json:"bg_style"`
BgColor string `json:"bg_color"`
BorderColor string `json:"border_color"`
UseImgLabel bool `json:"use_img_label"`
ImgLabelUriHans string `json:"img_label_uri_hans"`
ImgLabelUriHant string `json:"img_label_uri_hant"`
ImgLabelUriHansStatic string `json:"img_label_uri_hans_static"`
ImgLabelUriHantStatic string `json:"img_label_uri_hant_static"`
} `json:"label"`
AvatarSubscript int `json:"avatar_subscript"`
NicknameColor string `json:"nickname_color"`
Role int `json:"role"`
AvatarSubscriptUrl string `json:"avatar_subscript_url"`
TvVipStatus int `json:"tv_vip_status"`
TvVipPayType int `json:"tv_vip_pay_type"`
TvDueDate int `json:"tv_due_date"`
} `json:"vip"`
Wallet struct {
Mid int `json:"mid"`
BcoinBalance int `json:"bcoin_balance"`
CouponBalance int `json:"coupon_balance"`
CouponDueTime int `json:"coupon_due_time"`
} `json:"wallet"`
HasShop bool `json:"has_shop"`
ShopUrl string `json:"shop_url"`
AllowanceCount int `json:"allowance_count"`
AnswerStatus int `json:"answer_status"`
IsSeniorMember int `json:"is_senior_member"`
WbiImg struct {
ImgUrl string `json:"img_url"`
SubUrl string `json:"sub_url"`
} `json:"wbi_img"`
IsJury bool `json:"is_jury"`
} `json:"data"`
}