// ==UserScript== // @name B站视频观看次数统计 // @namespace http://tampermonkey.net/ // @version 2.0 // @description 每次刷新/跳转进入视频页时观看次数+1,用 🔁 显示在视频信息栏(播放量/弹幕那一栏),数据存 IndexedDB。静默运行,不做实时监听,性能零负担。附带标签收集与归类筛选(油猴菜单「观看统计」)。V1.7:新增 events 观看事件表(详细时间戳+封面/头像快照),供 5.js「B站视频数据一览」统计 // @author Anonymity // @match *://www.bilibili.com/video/* // @grant GM_registerMenuCommand // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @run-at document-end // @license MIT // ==/UserScript== (function () { 'use strict'; const DB_NAME = 'BiliViewCountDB'; const STORE = 'views'; // 记录格式 { id: "BV1xxx", times: num } const ITEM_ID = 'bili-view-count-item'; // ====================== IndexedDB ====================== function openDB() { return new Promise((resolve, reject) => { const req = indexedDB.open(DB_NAME, 3); // v3:events 增加 by_t 时间索引(供 5.js 保留期限清理走游标区间,不再全表遍历) req.onupgradeneeded = () => { const db = req.result; if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE, { keyPath: 'id' }); if (!db.objectStoreNames.contains('events')) db.createObjectStore('events', { autoIncrement: true }); const est = req.transaction.objectStore('events'); if (!est.indexNames.contains('by_t')) est.createIndex('by_t', 't', { unique: false }); }; req.onsuccess = () => resolve(req.result); req.onerror = () => reject(req.error); }); } // 记录格式 { id: "BV1xxx", title, times: num, uid: "UP主UID", name: "UP主名", lastTime: 时间戳, lastCid: 分P的cid, lastP: 分P页码, tags: ["标签", ...] } async function increment(bv, meta, title, pos, tags) { const db = await openDB(); return new Promise((resolve, reject) => { // views + events 走同一事务:两表要么同时提交、要么同时回滚(保证 views.times 与 events 条数一致,无需事后补偿) const tx = db.transaction([STORE, 'events'], 'readwrite'); let finalTimes = 0; tx.oncomplete = () => resolve(finalTimes); // 等事务真正提交再返回,而非 put 后立即 resolve tx.onabort = () => reject(tx.error || new Error('increment 事务中止')); const getReq = tx.objectStore(STORE).get(bv); getReq.onsuccess = () => { const rec = getReq.result || { id: bv, times: 0 }; rec.times += 1; rec.lastTime = Date.now(); if (meta) { if (meta.uid) rec.uid = meta.uid; if (meta.name) rec.name = meta.name; } if (title) rec.title = title; if (tags && tags.length) rec.tags = [...new Set([...(rec.tags || []), ...tags])]; // 合并不覆盖:多P/分P标签都保留 if (pos) { if (pos.cid) rec.lastCid = pos.cid; if (pos.p) rec.lastP = pos.p; } tx.objectStore(STORE).put(rec); finalTimes = rec.times; // V1.7 事件快照(同一事务原子写入):一次确认观看 = 一条 events 记录。 // t 为毫秒时间戳,年/月/日/小时/星期由查询方用 new Date(t) 推导(等价且省存储); // pic/face 在观看瞬间从页面 JSON 免费快照,供 5.js 报告页直接展示 const pf = getVideoPicFace(); tx.objectStore('events').add({ bv, t: rec.lastTime, p: pos && pos.p ? pos.p : null, uid: (meta && meta.uid) || null, name: (meta && meta.name) || null, face: pf.face, pic: pf.pic, title: title || null, tags: tags || [] }); }; getReq.onerror = () => reject(getReq.error); }); } // 观看瞬间快照封面图与UP头像 URL(新版页面 JSON 直取,零请求;拿不到返回 null,报告页用占位样式兜底) function getVideoPicFace() { try { const vd = getInitialStateVideo(); if (vd && vd.bvid === getBv()) { return { pic: vd.pic ? String(vd.pic) : null, face: (vd.owner && vd.owner.face) ? String(vd.owner.face) : null }; } } catch (e) {} return { pic: null, face: null }; } // 更新分P位置标签(lastCid/lastP)+ 最近观看时间,供 1.js“跳到上次看的分P/合集最近时间”使用。 // 计数不变;记录不存在时以 times:0 先建立(30s 确认后计数才会 +1) async function updatePosition(bv, pos) { try { const db = await openDB(); await new Promise(resolve => { const tx = db.transaction(STORE, 'readwrite'); const g = tx.objectStore(STORE).get(bv); g.onsuccess = () => { const rec = g.result || { id: bv, times: 0 }; if (pos && pos.cid) rec.lastCid = pos.cid; if (pos && pos.p) rec.lastP = pos.p; rec.lastTime = Date.now(); tx.objectStore(STORE).put(rec); tx.oncomplete = () => resolve(); }; g.onerror = () => resolve(); }); } catch (e) { /* 静默 */ } } // 读取全部记录(数组) function getAllRecords() { return openDB().then(db => new Promise(resolve => { try { const req = db.transaction(STORE, 'readonly').objectStore(STORE).getAll(); req.onsuccess = () => resolve(req.result || []); req.onerror = () => resolve([]); } catch (e) { resolve([]); } })).catch(() => []); } // 只补录 UP 主信息/标题/标签(不改 times / lastTime) async function updateMeta(bv, meta) { if (!meta || (!meta.uid && !meta.name && !meta.title && !(meta.tags && meta.tags.length))) return false; try { const db = await openDB(); return await new Promise(resolve => { const tx = db.transaction(STORE, 'readwrite'); const g = tx.objectStore(STORE).get(bv); g.onsuccess = () => { const rec = g.result; if (!rec) { resolve(false); return; } if (meta.uid) rec.uid = meta.uid; if (meta.name) rec.name = meta.name; if (meta.title) rec.title = meta.title; // 与 increment 同语义:合并不覆盖,避免批量补录冲掉多P/分P攒下的旧标签 if (meta.tags && meta.tags.length) rec.tags = [...new Set([...(rec.tags || []), ...meta.tags])]; tx.objectStore(STORE).put(rec); tx.oncomplete = () => resolve(true); }; g.onerror = () => resolve(false); }); } catch (e) { return false; } } // 按 BV 反查 UP 主(B站 view API,绕过 DOM/CORS) function gmGet(url) { return new Promise(resolve => { GM_xmlhttpRequest({ method: 'GET', url, timeout: 8000, onload: r => resolve(r.status === 200 ? r.responseText : null), onerror: () => resolve(null), ontimeout: () => resolve(null) }); }); } // 标签:view 接口实际不返回标签(只有分区名 tname),需单独请求 x/tag/archive/tags // 返回 data 为数组,新版字段 tag_name,老版字段 name,两者都解析兜底 async function fetchVideoTags(bv) { try { const ctl = new AbortController(); const timer = setTimeout(() => ctl.abort(), 8000); const resp = await fetch('https://api.bilibili.com/x/tag/archive/tags?bvid=' + bv, { credentials: 'include', signal: ctl.signal }); clearTimeout(timer); if (!resp.ok) return null; const json = await resp.json(); const arr = json && json.code === 0 && Array.isArray(json.data) ? json.data : null; if (!arr) return null; return arr.map(t => String((t && (t.tag_name || t.name)) || '').trim()).filter(Boolean); } catch (e) { return null; } } async function fetchUpMetaByApi(bv) { try { // 页面上下文 fetch(带全量 cookie/Referer/正常UA):与 B 站前端自身请求无法区分,比 GM_xmlhttpRequest 更不容易触发风控 const ctl = new AbortController(); const timer = setTimeout(() => ctl.abort(), 8000); const resp = await fetch('https://api.bilibili.com/x/web-interface/view?bvid=' + bv, { credentials: 'include', signal: ctl.signal }); clearTimeout(timer); if (!resp.ok) return null; const json = await resp.json(); const d = json && json.code === 0 && json.data; if (!d) return null; const meta = {}; if (d.owner && d.owner.mid) meta.uid = String(d.owner.mid); if (d.owner && d.owner.name) meta.name = String(d.owner.name).trim(); if (d.title) meta.title = String(d.title).trim(); // 标签:主路走独立标签接口;万一 view 接口带了 Retags/Tag 也兜底收下 const tags = await fetchVideoTags(bv); if (tags && tags.length) { meta.tags = tags; } else if (Array.isArray(d.Retags) && d.Retags.length) { meta.tags = d.Retags.map(t => String((t && t.tag_name) || '').trim()).filter(Boolean); } else if (typeof d.Tag === 'string' && d.Tag) { meta.tags = d.Tag.split(',').map(s => s.trim()).filter(Boolean); } return meta.uid || meta.name || meta.title || (meta.tags && meta.tags.length) ? meta : null; } catch (e) { return null; } } // ====================== 计数核心 ====================== // 新版页面从 window.__INITIAL_STATE__.videoData 取视频数据(不受 DOM 改版影响); // 油猴/脚本猫沙箱里 window.__INITIAL_STATE__ 不存在,必须走 unsafeWindow; // 旧版页面拿不到时,各函数自动退回 URL/DOM 解析,保持兼容 function getInitialStateVideo() { try { const g = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; const vd = g.__INITIAL_STATE__ && g.__INITIAL_STATE__.videoData; if (vd && vd.bvid) return vd; } catch (e) {} return null; } function getBv() { // URL 优先:SPA 跳转时 __INITIAL_STATE__ 可能还是上一个视频的陈旧数据 const m = location.pathname.match(/\/video\/(BV[0-9A-Za-z]+)/); if (m) return m[1]; const vd = getInitialStateVideo(); return (vd && vd.bvid) ? vd.bvid : null; } // 取多P视频的当前分P位置(cid + 页码),供 1.js 跳转“上一次退出的分P”; // 单P视频返回 null,不记录。只作标签,不影响计数 function getVideoPosition() { const pMatch = location.search.match(/[?&]p=(\d+)/); const p = pMatch ? parseInt(pMatch[1], 10) : 1; const vd = getInitialStateVideo(); const fresh = !!(vd && vd.bvid && vd.bvid === getBv()); // 与地址栏一致才可信(防 SPA 陈旧数据) const pagesOk = fresh && Array.isArray(vd.pages) && vd.pages.length > 1; if (!pagesOk && p < 2) return null; // 无 pages 佐证且 URL 也没带 p:视为非多P return { cid: pagesOk && vd.cid ? String(vd.cid) : null, p: p }; } const timesCache = new Map(); // bv -> times,用于 DOM 重建后恢复显示 // 从视频页读取 UP 主信息 function getUpInfo() { // 新版:直接读页面 JSON 的 owner(最准,不受 DOM 结构变动影响) const vd = getInitialStateVideo(); if (vd && vd.owner && vd.owner.mid) { return { uid: String(vd.owner.mid), name: String(vd.owner.name || '').trim() }; } let uid = null, name = ''; // 只取 UP 主信息区(视频作者区),避开页头登录账号自己的 space 链接 const box = document.querySelector('.up-info-container'); if (box) { const link = box.querySelector('a[href*="space.bilibili.com"]'); if (link) { const m = (link.getAttribute('href') || '').match(/space\.bilibili\.com\/(\d+)/); if (m) uid = m[1]; } const nameEl = box.querySelector('.up-name'); if (nameEl) name = nameEl.textContent.trim(); } // 兜底:容器没渲染时,只用 up-avatar 专用类(该 class 只属于 UP 主头像,不会命中页头) if (!uid) { const a = document.querySelector('.up-avatar[href*="space.bilibili.com"]'); if (a) { const m = (a.getAttribute('href') || '').match(/space\.bilibili\.com\/(\d+)/); if (m) uid = m[1]; } } // 第三层:排除页头(登录账号自己的入口)后,正文区第一个 space 链接 if (!uid) { const headerLinks = new Set(document.querySelectorAll('.bili-header a[href*="space.bilibili.com"], header a[href*="space.bilibili.com"]')); for (const a of document.querySelectorAll('a[href*="space.bilibili.com"]')) { if (headerLinks.has(a)) continue; const m = (a.getAttribute('href') || '').match(/space\.bilibili\.com\/(\d+)/); if (m) { uid = m[1]; break; } } } if (!name) { const n = document.querySelector('.up-name'); if (n) name = n.textContent.trim(); } return { uid, name }; } // 取视频标题:新版读页面 JSON,旧版从 document.title(B站格式:视频标题_哔哩哔哩_bilibili) function getVideoTitle() { const vd = getInitialStateVideo(); if (vd && vd.title) return String(vd.title).trim(); const t = (document.title || '').split('_哔哩哔哩')[0].trim(); return t && t !== location.hostname ? t : ''; } // 从视频页标签区抓标签(仅作筛选数据用,不影响任何显示): // 普通标签取 a.tag-link 的 keyword= 参数(比文本稳定,自动处理 URL 编码);BGM 取 .bgm-link 的 title("发现《多幸运》") function getVideoTagsFromPage() { const out = []; try { document.querySelectorAll('.tag-panel a.tag-link[href*="keyword="]').forEach(a => { const m = (a.getAttribute('href') || '').match(/keyword=([^&]+)/); if (!m) return; try { const t = decodeURIComponent(m[1]).trim(); if (t && !out.includes(t)) out.push(t); } catch (e) {} }); document.querySelectorAll('.tag-panel .bgm-link[title]').forEach(el => { const t = (el.getAttribute('title') || '').replace(/^发现《?/, '').replace(/》$/, '').trim(); if (t && !out.includes(t)) out.push(t); }); } catch (e) {} return out; } // ====================== 30s 确认窗口计数 ====================== // 兜底方案:检测到新BV后不立即计数,进入 CONFIRM_MS 确认窗口, // 30s 后复查仍是该视频才 +1;窗口内重复触发被合并。 // 防重复的关键:只记住「最近一次导航的BV」。BV没变(切P/参数变化)= 同一次观看,不重计; // BV变了(含列表循环跳回旧视频)= 新一次进入,重新走确认窗口。 const CONFIRM_MS = 30000; let lastNavBv = null; // 最近一次导航到的 BV let pendingBv = null; // 正在确认窗口内的 BV let confirmTimer = null; function cancelConfirm() { if (confirmTimer) { clearTimeout(confirmTimer); confirmTimer = null; } pendingBv = null; } // 所有 URL 相关入口(初始化 / pushState / replaceState / popstate)统一走这里 let visitTimer = null; // 延迟落库定时器 let visitBv = null; // 等待落库的 BV // 进入新 BV 后延迟 5 秒才落库「最近观看」:期间划走就不写, // 避免“一划而过”的 BV 留下 times:0 且无 meta 的垃圾记录 function scheduleVisit(bv) { if (visitTimer) clearTimeout(visitTimer); visitBv = bv; visitTimer = setTimeout(() => { visitTimer = null; if (visitBv !== bv || getBv() !== bv) return; // 已切走:放弃落库 updatePosition(bv, getVideoPosition()); }, 5000); } function handleNav() { const bv = getBv(); if (!bv) { cancelConfirm(); if (visitTimer) { clearTimeout(visitTimer); visitTimer = null; visitBv = null; } return; // 离开视频页:放弃未确认的计数和未落库的访问 } if (bv === pendingBv) return; // 确认窗口内:合并瞬时重复触发 if (bv === lastNavBv) { updatePosition(bv, getVideoPosition()); render(bv); return; } // BV 没变:切P/改参,不重计,只更新分P位置标签并补显示 // 跳到了与最近一次不同的 BV:延迟落库「最近观看」位置/时间(不计数,防划过垃圾), // 再开启 30s 确认窗口,确认后才 +1 cancelConfirm(); lastNavBv = bv; pendingBv = bv; scheduleVisit(bv); confirmTimer = setTimeout(async () => { confirmTimer = null; if (pendingBv !== bv) return; // 窗口内又导航走了:放弃 pendingBv = null; try { const meta = getUpInfo(); const title = getVideoTitle(); const pos = getVideoPosition(); // 实时取位置(窗口内可能切过P) const tags = getVideoTagsFromPage(); // 30s 时页面已完全渲染,标签稳定可抓 const times = await increment(bv, meta, title, pos, tags); timesCache.set(bv, times); // 兜底:DOM 没抓到 UP 主/标题/标签 → API 反查补录(不影响计数结果) if (!meta.uid || !meta.name || !title || !tags.length) { fetchUpMetaByApi(bv).then(apiMeta => { if (apiMeta) updateMeta(bv, apiMeta); }); } } catch (e) { /* IndexedDB 失败静默 */ } startRenderLoop(); }, CONFIRM_MS); } // ====================== 显示 ====================== // 返回 true 表示已成功显示,轮询可停止 function render(bv) { if (!bv) return false; const times = timesCache.get(bv); if (times === undefined) return false; const bar = document.querySelector('.video-info-detail-list'); if (!bar) return false; let el = document.getElementById(ITEM_ID); if (!el || !el.isConnected) { el = document.createElement('div'); el.id = ITEM_ID; el.className = 'item'; el.title = '本机观看次数'; el.style.cssText = 'display:flex;align-items:center;gap:4px;font-size:13px;color:inherit;white-space:nowrap;cursor:default;'; el.innerHTML = '🔁'; bar.appendChild(el); } const textEl = el.querySelector('.times-text'); if (textEl.textContent !== String(times)) { textEl.textContent = times; } return true; } // 低频轮询:1秒1次,成功显示即停,最多尝试60次;之后完全零开销(不用 MutationObserver) let renderTimer = null; function startRenderLoop() { if (renderTimer) return; let attempts = 0; renderTimer = setInterval(() => { attempts++; const done = render(getBv()); if (done || attempts >= 60) { clearInterval(renderTimer); renderTimer = null; } }, 1000); } // ====================== 路由监听 ====================== // 仅在跳转瞬间触发一次轻量函数(正则+查表),无任何持续监听 const _push = history.pushState.bind(history); history.pushState = function (...args) { _push(...args); setTimeout(handleNav, 0); }; const _replace = history.replaceState.bind(history); history.replaceState = function (...args) { _replace(...args); setTimeout(handleNav, 0); }; window.addEventListener('popstate', () => setTimeout(handleNav, 0)); // ====================== 观看统计表格(GM菜单) ====================== function escapeHtml(s) { return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } // ====================== 标签归类器 ====================== // 第一层:内置规则表(正则 → 大类,命中即归类);第二层:未命中规则的标签按字符相似度自动聚类 // 注意:避免高频单字/缩写误伤(如 猫→熊猫、狗→热狗、LOL→lol笑话、MC→MC主播),单字核心词一律用双字组合 const TAG_GROUP_RULES = [ { group: '游戏', re: /游戏|原神|王者荣耀|英雄联盟|LOL|崩坏|星穹|绝区零|我的世界|Minecraft|MC|明日方舟|碧蓝|FGO|Fate|守望先锋|泰拉瑞亚|饥荒|塞尔达|马里奥|宝可梦|口袋妖怪|steam|主机游戏|手游|网游|电竞|吃鸡|和平精英|APEX|CSGO|无畏契约|瓦罗兰特|DOTA|炉石|魔兽|剑网|永劫无间|幻兽帕鲁|帕鲁|黑神话|GTA|荒野大镖客|使命召唤|战地|命运2|星际战甲|FPS|MOBA|RPG|SLG|任天堂|Switch|PS5|Xbox|暴雪|米哈游|腾讯游戏|网易游戏|开黑|实况|通关|攻略|单机|独立游戏/i }, { group: '音乐', re: /音乐|翻唱|唱见|唱歌|原创曲|歌曲|钢琴|吉他|尤克里里|小提琴|编曲|混音|BGM|合唱|伴奏|调教|Vocaloid|VOCALOID|UTAU|说唱|嘻哈|民谣|摇滚|古典|演唱会|音MAD|纯音乐|乐器|二胡|古筝|笛子|萨克斯|架子鼓|贝斯|DJ|电音|EDM|流行|R&B|爵士|美声|作词|作曲|填词|扒带|翻弹|指弹|乐评|Hi-Res|无损/i }, { group: '虚拟主播', re: /Vtuber|VTuber|Vup|VUP|虚拟主播|虚拟偶像|虚拟UP|VirtuaReal|歌势|皮套|虚拟区|套皮|中之人|切片|熟肉|生肉|直播回放|V圈|Hololive|彩虹社|NIJISANJI|A-SOUL|星街|绊爱|嘉然|向晚/i }, { group: '萌宠', re: /萌宠|宠物|猫咪|猫咖|橘猫|流浪猫|布偶猫|英短|狗狗|柯基|金毛|柴犬|哈士奇|边牧|泰迪|兔子|仓鼠|鹦鹉|爬宠|乌龟|水族|钓鱼|猫粮|狗粮|铲屎官|野生动物|大熊猫|熊猫|老虎|狮子|猩猩|猴子|蜥蜴|水母/i }, { group: '鬼畜', re: /鬼畜|人力VOCALOID|鬼畜调教|全明星|RAP|洗脑|空耳|黑乐谱/i }, { group: '美食', re: /美食|烹饪|料理|做菜|烘焙|试吃|吃播|食谱|菜谱|热狗|探店|厨师|厨艺|家常菜|川菜|粤菜|火锅|烧烤|烤肉|甜点|蛋糕|面包|奶茶|咖啡|零食|泡面|夜宵|海鲜|牛排|米其林|王刚/i }, { group: '知识', re: /知识|科普|教程|学习|课程|考试|公开课|演讲|历史|物理|化学|数学|生物|编程|计算机|心理学|经济学|语文|英语|政治|地理|考研|高考|中考|四六级|雅思|托福|公务员|前端|后端|算法|Python|Java|C\+\+|代码|高数|线代|哲学|法学|医学|金融|理财|投资|股票|基金|商业|职场|面试|简历|罗翔|法律/i }, { group: '影视', re: /影视|电影|电视剧|短片|影评|预告|混剪|纪录片|影视解说|剧评|美剧|英剧|韩剧|日剧|恐怖片|喜剧|动作片|科幻|悬疑|爱情片|漫威|DC|哈利波特|指环王|流浪地球|奥特曼|假面骑士|特摄/i }, { group: '动画', re: /动画|动漫|番剧|国创|漫剪|手书|猫和老鼠|新番|剧场版|OVA|MAD|AMV|二次元|日漫|国漫|热血|恋爱|治愈|致郁|机战|京阿尼|骨头社|MAPPA|飞碟社|鬼灭之刃|咒术回战|火影|海贼王|名侦探柯南|进击的巨人|间谍过家家/i }, { group: '舞蹈', re: /舞蹈|宅舞|翻跳|编舞|街舞|爵士舞|舞蹈教程|中国舞|古典舞|民族舞|现代舞|芭蕾|拉丁舞|韩舞|K-pop|Popping|Breaking|Hiphop|Waacking|Locking|齐舞|双人舞/i }, { group: '时尚', re: /时尚|美妆|穿搭|化妆|护肤|口红|仿妆|彩妆|底妆|眼影|香水|美甲|发型|理发|烫发|染发|美发|OOTD|潮牌|汉服|JK|Lolita|洛丽塔|球鞋|奢侈品/i }, { group: '生活', re: /生活|日常|Vlog|vlog|VLOG|旅行|旅游|出行|开箱|记录|挑战|第一次|独居|租房|装修|收纳|清洁|家居|好物推荐|测评|手工|DIY|手作|木工|拼图|乐高|积木|风景|露营|徒步|自驾游/i }, { group: 'B站激励活动', re: /激励活动|狂欢节|应援计划|创作者|知识分享官|跃迁计划|分享官|创作计划|挑战赛|大赛|创作激励|新人福利|专属流量|打卡|参赛|招募|海选|投稿|征稿|官方活动|B站活动|活动企划/i }, // ====== 新增极易出现的高频大类 ====== { group: '科技数码', re: /数码|手机|电脑|装机|键盘|鼠标|耳机|平板|智能家居|评测|科技|极客|iPhone|苹果|华为|小米|安卓|Windows|Mac|相机|摄影|数码测评|黑科技/i }, { group: '体育运动', re: /运动|健身|减脂|增肌|跑步|马拉松|篮球|足球|羽毛球|乒乓球|网球|游泳|瑜伽|普拉提|减肥|瘦身|跟练|帕梅拉|NBA|CBA|世界杯|欧洲杯/i }, { group: '汽车', re: /汽车|车评|试驾|新能源|电动车|燃油车|改装|驾驶|考驾照|特斯拉|比亚迪|小米汽车|赛车|F1|二手车|机车|摩托车/i }, { group: '手工绘画', re: /绘画|画画|手绘|板绘|插画|原画|素描|水彩|油画|折纸|黏土|模型|手办|GK|雕刻/i } ]; // 展示层映射:内部保留键 → 显示名 const TAG_DISP = n => n === '__misc__' ? '未分类' : n; // 第二层:字符相似度自动聚类(bigram 版)—— // 用相邻二字组合而非单字集合:中文短标签召回更稳,且天然抑制单字歧义(猫≠熊猫、狗≠热狗)。 // 长度 1 的标签不参与聚类(无 bigram,只能靠规则/人工指认);contain 规则要求双方长度 ≥ 2。 // 阈值:bigram Jaccard ≥ 0.5,或重叠 ≥ 70%(互相包含变体,如 翻唱⊂翻唱指导)则连边。 // 连通分量成组(≥2 个成员才算组);组名取组内最短标签。O(n²),标签几百个也在毫秒级 function autoClusterTags(tags) { const uniq = [...new Set(tags)].filter(t => [...t].length >= 2); const grams = uniq.map(t => { const s = [...t.toLowerCase()]; const set = new Set(); for (let i = 0; i < s.length - 1; i++) set.add(s[i] + s[i + 1]); return set; }); const parent = uniq.map((_, i) => i); const find = i => parent[i] === i ? i : (parent[i] = find(parent[i])); for (let i = 0; i < uniq.length; i++) { for (let j = i + 1; j < uniq.length; j++) { const A = grams[i], B = grams[j]; if (!A.size || !B.size) continue; let inter = 0; A.forEach(g => { if (B.has(g)) inter++; }); const uni = A.size + B.size - inter; const sim = uni ? inter / uni : 0; const minLen = Math.min([...uniq[i]].length, [...uniq[j]].length); const contain = minLen >= 2 && (inter / Math.min(A.size, B.size)) >= 0.7; if (sim >= 0.5 || contain) parent[find(j)] = find(i); } } const clusters = {}; uniq.forEach((t, i) => { const r = find(i); (clusters[r] || (clusters[r] = [])).push(t); }); return Object.values(clusters) .filter(m => m.length >= 2) .map(members => ({ name: members.slice().sort((a, b) => a.length - b.length)[0], members })) .sort((a, b) => b.members.length - a.members.length); } // ====================== 人工索引(复核结果持久化,优先级最高) ====================== // GM: bili_tag_index_v1 = { assign: { "标签": "主组" }, extra: { "标签": ["附加组", ...] }, excl: { "标签": ["剔除组", ...] } } // - assign = 主组(第一性原则:一个标签的第一归属),extra = 附加归属(一个标签可同时出现在多个组) // - excl = 剔除名单:视频只要含有该标签,就整条从这些组里除名(一票否决,最后生效;挂在标签上 → 同标签的所有视频批量生效) // - 组名可以是内置组(游戏/音乐…),也可以是自建新组名——自建组名即“顶层表”的扩展 function loadTagIndex() { try { const idx = JSON.parse(GM_getValue('bili_tag_index_v1', '{}')); return { assign: (idx && idx.assign) || {}, extra: (idx && idx.extra) || {}, excl: (idx && idx.excl) || {} }; } catch (e) { return { assign: {}, extra: {}, excl: {} }; } } function saveTagIndex(idx) { try { GM_setValue('bili_tag_index_v1', JSON.stringify(idx)); } catch (e) {} } // 构建标签分组视图。分类瀑布:① 人工索引(主组 + 附加组,可多组并存)→ ② 内置规则表 → ③ 自动聚类兜底 // 返回 [{name, members, count, auto}];同一标签可同时出现在多个组的 members 里(主组/附加组联动) function buildTagGroups(records) { const idx = loadTagIndex(); const allTags = []; records.forEach(r => (r.tags || []).forEach(t => { if (t && !allTags.includes(t)) allTags.push(t); })); const groups = []; // ① 人工索引:主组 assign + 附加组 extra(“小狗吃饭”→ 主组萌宠,同时归日常) const rest = []; const manualMap = {}; allTags.forEach(t => { const main = idx.assign[t]; const ex = idx.extra[t] || []; if (main || ex.length) { [main, ...ex].filter(Boolean).forEach(g => (manualMap[g] || (manualMap[g] = [])).push(t)); } else rest.push(t); }); Object.keys(manualMap).forEach(g => groups.push({ name: g, members: manualMap[g], auto: false })); // ② 内置规则表 const afterRules = []; rest.forEach(t => { const r = TAG_GROUP_RULES.find(x => x.re.test(t)); if (r) { let g = groups.find(x => x.name === r.group && !x.auto); if (!g) { g = { name: r.group, members: [], auto: false }; groups.push(g); } g.members.push(t); } else afterRules.push(t); }); // ③ 自动聚类兜底 autoClusterTags(afterRules).forEach(g => groups.push({ name: g.name, members: g.members, auto: true })); // 同名组合并(自建组名可能与自动组名撞名) const byName = new Map(); groups.forEach(g => { const p = byName.get(g.name); if (p) { p.members.push(...g.members); p.auto = p.auto && g.auto; } else byName.set(g.name, g); }); // ④ excl 剔除(视频级,最后生效):视频含触发标签 → 整条从指定组除名 // 触发反转表:组名 → [触发标签...];剔除挂在标签上,同标签的所有视频天然批量生效 const exclTrig = {}; Object.keys(idx.excl || {}).forEach(t => (idx.excl[t] || []).forEach(gn => (exclTrig[gn] || (exclTrig[gn] = [])).push(t))); const recExcluded = (rec, gname) => (exclTrig[gname] || []).some(t => (rec.tags || []).includes(t)); // 统一去重成员并统计视频数(统计时同样应用剔除) return [...byName.values()] .map(g => { g.members = [...new Set(g.members)]; g.count = records.filter(rec => (rec.tags || []).some(t => g.members.includes(t)) && !recExcluded(rec, g.name)).length; return g; }) .filter(g => g.members.length) .sort((a, b) => b.count - a.count); } function showStatsPanel() { // 面板样式放独立 style 里,用 ID 作用域避免被 B 站全局样式(如 h3 黑色)污染 const CSS_ID = 'bili-view-stats-style'; let styleEl = document.getElementById(CSS_ID); if (!styleEl) { styleEl = document.createElement('style'); styleEl.id = CSS_ID; styleEl.textContent = ` #bili-view-stats-panel{position:fixed;top:80px;right:24px;width:460px;max-height:70vh;overflow:hidden;background:rgba(16,16,22,0.92);backdrop-filter:blur(14px);color:#fff;padding:16px;border-radius:14px;z-index:100002;box-shadow:0 6px 24px rgba(0,0,0,0.5);font-size:13px;display:flex;flex-direction:column;} #bili-view-stats-panel .panel-body{overflow-y:auto;min-height:0;flex:1 1 auto;} #bili-view-stats-panel .rs-nw,#bili-view-stats-panel .rs-ne,#bili-view-stats-panel .rs-sw,#bili-view-stats-panel .rs-se{position:absolute;width:16px;height:16px;z-index:12;} #bili-view-stats-panel .rs-nw{left:0;top:0;cursor:nwse-resize;} #bili-view-stats-panel .rs-ne{right:0;top:0;cursor:nesw-resize;} #bili-view-stats-panel .rs-sw{left:0;bottom:0;cursor:nesw-resize;} #bili-view-stats-panel .rs-se{right:0;bottom:0;cursor:nwse-resize;} #bili-view-stats-panel h3{margin:0;font-size:15px;color:#fff;} #bili-view-stats-panel .head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px;padding-bottom:8px;border-bottom:1px solid rgba(255,255,255,0.15);cursor:move;user-select:none;flex:0 0 auto;} #bili-view-stats-panel .head h3{border:none;padding:0;margin:0;} #bili-view-stats-panel .theme-btn{flex-shrink:0;padding:3px 10px;font-size:13px;line-height:1.4;background:rgba(255,255,255,0.12);color:inherit;border:1px solid rgba(255,255,255,0.25);border-radius:6px;cursor:pointer;} #bili-view-stats-panel table{width:100%;border-collapse:collapse;} #bili-view-stats-panel th{text-align:left;padding:6px 8px;color:#ff69b4;border-bottom:1px solid rgba(255,255,255,0.2);font-weight:600;} #bili-view-stats-panel td{padding:6px 8px;color:inherit;} #bili-view-stats-panel .up-link{color:#6cb8ff;text-decoration:none;} #bili-view-stats-panel .up-link:hover{text-decoration:underline;} #bili-view-stats-panel .col-times{font-weight:bold;color:#ffd700;cursor:pointer;user-select:none;white-space:nowrap;} #bili-view-stats-panel .col-times:hover{text-decoration:underline;} #bili-view-stats-panel .unknown{opacity:0.5;} #bili-view-stats-panel .meta{margin-top:10px;padding-top:8px;border-top:1px solid rgba(255,255,255,0.15);font-size:12px;opacity:0.75;} #bili-view-stats-panel .btn{display:block;width:100%;margin-top:12px;padding:7px;background:rgba(255,255,255,0.14);border:none;border-radius:6px;color:inherit;cursor:pointer;} #bili-view-stats-panel .detail{margin-top:10px;padding-top:8px;border-top:1px solid rgba(255,255,255,0.15);} #bili-view-stats-panel .detail-title{font-size:12px;font-weight:bold;margin-bottom:6px;color:inherit;} #bili-view-stats-panel .detail-row{display:flex;justify-content:space-between;gap:10px;padding:3px 0;font-size:12px;opacity:0.92;color:inherit;} #bili-view-stats-panel .detail-row .d-time{opacity:0.6;white-space:nowrap;} /* 浅色主题 */ #bili-view-stats-panel.stats-light{background:rgba(255,255,255,0.96);color:#18191c;box-shadow:0 6px 24px rgba(0,0,0,0.25);} #bili-view-stats-panel.stats-light h3{color:#18191c;} #bili-view-stats-panel.stats-light .head{border-bottom:1px solid rgba(0,0,0,0.15);} #bili-view-stats-panel.stats-light .theme-btn{background:rgba(0,0,0,0.06);border-color:rgba(0,0,0,0.2);} #bili-view-stats-panel.stats-light th{color:#d63384;border-bottom:1px solid rgba(0,0,0,0.2);} #bili-view-stats-panel.stats-light .up-link{color:#0a7de0;} #bili-view-stats-panel.stats-light .col-times{color:#b8860b;} #bili-view-stats-panel.stats-light .meta{border-top:1px solid rgba(0,0,0,0.15);} #bili-view-stats-panel.stats-light .btn{background:rgba(0,0,0,0.07);} #bili-view-stats-panel.stats-light .detail{border-top:1px solid rgba(0,0,0,0.15);} #bili-view-stats-panel .back-btn{display:inline-block;margin-bottom:10px;padding:4px 12px;font-size:12px;background:rgba(255,255,255,0.12);color:inherit;border:1px solid rgba(255,255,255,0.25);border-radius:6px;cursor:pointer;} #bili-view-stats-panel .back-btn:hover{opacity:0.85;} #bili-view-stats-panel .v-item{padding:6px 2px;border-bottom:1px solid rgba(255,255,255,0.08);} #bili-view-stats-panel .v-item:last-child{border-bottom:none;} #bili-view-stats-panel .v-title{display:block;color:inherit;text-decoration:none;font-size:13px;line-height:1.5;} #bili-view-stats-panel .v-title:hover{color:#6cb8ff;text-decoration:underline;} #bili-view-stats-panel .v-sub{font-size:11px;opacity:0.6;margin-top:1px;} #bili-view-stats-panel.stats-light .back-btn{background:rgba(0,0,0,0.06);border-color:rgba(0,0,0,0.2);} #bili-view-stats-panel.stats-light .v-item{border-bottom:1px solid rgba(0,0,0,0.08);} #bili-view-stats-panel.stats-light .v-title:hover{color:#0a7de0;} #bili-view-stats-panel .head-btns{display:flex;align-items:center;gap:6px;flex-shrink:0;} #bili-view-stats-panel .icon-btn{padding:3px 9px;font-size:13px;line-height:1.4;background:rgba(255,255,255,0.12);color:inherit;border:1px solid rgba(255,255,255,0.25);border-radius:6px;cursor:pointer;} #bili-view-stats-panel .toolbar{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:8px;} #bili-view-stats-panel .toolbar .flt{display:flex;align-items:center;gap:6px;font-size:12px;color:inherit;white-space:nowrap;} #bili-view-stats-panel .toolbar input[type=number]{width:60px;padding:3px 6px;background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.25);border-radius:5px;color:inherit;font-size:12px;} #bili-view-stats-panel .tool-btn{padding:4px 10px;font-size:12px;background:rgba(255,255,255,0.12);color:inherit;border:1px solid rgba(255,255,255,0.25);border-radius:6px;cursor:pointer;white-space:nowrap;} #bili-view-stats-panel .theme-btn:hover,#bili-view-stats-panel .icon-btn:hover,#bili-view-stats-panel .tool-btn:hover{opacity:0.85;} #bili-view-stats-panel.stats-light .icon-btn{background:rgba(0,0,0,0.06);border-color:rgba(0,0,0,0.2);} #bili-view-stats-panel.stats-light .tool-btn{background:rgba(0,0,0,0.06);border-color:rgba(0,0,0,0.2);} #bili-view-stats-panel.stats-light .toolbar input[type=number]{background:rgba(0,0,0,0.05);border-color:rgba(0,0,0,0.2);} #bili-view-stats-panel .tool-btn.active{background:rgba(64,158,255,0.35);border-color:rgba(64,158,255,0.7);} #bili-view-stats-panel #bili-tag-filter{margin-bottom:10px;} #bili-view-stats-panel .tag-groups{display:flex;flex-wrap:wrap;gap:6px;align-items:center;padding:8px 10px;background:rgba(255,255,255,0.06);border-radius:8px;margin-bottom:8px;} #bili-view-stats-panel.stats-light .tag-groups{background:rgba(0,0,0,0.05);} #bili-view-stats-panel .tag-group-btn{padding:3px 10px;font-size:12px;background:rgba(255,255,255,0.12);color:inherit;border:1px solid rgba(255,255,255,0.25);border-radius:12px;cursor:pointer;white-space:nowrap;} #bili-view-stats-panel .tag-group-btn:hover{opacity:0.85;} #bili-view-stats-panel .tag-group-btn.selected{background:rgba(251,114,153,0.4);border-color:rgba(251,114,153,0.8);} #bili-view-stats-panel .tag-group-btn .cnt{opacity:0.65;margin-left:3px;font-size:11px;} #bili-view-stats-panel .tag-chips{display:flex;flex-wrap:wrap;gap:5px;padding:4px 10px 8px;} #bili-view-stats-panel .tag-chip{padding:2px 9px;font-size:11px;background:rgba(255,255,255,0.1);color:inherit;border:1px solid rgba(255,255,255,0.2);border-radius:10px;cursor:pointer;opacity:0.75;} #bili-view-stats-panel .tag-chip:hover{opacity:1;} #bili-view-stats-panel .tag-chip.selected{background:rgba(64,158,255,0.4);border-color:rgba(64,158,255,0.8);opacity:1;} #bili-view-stats-panel .tag-empty{font-size:12px;opacity:0.6;padding:6px 2px;} #bili-view-stats-panel .v-tags{font-size:11px;opacity:0.55;margin-top:2px;} #bili-view-stats-panel #bili-tag-review{padding:8px 10px;background:rgba(255,255,255,0.05);border-radius:8px;margin-bottom:8px;max-height:42vh;overflow:auto;} #bili-view-stats-panel.stats-light #bili-tag-review{background:rgba(0,0,0,0.04);} #bili-view-stats-panel .review-tip{font-size:11px;opacity:0.65;margin-bottom:8px;line-height:1.5;} #bili-view-stats-panel .review-group{margin-bottom:8px;} #bili-view-stats-panel .review-head{display:flex;align-items:center;gap:8px;font-size:12px;margin-bottom:4px;flex-wrap:wrap;} #bili-view-stats-panel .review-head-btns{display:inline-flex;gap:5px;margin-left:auto;} #bili-view-stats-panel .review-batch,#bili-view-stats-panel .review-dissolve{font-size:11px;padding:2px 8px;background:rgba(255,255,255,0.1);border:1px solid rgba(255,255,255,0.3);color:inherit;border-radius:9px;cursor:pointer;} #bili-view-stats-panel .review-dissolve{color:#ff9db8;border-color:rgba(251,114,153,0.5);} #bili-view-stats-panel .review-batch:hover,#bili-view-stats-panel .review-dissolve:hover{opacity:0.85;} #bili-view-stats-panel .review-auto{font-style:normal;font-size:10px;opacity:0.6;background:rgba(255,255,255,0.1);padding:1px 6px;border-radius:8px;} #bili-view-stats-panel .review-adopt{font-size:11px;padding:2px 9px;background:rgba(64,158,255,0.25);border:1px solid rgba(64,158,255,0.6);color:inherit;border-radius:9px;cursor:pointer;} #bili-view-stats-panel .review-adopt:hover{background:rgba(64,158,255,0.4);} #bili-view-stats-panel .review-chips{display:flex;flex-wrap:wrap;gap:5px;} #bili-view-stats-panel .review-chip u{opacity:0.7;font-size:10px;} #bili-view-stats-panel .review-chip u.excl{opacity:0.9;color:#ff9db8;} #bili-view-stats-panel .review-tip u.excl{color:#ff9db8;} #bili-view-stats-panel .review-chip.assigned{border-color:rgba(251,114,153,0.65);} #bili-assign-menu button:hover{background:rgba(255,255,255,0.18) !important;} `; document.head.appendChild(styleEl); } getAllRecords().then(records => { // UP 聚合只统计真正计过数的记录(times>0);times:0 是仅更新过位置的未确认访问 const counted = records.filter(r => (r.times || 0) > 0); // 按 UP 主 UID 聚合:总观看数、最近观看时间 const groups = {}; counted.forEach(r => { const key = r.uid || '未知'; const g = groups[key] || (groups[key] = { uid: key, name: '', times: 0, last: 0 }); g.times += r.times; g.last = Math.max(g.last, r.lastTime || 0); if (!g.name && r.name) g.name = r.name; }); const rows = Object.values(groups).sort((a, b) => b.times - a.times); let old = document.getElementById('bili-view-stats-panel'); if (old) old.remove(); const panel = document.createElement('div'); panel.id = 'bili-view-stats-panel'; let body = ''; if (!rows.length) { body = '
'; } else { const trs = rows.map(g => { const lastStr = g.last ? new Date(g.last).toLocaleString('zh-CN', { hour12: false }) : '—'; const isUnknown = g.uid === '未知'; const uidTd = isUnknown ? '未知' : escapeHtml(g.uid); const nameTd = !g.name ? '未知' : (isUnknown ? `${escapeHtml(g.name)}` : `${escapeHtml(g.name)}`); const timesTd = isUnknown ? `| UID | 用户名 | 总观看数 | 最近观看 |
|---|