// ==UserScript== // @name GOG 平台增强 // @name:en GOG Platform Enhancer // @namespace gog-platform-enhancer // @version 1.0.0 // @description GOG 双合一:免费雷达自动扫描 0 元商品(试玩识别、新上架提醒、本机已领标记)+ 库存分析(发行年代/平台/类型/评分、库面值、审计),支持 JSON / CSV / Markdown 导出 // @description:en Two in one for GOG: a free-games radar (zero-price scan, demo detection, new-entry alerts, local claim marks) plus library analytics (release year / platform / genre / rating, shelf value, audit) with JSON / CSV / Markdown export. // @author SmallRob // @match https://www.gog.com/* // @grant none // @run-at document-idle // @noframes // @license MIT // @icon data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2064%2064'%20width='64'%20height='64'%3E%3Cdefs%3E%3ClinearGradient%20id='bg-gog'%20x1='0'%20y1='0'%20x2='1'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%231f0a38'/%3E%3Cstop%20offset='100%25'%20stop-color='%230d0818'/%3E%3C/linearGradient%3E%3ClinearGradient%20id='gog-purple'%20x1='0'%20y1='0'%20x2='1'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%23c084fc'/%3E%3Cstop%20offset='60%25'%20stop-color='%23a855f7'/%3E%3Cstop%20offset='100%25'%20stop-color='%237c3aed'/%3E%3C/linearGradient%3E%3ClinearGradient%20id='gog-gold'%20x1='0'%20y1='0'%20x2='0'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%23fde68a'/%3E%3Cstop%20offset='100%25'%20stop-color='%23f59e0b'/%3E%3C/linearGradient%3E%3Cfilter%20id='glow-gog'%20x='-30%25'%20y='-30%25'%20width='160%25'%20height='160%25'%3E%3CfeGaussianBlur%20stdDeviation='2'%20result='blur'/%3E%3CfeMerge%3E%3CfeMergeNode%20in='blur'/%3E%3CfeMergeNode%20in='SourceGraphic'/%3E%3C/feMerge%3E%3C/filter%3E%3C/defs%3E%3Crect%20width='64'%20height='64'%20rx='14'%20fill='url(%23bg-gog)'/%3E%3Cellipse%20cx='32'%20cy='14'%20rx='24'%20ry='10'%20fill='%23a855f7'%20opacity='0.15'/%3E%3Cg%20transform='translate(16,%2012)'%20filter='url(%23glow-gog)'%3E%3Ccircle%20cx='16'%20cy='16'%20r='14'%20fill='none'%20stroke='url(%23gog-purple)'%20stroke-width='4.5'%20stroke-linecap='round'/%3E%3Cpath%20d='M%2026%2010%20A%2012%2012%200%200%201%2026%2022'%20fill='%230d0818'%20stroke='none'/%3E%3Ccircle%20cx='11'%20cy='14'%20r='2.2'%20fill='url(%23gog-purple)'/%3E%3Ccircle%20cx='20'%20cy='14'%20r='2.2'%20fill='url(%23gog-purple)'/%3E%3Cpath%20d='M%208%2030%20L%206%2040%20L%2010%2036%20Z'%20fill='url(%23gog-purple)'/%3E%3Cpath%20d='M%2024%2030%20L%2026%2040%20L%2022%2036%20Z'%20fill='url(%23gog-purple)'/%3E%3C/g%3E%3Cg%20transform='translate(38,%208)'%3E%3Crect%20x='0'%20y='0'%20width='17'%20height='12'%20rx='3.5'%20fill='url(%23gog-gold)'/%3E%3Cpath%20d='M%2012%2012%20L%2017%2017%20L%2017%2012%20Z'%20fill='%23f59e0b'/%3E%3Ctext%20x='8.5'%20y='9.4'%20text-anchor='middle'%20font-family='Arial%20Black,%20sans-serif'%20font-size='9'%20font-weight='900'%20fill='%231a0608'%3E0%3C/text%3E%3C/g%3E%3Ccircle%20cx='52'%20cy='48'%20r='2'%20fill='%23c084fc'%20opacity='0.7'/%3E%3Ccircle%20cx='58'%20cy='54'%20r='1.5'%20fill='%23fde68a'%20opacity='0.8'/%3E%3Ccircle%20cx='46'%20cy='54'%20r='1'%20fill='%23c084fc'%20opacity='0.6'/%3E%3C/svg%3E // ==/UserScript== (function () { 'use strict'; const VERSION = '1.0.0'; const LOG_PREFIX = '[GOG 助手]'; const SITE = 'https://www.gog.com'; const USERS_HOST = 'https://users.gog.com'; const CATALOG_HOST = 'https://catalog.gog.com'; // 目录接口一次最多 48 条;免费扫描按「价格升序」翻页,遇到收费商品即可停 const CATALOG_PAGE = 48; const FREE_SCAN_MAX_PAGES = 12; const LIBRARY_PAGE_MAX = 40; const SNAPSHOT_KEY = 'gpe.snapshots'; const SNAPSHOT_MAX = 20; const LEDGER_KEY = 'gpe.freeLedger'; const RADAR_KEY = 'gpe.radar'; const LEDGER_MAX = 600; const CFG_KEY = 'gpe.cfg'; const LOCALES = { CN: { countryCode: 'CN', currencyCode: 'CNY', locale: 'zh-Hans', label: '中国 · CNY' }, US: { countryCode: 'US', currencyCode: 'USD', locale: 'en-US', label: '美国 · USD' }, HK: { countryCode: 'HK', currencyCode: 'HKD', locale: 'zh-Hant', label: '中国香港 · HKD' }, TW: { countryCode: 'TW', currencyCode: 'TWD', locale: 'zh-Hant', label: '中国台湾 · TWD' }, JP: { countryCode: 'JP', currencyCode: 'JPY', locale: 'ja-JP', label: '日本 · JPY' }, GB: { countryCode: 'GB', currencyCode: 'GBP', locale: 'en-GB', label: '英国 · GBP' }, DE: { countryCode: 'DE', currencyCode: 'EUR', locale: 'de-DE', label: '德国 · EUR' } }; const CURRENCY_SYMBOL = { CNY: '¥', USD: '$', EUR: '€', GBP: '£', JPY: '¥', HKD: 'HK$', TWD: 'NT$', KRW: '₩', RUB: '₽' }; const CFG_DEFAULTS = { region: 'CN', includeDemos: false, // 免费雷达是否显示试玩版 autoRadar: false, // 打开页面自动扫一次免费商品 toast: true }; function getStored(key, fallback) { try { const raw = localStorage.getItem(key); if (!raw) return fallback; return JSON.parse(raw); } catch (e) { return fallback; } } function setStored(key, value) { try { if (value === null) localStorage.removeItem(key); else localStorage.setItem(key, JSON.stringify(value)); } catch (e) { console.warn(LOG_PREFIX, '本地存储写入失败', e); } } const CFG = Object.assign({}, CFG_DEFAULTS, getStored(CFG_KEY, {})); const state = { library: null, // 库存读取结果(含 analysis) diff: null, running: false, startedAt: 0, ledger: { version: 1, items: {} }, radar: null, // 免费雷达快照 {at, items, region, stoppedEarly} radarBusy: false, radarFilter: 'all', radarAnalysis: null, ticker: null }; (function restore() { const ledger = getStored(LEDGER_KEY, null); if (ledger && ledger.items && typeof ledger.items === 'object') { state.ledger = { version: 1, items: ledger.items }; } // 上一次扫描的 id 集合要持久化:否则重开页面后所有条目都会被当成「已结束」 const radar = getStored(RADAR_KEY, null); if (radar && Array.isArray(radar.ids)) { state.radar = { at: radar.at || 0, ids: radar.ids, region: radar.region || CFG.region, stoppedEarly: !!radar.stoppedEarly }; } })(); function saveCfg() { setStored(CFG_KEY, CFG); } // ==================== 通用工具 ==================== function pad2(n) { return n < 10 ? '0' + n : String(n); } function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); } function parseJson(text, what) { try { return JSON.parse(text); } catch (e) { throw new Error(what + ' 返回非 JSON(可能被登录墙拦下,请先在 gog.com 登录)'); } } function fmtAgo(ts) { if (!ts) return ''; const d = Date.now() - ts; if (d < 60000) return '刚刚'; const m = Math.floor(d / 60000); if (m < 60) return m + ' 分钟前'; const h = Math.floor(m / 60); if (h < 24) return h + ' 小时前'; return Math.floor(h / 24) + ' 天前'; } function fmtIsoDay(iso) { if (!iso) return '—'; const s = String(iso); return s.length >= 10 ? s.slice(0, 10) : s; } function fmtMoney(value, currency) { if (!value) return (CURRENCY_SYMBOL[currency] || '¥') + '0'; const sym = CURRENCY_SYMBOL[currency] || (currency ? currency + ' ' : ''); const n = Math.round(value * 100) / 100; return sym + (n % 1 === 0 ? String(n) : n.toFixed(2)); } // 剩余时间:超过一天按「天 时:分」,否则「时:分」 function fmtRemain(ms) { if (ms === null || ms === undefined) return ''; if (ms <= 0) return '已结束'; const totalMin = Math.floor(ms / 60000); const d = Math.floor(totalMin / 1440); const h = Math.floor((totalMin % 1440) / 60); const m = totalMin % 60; if (d > 0) return d + ' 天 ' + h + ' 小时'; return h + ' 小时 ' + pad2(m) + ' 分'; } // ==================== 网络层 ==================== async function fetchJson(url, opts) { const o = opts || {}; const timeout = o.timeout || 20000; const retries = o.retries === undefined ? 1 : o.retries; let lastErr = null; for (let attempt = 0; attempt <= retries; attempt++) { const ctrl = typeof AbortController === 'function' ? new AbortController() : null; const timer = ctrl ? setTimeout(function () { ctrl.abort(); }, timeout) : null; try { const res = await fetch(url, { credentials: 'include', signal: ctrl ? ctrl.signal : undefined, headers: { Accept: 'application/json, text/plain, */*' } }); if (timer) clearTimeout(timer); if (res.status === 401 || res.status === 403) { throw new Error('未授权(' + res.status + '):请先在 gog.com 登录'); } if (res.status === 429 || res.status >= 500) { throw new Error('接口暂时不可用(HTTP ' + res.status + ')'); } if (!res.ok) { throw new Error('HTTP ' + res.status + ' ' + url.replace(/^https?:\/\/[^/]+/, '')); } const text = await res.text(); return parseJson(text, url.replace(/^https?:\/\/[^/]+/, '')); } catch (e) { if (timer) clearTimeout(timer); lastErr = e; if (attempt < retries) await sleep(600 * (attempt + 1)); } } throw lastErr || new Error('请求失败'); } // ==================== 库存采集 ==================== function normalizePlatforms(raw) { const out = []; if (!raw) return out; if (Array.isArray(raw)) { for (const p of raw) { const s = String(p || '').toLowerCase(); if (s === 'windows') out.push('Windows'); else if (s === 'osx' || s === 'mac' || s === 'macos') out.push('macOS'); else if (s === 'linux') out.push('Linux'); } return out; } // account 接口给的是 {Windows:true, Mac:false, Linux:true} if (raw.Windows) out.push('Windows'); if (raw.Mac || raw.macOS || raw.OSX) out.push('macOS'); if (raw.Linux) out.push('Linux'); return out; } // account 接口的 releaseDate 是 unix 秒,catalog 是 "1999.06.01" function releaseYear(raw) { if (raw === null || raw === undefined || raw === '') return null; if (typeof raw === 'number') { if (raw <= 0) return null; const d = new Date(raw * 1000); const y = d.getUTCFullYear(); return y > 1970 && y < 2100 ? y : null; } const m = String(raw).match(/^(\d{4})/); if (!m) return null; const y = Number(m[1]); return y > 1970 && y < 2100 ? y : null; } function imgUrl(raw) { if (!raw) return ''; const s = String(raw); if (s.indexOf('//') === 0) return 'https:' + s; return s; } function normalizeProduct(p) { if (!p || !p.id) return null; const slug = p.slug || ''; const url = p.storeLink || (p.url ? (String(p.url).indexOf('http') === 0 ? p.url : SITE + p.url) : (slug ? SITE + '/game/' + slug : '')); const priceObj = p.price || {}; const baseMoney = priceObj.baseMoney || {}; const finalMoney = priceObj.finalMoney || {}; const ratingRaw = (p.reviewsRating !== undefined && p.reviewsRating !== null) ? p.reviewsRating : p.rating; const rating = (typeof ratingRaw === 'number' && ratingRaw > 0) ? Math.round(ratingRaw) / 10 : null; return { id: String(p.id), title: p.title || '未知商品', slug: slug, url: url, cover: imgUrl(p.coverHorizontal || p.coverVertical || p.image || ''), platforms: normalizePlatforms(p.operatingSystems || p.worksOn), genres: Array.isArray(p.genres) ? p.genres.map(function (g) { return g && (g.name || g.slug); }).filter(Boolean) : (p.category ? [String(p.category)] : []), tags: Array.isArray(p.tags) ? p.tags.map(function (t) { return (t && t.slug) || ''; }).filter(Boolean) : [], rating: rating, reviews: Number(p.reviewsCount || 0) || 0, releaseYear: releaseYear(p.releaseDate), price: (baseMoney.amount !== undefined || priceObj.baseAmount !== undefined) ? { base: Number(baseMoney.amount !== undefined ? baseMoney.amount : priceObj.baseAmount) || 0, final: Number(finalMoney.amount !== undefined ? finalMoney.amount : priceObj.finalAmount) || 0, currency: baseMoney.currency || finalMoney.currency || priceObj.currency || '' } : null, isGame: p.isGame !== false, isMovie: !!p.isMovie }; } function pickArray(json) { if (Array.isArray(json)) return json; if (json && Array.isArray(json.products)) return json.products; if (json && Array.isArray(json.items)) return json.items; return []; } // 登录态:/user/data/games 给 owned id 列表,再用 getFilteredProducts 分页取详情 async function collectOwnedLibrary(onLog) { const owned = await fetchJson(SITE + '/user/data/games', { retries: 0 }); const raw = Array.isArray(owned && owned.owned) ? owned.owned : []; // 接口历史上给过 id 数组,也可能给对象数组,两种都收 const ids = raw.map(function (x) { return (x && typeof x === 'object') ? x.id : x; }).filter(function (x) { return x !== null && x !== undefined && x !== ''; }); if (!ids.length) throw new Error('账号里没有已购商品(或接口结构变了)'); onLog('· 已购条目 ' + ids.length + ' 个,开始拉详情', 'ok'); const want = {}; for (const id of ids) want[String(id)] = true; const games = []; const seen = {}; let page = 1; let totalPages = 1; while (page <= Math.min(totalPages, LIBRARY_PAGE_MAX)) { const url = SITE + '/account/getFilteredProducts?mediaType=1&page=' + page + '&sortBy=title'; const json = await fetchJson(url); const products = pickArray(json); if (!products.length) break; totalPages = Number(json.totalPages || totalPages) || totalPages; for (const raw of products) { const g = normalizeProduct(raw); if (!g || seen[g.id]) continue; seen[g.id] = true; // 接口会混入 DLC/原声等,只保留已购 id 且是游戏的条目 if (!want[g.id]) continue; if (!g.isGame || g.isMovie) continue; games.push(g); } onLog(' · 第 ' + page + '/' + totalPages + ' 页 → 累计 ' + games.length + ' 款', ''); if (page >= totalPages) break; page += 1; await sleep(220); } if (!games.length) throw new Error('未解析到游戏条目(接口字段可能变了)'); return { games: games, ownedCount: ids.length }; } // 公开档案:解析 userId + 头像(匿名可用);游戏列表接口 GOG 已加登录墙,失败时明确报出来 async function collectPublicProfile(username, onLog) { const u = String(username || '').trim().replace(/^https?:\/\/[^/]+/, '').replace(/^\/+|\/+$/g, ''); const name = u.split('/').filter(Boolean).pop() || ''; if (!name) throw new Error('请填写 GOG 用户名或主页链接'); const info = await fetchJson(USERS_HOST + '/users/' + encodeURIComponent(name)); onLog('· 公开档案:' + (info.username || name) + '(id ' + info.id + ')', 'ok'); const json = await fetchJson(SITE + '/u/' + encodeURIComponent(name) + '/games/stats?sort=title&order=asc&page=1'); const list = pickArray(json).length ? pickArray(json) : (Array.isArray(json && json.games) ? json.games : []); if (!list.length) throw new Error('公开档案里没有公开的游戏列表(或该账号设为私密)'); const games = []; for (const raw of list) { const g = normalizeProduct(raw.game || raw); if (g) { // 公开档案带时长:单位分钟 const st = raw.stats || raw; g.playtimeMinutes = Number(st.playtime || st.playtimeMinutes || 0) || 0; games.push(g); } } return { games: games, ownedCount: games.length, account: info }; } // ==================== 免费雷达 ==================== function demoOf(product) { if (!product) return false; if (product.tags && product.tags.indexOf('demo') >= 0) return true; return /(^|[\s(:-])(demo|prologue|prequel|试玩|试玩版|序章|前传)([\s):-]|$)/i.test(product.title || ''); } function freeKey(item) { return String(item && item.id); } // 免费雷达扫描:按价格升序翻页,遇到整页最低价 > 0 就停(免费商品都在最前面) async function scanFreeCatalog(region, onLog) { const loc = LOCALES[region] || LOCALES.CN; const items = []; let page = 1; let stoppedEarly = false; while (page <= FREE_SCAN_MAX_PAGES) { const url = CATALOG_HOST + '/v1/catalog?limit=' + CATALOG_PAGE + '&page=' + page + '&order=asc:price&productType=in:game' + '&countryCode=' + loc.countryCode + '¤cyCode=' + loc.currencyCode + '&locale=' + loc.locale; const json = await fetchJson(url); const products = pickArray(json); if (!products.length) break; let freeOnPage = 0; for (const raw of products) { const g = normalizeProduct(raw); if (!g) continue; const base = g.price ? g.price.base : 0; if (base > 0) continue; freeOnPage += 1; items.push({ id: g.id, title: g.title, cover: g.cover, url: g.url, slug: g.slug, rating: g.rating, reviews: g.reviews, platforms: g.platforms, genres: g.genres, isDemo: demoOf({ title: g.title, tags: g.tags }), currency: g.price ? g.price.currency : loc.currencyCode }); } onLog('· 第 ' + page + ' 页:0 元商品 ' + freeOnPage + ' 个', freeOnPage ? 'ok' : ''); if (freeOnPage === 0) { stoppedEarly = true; break; } const totalPages = Number(json.pages || 0) || 0; if (totalPages && page >= totalPages) break; page += 1; await sleep(260); } return { items: items, stoppedEarly: stoppedEarly, region: region, at: Date.now() }; } // 账本合并:记录首次发现、已领标记;本次没出现的保留(靠 lastSeenAt 与本次扫描时间比对判断是否仍在免费) function mergeFreeLedger(ledger, scan, now) { const at = now || Date.now(); const out = {}; const base = (ledger && ledger.items) ? ledger.items : {}; for (const k of Object.keys(base)) { out[k] = Object.assign({}, base[k]); } const items = (scan && scan.items) || []; const newIds = []; for (const it of items) { const k = freeKey(it); const prev = out[k]; if (!prev) newIds.push(k); out[k] = { key: k, id: it.id, title: it.title, cover: it.cover || '', url: it.url || '', rating: it.rating === undefined ? null : it.rating, reviews: it.reviews || 0, platforms: it.platforms || [], genres: it.genres || [], isDemo: !!it.isDemo, currency: it.currency || '', firstSeenAt: prev && prev.firstSeenAt ? prev.firstSeenAt : at, lastSeenAt: at, claimedAt: prev && prev.claimedAt ? prev.claimedAt : null }; } // 裁剪:先淘汰已领且很久没见的 const keys = Object.keys(out); if (keys.length > LEDGER_MAX) { keys.sort(function (a, b) { const ia = out[a]; const ib = out[b]; const ca = ia.claimedAt ? 1 : 0; const cb = ib.claimedAt ? 1 : 0; if (ca !== cb) return cb - ca; return (ia.lastSeenAt || 0) - (ib.lastSeenAt || 0); }); keys.slice(LEDGER_MAX).forEach(function (k) { delete out[k]; }); } return { version: 1, items: out, newIds: newIds }; } // 「免费中」= 出现在最近一次扫描的 id 集合里(不靠时间戳相等,避免 ms 抖动造成全变「已结束」) function analyzeFree(ledger, scanIds) { const activeMap = {}; for (const id of (scanIds || [])) activeMap[String(id)] = true; const all = Object.keys((ledger && ledger.items) || {}).map(function (k) { return ledger.items[k]; }); const rows = all.map(function (it) { const active = !!activeMap[String(it.id)]; return { key: it.key, id: it.id, title: it.title, cover: it.cover || '', url: it.url || '', rating: it.rating, reviews: it.reviews || 0, platforms: it.platforms || [], genres: it.genres || [], isDemo: !!it.isDemo, currency: it.currency || '', firstSeenAt: it.firstSeenAt || null, lastSeenAt: it.lastSeenAt || null, fresh: active && it.firstSeenAt === it.lastSeenAt, claimed: !!it.claimedAt, claimedAt: it.claimedAt || null, status: active ? 'active' : 'ended' }; }); rows.sort(function (a, b) { const rank = { active: 0, ended: 1 }; if (rank[a.status] !== rank[b.status]) return rank[a.status] - rank[b.status]; if (a.isDemo !== b.isDemo) return a.isDemo ? 1 : -1; const ra = a.rating === null ? -1 : a.rating; const rb = b.rating === null ? -1 : b.rating; if (ra !== rb) return rb - ra; return String(a.title).localeCompare(String(b.title), 'zh-Hans'); }); const byGenre = {}; for (const r of rows) { if (r.status !== 'active') continue; const gs = r.genres.length ? r.genres : ['未标注']; for (const g of gs) byGenre[g] = (byGenre[g] || 0) + 1; } const genres = Object.keys(byGenre).map(function (k) { return { key: k, count: byGenre[k] }; }) .sort(function (a, b) { return b.count - a.count || (a.key < b.key ? -1 : 1); }); const active = rows.filter(function (r) { return r.status === 'active'; }); const claimed = rows.filter(function (r) { return r.claimed; }); return { rows: rows, genres: genres, totals: { tracked: rows.length, active: active.length, ended: rows.length - active.length, demos: active.filter(function (r) { return r.isDemo; }).length, fresh: active.filter(function (r) { return r.fresh; }).length, claimed: claimed.length, unclaimed: active.filter(function (r) { return !r.claimed; }).length } }; } // ==================== 聚合分析 ==================== function countBy(list, keyFn) { const map = {}; for (const item of list) { const keys = keyFn(item); const arr = Array.isArray(keys) ? keys : [keys]; for (const k of arr) { const key = (k === null || k === undefined || k === '') ? '未标注' : String(k); map[key] = (map[key] || 0) + 1; } } return Object.keys(map).map(function (k) { return { key: k, count: map[k] }; }) .sort(function (a, b) { if (b.count !== a.count) return b.count - a.count; return a.key < b.key ? -1 : (a.key > b.key ? 1 : 0); }); } function buildTimeline(games) { const years = {}; let min = null; let max = null; let undated = 0; for (const g of games) { const y = g.releaseYear; if (!y) { undated += 1; continue; } years[y] = (years[y] || 0) + 1; if (min === null || y < min) min = y; if (max === null || y > max) max = y; } const byYear = []; if (min !== null) { for (let y = min; y <= max; y++) byYear.push({ key: String(y), count: years[y] || 0 }); } const decades = {}; for (const y of Object.keys(years)) { const d = Math.floor(Number(y) / 10) * 10; decades[d + 's'] = (decades[d + 's'] || 0) + years[y]; } const byDecade = Object.keys(decades).map(function (k) { return { key: k, count: decades[k] }; }) .sort(function (a, b) { return a.key < b.key ? -1 : 1; }); const peak = byYear.slice().sort(function (a, b) { return b.count - a.count || (a.key < b.key ? -1 : 1); })[0] || null; const spanYears = (min !== null) ? (max - min + 1) : 0; return { firstYear: min, lastYear: max, spanYears: spanYears, undated: undated, byYear: byYear, byDecade: byDecade, peakYear: peak && peak.count ? peak : null, avgPerYear: spanYears ? Math.round((games.length - undated) / spanYears * 10) / 10 : 0 }; } const RATING_BUCKETS = [ { key: '4.5 以上' }, { key: '4.0 – 4.4' }, { key: '3.5 – 3.9' }, { key: '3.5 以下' }, { key: '暂无评分' } ]; function ratingBucket(rating) { if (rating === null || rating === undefined) return '暂无评分'; if (rating >= 4.5) return '4.5 以上'; if (rating >= 4.0) return '4.0 – 4.4'; if (rating >= 3.5) return '3.5 – 3.9'; return '3.5 以下'; } function findDuplicateTitles(games) { const map = {}; for (const g of games) { const key = String(g.title || '').trim().toLowerCase(); if (!key) continue; if (!map[key]) map[key] = []; map[key].push(g.id); } return Object.keys(map).filter(function (k) { return map[k].length > 1; }) .map(function (k) { return { name: games.filter(function (g) { return String(g.title || '').trim().toLowerCase() === k; })[0].title, count: map[k].length, ids: map[k] }; }) .sort(function (a, b) { return b.count - a.count; }); } function analyzeLibrary(games) { const list = (games || []).filter(Boolean); const timeline = buildTimeline(list); const rated = list.filter(function (g) { return typeof g.rating === 'number'; }); const avgRating = rated.length ? Math.round(rated.reduce(function (s, g) { return s + g.rating; }, 0) / rated.length * 100) / 100 : null; // 平台是多值字段:分别按「任意平台」和「平台组合」两种口径统计 const platformFlat = list.map(function (g) { return (g.platforms && g.platforms.length) ? g.platforms : ['未标注']; }); const platforms = countBy(platformFlat.map(function (ps) { return { ps: ps }; }), function (x) { return x.ps; }); const platformCombos = countBy(list, function (g) { const ps = (g.platforms || []).slice().sort(); return ps.length ? ps.join(' + ') : '未标注'; }); const genres = countBy(list, function (g) { return (g.genres && g.genres.length) ? g.genres : ['未标注']; }); const ratings = RATING_BUCKETS.map(function (b) { return { key: b.key, count: list.filter(function (g) { return ratingBucket(g.rating) === b.key; }).length }; }); const shelfValue = list.reduce(function (s, g) { return s + ((g.price && typeof g.price.base === 'number') ? g.price.base : 0); }, 0); const currency = (list.find(function (g) { return g.price && g.price.currency; }) || { price: {} }).price.currency || ''; const playable = list.filter(function (g) { return Number(g.playtimeMinutes) > 0; }); const totalPlaytime = playable.reduce(function (s, g) { return s + Number(g.playtimeMinutes); }, 0); const topRated = rated.slice() .sort(function (a, b) { if (b.rating !== a.rating) return b.rating - a.rating; return (b.reviews || 0) - (a.reviews || 0); }) .slice(0, 10) .map(function (g) { return { id: g.id, title: g.title, rating: g.rating, reviews: g.reviews || 0 }; }); const missing = { cover: list.filter(function (g) { return !g.cover; }).length, platforms: list.filter(function (g) { return !g.platforms || !g.platforms.length; }).length, genres: list.filter(function (g) { return !g.genres || !g.genres.length; }).length, releaseYear: timeline.undated, rating: list.length - rated.length }; return { totals: { games: list.length, rated: rated.length, avgRating: avgRating, reviewSum: list.reduce(function (s, g) { return s + (Number(g.reviews) || 0); }, 0), playtimeGames: playable.length, totalPlaytimeHours: Math.round(totalPlaytime / 60), shelfValue: Math.round(shelfValue * 100) / 100, currency: currency, resolutionRate: list.length ? Math.round((list.length - missing.cover) / list.length * 1000) / 10 : 0 }, timeline: timeline, platforms: platforms, platformCombos: platformCombos, genres: genres, ratings: ratings, topRated: topRated, duplicates: findDuplicateTitles(list), missing: missing }; } // ==================== 快照与差异 ==================== function makeSnapshot(result) { const items = {}; for (const g of (result && result.games) || []) items[g.id] = g.title; return { at: (result && result.generatedAt) || new Date().toISOString(), gameCount: Object.keys(items).length, items: items }; } function diffSnapshots(prev, cur) { if (!prev || !prev.items || !cur || !cur.items) return null; const added = []; const removed = []; for (const id of Object.keys(cur.items)) { if (!prev.items[id]) added.push({ id: id, name: cur.items[id] }); } for (const id of Object.keys(prev.items)) { if (!cur.items[id]) removed.push({ id: id, name: prev.items[id] }); } added.sort(function (a, b) { return String(a.name).localeCompare(String(b.name), 'zh-Hans'); }); removed.sort(function (a, b) { return String(a.name).localeCompare(String(b.name), 'zh-Hans'); }); return { prevAt: prev.at, curAt: cur.at, prevCount: Object.keys(prev.items).length, curCount: Object.keys(cur.items).length, added: added, removed: removed }; } function loadSnapshots() { const list = getStored(SNAPSHOT_KEY, []); return Array.isArray(list) ? list : []; } function pushSnapshot(snap) { const list = loadSnapshots(); list.push(snap); while (list.length > SNAPSHOT_MAX) list.shift(); setStored(SNAPSHOT_KEY, list); } // ==================== 导出(纯函数) ==================== function csvCell(value) { const s = (value === null || value === undefined) ? '' : String(value); return '"' + s.replace(/"/g, '""') + '"'; } function escapeXml(text) { return String(text === null || text === undefined ? '' : text) .replace(/&/g, '&').replace(//g, '>') .replace(/"/g, '"'); } function buildYearChartSvg(byYear) { if (!byYear || !byYear.length) return ''; const W = 340; const H = 118; const padL = 6; const padR = 6; const padB = 16; const padT = 8; const n = byYear.length; const gap = n > 10 ? 2 : 4; const bw = Math.max(3, (W - padL - padR - gap * (n - 1)) / n); const max = byYear.reduce(function (m, d) { return Math.max(m, d.count); }, 1); const plotH = H - padT - padB; const parts = [''); return parts.join(''); } function toCsv(head, rows) { const lines = [head.map(csvCell).join(',')]; for (const row of rows) lines.push(row.map(csvCell).join(',')); return '\uFEFF' + lines.join('\r\n') + '\r\n'; } function buildCsv(result) { const head = ['游戏名', 'GOG ID', 'Slug', '平台', '类型', '评分', '评价数', '发行年份', '当前原价', '币种', '封面', '链接']; const rows = ((result && result.games) || []).map(function (g) { return [ g.title, g.id, g.slug, (g.platforms || []).join(' / '), (g.genres || []).join(' / '), typeof g.rating === 'number' ? g.rating.toFixed(1) : '', g.reviews || 0, g.releaseYear || '', g.price ? g.price.base : '', g.price ? g.price.currency : '', g.cover, g.url ]; }); return toCsv(head, rows); } function buildSummaryCsv(result) { const a = (result && result.analysis) || analyzeLibrary((result && result.games) || []); const rows = []; const push = function (group, key, count, extra) { rows.push([group, key, count, extra || '']); }; push('总量', '游戏数', a.totals.games); push('总量', '有评分', a.totals.rated); push('总量', '平均评分', a.totals.avgRating === null ? '' : a.totals.avgRating); push('总量', '评价总数', a.totals.reviewSum); push('总量', '库面值', a.totals.shelfValue, a.totals.currency); push('总量', '总时长(小时)', a.totals.totalPlaytimeHours); for (const d of a.timeline.byDecade) push('年代', d.key, d.count); for (const d of a.platforms) push('平台', d.key, d.count); for (const d of a.genres) push('类型', d.key, d.count); for (const d of a.ratings) push('评分档', d.key, d.count); return toCsv(['维度', '取值', '数量', '备注'], rows); } function buildFreeCsv(analysis) { const head = ['游戏', '状态', '类型', '领取状态', '评分', '评价数', '平台', '首次发现', '最近出现', '已领时间', '链接']; const rows = ((analysis && analysis.rows) || []).map(function (r) { return [ r.title, r.status === 'active' ? '免费中' : '已结束', r.isDemo ? '试玩/序章' : '正式版', r.claimed ? '已领' : '未领', typeof r.rating === 'number' ? r.rating.toFixed(1) : '', r.reviews || 0, (r.platforms || []).join(' / '), r.firstSeenAt ? new Date(r.firstSeenAt).toISOString().slice(0, 10) : '', r.lastSeenAt ? new Date(r.lastSeenAt).toISOString().slice(0, 10) : '', r.claimedAt ? new Date(r.claimedAt).toISOString().slice(0, 10) : '', r.url ]; }); return toCsv(head, rows); } function buildFreeMarkdown(analysis) { if (!analysis || !analysis.rows.length) return '## 免费领取\n\n还没有雷达记录,先在「免费」页签扫一次。\n'; const t = analysis.totals; const lines = []; lines.push('## 免费领取'); lines.push(''); lines.push('| 指标 | 值 |'); lines.push('| --- | --- |'); lines.push('| 记录条目 | ' + t.tracked + ' |'); lines.push('| 当前 0 元 | ' + t.active + ' |'); lines.push('| 其中试玩/序章 | ' + t.demos + ' |'); lines.push('| 已标记领取 | ' + t.claimed + ' |'); lines.push('| 本次新增 | ' + t.fresh + ' |'); lines.push(''); const active = analysis.rows.filter(function (r) { return r.status === 'active'; }).slice(0, 40); if (active.length) { lines.push('| 游戏 | 类型 | 评分 | 首次发现 | 已领 |'); lines.push('| --- | --- | --- | --- | --- |'); for (const r of active) { lines.push('| ' + String(r.title).replace(/\|/g, '\\|') + ' | ' + (r.isDemo ? '试玩' : '正式') + ' | ' + (typeof r.rating === 'number' ? r.rating.toFixed(1) : '—') + ' | ' + (r.firstSeenAt ? new Date(r.firstSeenAt).toISOString().slice(0, 10) : '—') + ' | ' + (r.claimed ? '是' : '否') + ' |'); } lines.push(''); } if (analysis.genres.length) { lines.push('类型分布:' + analysis.genres.slice(0, 8).map(function (d) { return d.key + ' ' + d.count; }).join(' / ')); lines.push(''); } return lines.join('\n'); } function buildReport(result, diff, freeAnalysis) { const a = (result && result.analysis) || analyzeLibrary((result && result.games) || []); const acc = (result && result.account) || {}; const lines = []; lines.push('# GOG 库存分析报告'); lines.push(''); lines.push('- 账号:' + (acc.username || acc.name || 'GOG 用户')); lines.push('- 生成时间:' + ((result && result.generatedAt) || new Date().toISOString())); lines.push('- 数据源:' + ((result && result.summary && result.summary.source) || 'gog.com 登录态库存接口')); lines.push('- 口径:GOG 账户已购条目(按商品 id 去重,剔除 DLC/原声等非游戏条目)'); lines.push(''); lines.push('## 概览'); lines.push(''); lines.push('| 指标 | 数值 |'); lines.push('| --- | --- |'); lines.push('| 游戏数 | ' + a.totals.games + ' |'); lines.push('| 有评分 | ' + a.totals.rated + ' |'); lines.push('| 平均评分 | ' + (a.totals.avgRating === null ? '—' : a.totals.avgRating + ' / 5') + ' |'); lines.push('| 评价总数 | ' + a.totals.reviewSum + ' |'); lines.push('| 库面值(按当前原价) | ' + fmtMoney(a.totals.shelfValue, a.totals.currency) + ' |'); lines.push('| 发行年份跨度 | ' + (a.timeline.firstYear ? a.timeline.firstYear + ' – ' + a.timeline.lastYear : '—') + ' |'); lines.push('| 峰值年 | ' + (a.timeline.peakYear ? a.timeline.peakYear.key + ' 年(' + a.timeline.peakYear.count + ' 款)' : '—') + ' |'); if (a.totals.totalPlaytimeHours) { lines.push('| 总时长 | ' + a.totals.totalPlaytimeHours + ' 小时(' + a.totals.playtimeGames + ' 款有记录) |'); } lines.push(''); lines.push('## 发行年代分布'); lines.push(''); lines.push('| 年代 | 数量 |'); lines.push('| --- | --- |'); for (const d of a.timeline.byDecade) lines.push('| ' + d.key + ' | ' + d.count + ' |'); if (!a.timeline.byDecade.length) lines.push('| (无数据) | 0 |'); lines.push(''); lines.push('## 平台分布'); lines.push(''); lines.push('| 平台 | 数量 |'); lines.push('| --- | --- |'); for (const d of a.platforms) lines.push('| ' + d.key + ' | ' + d.count + ' |'); lines.push(''); lines.push('## 类型分布(前 20)'); lines.push(''); lines.push('| 类型 | 数量 |'); lines.push('| --- | --- |'); for (const d of a.genres.slice(0, 20)) lines.push('| ' + d.key + ' | ' + d.count + ' |'); lines.push(''); lines.push('## 评分分布'); lines.push(''); lines.push('| 区间 | 数量 |'); lines.push('| --- | --- |'); for (const d of a.ratings) lines.push('| ' + d.key + ' | ' + d.count + ' |'); lines.push(''); if (a.topRated.length) { lines.push('## 评分 Top 10'); lines.push(''); lines.push('| 游戏 | 评分 | 评价数 |'); lines.push('| --- | --- | --- |'); for (const g of a.topRated) { lines.push('| ' + String(g.title).replace(/\|/g, '\\|') + ' | ' + g.rating.toFixed(1) + ' | ' + g.reviews + ' |'); } lines.push(''); } if (a.duplicates.length) { lines.push('## 同名条目'); lines.push(''); lines.push('| 游戏 | 条目数 |'); lines.push('| --- | --- |'); for (const d of a.duplicates.slice(0, 20)) lines.push('| ' + String(d.name).replace(/\|/g, '\\|') + ' | ' + d.count + ' |'); lines.push(''); } if (diff) { lines.push('## 与上次导出对比'); lines.push(''); lines.push('- 上次:' + fmtIsoDay(diff.prevAt) + '(' + diff.prevCount + ' 款)'); lines.push('- 本次:' + fmtIsoDay(diff.curAt) + '(' + diff.curCount + ' 款)'); lines.push('- 新增 ' + diff.added.length + ' 款' + (diff.added.length ? ':' + diff.added.map(function (x) { return x.name; }).join('、') : '')); lines.push('- 移除 ' + diff.removed.length + ' 款' + (diff.removed.length ? ':' + diff.removed.map(function (x) { return x.name; }).join('、') : '')); lines.push(''); } if (freeAnalysis && freeAnalysis.rows && freeAnalysis.rows.length) { lines.push(buildFreeMarkdown(freeAnalysis)); } lines.push('> 数据由 GOG 平台增强脚本在本机生成,未上传任何服务器。'); return lines.join('\n'); } function buildDigest(result, diff, freeAnalysis) { const a = (result && result.analysis) || analyzeLibrary((result && result.games) || []); const parts = []; parts.push('GOG 库存:' + a.totals.games + ' 款'); if (a.totals.currency) parts.push('面值 ' + fmtMoney(a.totals.shelfValue, a.totals.currency)); if (a.totals.avgRating !== null) parts.push('均分 ' + a.totals.avgRating); if (a.timeline.firstYear) parts.push('发行跨度 ' + a.timeline.firstYear + '–' + a.timeline.lastYear); if (a.platforms.length) parts.push('平台 ' + a.platforms.slice(0, 3).map(function (d) { return d.key + ' ' + d.count; }).join(' / ')); if (diff) parts.push('较上次 +' + diff.added.length + ' / -' + diff.removed.length); if (freeAnalysis && freeAnalysis.totals && freeAnalysis.totals.tracked) { parts.push('免费 0 元 ' + freeAnalysis.totals.active + ' / 新增 ' + freeAnalysis.totals.fresh); } return parts.join('|'); } // ==================== 界面 ==================== const ui = (function () { let shadow = null; const refs = {}; let currentTab = 'free'; function mount() { const host = document.createElement('div'); host.id = 'gpe-root'; host.style.cssText = 'position:fixed;inset:auto 0 0 auto;width:0;height:0;z-index:2147483647;'; const root = host.attachShadow({ mode: 'open' }); root.innerHTML = `