From 578e2f12fe1d587a1a068439f0343793a1bd46b8 Mon Sep 17 00:00:00 2001 From: pseudoyu Date: Thu, 17 Oct 2024 20:32:13 +0800 Subject: [PATCH] feat(route/bilibili): generate and replace `b_lsid` in cookie --- lib/routes/bilibili/cache.ts | 20 +++++++++++++++++++- lib/routes/bilibili/video.ts | 2 +- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/lib/routes/bilibili/cache.ts b/lib/routes/bilibili/cache.ts index 34c2502c397c1a..7e4c4951caf697 100644 --- a/lib/routes/bilibili/cache.ts +++ b/lib/routes/bilibili/cache.ts @@ -8,8 +8,18 @@ import puppeteer from '@/utils/puppeteer'; import { JSDOM } from 'jsdom'; let disableConfigCookie = false; + const getCookie = () => { if (!disableConfigCookie && Object.keys(config.bilibili.cookies).length > 0) { + // Update b_lsid in cookies + for (const key of Object.keys(config.bilibili.cookies)) { + const cookie = config.bilibili.cookies[key]; + if (cookie) { + const updatedCookie = cookie.replace(/b_lsid=[0-9A-F]+_[0-9A-F]+/, `b_lsid=${generateBLsid()}`); + config.bilibili.cookies[key] = updatedCookie; + } + } + return config.bilibili.cookies[Object.keys(config.bilibili.cookies)[Math.floor(Math.random() * Object.keys(config.bilibili.cookies).length)]]; } const key = 'bili-cookie'; @@ -22,7 +32,9 @@ const getCookie = () => { page.on('requestfinished', async (request) => { if (request.url() === 'https://api.bilibili.com/x/internal/gaia-gateway/ExClimbWuzhi') { const cookies = await page.cookies(); - const cookieString = cookies.map((cookie) => `${cookie.name}=${cookie.value}`).join('; '); + let cookieString = cookies.map((cookie) => `${cookie.name}=${cookie.value}`).join('; '); + + cookieString = cookieString.replace(/b_lsid=[0-9A-F]+_[0-9A-F]+/, `b_lsid=${generateBLsid()}`); resolve(cookieString); } }); @@ -35,6 +47,12 @@ const getCookie = () => { }); }; +const generateBLsid = () => { + const randomString = Array.from({ length: 8 }, () => '0123456789ABCDEF'[Math.floor(Math.random() * 16)]).join(''); + const timestamp = Date.now(); + return `${randomString}_${timestamp.toString(16).toUpperCase()}`; +}; + const clearCookie = () => { cache.set('bili-cookie'); disableConfigCookie = true; diff --git a/lib/routes/bilibili/video.ts b/lib/routes/bilibili/video.ts index 4013e17877fbb8..7e4ea66ad1e355 100644 --- a/lib/routes/bilibili/video.ts +++ b/lib/routes/bilibili/video.ts @@ -25,7 +25,7 @@ export const route: Route = { }, ], name: 'UP 主投稿', - maintainers: ['DIYgod', 'Konano'], + maintainers: ['DIYgod', 'Konano', 'pseudoyu'], handler, };