// ==UserScript== // @name B站视频数据一览 // @namespace http://tampermonkey.net/ // @version 1.2 // @description 读取 4.js 的观看事件表(详细时间戳,V1.7 起记录),生成一份自包含的单机统计报告页(新标签打开、零外部请求、可另存永久保留):最受喜欢的视频Top10(封面)/UP主排行榜(头像)/最受喜欢的标签、每月观看天数折线图、每日观看次数折线图、24×7作息热力图、连续观看/单日最高徽章、CSV导出、事件保留期限。每月1号/每年1号/每周一在左下角弹提示卡片。另含:观看时段趋势对比(年/月)、历史年度对比表、UP主关注变化(近30天vs前30天)、标签兴趣变化(近90天vs前90天)、GitHub风格观看记录日历、JSON完整备份/恢复 // @author Anonymity // @match *://www.bilibili.com/* // @grant GM_registerMenuCommand // @grant GM_getValue // @grant GM_setValue // @run-at document-idle // @license MIT // ==/UserScript== (function () { 'use strict'; const DB_NAME = 'BiliViewCountDB'; // ====================== IndexedDB(与 4.js 同库同构,谁先升级谁建表) ====================== function openDB() { return new Promise((resolve, reject) => { const req = indexedDB.open(DB_NAME, 3); // v3:events 增加 by_t 时间索引(与 4.js 保持同版本,谁先运行谁升级) req.onupgradeneeded = () => { const db = req.result; if (!db.objectStoreNames.contains('views')) db.createObjectStore('views', { 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); }); } function getAllEvents() { return openDB().then(db => new Promise(resolve => { try { const req = db.transaction('events', 'readonly').objectStore('events').getAll(); req.onsuccess = () => resolve(req.result || []); req.onerror = () => resolve([]); } catch (e) { resolve([]); } })).catch(() => []); } // 删除指定毫秒时间之前的事件(保留期限),返回删除数 // 走 by_t 时间索引游标(IDBKeyRange 区间扫描),长期大数据量下不再全表遍历 async function deleteEventsBefore(ts) { try { const db = await openDB(); return await new Promise(resolve => { let n = 0; const tx = db.transaction('events', 'readwrite'); const req = tx.objectStore('events').index('by_t').openCursor(IDBKeyRange.upperBound(ts, true)); // t < ts req.onsuccess = () => { const cur = req.result; if (!cur) return; const ev = cur.value; if (ev && typeof ev.t === 'number' && ev.t < ts) { cur.delete(); n++; } cur.continue(); }; tx.oncomplete = () => resolve(n); tx.onerror = () => resolve(n); }); } catch (e) { return 0; } } // ====================== JSON 完整备份/恢复 ====================== // CSV 适合分析,JSON 保留原始事件结构(含 bv/t/p/uid/face/pic/title/tags 全字段),适合做完整数据库备份 async function exportJsonBackup() { try { const events = await getAllEvents(); const views = await openDB().then(db => new Promise(res => { try { const rq = db.transaction('views', 'readonly').objectStore('views').getAll(); rq.onsuccess = () => res(rq.result || []); rq.onerror = () => res([]); } catch (e) { res([]); } })); const data = { app: 'bili-view-stats', version: 1, exportedAt: new Date().toISOString(), events, views }; const url = URL.createObjectURL(new Blob([JSON.stringify(data)], { type: 'application/json' })); const a = document.createElement('a'); a.href = url; a.download = 'bili-stats-backup-' + fmtDate(Date.now()) + '.json'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 30000); alert(`✅ 备份已导出:${events.length} 条事件 + ${views.length} 条观看记录`); } catch (e) { alert('导出失败:' + e); } } async function importJsonBackup() { const inp = document.createElement('input'); inp.type = 'file'; inp.accept = '.json,application/json'; inp.onchange = async () => { try { const data = JSON.parse(await inp.files[0].text()); if (!data || !Array.isArray(data.events)) { alert('文件格式不对:缺少 events 数组'); return; } if (data.app !== 'bili-view-stats' && !confirm('该文件不是本脚本导出的标准备份,仍要尝试导入吗?')) return; const db = await openDB(); // events 主键是自增,不能直接 put:以 bv|t 为自然键去重合并,只补缺失的 const existing = await getAllEvents(); const keys = new Set(existing.map(e => (e && e.bv) + '|' + (e && e.t))); const fresh = data.events.filter(e => e && e.bv && typeof e.t === 'number' && !keys.has(e.bv + '|' + e.t)); const views = Array.isArray(data.views) ? data.views.filter(v => v && v.id) : []; await new Promise((resolve, reject) => { const tx = db.transaction(['events', 'views'], 'readwrite'); fresh.forEach(e => tx.objectStore('events').add(e)); views.forEach(v => tx.objectStore('views').put(v)); // views 主键是 BV,put 语义整条覆盖 tx.oncomplete = resolve; tx.onabort = () => reject(tx.error || new Error('导入事务中止')); }); alert(`✅ 导入完成:新增事件 ${fresh.length} 条(跳过已存在 ${data.events.length - fresh.length} 条),覆盖记录 ${views.length} 条`); } catch (err) { alert('导入失败:' + err); } }; inp.click(); } // ====================== 周期工具 ====================== function fmtDate(t) { const d = new Date(t); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); } // 返回 [from, to) 毫秒区间 function periodRange(key, now) { now = now || new Date(); const today0 = new Date(now.getFullYear(), now.getMonth(), now.getDate()); if (key === 'lastweek') { const dow = (today0.getDay() + 6) % 7; // 周一=0 const thisMon = today0.getTime() - dow * 864e5; return [thisMon - 7 * 864e5, thisMon]; } if (key === 'lastmonth') { return [new Date(now.getFullYear(), now.getMonth() - 1, 1).getTime(), new Date(now.getFullYear(), now.getMonth(), 1).getTime()]; } if (key === 'month') { return [new Date(now.getFullYear(), now.getMonth(), 1).getTime(), today0.getTime() + 864e5]; } if (key === 'year') { return [new Date(now.getFullYear(), 0, 1).getTime(), today0.getTime() + 864e5]; } if (key === 'lastyear') { return [new Date(now.getFullYear() - 1, 0, 1).getTime(), new Date(now.getFullYear(), 0, 1).getTime()]; } return [0, Infinity]; // 'all' } async function countEventsIn(range) { const evs = await getAllEvents(); return evs.filter(e => e && e.t >= range[0] && e.t < range[1]).length; } // ====================== 左下角提示卡片 ====================== const POPUP_CSS = ` #bili-stats-popups{position:fixed;left:16px;bottom:16px;z-index:2147483646;display:flex;flex-direction:column;gap:10px;font-family:inherit;} .bsp-card{background:#fff;color:#18191c;border:1px solid #e3e5e7;border-radius:10px;box-shadow:0 6px 24px rgba(0,0,0,.18); padding:12px 14px;max-width:320px;font-size:13px;line-height:1.5;cursor:pointer; animation:bsp-in .35s cubic-bezier(.2,.8,.3,1);transition:transform .15s,box-shadow .15s;} .bsp-card:hover{transform:translateY(-2px);box-shadow:0 10px 28px rgba(0,0,0,.25);} .bsp-card .bsp-title{font-weight:600;margin-bottom:4px;} .bsp-card .bsp-act{color:#00a1d6;font-weight:600;} .bsp-card .bsp-x{float:right;color:#999;cursor:pointer;font-size:14px;padding:0 2px;margin-left:8px;} .bsp-card .bsp-x:hover{color:#f25d8e;} @keyframes bsp-in{from{opacity:0;transform:translateY(24px);}to{opacity:1;transform:none;}} @media (prefers-color-scheme: dark){ .bsp-card{background:#2b2b2b;color:#e6e6e6;border-color:#444;} .bsp-card .bsp-act{color:#4fc3f7;} }`; function showPopupCard(title, action, periodKey, seenKey) { let box = document.getElementById('bili-stats-popups'); if (!box) { const style = document.createElement('style'); style.textContent = POPUP_CSS; document.head.appendChild(style); box = document.createElement('div'); box.id = 'bili-stats-popups'; box.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:2147483646;display:flex;flex-direction:column;gap:10px;'; document.body.appendChild(box); } const card = document.createElement('div'); card.className = 'bsp-card'; card.innerHTML = '✕