Skip to content

Commit

Permalink
feat: support av
Browse files Browse the repository at this point in the history
  • Loading branch information
Ovler-Young committed Mar 21, 2024
1 parent 3ed8495 commit 840c390
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/lib/server/av2bv.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// https://github.com/SocialSisterYi/bilibili-API-collect/blob/d4cb300051671443faee9493b57e6c35ef5bb526/docs/misc/bvid_desc.md?plain=1#L73-L105
// Licensed under CC-BY-NC 4.0

const XOR_CODE = 23442827791579n;
const MASK_CODE = 2251799813685247n;
const MAX_AID = 1n << 51n;
const BASE = 58n;

const data = 'FcwAPNKTMug3GV5Lj7EJnHpWsx4tb8haYeviqBz6rkCy12mUSDQX9RdoZf';

export function av2bv(aid) {
const bytes = ['B', 'V', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0'];
let bvIndex = bytes.length - 1;
let tmp = (MAX_AID | BigInt(aid)) ^ XOR_CODE;
while (tmp > 0) {
bytes[bvIndex] = data[Number(tmp % BigInt(BASE))];
tmp = tmp / BASE;
bvIndex -= 1;
}
[bytes[3], bytes[9]] = [bytes[9], bytes[3]];
[bytes[4], bytes[7]] = [bytes[7], bytes[4]];
return bytes.join('');
}

export function bv2av(bvid) {
const bvidArr = Array.from(bvid);
[bvidArr[3], bvidArr[9]] = [bvidArr[9], bvidArr[3]];
[bvidArr[4], bvidArr[7]] = [bvidArr[7], bvidArr[4]];
bvidArr.splice(0, 3);
const tmp = bvidArr.reduce((pre, bvidChar) => pre * BASE + BigInt(data.indexOf(bvidChar)), 0n);
return Number((tmp & MASK_CODE) ^ XOR_CODE);
}
10 changes: 10 additions & 0 deletions src/lib/server/b23.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { av2bv } from './av2bv.js';

const fetchRedirectUrl = async (url: URL | string): Promise<URL | null> => {
try {
const response = await fetch(url, { redirect: 'follow' });
Expand All @@ -19,6 +21,14 @@ const resolveB23 = async (str: string): Promise<string> => {
let match: RegExpExecArray | null;
let updatedString = str;

const avRegex = /\/av(\d+)/g;
if ((match = avRegex.exec(str)) !== null) {
let av = match[1];
const bv = av2bv(match[1]);
console.info("av" + av + " -> " + bv);
updatedString = updatedString.replace("av" + av, bv);
}

while ((match = urlRegex.exec(str)) !== null) {
const originalUrl = match[0];
const redirectedUrl = await fetchRedirectUrl(originalUrl);
Expand Down

0 comments on commit 840c390

Please sign in to comment.