// ==UserScript== // @name O站 剧本积分统计 // @namespace https://userscripts.local/omnimundia-credits-stats // @version 2.4.0 // @description 读取 O站全部剧本的每回合积分消耗,统计平均值、中位数、分位数与区间占比,可导出 Markdown、CSV 与 JSON。 // @author fenglaosir // @icon https://omnimundia.cn/logo.svg // @license MIT // @homepage https://gitee.com/feng-lao-sir/omnimundia-credits-stats // @supportURL https://gitee.com/feng-lao-sir/omnimundia-credits-stats/issues // @match https://omnimundia.cn/* // @run-at document-idle // @noframes // @grant none // ==/UserScript== /* * O站 剧本积分统计 * Copyright (c) 2026 fenglaosir * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * 以上为 MIT 许可证正文,与仓库 LICENSE 文件一致。 */ (() => { 'use strict'; const VERSION = '2.4.0'; const HOST_ID = 'omd-credits-stats'; const DEFAULT_RANGES = '12-18,19-29,30-43,44+'; const FALLBACK_BUILD_TIME = '2026-11-29T13:32:00Z'; const LIST_PAGE_SIZE = 100; const CONCURRENCY = 4; const MAX_PAGES = 200; /* >>> stats-core >>> */ function quantile(sorted, p) { const n = sorted.length; if (!n) return NaN; if (n === 1) return sorted[0]; const pos = (n - 1) * p; const base = Math.floor(pos); const rest = pos - base; const next = sorted[base + 1]; return next === undefined ? sorted[base] : sorted[base] + rest * (next - sorted[base]); } function computeStats(values) { const n = values.length; if (!n) return null; const sorted = values.slice().sort((a, b) => a - b); const sum = sorted.reduce((acc, v) => acc + v, 0); const mean = sum / n; const variance = n > 1 ? sorted.reduce((acc, v) => acc + (v - mean) * (v - mean), 0) / (n - 1) : 0; return { count: n, sum, mean, median: quantile(sorted, 0.5), min: sorted[0], max: sorted[n - 1], q1: quantile(sorted, 0.25), q3: quantile(sorted, 0.75), p10: quantile(sorted, 0.1), p90: quantile(sorted, 0.9), p95: quantile(sorted, 0.95), std: Math.sqrt(variance), sorted }; } function parseRanges(spec) { const parts = String(spec || '').split(/[,,;;\s]+/).filter(Boolean); const ranges = []; for (const part of parts) { const text = part.trim(); if (!text) continue; let m = text.match(/^(\d+)\s*[-–~至]\s*(\d+)$/); if (m) { const min = Number(m[1]); const max = Number(m[2]); if (min > max) continue; ranges.push({ label: `${min}–${max}`, min, max }); continue; } m = text.match(/^(\d+)\s*\+$|^(\d+)\s*(?:以上|及以上)$/); if (m) { const min = Number(m[1] || m[2]); ranges.push({ label: `${min}+`, min, max: Infinity }); continue; } m = text.match(/^(\d+)$/); if (m) { const v = Number(m[1]); ranges.push({ label: `${v}`, min: v, max: v }); } } ranges.sort((a, b) => a.min - b.min || a.max - b.max); return ranges; } function buildBuckets(values, ranges) { const total = values.length || 1; return ranges.map((r) => { const items = values.filter((v) => v >= r.min && v <= r.max); return { label: r.label, min: r.min, max: r.max, count: items.length, share: items.length / total }; }); } function normalizeFilters(input) { const number = (value) => { const n = Number(value); return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0; }; return { minPlayers: number(input && input.minPlayers), minLikes: number(input && input.minLikes), minFavorites: number(input && input.minFavorites), topN: number(input && input.topN) }; } function filterScripts(items, filters) { const f = normalizeFilters(filters); let list = items.slice(); if (f.minPlayers > 0) list = list.filter((item) => Number(item.playerCount) >= f.minPlayers); if (f.minLikes > 0) list = list.filter((item) => Number(item.likeCount) >= f.minLikes); if (f.minFavorites > 0) list = list.filter((item) => Number(item.favoriteCount) >= f.minFavorites); if (f.topN > 0) list = list.slice(0, f.topN); return list; } function describeFilters(filters) { const f = normalizeFilters(filters); const parts = []; if (f.minPlayers > 0) parts.push(`游玩人数 ≥ ${f.minPlayers}`); if (f.minLikes > 0) parts.push(`点赞 ≥ ${f.minLikes}`); if (f.minFavorites > 0) parts.push(`收藏 ≥ ${f.minFavorites}`); if (f.topN > 0) parts.push(`榜单前 ${f.topN} 名`); return parts.length ? parts.join(',') : '不限'; } function round2(value) { return Math.round(value * 100) / 100; } function csvCell(value) { const text = value === null || value === undefined ? '' : String(value); return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text; } function recordsToCsv(records) { const lines = ['序号,剧本,每回合积分,最低,最高,游玩人数,点赞,收藏,链接']; records.forEach((r, i) => { lines.push([ i + 1, csvCell(r.name), r.cost, Number.isFinite(r.min) ? r.min : '', Number.isFinite(r.max) ? r.max : '', Number.isFinite(r.playerCount) ? r.playerCount : '', Number.isFinite(r.likeCount) ? r.likeCount : '', Number.isFinite(r.favoriteCount) ? r.favoriteCount : '', csvCell(r.url || '') ].join(',')); }); return '\ufeff' + lines.join('\r\n') + '\r\n'; } function buildMarkdownReport(meta, records, stats, buckets) { const lines = []; lines.push(`# ${meta.title}`); lines.push(''); lines.push(`- 统计时间:${meta.generatedAt}`); lines.push(`- 样本数量:${stats.count} 个剧本`); lines.push(`- 数据来源:${meta.source}`); if (meta.filters) lines.push(`- 筛选条件:${meta.filters}`); lines.push('- 统计口径:`latest_turn_credits`,即最新发布版本每回合消耗的积分'); lines.push(''); lines.push('## 总体指标'); lines.push(''); lines.push('| 指标 | 数值 |'); lines.push('| --- | --- |'); lines.push(`| 平均值 | ${round2(stats.mean)} |`); lines.push(`| 中位数 | ${round2(stats.median)} |`); lines.push(`| 最小值 | ${stats.min} |`); lines.push(`| 最大值 | ${stats.max} |`); lines.push(`| 标准差(样本) | ${round2(stats.std)} |`); lines.push(`| 下四分位 P25 | ${round2(stats.q1)} |`); lines.push(`| 上四分位 P75 | ${round2(stats.q3)} |`); lines.push(''); lines.push('## 分位分布'); lines.push(''); lines.push('| 分位 | 积分 |'); lines.push('| --- | --- |'); lines.push(`| P10 | ${round2(stats.p10)} |`); lines.push(`| P25 | ${round2(stats.q1)} |`); lines.push(`| P50(中位数) | ${round2(stats.median)} |`); lines.push(`| P75 | ${round2(stats.q3)} |`); lines.push(`| P90 | ${round2(stats.p90)} |`); lines.push(`| P95 | ${round2(stats.p95)} |`); lines.push(''); lines.push('## 积分区间占比'); lines.push(''); lines.push('| 区间 | 数量 | 占比 |'); lines.push('| --- | --- | --- |'); buckets.forEach((b) => { lines.push(`| ${b.label} | ${b.count} | ${round2(b.share * 100)}% |`); }); lines.push(''); const sorted = records.slice().sort((a, b) => a.cost - b.cost || a.name.localeCompare(b.name, 'zh-Hans-CN')); lines.push('## 积分最低的 10 个剧本'); lines.push(''); lines.push('| 剧本 | 积分 |'); lines.push('| --- | --- |'); sorted.slice(0, 10).forEach((r) => lines.push(`| ${r.name} | ${r.cost} |`)); lines.push(''); lines.push('## 积分最高的 10 个剧本'); lines.push(''); lines.push('| 剧本 | 积分 |'); lines.push('| --- | --- |'); sorted.slice(-10).reverse().forEach((r) => lines.push(`| ${r.name} | ${r.cost} |`)); lines.push(''); lines.push('## 全部剧本'); lines.push(''); lines.push('| 剧本 | 每回合积分 | 最低 | 最高 |'); lines.push('| --- | --- | --- | --- |'); sorted.forEach((r) => lines.push(`| ${r.name} | ${r.cost} | ${r.min ?? ''} | ${r.max ?? ''} |`)); lines.push(''); return lines.join('\n'); } /* <<< stats-core <<< */ const state = { running: false, aborted: false, records: [], failed: 0, stats: null, buckets: [], ranges: DEFAULT_RANGES, rankMode: 'hot', filters: { minPlayers: 0, minLikes: 0, minFavorites: 0, topN: 0 }, startedAt: 0 }; let buildTime = ''; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); function readToken() { try { return localStorage.getItem('access_token') || ''; } catch (error) { return ''; } } function buildHeaders() { const headers = { accept: 'application/json' }; const token = readToken(); if (token) headers.authorization = `Bearer ${token}`; if (buildTime) headers['x-client-version'] = buildTime; return headers; } async function readBuildTime() { const sources = Array.from(document.scripts) .map((script) => script.src) .filter((src) => src && src.includes('/assets/')); for (const source of sources.reverse()) { try { const response = await fetch(source, { credentials: 'same-origin' }); if (!response.ok) continue; const text = await response.text(); const match = /"X-Client-Version"\s*:\s*"([^"]+)"/.exec(text); if (match) return match[1]; } catch (error) { // 取不到就退回固定值 } } return FALLBACK_BUILD_TIME; } async function ensureBuildTime(force) { if (!buildTime || force) buildTime = await readBuildTime(); return buildTime; } class ApiError extends Error { constructor(message, status) { super(message); this.name = 'ApiError'; this.status = status; } } async function apiGet(path, options = {}) { const retries = options.retries ?? 2; let lastError = null; for (let attempt = 0; attempt <= retries; attempt += 1) { let response; try { response = await fetch(path, { headers: buildHeaders(), credentials: 'same-origin' }); } catch (error) { lastError = new ApiError('网络请求失败'); await sleep(600 * (attempt + 1)); continue; } if (response.ok) return response.json(); if (response.status === 409) { await ensureBuildTime(true); lastError = new ApiError('客户端版本需要刷新', 409); await sleep(300); continue; } if (response.status === 401 || response.status === 403) { throw new ApiError('登录状态已失效,请刷新页面或重新登录', response.status); } if (response.status === 429) { lastError = new ApiError('请求过于频繁', 429); await sleep(1500 * (attempt + 1)); continue; } if (response.status >= 500) { lastError = new ApiError(`服务端错误 ${response.status}`, response.status); await sleep(800 * (attempt + 1)); continue; } const text = await response.text().catch(() => ''); throw new ApiError(`HTTP ${response.status} ${text.slice(0, 100)}`, response.status); } throw lastError || new ApiError('请求失败'); } function countOf(value) { const n = Number(value); return Number.isFinite(n) && n >= 0 ? n : 0; } function parseTurnCredits(payload) { const data = payload && payload.data ? payload.data : payload; if (!data || typeof data !== 'object') return null; const latest = Number(data.latest_turn_credits); if (!Number.isFinite(latest)) return null; return { cost: latest, min: Number.isFinite(Number(data.min_turn_credits)) ? Number(data.min_turn_credits) : null, max: Number.isFinite(Number(data.max_turn_credits)) ? Number(data.max_turn_credits) : null }; } async function collectScripts(ui) { const map = new Map(); let zeroStreak = 0; let total = 0; for (let page = 1; page <= MAX_PAGES; page += 1) { if (state.aborted) break; const query = `rank_mode=${encodeURIComponent(state.rankMode)}&page=${page}&page_size=${LIST_PAGE_SIZE}`; let payload; try { payload = await apiGet(`/api/scripts?${query}`, { retries: 2 }); } catch (error) { if (page === 1) throw error; if (total > 0 && map.size >= total) break; ui.setStatus(`列表第 ${page} 页失败:${error.message},已停在 ${map.size} 个剧本。`); break; } const items = Array.isArray(payload.data) ? payload.data : []; let added = 0; for (const item of items) { const id = item && (item.script_id || item.id); if (!id || map.has(id)) continue; map.set(id, { id, name: String(item.name || id), playerCount: countOf(item.player_count), likeCount: countOf(item.like_count), favoriteCount: countOf(item.favorite_count), commentCount: countOf(item.comment_count), rank: map.size + 1, url: `https://omnimundia.cn/game/${id}` }); added += 1; } const pagination = payload && payload.meta && payload.meta.pagination; if (pagination && Number.isFinite(Number(pagination.total))) total = Number(pagination.total); // total 会被服务端截断为 page_size × 100,达到这个值就不可信 const trusted = total > 0 && total < LIST_PAGE_SIZE * 100; ui.setListProgress(page, map.size, items.length, trusted ? total : null); if (!items.length) break; if (trusted && map.size >= total) break; if (trusted && items.length < LIST_PAGE_SIZE) break; zeroStreak = added === 0 ? zeroStreak + 1 : 0; if (zeroStreak >= 2) break; await sleep(220); } return Array.from(map.values()); } async function collectCredits(scripts, ui) { const total = scripts.length; const results = []; let cursor = 0; let done = 0; let failed = 0; const worker = async () => { while (!state.aborted) { const index = cursor; cursor += 1; if (index >= total) return; const script = scripts[index]; try { const payload = await apiGet(`/api/scripts/${encodeURIComponent(script.id)}/turn-credits`, { retries: 3 }); const parsed = parseTurnCredits(payload); if (parsed) { results.push({ ...script, ...parsed }); } else { failed += 1; } } catch (error) { failed += 1; } done += 1; if (done % 5 === 0 || done === total) ui.setCreditProgress(done, total, results.length); await sleep(70 + Math.random() * 70); } }; await Promise.all(Array.from({ length: CONCURRENCY }, worker)); state.failed = failed; state.records = results; } async function runScan(ui) { state.running = true; state.aborted = false; state.records = []; state.failed = 0; state.stats = null; state.buckets = []; state.startedAt = Date.now(); ui.setBusy(true); ui.setStatus('正在准备:读取版本号…'); try { if (!readToken()) { ui.setStatus('没有找到登录令牌(localStorage.access_token)。请先登录 O站再刷新页面。'); return; } await ensureBuildTime(); ui.setStatus('正在获取剧本列表…'); const scripts = await collectScripts(ui); if (!scripts.length) { ui.setStatus('列表为空。可能是 rank_mode 不正确,或当前账号看不到剧本。'); return; } const filtered = filterScripts(scripts, state.filters); if (!filtered.length) { ui.setStatus(`列表共 ${scripts.length} 个剧本,但没有符合当前筛选条件的,请放宽条件后重试。`); return; } ui.setStatus(`列表共 ${scripts.length} 个剧本,筛选后 ${filtered.length} 个,开始读取积分…`); await collectCredits(filtered, ui); if (!state.records.length) { ui.setStatus('没有取到任何积分数据。请确认登录状态是否正常。'); return; } recompute(ui); const seconds = ((Date.now() - state.startedAt) / 1000).toFixed(1); const failedText = state.failed ? `,${state.failed} 个读取失败` : ''; ui.setStatus(state.aborted ? `已停止:${state.records.length} 个剧本,用时 ${seconds} 秒${failedText}。` : `完成:${state.records.length} 个剧本,用时 ${seconds} 秒${failedText}。`); } catch (error) { ui.setStatus(`出错:${error.message}`); } finally { state.running = false; ui.setBusy(false); } } function recompute(ui) { const values = state.records.map((r) => r.cost); state.stats = computeStats(values); const ranges = parseRanges(state.ranges); state.buckets = buildBuckets(values, ranges.length ? ranges : parseRanges(DEFAULT_RANGES)); if (ui) ui.renderResults(); } function reportMeta() { return { title: 'O站 剧本积分统计', generatedAt: new Date().toLocaleString('zh-CN', { hour12: false }), source: `GET /api/scripts + /api/scripts/{id}/turn-credits(rank_mode=${state.rankMode})`, filters: describeFilters(state.filters) }; } function download(filename, content, type) { const blob = new Blob([content], { type }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = filename; document.body.appendChild(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(url), 2000); } function timestamp() { const d = new Date(); const pad = (v) => String(v).padStart(2, '0'); return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}`; } function escapeHtml(text) { return String(text) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } const STYLES = ` :host { all: initial; } * { box-sizing: border-box; font-family: system-ui, -apple-system, "Segoe UI", "Microsoft YaHei", sans-serif; } .panel { position: fixed; z-index: 2147483001; top: 50%; left: 50%; width: min(760px, calc(100vw - 32px)); max-height: min(86vh, 900px); transform: translate(-50%, -50%); display: flex; flex-direction: column; background: #1b1f29; color: #e8ebf2; border-radius: 14px; border: 1px solid rgba(255,255,255,.14); box-shadow: 0 24px 70px rgba(0,0,0,.5); font-size: 13px; overflow: hidden; } .head { display: flex; align-items: center; gap: 10px; padding: 14px 16px; border-bottom: 1px solid rgba(255,255,255,.1); } .head h2 { margin: 0; font-size: 15px; font-weight: 600; flex: 1; } .head .ver { font-size: 11px; color: #8e97a8; } .body { padding: 14px 16px 18px; overflow: auto; } .row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } button { font: inherit; padding: 6px 12px; border-radius: 8px; cursor: pointer; background: #262c3a; color: #dfe4ee; border: 1px solid rgba(255,255,255,.14); } button:hover:not(:disabled) { background: #313849; } button:disabled { opacity: .45; cursor: default; } button.primary { background: #2f6feb; border-color: #2f6feb; color: #fff; } button.primary:hover:not(:disabled) { background: #3c7bf5; } .status { margin: 10px 0 4px; color: #a9b2c3; min-height: 20px; line-height: 1.6; } .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 8px; margin: 12px 0; } .cell { background: #232936; border-radius: 10px; padding: 10px 12px; } .cell .k { color: #8e97a8; font-size: 11px; margin-bottom: 4px; } .cell .v { font-size: 18px; font-weight: 600; font-variant-numeric: tabular-nums; } h3 { font-size: 13px; margin: 18px 0 8px; color: #c8d0de; font-weight: 600; } table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; } th, td { padding: 5px 6px; text-align: left; border-bottom: 1px solid rgba(255,255,255,.07); } th { color: #8e97a8; font-weight: 500; font-size: 11px; } td.num, th.num { text-align: right; } .bar { height: 6px; border-radius: 3px; background: #2f6feb; min-width: 2px; } .barwrap { background: rgba(255,255,255,.07); border-radius: 3px; width: 100%; } input[type="text"] { font: inherit; padding: 6px 8px; border-radius: 8px; width: 160px; background: #141821; color: #e8ebf2; border: 1px solid rgba(255,255,255,.16); } input[type="number"] { font: inherit; padding: 6px 8px; border-radius: 8px; width: 92px; background: #141821; color: #e8ebf2; border: 1px solid rgba(255,255,255,.16); } .filters h3 { margin-top: 0; } .filters label { display: inline-flex; align-items: center; gap: 6px; color: #a9b2c3; white-space: nowrap; } input.wide { width: 280px; } .hint { color: #7d879a; font-size: 11px; margin-top: 6px; line-height: 1.7; } .close { background: transparent; border: none; color: #9aa4b6; font-size: 18px; padding: 2px 6px; } .close:hover { color: #fff; background: transparent; } .top-list { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; } @media (max-width: 620px) { .top-list { grid-template-columns: 1fr; } } `; function createUi() { const host = document.createElement('div'); host.id = HOST_ID; host.style.all = 'initial'; const root = host.attachShadow({ mode: 'open' }); const style = document.createElement('style'); style.textContent = STYLES; root.appendChild(style); const panel = document.createElement('div'); panel.className = 'panel'; panel.style.display = 'none'; panel.innerHTML = `
rank_mode 的顺序截取,在所有数值条件之后生效。latest_turn_credits,即最新发布版本每回合消耗的积分;最低/最高来自 min_turn_credits / max_turn_credits。约 4 路并发,不写日志、不保存令牌。| 区间 | 数量 | 占比 |
|---|