koishi-plugin-bilibili-notify 3.2.4 → 3.2.5-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/lib/biliAPI-BB6Ih4EM.mjs +659 -0
  2. package/lib/biliAPI-GF2e2-2V.js +664 -0
  3. package/lib/biliAPI.d.mts +82 -0
  4. package/lib/biliAPI.d.ts +75 -70
  5. package/lib/biliAPI.js +5 -762
  6. package/lib/biliAPI.mjs +4 -0
  7. package/lib/blive-BBVUYbxX.js +43 -0
  8. package/lib/blive-CyC_0-9A.mjs +37 -0
  9. package/lib/blive.d.mts +19 -0
  10. package/lib/blive.d.ts +15 -12
  11. package/lib/blive.js +4 -59
  12. package/lib/blive.mjs +3 -0
  13. package/lib/chunk-CrFLpmCJ.js +67 -0
  14. package/lib/chunk-DBmNgn_A.mjs +40 -0
  15. package/lib/comRegister-CcqOpkwB.mjs +1421 -0
  16. package/lib/comRegister-t7UnYFig.js +1426 -0
  17. package/lib/comRegister.d.mts +109 -0
  18. package/lib/comRegister.d.ts +103 -100
  19. package/lib/comRegister.js +6 -1896
  20. package/lib/comRegister.mjs +5 -0
  21. package/lib/database-4f9U--Ji.mjs +20 -0
  22. package/lib/database-Ct2yIdxk.js +37 -0
  23. package/lib/database-Do3O9MDA.d.mts +18 -0
  24. package/lib/database-KWDs372o.d.ts +18 -0
  25. package/lib/database.d.mts +2 -0
  26. package/lib/database.d.ts +2 -14
  27. package/lib/database.js +5 -14
  28. package/lib/database.mjs +3 -0
  29. package/lib/font/HYZhengYuan-75W.js +5 -0
  30. package/lib/font/HYZhengYuan-75W.mjs +5 -0
  31. package/lib/generateImg-E9JeFpQX.js +92628 -0
  32. package/lib/generateImg-zwzMYjw6.mjs +92623 -0
  33. package/lib/generateImg.d.mts +65 -0
  34. package/lib/generateImg.d.ts +59 -46
  35. package/lib/generateImg.js +4 -1504
  36. package/lib/generateImg.mjs +4 -0
  37. package/lib/img/arrow.js +5 -0
  38. package/lib/img/arrow.mjs +5 -0
  39. package/lib/index-DeGUe4jM.d.mts +265 -0
  40. package/lib/index-MJKYbMf7.d.ts +265 -0
  41. package/lib/index.d.mts +73 -0
  42. package/lib/index.d.ts +65 -62
  43. package/lib/index.js +296 -394
  44. package/lib/index.mjs +300 -0
  45. package/lib/page/0.mjs +0 -0
  46. package/lib/type/index.d.mts +2 -0
  47. package/lib/type/index.d.ts +2 -262
  48. package/lib/type/index.js +5 -18
  49. package/lib/type/index.mjs +3 -0
  50. package/lib/type-C5ZxPrgY.mjs +19 -0
  51. package/lib/type-WjCy4YMc.js +31 -0
  52. package/lib/utils/index.d.mts +15 -0
  53. package/lib/utils/index.d.ts +8 -6
  54. package/lib/utils/index.js +6 -102
  55. package/lib/utils/index.mjs +3 -0
  56. package/lib/utils-BoaYrSvG.js +79 -0
  57. package/lib/utils-C95cnBJG.mjs +61 -0
  58. package/package.json +16 -11
  59. package/readme.md +12 -2
  60. package/lib/img/arrow.png +0 -0
  61. /package/lib/{font/HYZhengYuan-75W.ttf → assets/HYZhengYuan-75W-CAgMN3FH.ttf} +0 -0
  62. /package/lib/page/{0.html → 0.js} +0 -0
