// ==UserScript== // @name 哔哩哔哩主页 IP 属地 // @namespace https://maxchang.me // @version 0.1.0 // @author maxchang3 // @description 在哔哩哔哩个人主页显示 IP 属地。 // @license MIT // @icon https://www.bilibili.com/favicon.ico // @match https://space.bilibili.com/* // @connect app.bilibili.com // @connect passport.bilibili.com // @grant GM.registerMenuCommand // @grant GM.xmlHttpRequest // @grant GM_addStyle // @grant GM_getValue // @grant GM_info // @grant GM_registerMenuCommand // @grant GM_setClipboard // @grant GM_setValue // @grant GM_xmlhttpRequest // @run-at document-idle // @noframes // ==/UserScript== (function() { "use strict"; var s = new Set(); var _css = async (t) => { if (s.has(t)) return; s.add(t); ((c) => { if (typeof GM_addStyle === "function") GM_addStyle(c); else (document.head || document.documentElement).appendChild(document.createElement("style")).append(c); })(t); }; var _GM = (() => typeof GM != "undefined" ? GM : void 0)(); var _GM_getValue = (() => typeof GM_getValue != "undefined" ? GM_getValue : void 0)(); var _GM_info = (() => typeof GM_info != "undefined" ? GM_info : void 0)(); var _GM_registerMenuCommand = (() => typeof GM_registerMenuCommand != "undefined" ? GM_registerMenuCommand : void 0)(); var _GM_setClipboard = (() => typeof GM_setClipboard != "undefined" ? GM_setClipboard : void 0)(); var _GM_setValue = (() => typeof GM_setValue != "undefined" ? GM_setValue : void 0)(); var _GM_xmlhttpRequest = (() => typeof GM_xmlhttpRequest != "undefined" ? GM_xmlhttpRequest : void 0)(); var QrCodeDataType = ((QrCodeDataType2) => { QrCodeDataType2[QrCodeDataType2["Border"] = -1] = "Border"; QrCodeDataType2[QrCodeDataType2["Data"] = 0] = "Data"; QrCodeDataType2[QrCodeDataType2["Function"] = 1] = "Function"; QrCodeDataType2[QrCodeDataType2["Position"] = 2] = "Position"; QrCodeDataType2[QrCodeDataType2["Timing"] = 3] = "Timing"; QrCodeDataType2[QrCodeDataType2["Alignment"] = 4] = "Alignment"; return QrCodeDataType2; })(QrCodeDataType || {}); var LOW = [0, 1]; var MEDIUM = [1, 0]; var QUARTILE = [2, 3]; var HIGH = [3, 2]; var EccMap = { L: LOW, M: MEDIUM, Q: QUARTILE, H: HIGH }; var NUMERIC_REGEX = /^\d*$/; var ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+./:-]*$/; var ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; var MIN_VERSION = 1; var MAX_VERSION = 40; var PENALTY_N1 = 3; var PENALTY_N2 = 3; var PENALTY_N3 = 40; var PENALTY_N4 = 10; var ECC_CODEWORDS_PER_BLOCK = [ [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30] ]; var NUM_ERROR_CORRECTION_BLOCKS = [ [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81] ]; var QrCode = class { constructor(version, ecc, dataCodewords, msk) { this.version = version; this.ecc = ecc; if (version < MIN_VERSION || version > MAX_VERSION) throw new RangeError("Version value out of range"); if (msk < -1 || msk > 7) throw new RangeError("Mask value out of range"); this.size = version * 4 + 17; const row = Array.from({ length: this.size }).fill(false); for (let i = 0; i < this.size; i++) { this.modules.push(row.slice()); this.types.push(row.map(() => 0)); } this.drawFunctionPatterns(); const allCodewords = this.addEccAndInterleave(dataCodewords); this.drawCodewords(allCodewords); if (msk === -1) { let minPenalty = 1e9; for (let i = 0; i < 8; i++) { this.applyMask(i); this.drawFormatBits(i); const penalty = this.getPenaltyScore(); if (penalty < minPenalty) { msk = i; minPenalty = penalty; } this.applyMask(i); } } this.mask = msk; this.applyMask(msk); this.drawFormatBits(msk); } size; mask; modules = []; types = []; getModule(x, y) { return x >= 0 && x < this.size && y >= 0 && y < this.size && this.modules[y][x]; } drawFunctionPatterns() { for (let i = 0; i < this.size; i++) { this.setFunctionModule(6, i, i % 2 === 0, QrCodeDataType.Timing); this.setFunctionModule(i, 6, i % 2 === 0, QrCodeDataType.Timing); } this.drawFinderPattern(3, 3); this.drawFinderPattern(this.size - 4, 3); this.drawFinderPattern(3, this.size - 4); const alignPatPos = this.getAlignmentPatternPositions(); const numAlign = alignPatPos.length; for (let i = 0; i < numAlign; i++) for (let j = 0; j < numAlign; j++) if (!(i === 0 && j === 0 || i === 0 && j === numAlign - 1 || i === numAlign - 1 && j === 0)) this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]); this.drawFormatBits(0); this.drawVersion(); } drawFormatBits(mask) { const data = this.ecc[1] << 3 | mask; let rem = data; for (let i = 0; i < 10; i++) rem = rem << 1 ^ (rem >>> 9) * 1335; const bits = (data << 10 | rem) ^ 21522; for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i)); this.setFunctionModule(8, 7, getBit(bits, 6)); this.setFunctionModule(8, 8, getBit(bits, 7)); this.setFunctionModule(7, 8, getBit(bits, 8)); for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i)); for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i)); for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i)); this.setFunctionModule(8, this.size - 8, true); } drawVersion() { if (this.version < 7) return; let rem = this.version; for (let i = 0; i < 12; i++) rem = rem << 1 ^ (rem >>> 11) * 7973; const bits = this.version << 12 | rem; for (let i = 0; i < 18; i++) { const color = getBit(bits, i); const a = this.size - 11 + i % 3; const b = Math.floor(i / 3); this.setFunctionModule(a, b, color); this.setFunctionModule(b, a, color); } } drawFinderPattern(x, y) { for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) { const dist = Math.max(Math.abs(dx), Math.abs(dy)); const xx = x + dx; const yy = y + dy; if (xx >= 0 && xx < this.size && yy >= 0 && yy < this.size) this.setFunctionModule(xx, yy, dist !== 2 && dist !== 4, QrCodeDataType.Position); } } drawAlignmentPattern(x, y) { for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1, QrCodeDataType.Alignment); } setFunctionModule(x, y, isDark, type = QrCodeDataType.Function) { this.modules[y][x] = isDark; this.types[y][x] = type; } addEccAndInterleave(data) { const ver = this.version; const ecl = this.ecc; if (data.length !== getNumDataCodewords(ver, ecl)) throw new RangeError("Invalid argument"); const numBlocks = NUM_ERROR_CORRECTION_BLOCKS[ecl[0]][ver]; const blockEccLen = ECC_CODEWORDS_PER_BLOCK[ecl[0]][ver]; const rawCodewords = Math.floor(getNumRawDataModules(ver) / 8); const numShortBlocks = numBlocks - rawCodewords % numBlocks; const shortBlockLen = Math.floor(rawCodewords / numBlocks); const blocks = []; const rsDiv = reedSolomonComputeDivisor(blockEccLen); for (let i = 0, k = 0; i < numBlocks; i++) { const dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); k += dat.length; const ecc = reedSolomonComputeRemainder(dat, rsDiv); if (i < numShortBlocks) dat.push(0); blocks.push(dat.concat(ecc)); } const result = []; for (let i = 0; i < blocks[0].length; i++) blocks.forEach((block, j) => { if (i !== shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]); }); return result; } drawCodewords(data) { if (data.length !== Math.floor(getNumRawDataModules(this.version) / 8)) throw new RangeError("Invalid argument"); let i = 0; for (let right = this.size - 1; right >= 1; right -= 2) { if (right === 6) right = 5; for (let vert = 0; vert < this.size; vert++) for (let j = 0; j < 2; j++) { const x = right - j; const y = (right + 1 & 2) === 0 ? this.size - 1 - vert : vert; if (!this.types[y][x] && i < data.length * 8) { this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7)); i++; } } } } applyMask(mask) { if (mask < 0 || mask > 7) throw new RangeError("Mask value out of range"); for (let y = 0; y < this.size; y++) for (let x = 0; x < this.size; x++) { let invert; switch (mask) { case 0: invert = (x + y) % 2 === 0; break; case 1: invert = y % 2 === 0; break; case 2: invert = x % 3 === 0; break; case 3: invert = (x + y) % 3 === 0; break; case 4: invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0; break; case 5: invert = x * y % 2 + x * y % 3 === 0; break; case 6: invert = (x * y % 2 + x * y % 3) % 2 === 0; break; case 7: invert = ((x + y) % 2 + x * y % 3) % 2 === 0; break; default: throw new Error("Unreachable"); } if (!this.types[y][x] && invert) this.modules[y][x] = !this.modules[y][x]; } } getPenaltyScore() { let result = 0; for (let y = 0; y < this.size; y++) { let runColor = false; let runX = 0; const runHistory = [0, 0, 0, 0, 0, 0, 0]; for (let x = 0; x < this.size; x++) if (this.modules[y][x] === runColor) { runX++; if (runX === 5) result += PENALTY_N1; else if (runX > 5) result++; } else { this.finderPenaltyAddHistory(runX, runHistory); if (!runColor) result += this.finderPenaltyCountPatterns(runHistory) * PENALTY_N3; runColor = this.modules[y][x]; runX = 1; } result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3; } for (let x = 0; x < this.size; x++) { let runColor = false; let runY = 0; const runHistory = [0, 0, 0, 0, 0, 0, 0]; for (let y = 0; y < this.size; y++) if (this.modules[y][x] === runColor) { runY++; if (runY === 5) result += PENALTY_N1; else if (runY > 5) result++; } else { this.finderPenaltyAddHistory(runY, runHistory); if (!runColor) result += this.finderPenaltyCountPatterns(runHistory) * PENALTY_N3; runColor = this.modules[y][x]; runY = 1; } result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3; } for (let y = 0; y < this.size - 1; y++) for (let x = 0; x < this.size - 1; x++) { const color = this.modules[y][x]; if (color === this.modules[y][x + 1] && color === this.modules[y + 1][x] && color === this.modules[y + 1][x + 1]) result += PENALTY_N2; } let dark = 0; for (const row of this.modules) dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark); const total = this.size * this.size; const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1; result += k * PENALTY_N4; return result; } getAlignmentPatternPositions() { if (this.version === 1) return []; else { const numAlign = Math.floor(this.version / 7) + 2; const step = this.version === 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2; const result = [6]; for (let pos = this.size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos); return result; } } finderPenaltyCountPatterns(runHistory) { const n = runHistory[1]; const core = n > 0 && runHistory[2] === n && runHistory[3] === n * 3 && runHistory[4] === n && runHistory[5] === n; return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); } finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) { if (currentRunColor) { this.finderPenaltyAddHistory(currentRunLength, runHistory); currentRunLength = 0; } currentRunLength += this.size; this.finderPenaltyAddHistory(currentRunLength, runHistory); return this.finderPenaltyCountPatterns(runHistory); } finderPenaltyAddHistory(currentRunLength, runHistory) { if (runHistory[0] === 0) currentRunLength += this.size; runHistory.pop(); runHistory.unshift(currentRunLength); } }; function appendBits(val, len, bb) { if (len < 0 || len > 31 || val >>> len !== 0) throw new RangeError("Value out of range"); for (let i = len - 1; i >= 0; i--) bb.push(val >>> i & 1); } function getBit(x, i) { return (x >>> i & 1) !== 0; } var QrSegment = class { constructor(mode, numChars, bitData) { this.mode = mode; this.numChars = numChars; this.bitData = bitData; if (numChars < 0) throw new RangeError("Invalid argument"); this.bitData = bitData.slice(); } getData() { return this.bitData.slice(); } }; var MODE_NUMERIC = [1, 10, 12, 14]; var MODE_ALPHANUMERIC = [2, 9, 11, 13]; var MODE_BYTE = [4, 8, 16, 16]; function numCharCountBits(mode, ver) { return mode[Math.floor((ver + 7) / 17) + 1]; } function makeBytes(data) { const bb = []; for (const b of data) appendBits(b, 8, bb); return new QrSegment(MODE_BYTE, data.length, bb); } function makeNumeric(digits) { if (!isNumeric(digits)) throw new RangeError("String contains non-numeric characters"); const bb = []; for (let i = 0; i < digits.length;) { const n = Math.min(digits.length - i, 3); appendBits(Number.parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb); i += n; } return new QrSegment(MODE_NUMERIC, digits.length, bb); } function makeAlphanumeric(text) { if (!isAlphanumeric(text)) throw new RangeError("String contains unencodable characters in alphanumeric mode"); const bb = []; let i = 0; for (; i + 2 <= text.length; i += 2) { let temp = ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45; temp += ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1)); appendBits(temp, 11, bb); } if (i < text.length) appendBits(ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb); return new QrSegment(MODE_ALPHANUMERIC, text.length, bb); } function makeSegments(text) { if (text === "") return []; else if (isNumeric(text)) return [makeNumeric(text)]; else if (isAlphanumeric(text)) return [makeAlphanumeric(text)]; else return [makeBytes(toUtf8ByteArray(text))]; } function isNumeric(text) { return NUMERIC_REGEX.test(text); } function isAlphanumeric(text) { return ALPHANUMERIC_REGEX.test(text); } function getTotalBits(segs, version) { let result = 0; for (const seg of segs) { const ccbits = numCharCountBits(seg.mode, version); if (seg.numChars >= 1 << ccbits) return Number.POSITIVE_INFINITY; result += 4 + ccbits + seg.bitData.length; } return result; } function toUtf8ByteArray(str) { str = encodeURI(str); const result = []; for (let i = 0; i < str.length; i++) if (str.charAt(i) !== "%") result.push(str.charCodeAt(i)); else { result.push(Number.parseInt(str.substring(i + 1, i + 3), 16)); i += 2; } return result; } function getNumRawDataModules(ver) { if (ver < MIN_VERSION || ver > MAX_VERSION) throw new RangeError("Version number out of range"); let result = (16 * ver + 128) * ver + 64; if (ver >= 2) { const numAlign = Math.floor(ver / 7) + 2; result -= (25 * numAlign - 10) * numAlign - 55; if (ver >= 7) result -= 36; } return result; } function getNumDataCodewords(ver, ecl) { return Math.floor(getNumRawDataModules(ver) / 8) - ECC_CODEWORDS_PER_BLOCK[ecl[0]][ver] * NUM_ERROR_CORRECTION_BLOCKS[ecl[0]][ver]; } function reedSolomonComputeDivisor(degree) { if (degree < 1 || degree > 255) throw new RangeError("Degree out of range"); const result = []; for (let i = 0; i < degree - 1; i++) result.push(0); result.push(1); let root = 1; for (let i = 0; i < degree; i++) { for (let j = 0; j < result.length; j++) { result[j] = reedSolomonMultiply(result[j], root); if (j + 1 < result.length) result[j] ^= result[j + 1]; } root = reedSolomonMultiply(root, 2); } return result; } function reedSolomonComputeRemainder(data, divisor) { const result = divisor.map((_) => 0); for (const b of data) { const factor = b ^ result.shift(); result.push(0); divisor.forEach((coef, i) => result[i] ^= reedSolomonMultiply(coef, factor)); } return result; } function reedSolomonMultiply(x, y) { if (x >>> 8 !== 0 || y >>> 8 !== 0) throw new RangeError("Byte out of range"); let z = 0; for (let i = 7; i >= 0; i--) { z = z << 1 ^ (z >>> 7) * 285; z ^= (y >>> i & 1) * x; } return z; } function encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) { if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7) throw new RangeError("Invalid value"); let version; let dataUsedBits; for (version = minVersion;; version++) { const dataCapacityBits2 = getNumDataCodewords(version, ecl) * 8; const usedBits = getTotalBits(segs, version); if (usedBits <= dataCapacityBits2) { dataUsedBits = usedBits; break; } if (version >= maxVersion) throw new RangeError("Data too long"); } for (const newEcl of [MEDIUM, QUARTILE, HIGH]) if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) ecl = newEcl; const bb = []; for (const seg of segs) { appendBits(seg.mode[0], 4, bb); appendBits(seg.numChars, numCharCountBits(seg.mode, version), bb); for (const b of seg.getData()) bb.push(b); } const dataCapacityBits = getNumDataCodewords(version, ecl) * 8; appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb); appendBits(0, (8 - bb.length % 8) % 8, bb); for (let padByte = 236; bb.length < dataCapacityBits; padByte ^= 253) appendBits(padByte, 8, bb); const dataCodewords = Array.from({ length: Math.ceil(bb.length / 8) }, () => 0); bb.forEach((b, i) => dataCodewords[i >>> 3] |= b << 7 - (i & 7)); return new QrCode(version, ecl, dataCodewords, mask); } function encode(data, options) { const { ecc = "L", boostEcc = false, minVersion = 1, maxVersion = 40, maskPattern = -1, border = 1 } = options || {}; const segment = typeof data === "string" ? makeSegments(data) : Array.isArray(data) ? [makeBytes(data)] : void 0; if (!segment) throw new Error(`uqr only supports encoding string and binary data, but got: ${typeof data}`); const qr = encodeSegments(segment, EccMap[ecc], minVersion, maxVersion, maskPattern, boostEcc); const result = addBorder({ version: qr.version, maskPattern: qr.mask, size: qr.size, data: qr.modules, types: qr.types }, border); if (options?.invert) result.data = result.data.map((row) => row.map((mod) => !mod)); options?.onEncoded?.(result); return result; } function addBorder(input, border = 1) { if (!border) return input; const { size } = input; const newSize = size + border * 2; input.size = newSize; input.data.forEach((row) => { for (let i = 0; i < border; i++) { row.unshift(false); row.push(false); } }); for (let i = 0; i < border; i++) { input.data.unshift(Array.from({ length: newSize }, (_) => false)); input.data.push(Array.from({ length: newSize }, (_) => false)); } const b = QrCodeDataType.Border; input.types.forEach((row) => { for (let i = 0; i < border; i++) { row.unshift(b); row.push(b); } }); for (let i = 0; i < border; i++) { input.types.unshift(Array.from({ length: newSize }, (_) => b)); input.types.push(Array.from({ length: newSize }, (_) => b)); } return input; } var fromNumH = (n) => n / 2 ** 32 | 0; var fromNumL = (n) => n >>> 0; function setU64FromNum(view, byteOffset, n, isLE) { const h = fromNumH(n); const l = fromNumL(n); view.setUint32(byteOffset, isLE ? l : h, isLE); view.setUint32(byteOffset + 4, isLE ? h : l, isLE); } function isBytes(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; } var atitle = (title) => title ? `"${title}" ` : ""; function anumber(n, title = "") { if (typeof n !== "number") throw new TypeError(atitle(title) + "expected number, got " + typeof n); if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(atitle(title) + "expected integer >= 0, got " + n); return n; } function abytes(value, length, title = "") { if (isBytes(value) && (length === void 0 || value.length === length)) return value; if (length !== void 0) anumber(length, "length"); const bytes = isBytes(value); const ofLen = length !== void 0 ? ` of length ${length}` : ""; const got = bytes ? `length=${value.length}` : `type=${typeof value}`; const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got; if (!bytes) throw new TypeError(message); throw new RangeError(message); } var aobject = (value, label) => { if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value); }; var aopts = (value, label) => { aobject(value, label); const proto = Object.getPrototypeOf(value); if (proto !== Object.prototype && proto !== null) throw new TypeError(`"${label}" expected plain object`); if (Object.hasOwn(value, "__proto__")) throw new TypeError(`"${label}.__proto__" is not allowed`); }; function aexists(instance, checkFinished = true) { if (instance.destroyed) throw new Error("hash was destroyed"); if (checkFinished && instance.finished) throw new Error("digest() was already called"); } function aoutput(out, instance) { abytes(out, void 0, "output"); const min = instance.outputLen; if (!(out.length >= min)) throw new RangeError("\"output\" expected length >= " + min); } function clean(...arrays) { for (let i = 0; i < arrays.length; i++) arrays[i].fill(0); } function createView(arr) { return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); } function rotl(word, shift) { return word << shift | word >>> 32 - shift >>> 0; } function checkOpts(defaults, opts, title = "opts") { aopts(defaults, "defaults"); if (opts !== void 0) aopts(opts, title); return Object.assign(Object.create(null), defaults, opts); } function createHasher(hashCons, info = {}) { if (typeof hashCons !== "function") throw new TypeError("\"hashCons\" expected function, got type=" + typeof hashCons); info = checkOpts({}, info, "info"); const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); const tmp = hashCons(void 0); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.canXOF = tmp.canXOF; hashC.create = (opts) => hashCons(opts); Object.assign(hashC, info); return Object.freeze(hashC); } function Chi(a, b, c) { return a & b ^ ~a & c; } var HashMD = class { blockLen; outputLen; canXOF = false; padOffset; isLE; buffer; view; finished = false; length = 0; pos = 0; destroyed = false; constructor(blockLen, outputLen, padOffset, isLE) { this.blockLen = blockLen; this.outputLen = outputLen; this.padOffset = padOffset; this.isLE = isLE; this.buffer = new Uint8Array(blockLen); this.view = createView(this.buffer); } update(data) { aexists(this); abytes(data); const { view, buffer, blockLen } = this; const len = data.length; let processed = false; for (let pos = 0; pos < len;) { const take = Math.min(blockLen - this.pos, len - pos); if (take === blockLen) { const dataView = createView(data); for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); processed = true; continue; } buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos); this.pos += take; pos += take; if (this.pos === blockLen) { this.process(view, 0); this.pos = 0; processed = true; } } this.length += data.length; if (processed) this.roundClean(); return this; } digestInto(out) { aexists(this); aoutput(out, this); this.finished = true; const { buffer, view, blockLen, isLE } = this; let { pos } = this; buffer[pos++] = 128; buffer.fill(0, pos); if (this.padOffset > blockLen - pos) { this.process(view, 0); buffer.fill(0); } setU64FromNum(view, blockLen - 8, this.length * 8, isLE); this.process(view, 0); this.roundClean(); const oview = out === buffer ? view : createView(out); const len = this.outputLen; const outLen = len / 4; const state = this.get(); if (len % 4 || outLen > state.length) throw new Error("invalid outputLen"); for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE); } digest() { const { buffer, outputLen } = this; this.digestInto(buffer); const res = buffer.slice(0, outputLen); this.destroy(); return res; } _cloneIntoMeta(to) { const { buffer, length, finished, destroyed, pos } = this; to.destroyed = destroyed; to.finished = finished; to.length = length; to.pos = pos; if (pos) to.buffer.set(buffer); return to; } clone() { return this._cloneInto(); } }; var SHA1_IV = Uint32Array.from([1732584193, 4023233417, 2562383102, 271733878, 3285377520]); var p32 = Math.pow(2, 32); var K = Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1)))); var MD5_IV = SHA1_IV.slice(0, 4); var MD5_W = new Uint32Array(16); var MD5_SHIFTS = (() => { const S = [[7, 12, 17, 22], [5, 9, 14, 20], [4, 11, 16, 23], [6, 10, 15, 21]]; return Uint8Array.from({ length: 64 }, (_, i) => S[Math.floor(i / 16)][i % 4]); })(); var _MD5 = class extends HashMD { A = MD5_IV[0] | 0; B = MD5_IV[1] | 0; C = MD5_IV[2] | 0; D = MD5_IV[3] | 0; constructor() { super(64, 16, 8, true); } get() { const { A, B, C, D } = this; return [A, B, C, D]; } set(A, B, C, D) { this.A = A | 0; this.B = B | 0; this.C = C | 0; this.D = D | 0; } _cloneInto(to) { (to ||= new this.constructor()).set(...this.get()); return this._cloneIntoMeta(to); } process(view, offset) { for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true); let { A, B, C, D } = this; for (let i = 0; i < 64; i++) { let F, g; if (i < 16) { F = Chi(B, C, D); g = i; } else if (i < 32) { F = Chi(D, B, C); g = (5 * i + 1) % 16; } else if (i < 48) { F = B ^ C ^ D; g = (3 * i + 5) % 16; } else { F = C ^ (B | ~D); g = 7 * i % 16; } F = F + A + K[i] + MD5_W[g]; A = D; D = C; C = B; B = B + rotl(F, MD5_SHIFTS[i]); } A = A + this.A | 0; B = B + this.B | 0; C = C + this.C | 0; D = D + this.D | 0; this.set(A, B, C, D); } roundClean() { clean(MD5_W); } destroy() { this.destroyed = true; this.set(0, 0, 0, 0); clean(this.buffer); } }; var md5 = createHasher(() => new _MD5()); var events = []; var maxEvents = 50; function record(event, fields = {}) { const entry = { ...fields, at: new Date().toISOString(), event }; events.push(entry); if (events.length > maxEvents) events.shift(); console.info("[BiliRevealForSpace]", entry); } function diagnosticReport(hasCredential) { return JSON.stringify({ scriptVersion: _GM_info.script.version, manager: _GM_info.scriptHandler, managerVersion: _GM_info.version, hasCredential, events }, null, 2); } var sites = { space: "https://app.bilibili.com/x/v2/space", tokenInfo: "https://passport.bilibili.com/x/passport-login/oauth2/info", qrStart: "https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code", qrPoll: "https://passport.bilibili.com/x/passport-tv-login/qrcode/poll" }; var timeoutMs = 1e4; var cooldowns = new Map(); var rateLimitCodes = new Set([-352, -412, -799]); function asRecord(value) { if (value !== null && typeof value === "object" && !Array.isArray(value)) return value; } var RequestFailure = class extends Error { kind; code; constructor(kind, code) { super(kind); this.kind = kind; this.code = code; } }; function failureMessage(error) { if (!(error instanceof RequestFailure)) return "脚本执行出错,请查看诊断信息"; switch (error.kind) { case "timeout": return "请求超时,请稍后重试"; case "network": return "请求失败,请检查网络和脚本管理器的跨域权限"; case "http": return `请求失败(HTTP ${error.code})`; case "api": return `B 站接口返回错误(${error.code})`; case "response": return "B 站接口返回了无法识别的数据"; case "rateLimited": return "请求暂受 B 站限制,请稍后重试"; case "unsupported": return "当前脚本管理器缺少跨域请求接口"; case "aborted": return "操作已取消"; default: return error.kind; } } function send(options, signal) { if (signal?.aborted) throw new RequestFailure("aborted"); const { promise, resolve, reject } = Promise.withResolvers(); let handle; const cleanup = () => { clearTimeout(timer); signal?.removeEventListener("abort", cancel); }; const fail = (kind) => { cleanup(); reject(new RequestFailure(kind)); }; const stop = (kind) => { fail(kind); handle?.abort(); }; const cancel = () => stop("aborted"); const timer = setTimeout(() => stop("timeout"), timeoutMs); signal?.addEventListener("abort", cancel, { once: true }); const callbacks = { onload: (response) => { cleanup(); resolve(response); }, onerror: () => fail("network"), ontimeout: () => fail("timeout"), onabort: () => fail("aborted") }; const request = { ...options, ...callbacks, anonymous: true, timeout: timeoutMs }; try { if (typeof _GM_xmlhttpRequest === "function") handle = _GM_xmlhttpRequest(request); else if (typeof _GM?.xmlHttpRequest === "function") { const pending = _GM.xmlHttpRequest(request); handle = pending; pending.then(callbacks.onload, callbacks.onerror); } else fail("unsupported"); } catch { fail("network"); } return promise; } function cooldownFor(headers) { const retryAfter = /^retry-after:\s*([^\r\n]+)/im.exec(headers)?.[1]?.trim(); if (!retryAfter) return 6e4; const delay = /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1e3 : Date.parse(retryAfter) - Date.now(); return Number.isFinite(delay) && delay > 0 ? delay : 6e4; } function parseJSONRecord(text) { try { const record = asRecord(JSON.parse(text)); if (record) return record; } catch {} throw new RequestFailure("response"); } async function request(endpoint, options = {}) { const base = new URL(sites[endpoint]); const started = Date.now(); let status = null; let code = null; let outcome = "ok"; try { const cooldown = cooldowns.get(base.origin); if (cooldown && cooldown > started) throw new RequestFailure("rateLimited"); const response = await send({ method: options.body === void 0 ? "GET" : "POST", url: options.query ? `${base.href}?${options.query}` : base.href, data: options.body, headers: options.body === void 0 ? options.headers : { ...options.headers, "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }, responseType: "json" }, options.signal); status = response.status; if (status === 412 || status === 429) { cooldowns.set(base.origin, Date.now() + cooldownFor(response.responseHeaders)); throw new RequestFailure("rateLimited", status); } if (status === 0) throw new RequestFailure("network"); if (status < 200 || status >= 300) throw new RequestFailure("http", status); const payload = asRecord(response.response) ?? parseJSONRecord(typeof response.response === "string" ? response.response : response.responseText); if (typeof payload.code !== "number") throw new RequestFailure("response"); code = payload.code; if (rateLimitCodes.has(code)) { cooldowns.set(base.origin, Date.now() + cooldownFor(response.responseHeaders)); throw new RequestFailure("rateLimited", code); } return { code, data: payload.data }; } catch (error) { outcome = error instanceof RequestFailure ? error.kind : "error"; throw error; } finally { record("request", { endpoint, status, code, outcome, durationMs: Date.now() - started }); } } var spaceClient = { key: "1d8b6e7d45233436", secret: "560c52ccd288fed045859ed18bffd973" }; var loginClient = { key: "783bbb7264451d82", secret: "2653583c8873dea268ab9386918b1d65" }; var build = "6720300"; var mobiApp = "android"; var textEncoder = new TextEncoder(); var qrLifetimeMs = 18e4; var qrPollIntervalMs = 2e3; function signParameters(parameters, client) { const timestamp = Math.floor(Date.now() / 1e3); const query = new URLSearchParams({ ...parameters, appkey: client.key, ts: String(timestamp) }); query.sort(); const encoded = query.toString(); const digest = md5(textEncoder.encode(encoded + client.secret)); return `${encoded}&sign=${digest.toHex?.() ?? Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`; } function nonEmptyText(value) { return typeof value === "string" && value.trim() ? value.trim() : void 0; } function uid(value) { if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) return String(value); if (typeof value === "string" && /^[1-9]\d*$/.test(value)) return value; } function describeTags(value) { if (Array.isArray(value)) return `array(${value.length})`; return value === null ? "null" : typeof value; } function parseSpace(data, vmid) { const card = asRecord(asRecord(data)?.card); if (!card) { record("space.response", { card: false }); throw new RequestFailure("response"); } const returnedUID = uid(card.mid); const groups = [card.space_tag, card.space_tag_bottom]; record("space.response", { card: true, uidMatches: returnedUID === void 0 ? null : returnedUID === vmid, spaceTag: describeTags(groups[0]), spaceTagBottom: describeTags(groups[1]) }); if (card.mid != null && returnedUID !== vmid) throw new RequestFailure("response"); for (const group of groups) { if (!Array.isArray(group)) continue; for (const item of group) { const tag = asRecord(item); const title = nonEmptyText(tag?.title); if (tag?.type === "location" && title) return title; } } if (groups.some((group) => group != null && !Array.isArray(group))) throw new RequestFailure("response"); } function readCredential(data) { const response = asRecord(data); const token = asRecord(response?.token_info) ?? response; const accessToken = nonEmptyText(token?.access_token); if (!accessToken) throw new RequestFailure("response"); const expiresIn = token?.expires_in; const expiresAt = typeof expiresIn === "number" && Number.isSafeInteger(expiresIn) && expiresIn > 0 ? Date.now() + expiresIn * 1e3 : void 0; return { accessToken, refreshToken: nonEmptyText(token?.refresh_token), expiresAt }; } function qrURL(value) { if (typeof value === "string") try { const url = new URL(value); if (url.origin === "https://passport.bilibili.com" && !url.username && !url.password) return url.href; } catch {} throw new RequestFailure("response"); } function createBiliAPI(deviceID) { const headers = { "user-agent": "Mozilla/5.0 BiliDroid/6.72.0 os/android model/XQ-CT72 mobi_app/android build/6720300 channel/bilih5 innerVer/6720310 osVer/12 network/2", buvid: deviceID }; const loginParameters = { build, c_locale: "zh-Hans_CN", channel: "website", local_id: deviceID, mobi_app: mobiApp, platform: "android", s_locale: "zh-Hans_CN" }; return { async getLocation(vmid, accessToken, signal) { const { code, data } = await request("space", { query: signParameters({ access_key: accessToken, build, mobi_app: mobiApp, vmid }, spaceClient), headers, signal }); if (code !== 0) throw new RequestFailure("api", code); return parseSpace(data, vmid); }, async verifyCredential(accessToken) { const { code, data } = await request("tokenInfo", { query: signParameters({ access_key: accessToken, actionKey: "appkey" }, loginClient), headers }); if (code === -101) return "invalid"; if (code !== 0) throw new RequestFailure("api", code); if (!uid(asRecord(data)?.mid)) throw new RequestFailure("response"); return "valid"; }, async createQR(signal) { const { code, data } = await request("qrStart", { body: signParameters(loginParameters, loginClient), headers, signal }); if (code !== 0) throw new RequestFailure("api", code); const payload = asRecord(data); const authCode = nonEmptyText(payload?.auth_code); if (!authCode) throw new RequestFailure("response"); return { authCode, url: qrURL(payload?.url) }; }, async pollQR(authCode, signal) { const { code, data } = await request("qrPoll", { body: signParameters({ ...loginParameters, auth_code: authCode }, loginClient), headers, signal }); switch (code) { case 0: return { state: "authorized", credential: readCredential(data) }; case 86038: return { state: "expired" }; case 86039: return { state: "waiting" }; case 86090: return { state: "scanned" }; default: throw new RequestFailure("api", code); } } }; } function drawQR(text) { const { data, size } = encode(text, { ecc: "M", border: 4 }); const canvas = document.createElement("canvas"); const scale = Math.max(2, Math.floor(280 / size)); canvas.width = canvas.height = size * scale; canvas.setAttribute("role", "img"); canvas.setAttribute("aria-label", "授权二维码"); const context = canvas.getContext("2d"); if (!context) throw new Error("Canvas unavailable"); context.fillStyle = "#fff"; context.fillRect(0, 0, canvas.width, canvas.height); context.fillStyle = "#000"; data.forEach((row, y) => { row.forEach((dark, x) => { if (dark) context.fillRect(x * scale, y * scale, scale, scale); }); }); return canvas; } function waitToPoll(signal) { signal.throwIfAborted(); return new Promise((resolve, reject) => { const cancel = () => { clearTimeout(timer); reject(signal.reason); }; const timer = setTimeout(() => { signal.removeEventListener("abort", cancel); resolve(); }, qrPollIntervalMs); signal.addEventListener("abort", cancel, { once: true }); }); } function createAuthorization(api, onAuthorized) { let activeDialog; return async () => { if (activeDialog?.open) return; const dialog = document.createElement("dialog"); dialog.className = "bilireveal-auth"; dialog.setAttribute("aria-labelledby", "bilireveal-auth-title"); const header = document.createElement("header"); header.className = "bilireveal-auth__header"; const heading = document.createElement("h2"); heading.className = "bilireveal-auth__title"; heading.id = "bilireveal-auth-title"; heading.textContent = "扫码授权"; const close = document.createElement("button"); close.className = "bilireveal-auth__close"; close.type = "button"; close.autofocus = true; close.textContent = "×"; close.setAttribute("aria-label", "关闭"); header.append(heading, close); const qrPanel = document.createElement("div"); qrPanel.className = "bilireveal-auth__qr"; const status = document.createElement("p"); status.className = "bilireveal-auth__status"; status.setAttribute("role", "status"); const action = document.createElement("button"); action.className = "bilireveal-auth__action"; action.type = "button"; dialog.append(header, qrPanel, status, action); document.body.append(dialog); activeDialog = dialog; let controller; let state; function show(next, message, canRetry = false) { state = next; dialog.dataset.state = next; status.textContent = message; action.hidden = next !== "success" && !canRetry; action.textContent = next === "success" ? "完成" : "重新获取二维码"; qrPanel.hidden = next === "success" || next === "expired" || next === "error"; if (qrPanel.hidden || next === "saving") qrPanel.replaceChildren(); } async function requestQR() { if (controller || !dialog.open) return; const attempt = new AbortController(); controller = attempt; const { signal } = attempt; const expired = new DOMException("QR code expired", "TimeoutError"); const expiry = setTimeout(() => attempt.abort(expired), qrLifetimeMs); try { show("loading", "正在生成二维码…"); record("auth.started"); const QR = await api.createQR(signal); signal.throwIfAborted(); qrPanel.replaceChildren(drawQR(QR.url)); show("waiting", "请使用哔哩哔哩 App 扫码"); for (;;) { await waitToPoll(signal); const result = await api.pollQR(QR.authCode, signal); signal.throwIfAborted(); if (result.state === "expired") { attempt.abort(expired); return; } if (result.state === "authorized") { clearTimeout(expiry); show("saving", "正在保存授权并查询当前主页…"); const message = await onAuthorized(result.credential); signal.throwIfAborted(); heading.textContent = "授权成功"; show("success", message); return; } if (result.state === "scanned" && state !== "scanned") show("scanned", "已扫码,请在 B 站 App 确认"); } } catch (error) { if (!signal.aborted) { const reason = error instanceof RequestFailure ? error.kind : "error"; record("auth.failed", { reason }); show("error", failureMessage(error), reason !== "rateLimited"); } } finally { clearTimeout(expiry); controller = void 0; if (signal.reason === expired && dialog.open) { record("auth.expired"); show("expired", "二维码已过期,请重新获取。", true); } } } close.addEventListener("click", () => { controller?.abort(); dialog.close(); }); action.addEventListener("click", () => { if (state === "success") dialog.close(); else requestQR(); }); dialog.addEventListener("cancel", () => controller?.abort()); dialog.addEventListener("close", () => { controller?.abort(); dialog.remove(); if (activeDialog === dialog) activeDialog = void 0; }, { once: true }); try { dialog.showModal(); } catch (error) { dialog.remove(); if (activeDialog === dialog) activeDialog = void 0; throw error; } await requestQR(); }; } var credentialKey = "biliReveal.credential"; var deviceKey = "biliReveal.deviceId"; function loadCredential() { const saved = asRecord(_GM_getValue(credentialKey)); const accessToken = typeof saved?.accessToken === "string" ? saved.accessToken.trim() : ""; if (accessToken) return { accessToken, refreshToken: (typeof saved?.refreshToken === "string" ? saved.refreshToken.trim() : void 0) || void 0, expiresAt: typeof saved?.expiresAt === "number" && Number.isFinite(saved.expiresAt) ? saved.expiresAt : void 0 }; const legacy = _GM_getValue("aceess_key"); if (typeof legacy === "string" && legacy.trim()) return { accessToken: legacy.trim() }; } function saveCredential(credential) { _GM_setValue(credentialKey, { accessToken: credential.accessToken, refreshToken: credential.refreshToken ?? null, expiresAt: credential.expiresAt ?? null }); } function getDeviceID() { const stored = _GM_getValue(deviceKey); if (typeof stored === "string" && /^XX[0-9A-F]{35}$/.test(stored)) return stored; const hex = crypto.randomUUID().replaceAll("-", "").toUpperCase(); const device = `XX${hex[2]}${hex[12]}${hex[22]}${hex}`; _GM_setValue(deviceKey, device); return device; } function currentVmid() { return /^\/(\d+)(?:\/|$)/.exec(window.location.pathname)?.[1]; } function createSpaceView() { let badge; function clear() { badge?.remove(); badge = void 0; } function show(location) { const current = document.querySelector("#app .upinfo__main .upinfo-detail__top"); const target = current ?? document.querySelector("#app .h-inner .h-basic div"); if (!target) { clear(); return; } if (!badge || badge.parentElement !== target) { clear(); badge = document.createElement("span"); badge.dataset.bilirevealSpace = ""; badge.textContent = location; target.append(badge); } else if (badge.textContent !== location) badge.textContent = location; return current ? "current" : "legacy"; } return { clear, show }; } _css(".bilireveal-auth{box-sizing:border-box;border:1px solid var(--line_regular,#e3e5e7);color:canvastext;background:canvas;border-radius:12px;width:320px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);margin:auto;padding:20px 24px 24px;font-size:14px;line-height:1.5;position:fixed;inset:0;box-shadow:0 10px 36px #0000002e}.bilireveal-auth__header{justify-content:space-between;align-items:center;gap:8px;display:flex}.bilireveal-auth__title{color:inherit;margin:0;font-size:18px;font-weight:600;line-height:1.4}.bilireveal-auth__close,.bilireveal-auth__action{box-sizing:border-box;cursor:pointer;font:inherit;border:0}.bilireveal-auth__close{height:32px;color:var(--text2,#777e87);background:0 0;border-radius:6px;flex:0 0 32px;place-items:center;padding:0;font-size:24px;line-height:1;display:grid}.bilireveal-auth__close:hover{background:var(--graph_bg_regular,#7f7f7f24);color:inherit}.bilireveal-auth__close:focus-visible,.bilireveal-auth__action:focus-visible{outline:2px solid var(--brand_blue,#00aeec);outline-offset:2px}.bilireveal-auth__qr{box-sizing:border-box;aspect-ratio:1;border:1px solid var(--line_regular,#e3e5e7);background:#fff;border-radius:8px;place-items:center;width:min(196px,100%);margin:18px auto 0;display:grid;overflow:hidden}.bilireveal-auth__qr canvas{width:100%;height:auto;image-rendering:pixelated;display:block}.bilireveal-auth:is([data-state=loading],[data-state=saving]) .bilireveal-auth__qr:before{border:2px solid #e3e5e7;border-top-color:var(--brand_blue,#00aeec);content:\"\";border-radius:50%;width:20px;height:20px}@keyframes bilireveal-qr-loading{to{transform:rotate(1turn)}}@media (prefers-reduced-motion:no-preference){.bilireveal-auth__qr:before{animation:.8s linear infinite bilireveal-qr-loading}}.bilireveal-auth__status{min-height:21px;color:var(--text2,inherit);text-align:center;margin:14px 0 0;font-size:14px;line-height:1.5}.bilireveal-auth[data-state=scanned] .bilireveal-auth__status{color:var(--text1,CanvasText);font-weight:600}.bilireveal-auth__action{background:#007ba9;background:color-mix(in srgb, var(--brand_blue,#00aeec) 52%, #00517a);color:#fff;border-radius:6px;min-width:88px;min-height:36px;margin:16px auto 0;padding:0 16px;display:block}.bilireveal-auth__action:hover{filter:brightness(1.1)}.bilireveal-auth [hidden]{display:none}[data-bilireveal-space]{color:#fff;white-space:nowrap;vertical-align:middle;background:#00000080;border-radius:4px;align-self:center;align-items:center;margin-inline-start:6px;padding:1px 6px;font-size:12px;font-weight:400;line-height:18px;display:inline-flex}"); var api = createBiliAPI(getDeviceID()); var view = createSpaceView(); var credential = loadCredential(); var page; var verification; var scheduledFrame; var verificationTTLMs = 3e5; record("script.started", { hasCredential: Boolean(credential) }); function verify(accessToken) { if (verification?.key === accessToken && verification.until > Date.now()) return verification.pending; const pending = api.verifyCredential(accessToken); const query = { key: accessToken, until: Date.now() + verificationTTLMs, pending }; verification = query; pending.then((state) => record("credential.checked", { state }), () => { if (verification === query) verification = void 0; record("credential.checked", { state: "unknown" }); }); return pending; } async function queryProfile(state) { const { vmid, credential, controller } = state; if (credential.expiresAt !== void 0 && credential.expiresAt <= Date.now()) return { message: "授权已到期,请从脚本菜单重新扫码。" }; try { const location = await api.getLocation(vmid, credential.accessToken, controller.signal); if (controller.signal.aborted) return { message: "查询已取消。" }; if (location) return { location, message: "当前主页已返回属地。" }; try { if (await verify(credential.accessToken) === "invalid") return { message: "授权已失效,请从脚本菜单重新扫码。" }; return { message: "授权有效,本次主页查询未返回属地。" }; } catch { return { message: "本次主页查询未返回属地,暂时无法确认授权状态。" }; } } catch (error) { if (error instanceof RequestFailure && error.kind === "api" && error.code === -101) return { message: "主页接口要求登录,请从脚本菜单重新扫码。" }; return { message: failureMessage(error) }; } } function renderPage(state) { if (page !== state || currentVmid() !== state.vmid || !state.result?.location) return; const layout = view.show(state.result.location); if (!state.mounted && layout) record("page.mounted", { layout }); state.mounted = Boolean(layout); } function updatePage(force = false) { const vmid = currentVmid(); if (page && vmid === page.vmid && credential === page.credential) { if (page.pending) return page.pending; if (!force && page.result) { renderPage(page); return Promise.resolve(page.result); } } page?.controller.abort(); page = void 0; view.clear(); if (!vmid) return Promise.resolve({ message: "当前页面不是个人主页。" }); if (!credential) return Promise.resolve({ message: "请从脚本菜单发起扫码授权。" }); const state = { vmid, credential, controller: new AbortController(), mounted: false }; page = state; state.pending = queryProfile(state).then((result) => { state.pending = void 0; if (page !== state || currentVmid() !== vmid) return { message: "主页已切换。" }; state.result = result; record("space.result", { hasLocation: Boolean(result.location), message: result.message }); renderPage(state); if (result.location && !state.mounted) setTimeout(() => { if (page === state && currentVmid() === vmid && !state.mounted) record("page.mountTimeout"); }, 8e3); return result; }); return state.pending; } var authorize = createAuthorization(api, async (replacement) => { saveCredential(replacement); credential = replacement; verification = void 0; record("credential.saved", { hasRefresh: Boolean(credential.refreshToken), hasExpiry: credential.expiresAt !== void 0 }); return (await updatePage(true)).message; }); function schedulePageUpdate() { if (scheduledFrame !== void 0) return; scheduledFrame = requestAnimationFrame(() => { scheduledFrame = void 0; updatePage(); }); } function registerMenu(label, handler) { const run = () => { Promise.resolve().then(handler).catch(() => { record("menu.failed"); alert("操作失败,请查看诊断信息。"); }); }; try { if (typeof _GM_registerMenuCommand === "function") _GM_registerMenuCommand(label, run); else if (typeof _GM?.registerMenuCommand === "function") Promise.resolve(_GM.registerMenuCommand(label, run)).catch(() => record("menu.unavailable")); else record("menu.unavailable"); } catch { record("menu.unavailable"); } } registerMenu("扫码授权", authorize); registerMenu("测试当前主页", async () => { const testing = credential; const lookup = updatePage(true); if (!testing) { alert((await lookup).message); return; } const auth = verify(testing.accessToken).then((state) => state === "valid" ? "B 站凭据有效。" : "B 站凭据已失效。", failureMessage); const [authResult, profileResult] = await Promise.all([auth, lookup]); alert(`${authResult}\n${profileResult.message}`); }); registerMenu("复制诊断信息", () => { _GM_setClipboard(diagnosticReport(Boolean(credential)), "text"); alert("诊断信息已复制。"); }); new MutationObserver(schedulePageUpdate).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["class"] }); window.addEventListener("popstate", schedulePageUpdate); window.navigation?.addEventListener("currententrychange", schedulePageUpdate); document.addEventListener("visibilitychange", () => { if (document.hidden) return; const latest = loadCredential(); if (latest?.accessToken !== credential?.accessToken || latest?.expiresAt !== credential?.expiresAt) { credential = latest; verification = void 0; updatePage(true); } }); updatePage(); })();