package/lib/biliAPI.js CHANGED
@@ -1,762 +1,5 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __importDefault = (this && this.__importDefault) || function (mod) {
9
- return (mod && mod.__esModule) ? mod : { "default": mod };
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- const koishi_1 = require("koishi");
13
- const md5_1 = __importDefault(require("md5"));
14
- const node_crypto_1 = __importDefault(require("node:crypto"));
15
- const axios_1 = __importDefault(require("axios"));
16
- const tough_cookie_1 = require("tough-cookie");
17
- const axios_cookiejar_support_1 = require("axios-cookiejar-support");
18
- const jsdom_1 = require("jsdom");
19
- const utils_1 = require("./utils");
20
- const mixinKeyEncTab = [
21
- 46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49,
22
- 33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40, 61,
23
- 26, 17, 0, 1, 60, 51, 30, 4, 22, 25, 54, 21, 56, 59, 6, 63, 57, 62, 11, 36,
24
- 20, 34, 44, 52,
25
- ];
26
- // 在getUserInfo中检测到番剧出差的UID时,要传回的数据:
27
- const bangumiTripData = { code: 0, data: { live_room: { roomid: 931774 } } };
28
- const GET_USER_SPACE_DYNAMIC_LIST = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space?platform=web&features=itemOpusStyle";
29
- const GET_ALL_DYNAMIC_LIST = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all?platform=web&features=itemOpusStyle";
30
- const HAS_NEW_DYNAMIC = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all/update";
31
- const GET_COOKIES_INFO = "https://passport.bilibili.com/x/passport-login/web/cookie/info";
32
- const GET_USER_INFO = "https://api.bilibili.com/x/space/wbi/acc/info";
33
- const GET_MYSELF_INFO = "https://api.bilibili.com/x/member/web/account";
34
- const GET_LOGIN_QRCODE = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate";
35
- const GET_LOGIN_STATUS = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll";
36
- const GET_LIVE_ROOM_INFO = "https://api.live.bilibili.com/room/v1/Room/get_info";
37
- const GET_MASTER_INFO = "https://api.live.bilibili.com/live_user/v1/Master/info";
38
- const GET_TIME_NOW = "https://api.bilibili.com/x/report/click/now";
39
- const GET_SERVER_UTC_TIME = "https://interface.bilibili.com/serverdate.js";
40
- // 最近更新UP
41
- const GET_LATEST_UPDATED_UPS = "https://api.bilibili.com/x/polymer/web-dynamic/v1/portal";
42
- // 操作
43
- const MODIFY_RELATION = "https://api.bilibili.com/x/relation/modify";
44
- const CREATE_GROUP = "https://api.bilibili.com/x/relation/tag/create";
45
- const MODIFY_GROUP_MEMBER = "https://api.bilibili.com/x/relation/tags/addUsers";
46
- const GET_ALL_GROUP = "https://api.bilibili.com/x/relation/tags";
47
- const COPY_USER_TO_GROUP = "https://api.bilibili.com/x/relation/tags/copyUsers";
48
- const GET_RELATION_GROUP_DETAIL = "https://api.bilibili.com/x/relation/tag";
49
- // 直播
50
- const GET_LIVE_ROOM_INFO_STREAM_KEY = "https://api.live.bilibili.com/xlive/web-room/v1/index/getDanmuInfo";
51
- const GET_LIVE_ROOMS_INFO = "https://api.live.bilibili.com/room/v1/Room/get_status_info_by_uids";
52
- class BiliAPI extends koishi_1.Service {
53
- static inject = ["database", "notifier"];
54
- jar;
55
- client;
56
- apiConfig;
57
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
58
- loginData;
59
- loginNotifier;
60
- refreshCookieTimer;
61
- loginInfoIsLoaded = false;
62
- constructor(ctx, config) {
63
- super(ctx, "ba");
64
- this.apiConfig = config;
65
- }
66
- start() {
67
- // 创建新的http客户端(axios)
68
- this.createNewClient();
69
- // 从数据库加载cookies
70
- this.loadCookiesFromDatabase();
71
- }
72
- // WBI签名
73
- // 对 imgKey 和 subKey 进行字符顺序打乱编码
74
- getMixinKey = (orig) => mixinKeyEncTab
75
- .map((n) => orig[n])
76
- .join("")
77
- .slice(0, 32);
78
- // 为请求参数进行 wbi 签名
79
- encWbi(params, img_key, sub_key) {
80
- const mixin_key = this.getMixinKey(img_key + sub_key);
81
- const curr_time = Math.round(Date.now() / 1000);
82
- const chr_filter = /[!'()*]/g;
83
- Object.assign(params, { wts: curr_time }); // 添加 wts 字段
84
- // 按照 key 重排参数
85
- const query = Object.keys(params)
86
- .sort()
87
- .map((key) => {
88
- // 过滤 value 中的 "!'()*" 字符
89
- const value = params[key].toString().replace(chr_filter, "");
90
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
91
- })
92
- .join("&");
93
- const wbi_sign = (0, md5_1.default)(query + mixin_key); // 计算 w_rid
94
- return `${query}&w_rid=${wbi_sign}`;
95
- }
96
- async getWbi(params) {
97
- const web_keys = await this.getWbiKeys();
98
- const img_key = web_keys.img_key;
99
- const sub_key = web_keys.sub_key;
100
- const query = this.encWbi(params, img_key, sub_key);
101
- return query;
102
- }
103
- encrypt(text) {
104
- const iv = node_crypto_1.default.randomBytes(16);
105
- const cipher = node_crypto_1.default.createCipheriv("aes-256-cbc", Buffer.from(this.apiConfig.key), iv);
106
- const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
107
- return `${iv.toString("hex")}:${encrypted.toString("hex")}`;
108
- }
109
- decrypt(text) {
110
- const textParts = text.split(":");
111
- const iv = Buffer.from(textParts.shift(), "hex");
112
- const encryptedText = Buffer.from(textParts.join(":"), "hex");
113
- const decipher = node_crypto_1.default.createDecipheriv("aes-256-cbc", Buffer.from(this.apiConfig.key), iv);
114
- const decrypted = Buffer.concat([
115
- decipher.update(encryptedText),
116
- decipher.final(),
117
- ]);
118
- return decrypted.toString();
119
- }
120
- // BA API
121
- async getTheUserWhoIsLiveStreaming() {
122
- // 获取直播间信息流密钥
123
- const { data } = await this.client.get(GET_LATEST_UPDATED_UPS);
124
- // 返回data
125
- return data;
126
- }
127
- async getLiveRoomInfoStreamKey(roomId) {
128
- // 获取直播间信息流密钥
129
- const { data } = await this.client.get(`${GET_LIVE_ROOM_INFO_STREAM_KEY}?id=${roomId}`);
130
- // 返回data
131
- return data;
132
- }
133
- async getLiveRoomInfoByUids(uids) {
134
- // 构建查询参数
135
- const params = uids.map((uid) => `uids[]=${uid}`).join("&");
136
- // 获取直播间信息
137
- const { data } = await this.client.get(`${GET_LIVE_ROOMS_INFO}?${params}`);
138
- // 返回数据
139
- return data;
140
- }
141
- async getServerUTCTime() {
142
- const { data } = await this.client.get(GET_SERVER_UTC_TIME);
143
- const regex = /Date\.UTC\((.*?)\)/;
144
- const match = data.match(regex);
145
- if (match) {
146
- const timestamp = new Function(`return Date.UTC(${match[1]})`)();
147
- return timestamp / 1000;
148
- }
149
- throw new Error("解析服务器时间失败!");
150
- }
151
- async getTimeNow() {
152
- const { data } = await this.client.get(GET_TIME_NOW);
153
- return data;
154
- }
155
- async getAllGroup() {
156
- const { data } = await this.client.get(GET_ALL_GROUP);
157
- return data;
158
- }
159
- async removeUserFromGroup(mid) {
160
- // 获取csrf
161
- const csrf = this.getCSRF();
162
- // 将用户mid添加到groupId
163
- const { data } = await this.client.post(MODIFY_GROUP_MEMBER, {
164
- fids: mid,
165
- tagids: 0,
166
- csrf,
167
- }, {
168
- headers: {
169
- "Content-Type": "application/x-www-form-urlencoded",
170
- },
171
- });
172
- return data;
173
- }
174
- async copyUserToGroup(mid, groupId) {
175
- // 获取csrf
176
- const csrf = this.getCSRF();
177
- // 将用户mid添加到groupId
178
- const { data } = await this.client.post(COPY_USER_TO_GROUP, {
179
- fids: mid,
180
- tagids: groupId,
181
- csrf,
182
- }, {
183
- headers: {
184
- "Content-Type": "application/x-www-form-urlencoded",
185
- },
186
- });
187
- return data;
188
- }
189
- async getUserSpaceDynamic(mid) {
190
- const { data } = await this.client.get(`${GET_USER_SPACE_DYNAMIC_LIST}&host_mid=${mid}`);
191
- return data;
192
- }
193
- async createGroup(tag) {
194
- const { data } = await this.client.post(CREATE_GROUP, {
195
- tag,
196
- csrf: this.getCSRF(),
197
- }, {
198
- headers: {
199
- "Content-Type": "application/x-www-form-urlencoded",
200
- },
201
- });
202
- return data;
203
- }
204
- async getAllDynamic() {
205
- const { data } = await this.client.get(GET_ALL_DYNAMIC_LIST);
206
- return data;
207
- }
208
- async hasNewDynamic(updateBaseline) {
209
- const { data } = await this.client.get(`${HAS_NEW_DYNAMIC}?update_baseline=${updateBaseline}`);
210
- return data;
211
- }
212
- async follow(fid) {
213
- const { data } = await this.client.post(MODIFY_RELATION, {
214
- fid,
215
- act: 1,
216
- re_src: 11,
217
- csrf: this.getCSRF(),
218
- }, {
219
- headers: {
220
- "Content-Type": "application/x-www-form-urlencoded",
221
- },
222
- });
223
- return data;
224
- }
225
- async getRelationGroupDetail(tagid) {
226
- const { data } = await this.client.get(`${GET_RELATION_GROUP_DETAIL}?tagid=${tagid}`);
227
- return data;
228
- }
229
- // Check if Token need refresh
230
- async getCookieInfo(refreshToken) {
231
- const { data } = await this.client.get(`${GET_COOKIES_INFO}?csrf=${refreshToken}`);
232
- return data;
233
- }
234
- async getUserInfo(mid) {
235
- //如果为番剧出差的UID,则不从远程接口拉取数据,直接传回一段精简过的有效数据
236
- if (mid === "11783021") {
237
- console.log("检测到番剧出差UID,跳过远程用户接口访问");
238
- return bangumiTripData;
239
- }
240
- const wbi = await this.getWbi({ mid });
241
- const { data } = await this.client.get(`${GET_USER_INFO}?${wbi}`);
242
- return data;
243
- }
244
- // 获取最新的 img_key 和 sub_key
245
- async getWbiKeys() {
246
- const { data } = await this.client.get("https://api.bilibili.com/x/web-interface/nav");
247
- const { data: { wbi_img: { img_url, sub_url }, }, } = data;
248
- return {
249
- img_key: img_url.slice(img_url.lastIndexOf("/") + 1, img_url.lastIndexOf(".")),
250
- sub_key: sub_url.slice(sub_url.lastIndexOf("/") + 1, sub_url.lastIndexOf(".")),
251
- };
252
- }
253
- async getMyselfInfo() {
254
- const { data } = await this.client.get(GET_MYSELF_INFO);
255
- return data;
256
- }
257
- async getLoginQRCode() {
258
- const { data } = await this.client.get(GET_LOGIN_QRCODE);
259
- return data;
260
- }
261
- async getLoginStatus(qrcodeKey) {
262
- const { data } = await this.client.get(`${GET_LOGIN_STATUS}?qrcode_key=${qrcodeKey}`);
263
- return data;
264
- }
265
- async getLiveRoomInfo(roomId) {
266
- const { data } = await this.client.get(`${GET_LIVE_ROOM_INFO}?room_id=${roomId}`);
267
- return data;
268
- }
269
- async getMasterInfo(mid) {
270
- const { data } = await this.client.get(`${GET_MASTER_INFO}?uid=${mid}`);
271
- return data;
272
- }
273
- disposeNotifier() {
274
- if (this.loginNotifier)
275
- this.loginNotifier.dispose();
276
- }
277
- getRandomUserAgent() {
278
- const userAgents = [
279
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
280
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36",
281
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36",
282
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0",
283
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
284
- ];
285
- const index = Math.floor(Math.random() * userAgents.length);
286
- return userAgents[index];
287
- }
288
- createNewClient() {
289
- // 创建cookieJar
290
- this.jar = new tough_cookie_1.CookieJar();
291
- // 包装cookieJar
292
- this.client = (0, axios_cookiejar_support_1.wrapper)(axios_1.default.create({
293
- jar: this.jar,
294
- headers: {
295
- "Content-Type": "application/json",
296
- "User-Agent": this.apiConfig.userAgent !==
297
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
298
- ? this.apiConfig.userAgent
299
- : this.getRandomUserAgent(),
300
- Origin: "https://www.bilibili.com",
301
- Referer: "https://www.bilibili.com/",
302
- },
303
- }));
304
- }
305
- getCookies() {
306
- const cookies = JSON.stringify(this.jar.serializeSync().cookies);
307
- return cookies;
308
- }
309
- async getCookiesForHeader() {
310
- try {
311
- // 获取cookies对象
312
- const cookies = this.jar.serializeSync().cookies;
313
- // 将每个 cookie 对象转换为 "key=value" 形式,并用 "; " 连接起来
314
- const cookieHeader = cookies
315
- .map((cookie) => `${cookie.key}=${cookie.value}`)
316
- .join("; ");
317
- return cookieHeader;
318
- }
319
- catch (e) {
320
- console.error("无效的 JSON 格式:", e);
321
- return "";
322
- }
323
- }
324
- getLoginInfoIsLoaded() {
325
- return this.loginInfoIsLoaded;
326
- }
327
- async getLoginInfoFromDB() {
328
- // 读取数据库获取cookies
329
- const data = (await this.ctx.database.get("loginBili", 1))[0];
330
- // 判断是否登录
331
- if (data === undefined) {
332
- // 没有数据则直接返回
333
- // 未登录,在控制台提示
334
- this.loginNotifier = this.ctx.notifier.create({
335
- type: "warning",
336
- content: "您尚未登录,将无法使用插件提供的指令",
337
- });
338
- // 返回空值
339
- return {
340
- cookies: null,
341
- refresh_token: null,
342
- };
343
- }
344
- // 尝试解密
345
- try {
346
- // 解密数据
347
- const decryptedCookies = this.decrypt(data.bili_cookies);
348
- // 解密refresh_token
349
- const decryptedRefreshToken = this.decrypt(data.bili_refresh_token);
350
- // 解析从数据库读到的cookies
351
- const cookies = JSON.parse(decryptedCookies);
352
- // 返回值
353
- return {
354
- cookies,
355
- refresh_token: decryptedRefreshToken,
356
- };
357
- }
358
- catch (e) {
359
- // 数据库被篡改,在控制台提示
360
- this.loginNotifier = this.ctx.notifier.create({
361
- type: "warning",
362
- content: "数据库被篡改,请重新登录",
363
- });
364
- // 解密或解析失败,删除数据库登录信息
365
- await this.ctx.database.remove("loginBili", [1]);
366
- // 返回空值
367
- return {
368
- cookies: null,
369
- refresh_token: null,
370
- };
371
- }
372
- }
373
- getCSRF() {
374
- // 获取csrf
375
- return this.jar
376
- .serializeSync()
377
- .cookies.find((cookie) => cookie.key === "bili_jct").value;
378
- }
379
- async loadCookiesFromDatabase() {
380
- // Get login info from db
381
- const { cookies, refresh_token } = await this.getLoginInfoFromDB();
382
- // 判断是否有值
383
- if (!cookies || !refresh_token) {
384
- // Login info is loaded
385
- this.loginInfoIsLoaded = true;
386
- return;
387
- }
388
- // 定义CSRF Token
389
- let csrf;
390
- let expires;
391
- let domain;
392
- let path;
393
- let secure;
394
- let httpOnly;
395
- let sameSite;
396
- for (const cookieData of cookies) {
397
- // 获取key为bili_jct的值
398
- if (cookieData.key === "bili_jct") {
399
- csrf = cookieData.value;
400
- expires = new Date(cookieData.expires);
401
- domain = cookieData.domain;
402
- path = cookieData.path;
403
- secure = cookieData.secure;
404
- httpOnly = cookieData.httpOnly;
405
- sameSite = cookieData.sameSite;
406
- }
407
- // 创建一个完整的 Cookie 实例
408
- const cookie = new tough_cookie_1.Cookie({
409
- key: cookieData.key,
410
- value: cookieData.value,
411
- expires: new Date(cookieData.expires),
412
- domain: cookieData.domain,
413
- path: cookieData.path,
414
- secure: cookieData.secure,
415
- httpOnly: cookieData.httpOnly,
416
- sameSite: cookieData.sameSite,
417
- });
418
- this.jar.setCookieSync(cookie, `http${cookie.secure ? "s" : ""}://${cookie.domain}${cookie.path}`, {});
419
- }
420
- // 对于某些 IP 地址,需要在 Cookie 中提供任意非空的 buvid3 字段
421
- const buvid3Cookie = new tough_cookie_1.Cookie({
422
- key: "buvid3",
423
- value: "some_non_empty_value", // 设置任意非空值
424
- expires, // 设置过期时间
425
- domain, // 设置域名
426
- path, // 设置路径
427
- secure, // 设置是否为安全 cookie
428
- httpOnly, // 设置是否为 HttpOnly cookie
429
- sameSite, // 设置 SameSite 属性
430
- });
431
- this.jar.setCookieSync(buvid3Cookie, `http${buvid3Cookie.secure ? "s" : ""}://${buvid3Cookie.domain}${buvid3Cookie.path}`, {});
432
- // Login info is loaded
433
- this.loginInfoIsLoaded = true;
434
- // restart plugin check
435
- this.checkIfTokenNeedRefresh(refresh_token, csrf);
436
- // enable refresh cookies detect
437
- this.enableRefreshCookiesDetect();
438
- }
439
- enableRefreshCookiesDetect() {
440
- // 判断之前是否启动检测
441
- if (this.refreshCookieTimer)
442
- this.refreshCookieTimer();
443
- // Open scheduled tasks and check if token need refresh
444
- this.refreshCookieTimer = this.ctx.setInterval(async () => {
445
- // 每12小时检测一次
446
- // 从数据库获取登录信息
447
- const { cookies, refresh_token } = await this.getLoginInfoFromDB();
448
- // 判断是否有值
449
- if (!cookies || !refresh_token)
450
- return;
451
- // 获取csrf
452
- const csrf = cookies.find((cookie) => {
453
- // 判断key是否为bili_jct
454
- if (cookie.key === "bili_jct")
455
- return true;
456
- }).value;
457
- // 检查是否需要更新
458
- this.checkIfTokenNeedRefresh(refresh_token, csrf);
459
- }, 3600000);
460
- }
461
- async checkIfTokenNeedRefresh(refreshToken, csrf, times = 3) {
462
- // 定义方法
463
- const notifyAndError = (info) => {
464
- // 设置控制台通知
465
- this.loginNotifier = this.ctx.notifier.create({
466
- type: "warning",
467
- content: info,
468
- });
469
- // 重置为未登录状态
470
- this.createNewClient();
471
- // 关闭定时器
472
- this.refreshCookieTimer();
473
- // 抛出错误
474
- throw new Error(info);
475
- };
476
- // 尝试获取Cookieinfo
477
- try {
478
- const { data } = await this.getCookieInfo(refreshToken);
479
- // 不需要刷新,直接返回
480
- if (!data.refresh)
481
- return;
482
- }
483
- catch (e) {
484
- // 发送三次仍网络错误则直接刷新cookie
485
- if (times >= 1) {
486
- // 等待3秒再次尝试
487
- this.ctx.setTimeout(() => {
488
- this.checkIfTokenNeedRefresh(refreshToken, csrf, times - 1);
489
- }, 3000);
490
- }
491
- // 如果请求失败,有可能是404,直接刷新cookie
492
- }
493
- // 定义Key
494
- const publicKey = await node_crypto_1.default.subtle.importKey("jwk", {
495
- kty: "RSA",
496
- n: "y4HdjgJHBlbaBN04VERG4qNBIFHP6a3GozCl75AihQloSWCXC5HDNgyinEnhaQ_4-gaMud_GF50elYXLlCToR9se9Z8z433U3KjM-3Yx7ptKkmQNAMggQwAVKgq3zYAoidNEWuxpkY_mAitTSRLnsJW-NCTa0bqBFF6Wm1MxgfE",
497
- e: "AQAB",
498
- }, { name: "RSA-OAEP", hash: "SHA-256" }, true, ["encrypt"]);
499
- // 定义获取CorrespondPath方法
500
- async function getCorrespondPath(timestamp) {
501
- const data = new TextEncoder().encode(`refresh_${timestamp}`);
502
- const encrypted = new Uint8Array(await node_crypto_1.default.subtle.encrypt({ name: "RSA-OAEP" }, publicKey, data));
503
- return encrypted.reduce((str, c) => str + c.toString(16).padStart(2, "0"), "");
504
- }
505
- // 获取CorrespondPath
506
- const ts = Date.now();
507
- const correspondPath = await getCorrespondPath(ts);
508
- // 获取refresh_csrf
509
- const { data: refreshCsrfHtml } = await this.client.get(`https://www.bilibili.com/correspond/1/${correspondPath}`);
510
- // 创建一个虚拟的DOM元素
511
- const { document } = new jsdom_1.JSDOM(refreshCsrfHtml).window;
512
- // 提取标签name为1-name的内容
513
- const targetElement = document.getElementById("1-name");
514
- const refresh_csrf = targetElement ? targetElement.textContent : null;
515
- // 发送刷新请求
516
- const { data: refreshData } = await this.client.post("https://passport.bilibili.com/x/passport-login/web/cookie/refresh", {
517
- csrf,
518
- refresh_csrf,
519
- source: "main_web",
520
- refresh_token: refreshToken,
521
- }, {
522
- headers: {
523
- "Content-Type": "application/x-www-form-urlencoded",
524
- },
525
- });
526
- // 检查是否有其他问题
527
- switch (refreshData.code) {
528
- // 账号未登录
529
- case -101:
530
- return this.createNewClient();
531
- case -111: {
532
- await this.ctx.database.remove("loginBili", [1]);
533
- notifyAndError("csrf 校验错误,请重新登录");
534
- break;
535
- }
536
- case 86095: {
537
- await this.ctx.database.remove("loginBili", [1]);
538
- notifyAndError("refresh_csrf 错误或 refresh_token 与 cookie 不匹配,请重新登录");
539
- }
540
- }
541
- // 更新 新的cookies和refresh_token
542
- const encryptedCookies = this.encrypt(this.getCookies());
543
- const encryptedRefreshToken = this.encrypt(refreshData.data.refresh_token);
544
- await this.ctx.database.upsert("loginBili", [
545
- {
546
- id: 1,
547
- bili_cookies: encryptedCookies,
548
- bili_refresh_token: encryptedRefreshToken,
549
- },
550
- ]);
551
- // Get new csrf from cookies
552
- const newCsrf = this.jar.serializeSync().cookies.find((cookie) => {
553
- if (cookie.key === "bili_jct")
554
- return true;
555
- }).value;
556
- // Accept update
557
- const { data: aceeptData } = await this.client.post("https://passport.bilibili.com/x/passport-login/web/confirm/refresh", {
558
- csrf: newCsrf,
559
- refresh_token: refreshToken,
560
- }, {
561
- headers: {
562
- "Content-Type": "application/x-www-form-urlencoded",
563
- },
564
- });
565
- // 检查是否有其他问题
566
- switch (aceeptData.code) {
567
- case -111: {
568
- await this.ctx.database.remove("loginBili", [1]);
569
- notifyAndError("csrf 校验失败,请重新登录");
570
- break;
571
- }
572
- case -400:
573
- throw new Error("请求错误");
574
- }
575
- // 没有问题,cookies已更新完成
576
- }
577
- }
578
- __decorate([
579
- (0, utils_1.Retry)({
580
- attempts: 3,
581
- onFailure(error, attempts) {
582
- this.logger.error(`getTheUserWhoIsLiveStreaming() 第${attempts}次失败: ${error.message}`);
583
- },
584
- })
585
- ], BiliAPI.prototype, "getTheUserWhoIsLiveStreaming", null);
586
- __decorate([
587
- (0, utils_1.Retry)({
588
- attempts: 3,
589
- onFailure(error, attempts) {
590
- this.logger.error(`getLiveRoomInfoStreamKey() 第${attempts}次失败: ${error.message}`);
591
- },
592
- })
593
- ], BiliAPI.prototype, "getLiveRoomInfoStreamKey", null);
594
- __decorate([
595
- (0, utils_1.Retry)({
596
- attempts: 3,
597
- onFailure(error, attempts) {
598
- this.logger.error(`getLiveRoomInfoByUids() 第${attempts}次失败: ${error.message}`);
599
- },
600
- })
601
- ], BiliAPI.prototype, "getLiveRoomInfoByUids", null);
602
- __decorate([
603
- (0, utils_1.Retry)({
604
- attempts: 3,
605
- onFailure(error, attempts) {
606
- this.logger.error(`getServerUTCTime() 第${attempts}次失败: ${error.message}`);
607
- },
608
- })
609
- ], BiliAPI.prototype, "getServerUTCTime", null);
610
- __decorate([
611
- (0, utils_1.Retry)({
612
- attempts: 3,
613
- onFailure(error, attempts) {
614
- this.logger.error(`getTimeNow() 第${attempts}次失败: ${error.message}`);
615
- },
616
- })
617
- ], BiliAPI.prototype, "getTimeNow", null);
618
- __decorate([
619
- (0, utils_1.Retry)({
620
- attempts: 3,
621
- onFailure(error, attempts) {
622
- this.logger.error(`getAllGroup() 第${attempts}次失败: ${error.message}`);
623
- },
624
- })
625
- ], BiliAPI.prototype, "getAllGroup", null);
626
- __decorate([
627
- (0, utils_1.Retry)({
628
- attempts: 3,
629
- onFailure(error, attempts) {
630
- this.logger.error(`removeUserFromGroup() 第${attempts}次失败: ${error.message}`);
631
- },
632
- })
633
- ], BiliAPI.prototype, "removeUserFromGroup", null);
634
- __decorate([
635
- (0, utils_1.Retry)({
636
- attempts: 3,
637
- onFailure(error, attempts) {
638
- this.logger.error(`copyUserToGroup() 第${attempts}次失败: ${error.message}`);
639
- },
640
- })
641
- ], BiliAPI.prototype, "copyUserToGroup", null);
642
- __decorate([
643
- (0, utils_1.Retry)({
644
- attempts: 3,
645
- onFailure(error, attempts) {
646
- this.logger.error(`getUserSpaceDynamic() 第${attempts}次失败: ${error.message}`);
647
- },
648
- })
649
- ], BiliAPI.prototype, "getUserSpaceDynamic", null);
650
- __decorate([
651
- (0, utils_1.Retry)({
652
- attempts: 3,
653
- onFailure(error, attempts) {
654
- this.logger.error(`createGroup() 第${attempts}次失败: ${error.message}`);
655
- },
656
- })
657
- ], BiliAPI.prototype, "createGroup", null);
658
- __decorate([
659
- (0, utils_1.Retry)({
660
- attempts: 3,
661
- onFailure(error, attempts) {
662
- this.logger.error(`getAllDynamic() 第${attempts}次失败: ${error.message}`);
663
- },
664
- })
665
- ], BiliAPI.prototype, "getAllDynamic", null);
666
- __decorate([
667
- (0, utils_1.Retry)({
668
- attempts: 3,
669
- onFailure(error, attempts) {
670
- this.logger.error(`hasNewDynamic() 第${attempts}次失败: ${error.message}`);
671
- },
672
- })
673
- ], BiliAPI.prototype, "hasNewDynamic", null);
674
- __decorate([
675
- (0, utils_1.Retry)({
676
- attempts: 3,
677
- onFailure(error, attempts) {
678
- this.logger.error(`follow() 第${attempts}次失败: ${error.message}`);
679
- },
680
- })
681
- ], BiliAPI.prototype, "follow", null);
682
- __decorate([
683
- (0, utils_1.Retry)({
684
- attempts: 3,
685
- onFailure(error, attempts) {
686
- this.logger.error(`getRelationGroupDetail() 第${attempts}次失败: ${error.message}`);
687
- },
688
- })
689
- ], BiliAPI.prototype, "getRelationGroupDetail", null);
690
- __decorate([
691
- (0, utils_1.Retry)({
692
- attempts: 3,
693
- onFailure(error, attempts) {
694
- this.logger.error(`getCookieInfo() 第${attempts}次失败: ${error.message}`);
695
- },
696
- })
697
- ], BiliAPI.prototype, "getCookieInfo", null);
698
- __decorate([
699
- (0, utils_1.Retry)({
700
- attempts: 3,
701
- onFailure(error, attempts) {
702
- this.logger.error(`getUserInfo() 第${attempts}次失败: ${error.message}`);
703
- },
704
- })
705
- ], BiliAPI.prototype, "getUserInfo", null);
706
- __decorate([
707
- (0, utils_1.Retry)({
708
- attempts: 3,
709
- onFailure(error, attempts) {
710
- this.logger.error(`getWbiKeys() 第${attempts}次失败: ${error.message}`);
711
- },
712
- })
713
- ], BiliAPI.prototype, "getWbiKeys", null);
714
- __decorate([
715
- (0, utils_1.Retry)({
716
- attempts: 3,
717
- onFailure(error, attempts) {
718
- this.logger.error(`getMyselfInfo() 第${attempts}次失败: ${error.message}`);
719
- },
720
- })
721
- ], BiliAPI.prototype, "getMyselfInfo", null);
722
- __decorate([
723
- (0, utils_1.Retry)({
724
- attempts: 3,
725
- onFailure(error, attempts) {
726
- this.logger.error(`getLoginQRCode() 第${attempts}次失败: ${error.message}`);
727
- },
728
- })
729
- ], BiliAPI.prototype, "getLoginQRCode", null);
730
- __decorate([
731
- (0, utils_1.Retry)({
732
- attempts: 3,
733
- onFailure(error, attempts) {
734
- this.logger.error(`getLoginStatus() 第${attempts}次失败: ${error.message}`);
735
- },
736
- })
737
- ], BiliAPI.prototype, "getLoginStatus", null);
738
- __decorate([
739
- (0, utils_1.Retry)({
740
- attempts: 3,
741
- onFailure(error, attempts) {
742
- this.logger.error(`getLiveRoomInfo() 第${attempts}次失败: ${error.message}`);
743
- },
744
- })
745
- ], BiliAPI.prototype, "getLiveRoomInfo", null);
746
- __decorate([
747
- (0, utils_1.Retry)({
748
- attempts: 3,
749
- onFailure(error, attempts) {
750
- this.logger.error(`getMasterInfo() 第${attempts}次失败: ${error.message}`);
751
- },
752
- })
753
- ], BiliAPI.prototype, "getMasterInfo", null);
754
- (function (BiliAPI) {
755
- BiliAPI.Config = koishi_1.Schema.object({
756
- userAgent: koishi_1.Schema.string(),
757
- key: koishi_1.Schema.string()
758
- .pattern(/^[0-9a-f]{32}$/)
759
- .required(),
760
- });
761
- })(BiliAPI || (BiliAPI = {}));
762
- exports.default = BiliAPI;
1
+ const require_chunk = require('./chunk-CrFLpmCJ.js');
2
+ require('./utils-BoaYrSvG.js');
3
+ const require_biliAPI = require('./biliAPI-GF2e2-2V.js');
4
+
5
+ module.exports = require_biliAPI.biliAPI_default;