// ==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 = ['']; parts.push(''); for (let i = 0; i < n; i++) { const d = byYear[i]; const h = d.count ? Math.max(2, Math.round(d.count / max * plotH)) : 0; const x = padL + i * (bw + gap); const y = H - padB - h; if (h) { parts.push(''); parts.push('' + d.count + ''); } if (n <= 8 || i % 2 === 0 || i === n - 1) { parts.push('' + escapeXml(d.key) + ''); } } parts.push('' + '' + ''); parts.push(''); 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 = ` `; (document.body || document.documentElement).appendChild(host); shadow = root; refs.panel = root.getElementById('panel'); refs.fab = root.getElementById('fab'); refs.badge = root.getElementById('badge'); refs.radarStatus = root.getElementById('radarStatus'); refs.radarKpis = root.getElementById('radarKpis'); refs.radarChips = root.getElementById('radarChips'); refs.radarList = root.getElementById('radarList'); refs.btnScan = root.getElementById('btnScan'); refs.btnRadarCsv = root.getElementById('btnRadarCsv'); refs.btnRadarCopy = root.getElementById('btnRadarCopy'); refs.anaState = root.getElementById('anaState'); refs.anaKpis = root.getElementById('anaKpis'); refs.anaYears = root.getElementById('anaYears'); refs.anaPlatforms = root.getElementById('anaPlatforms'); refs.anaGenres = root.getElementById('anaGenres'); refs.anaRatings = root.getElementById('anaRatings'); refs.anaAudit = root.getElementById('anaAudit'); refs.anaDiff = root.getElementById('anaDiff'); refs.anaDiffTitle = root.getElementById('anaDiffTitle'); refs.btnAnaFetch = root.getElementById('btnAnaFetch'); refs.expState = root.getElementById('expState'); refs.expElapsed = root.getElementById('expElapsed'); refs.expBar = root.getElementById('expBar'); refs.expLog = root.getElementById('expLog'); refs.expAccount = root.getElementById('expAccount'); refs.expStats = root.getElementById('expStats'); refs.btnFetch = root.getElementById('btnFetch'); refs.btnJson = root.getElementById('btnJson'); refs.btnCsv = root.getElementById('btnCsv'); refs.btnMd = root.getElementById('btnMd'); refs.btnSum = root.getElementById('btnSum'); refs.btnDigest = root.getElementById('btnDigest'); refs.setRegion = root.getElementById('setRegion'); refs.setDemos = root.getElementById('setDemos'); refs.setAuto = root.getElementById('setAuto'); refs.setToast = root.getElementById('setToast'); refs.setUser = root.getElementById('setUser'); refs.btnProfile = root.getElementById('btnProfile'); refs.toasts = root.getElementById('toasts'); root.getElementById('ver').textContent = 'GOG 助手 v' + VERSION; root.getElementById('close').addEventListener('click', function () { close(); }); refs.fab.addEventListener('click', function () { toggle(); }); root.querySelectorAll('.tab').forEach(function (btn) { btn.addEventListener('click', function () { switchTab(btn.dataset.tab); }); }); refs.btnScan.addEventListener('click', function () { runRadar(false); }); refs.btnRadarCsv.addEventListener('click', function () { exportRadarCsv(); }); refs.btnRadarCopy.addEventListener('click', function () { copyRadar(); }); refs.btnFetch.addEventListener('click', function () { runExport(); }); refs.btnAnaFetch.addEventListener('click', function () { runExport(); }); refs.btnJson.addEventListener('click', function () { exportJson(); }); refs.btnCsv.addEventListener('click', function () { exportCsv(); }); refs.btnMd.addEventListener('click', function () { exportReport(); }); refs.btnSum.addEventListener('click', function () { exportSummaryCsv(); }); refs.btnDigest.addEventListener('click', function () { copyDigest(); }); refs.setRegion.addEventListener('change', function () { updateCfg('region', refs.setRegion.value); }); refs.setDemos.addEventListener('change', function () { updateCfg('includeDemos', refs.setDemos.checked); }); refs.setAuto.addEventListener('change', function () { updateCfg('autoRadar', refs.setAuto.checked); }); refs.setToast.addEventListener('change', function () { updateCfg('toast', refs.setToast.checked); }); refs.btnProfile.addEventListener('click', function () { runProfileImport(); }); document.addEventListener('keydown', function (e) { if (e.altKey && (e.key === 'g' || e.key === 'G')) { e.preventDefault(); toggle(); } }); } function open(tab) { if (!refs.panel) return; refs.panel.hidden = false; if (tab) switchTab(tab); } function close() { if (refs.panel) refs.panel.hidden = true; } function toggle() { if (!refs.panel) return; if (refs.panel.hidden) open(currentTab); else close(); } function switchTab(tab) { currentTab = tab || 'free'; if (!shadow) return; shadow.querySelectorAll('.tab').forEach(function (btn) { btn.classList.toggle('on', btn.dataset.tab === currentTab); }); shadow.querySelectorAll('.view').forEach(function (view) { view.hidden = view.dataset.view !== currentTab; }); if (currentTab === 'free') renderRadar(); if (currentTab === 'overview') renderAnalysis(state.library, state.diff); if (currentTab === 'settings') renderSettings(); } function renderSettings() { if (!refs.setRegion) return; refs.setRegion.value = CFG.region; refs.setDemos.checked = !!CFG.includeDemos; refs.setAuto.checked = !!CFG.autoRadar; refs.setToast.checked = !!CFG.toast; } function toast(msg, kind) { if (!refs.toasts) return; const el = document.createElement('div'); el.className = 'toast ' + (kind || ''); el.textContent = msg; refs.toasts.appendChild(el); setTimeout(function () { el.classList.add('out'); setTimeout(function () { if (el.parentNode) el.parentNode.removeChild(el); }, 300); }, 3200); } function badge(n) { if (!refs.badge) return; refs.badge.textContent = n > 99 ? '99+' : String(n); refs.badge.classList.toggle('show', n > 0); } function log(text, kind) { if (!refs.expLog) return; const line = document.createElement('div'); if (kind) line.className = kind; line.textContent = text; refs.expLog.appendChild(line); refs.expLog.scrollTop = refs.expLog.scrollHeight; } function progress(pct, text) { if (refs.expBar) refs.expBar.style.width = Math.max(0, Math.min(100, pct)) + '%'; if (text && refs.expState) refs.expState.textContent = text; } function clearLog() { if (refs.expLog) refs.expLog.textContent = ''; } // 公开档案(实验):GOG 现在对 /u//games/stats 加了登录要求,失败就如实报错 async function runProfileImport() { if (!refs.btnProfile) return; const name = (refs.setUser.value || '').trim(); if (!name) { toast('先填 GOG 用户名或主页链接', 'err'); return; } refs.btnProfile.disabled = true; refs.btnProfile.textContent = '读取中…'; try { const res = await collectPublicProfile(name, function (text, kind) { console.log(LOG_PREFIX, text, kind || ''); }); const games = res.games.slice().sort(function (a, b) { return String(a.title).localeCompare(String(b.title), 'zh-Hans'); }); const result = { schema: 'gog-library.v1', generatedAt: new Date().toISOString(), account: { username: name }, summary: { source: '公开档案 /u//games/stats', gameCount: games.length }, games: games }; result.analysis = analyzeLibrary(games); state.library = result; state.diff = null; setExportBusy(false); toast('公开档案读取成功:' + games.length + ' 款', 'ok'); switchTab('overview'); } catch (e) { toast('公开档案不可用:' + ((e && e.message) || e), 'err'); } finally { refs.btnProfile.disabled = false; refs.btnProfile.textContent = '读取公开档案'; } } function setExportBusy(on) { if (!refs.btnFetch) return; refs.btnFetch.disabled = !!on; refs.btnFetch.textContent = on ? '读取中…' : '读取库存'; const has = !!(state.library && state.library.games && state.library.games.length); refs.btnJson.disabled = !!on || !has; refs.btnCsv.disabled = !!on || !has; refs.btnMd.disabled = !!on || !has; refs.btnSum.disabled = !!on || !has; refs.btnDigest.disabled = !!on || !has; } function empty(text) { const el = document.createElement('div'); el.className = 'empty'; el.textContent = text; return el; } function kpi(container, items) { if (!container) return; container.textContent = ''; for (const it of items) { const box = document.createElement('div'); box.className = 'kpi'; const b = document.createElement('b'); b.textContent = it.value; const s = document.createElement('span'); s.textContent = it.label; box.appendChild(b); box.appendChild(s); container.appendChild(box); } } function hbars(container, data, limit, suffix) { if (!container) return; container.textContent = ''; const rows = (data || []).slice(0, limit || 8); if (!rows.length) { container.appendChild(empty('还没有数据')); return; } const max = rows.reduce(function (m, d) { return Math.max(m, d.count); }, 1); const total = rows.reduce(function (s, d) { return s + d.count; }, 0) || 1; for (const d of rows) { const row = document.createElement('div'); row.className = 'hbar'; const lb = document.createElement('span'); lb.className = 'lb'; lb.textContent = d.key; lb.title = d.key; const tr = document.createElement('span'); tr.className = 'tr'; const fl = document.createElement('span'); fl.className = 'fl'; fl.style.width = Math.max(2, d.count / max * 100) + '%'; tr.appendChild(fl); const vl = document.createElement('span'); vl.className = 'vl'; vl.textContent = d.count + (suffix === false ? '' : ' · ' + Math.round(d.count / total * 100) + '%'); row.appendChild(lb); row.appendChild(tr); row.appendChild(vl); container.appendChild(row); } } // ---- 免费雷达 ---- function renderRadar() { if (!refs.radarList) return; const analysis = state.radarAnalysis || analyzeFree(state.ledger, state.radar ? state.radar.ids : null); state.radarAnalysis = analysis; const t = analysis.totals; badge(t.unclaimed); refs.btnScan.disabled = state.radarBusy; refs.btnScan.textContent = state.radarBusy ? '扫描中…' : '扫描'; if (state.radarBusy) refs.radarStatus.textContent = '正在扫描免费商品…'; else if (!state.radar || !state.radar.at) refs.radarStatus.textContent = '尚未扫描'; else { let text = fmtAgo(state.radar.at) + '扫描 · 当前 0 元 ' + t.active + ' 个'; if (t.fresh) text += ' · 新增 ' + t.fresh; if (!state.radar.stoppedEarly) text += ' · 已达翻页上限'; refs.radarStatus.textContent = text; } kpi(refs.radarKpis, [ { label: '当前 0 元', value: String(t.active) }, { label: '本次新增', value: String(t.fresh) }, { label: '试玩/序章', value: String(t.demos) }, { label: '已标记领取', value: String(t.claimed) } ]); const chips = [ { key: 'all', text: '全部', n: analysis.rows.length }, { key: 'active', text: '免费中', n: t.active }, { key: 'new', text: '本次新增', n: t.fresh }, { key: 'full', text: '正式版', n: t.active - t.demos }, { key: 'claimed', text: '已领', n: t.claimed }, { key: 'ended', text: '已结束', n: t.ended } ]; if (refs.radarChips) { refs.radarChips.textContent = ''; for (const c of chips) { const b = document.createElement('button'); b.className = 'chip' + (state.radarFilter === c.key ? ' on' : ''); b.textContent = c.text + ' ' + c.n; b.disabled = c.n === 0 && c.key !== 'all'; b.addEventListener('click', function () { state.radarFilter = c.key; renderRadar(); }); refs.radarChips.appendChild(b); } } refs.btnRadarCsv.disabled = !analysis.rows.length; refs.btnRadarCopy.disabled = !analysis.rows.length; refs.radarList.textContent = ''; if (!analysis.rows.length) { refs.radarList.appendChild(empty(state.radarBusy ? '正在读取 GOG 免费商品…' : '还没有记录。点右上角「扫描」拉一次 0 元商品(约 10 秒)。')); return; } const rows = filterRadar(analysis, state.radarFilter || 'all'); if (!rows.length) { refs.radarList.appendChild(empty('这个筛选下没有条目。')); return; } const head = document.createElement('div'); head.className = 'sec'; head.textContent = chipLabel(state.radarFilter) + ' · ' + rows.length; refs.radarList.appendChild(head); for (const r of rows) refs.radarList.appendChild(radarCard(r)); } function chipLabel(key) { const map = { all: '全部记录', active: '免费中', new: '本次新增', full: '正式版', claimed: '已标记领取', ended: '已结束' }; return map[key] || '全部记录'; } function filterRadar(analysis, key) { const rows = (analysis && analysis.rows) || []; const demoOk = !!CFG.includeDemos; const base = demoOk ? rows : rows.filter(function (r) { return !r.isDemo || r.claimed; }); if (!key || key === 'all') return base; if (key === 'active') return base.filter(function (r) { return r.status === 'active'; }); if (key === 'new') return base.filter(function (r) { return r.fresh; }); if (key === 'full') return base.filter(function (r) { return r.status === 'active' && !r.isDemo; }); if (key === 'claimed') return base.filter(function (r) { return r.claimed; }); if (key === 'ended') return base.filter(function (r) { return r.status === 'ended'; }); return base; } function radarCard(r) { const item = document.createElement('div'); item.className = 'card' + (r.status === 'ended' ? ' dim' : ''); if (r.cover) { const img = document.createElement('img'); img.className = 'thumb'; img.src = r.cover; img.alt = ''; img.loading = 'lazy'; img.referrerPolicy = 'no-referrer'; img.addEventListener('error', function () { const ph = document.createElement('div'); ph.className = 'ph'; ph.textContent = (r.title || 'G').slice(0, 1).toUpperCase(); if (img.parentNode) img.parentNode.replaceChild(ph, img); }); item.appendChild(img); } else { const ph = document.createElement('div'); ph.className = 'ph'; ph.textContent = (r.title || 'G').slice(0, 1).toUpperCase(); item.appendChild(ph); } const meta = document.createElement('div'); meta.className = 'meta'; const name = document.createElement('div'); name.className = 'name'; name.textContent = r.title; name.title = r.title; meta.appendChild(name); const price = document.createElement('div'); price.className = 'price'; const free = document.createElement('span'); free.className = 'free'; free.textContent = r.status === 'active' ? '免费' : '已结束'; price.appendChild(free); if (r.isDemo) { const tag = document.createElement('span'); tag.className = 'tag mute'; tag.textContent = '试玩'; price.appendChild(tag); } if (r.fresh) { const tag = document.createElement('span'); tag.className = 'tag hot'; tag.textContent = '新'; price.appendChild(tag); } if (r.claimed) { const tag = document.createElement('span'); tag.className = 'tag ok'; tag.textContent = '已领'; price.appendChild(tag); } if (typeof r.rating === 'number') { const tag = document.createElement('span'); tag.className = 'tag warn'; tag.textContent = r.rating.toFixed(1) + ' 分'; price.appendChild(tag); } meta.appendChild(price); const sub = document.createElement('div'); sub.className = 'sub'; const bits = []; if (r.genres && r.genres.length) bits.push(r.genres.slice(0, 2).join(' / ')); if (r.platforms && r.platforms.length) bits.push(r.platforms.join(' / ')); if (r.firstSeenAt) bits.push('首次发现 ' + new Date(r.firstSeenAt).toISOString().slice(5, 10)); sub.textContent = bits.join(' · '); meta.appendChild(sub); item.appendChild(meta); const ops = document.createElement('div'); ops.className = 'ops'; const btn = document.createElement('button'); btn.className = 'claim' + (r.status === 'active' ? '' : ' alt'); btn.textContent = '打开'; btn.addEventListener('click', function () { openGame(r); }); ops.appendChild(btn); const mark = document.createElement('button'); mark.className = 'mark' + (r.claimed ? ' on' : ''); mark.textContent = r.claimed ? '✓ 已领' : '标记已领'; mark.title = r.claimed ? '点击取消标记' : '只记在本机账本,GOG 免费游戏需自己点「添加到库」'; mark.addEventListener('click', function () { toggleRadarClaimed(r.key); }); ops.appendChild(mark); item.appendChild(ops); return item; } function toggleRadarClaimed(key) { const item = state.ledger && state.ledger.items ? state.ledger.items[key] : null; if (!item) return; item.claimedAt = item.claimedAt ? null : Date.now(); setStored(LEDGER_KEY, state.ledger); state.radarAnalysis = analyzeFree(state.ledger, state.radar ? state.radar.ids : null); renderRadar(); } // ---- 概览 / 分析 ---- function renderAnalysis(result, diff) { if (!refs.anaKpis) return; if (!result || !result.games || !result.games.length) { refs.anaState.textContent = '尚无数据'; kpi(refs.anaKpis, [{ label: '游戏数', value: '—' }, { label: '库面值', value: '—' }, { label: '平均评分', value: '—' }, { label: '总时长', value: '—' }]); refs.anaYears.textContent = ''; hbars(refs.anaPlatforms, []); hbars(refs.anaGenres, []); hbars(refs.anaRatings, []); refs.anaAudit.textContent = '还没有读取库存。点右上角「读取库存」。'; refs.anaDiffTitle.hidden = true; refs.anaDiff.hidden = true; return; } const a = result.analysis || analyzeLibrary(result.games); refs.anaState.textContent = fmtAgo(Date.parse(result.generatedAt)) + '读取 · ' + a.totals.games + ' 款'; kpi(refs.anaKpis, [ { label: '游戏数', value: String(a.totals.games) }, { label: '库面值', value: fmtMoney(a.totals.shelfValue, a.totals.currency) }, { label: '平均评分', value: a.totals.avgRating === null ? '—' : String(a.totals.avgRating) }, { label: a.totals.totalPlaytimeHours ? '总时长' : '发行跨度', value: a.totals.totalPlaytimeHours ? a.totals.totalPlaytimeHours + ' 小时' : (a.timeline.firstYear ? a.timeline.firstYear + '–' + a.timeline.lastYear : '—') } ]); refs.anaYears.innerHTML = buildYearChartSvg(a.timeline.byYear) || '
还没有发行年份
'; hbars(refs.anaPlatforms, a.platforms, 8); hbars(refs.anaGenres, a.genres, 8); hbars(refs.anaRatings, a.ratings, 6); const audit = []; audit.push('平均评分 ' + (a.totals.avgRating === null ? '—' : a.totals.avgRating + ' / 5') + ' · 评价总数 ' + a.totals.reviewSum); audit.push('发行年份覆盖 ' + (a.timeline.firstYear ? a.timeline.firstYear + '–' + a.timeline.lastYear : '—') + (a.timeline.undated ? ' · 无年份 ' + a.timeline.undated + ' 款' : '')); if (a.timeline.peakYear) audit.push('峰值年 ' + a.timeline.peakYear.key + '(' + a.timeline.peakYear.count + ' 款)'); audit.push('缺平台标注 ' + a.missing.platforms + ' · 缺类型 ' + a.missing.genres + ' · 缺评分 ' + a.missing.rating + ' · 缺封面 ' + a.missing.cover); if (a.duplicates.length) audit.push('同名条目 ' + a.duplicates.length + ' 组'); if (a.topRated.length) { audit.push('最高分:' + a.topRated.slice(0, 3).map(function (g) { return g.title + ' ' + g.rating.toFixed(1); }).join('、')); } refs.anaAudit.textContent = audit.join('\n'); if (diff) { refs.anaDiffTitle.hidden = false; refs.anaDiff.hidden = false; refs.anaDiff.innerHTML = ''; const line1 = document.createElement('div'); line1.textContent = '上次 ' + fmtIsoDay(diff.prevAt) + '(' + diff.prevCount + ' 款)→ 本次 ' + fmtIsoDay(diff.curAt) + '(' + diff.curCount + ' 款)'; refs.anaDiff.appendChild(line1); const add = document.createElement('div'); add.className = 'add'; add.textContent = '新增 ' + diff.added.length + (diff.added.length ? ':' + diff.added.slice(0, 8).map(function (x) { return x.name; }).join('、') : ''); refs.anaDiff.appendChild(add); const del = document.createElement('div'); del.className = 'del'; del.textContent = '移除 ' + diff.removed.length + (diff.removed.length ? ':' + diff.removed.slice(0, 8).map(function (x) { return x.name; }).join('、') : ''); refs.anaDiff.appendChild(del); } else { refs.anaDiffTitle.hidden = true; refs.anaDiff.hidden = true; } } return { mount: mount, open: open, close: close, toggle: toggle, toast: toast, log: log, clearLog: clearLog, progress: progress, setExportBusy: setExportBusy, renderRadar: renderRadar, renderAnalysis: renderAnalysis, renderSettings: renderSettings, badge: badge }; })(); // ==================== 业务编排 ==================== function openGame(game) { try { window.open(game.url || (SITE + '/games'), '_blank', 'noopener'); } catch (e) { console.warn(LOG_PREFIX, '打开页面失败', e); } } async function copyText(text) { try { await navigator.clipboard.writeText(text); return true; } catch (e) { return false; } } function updateCfg(key, value) { CFG[key] = value; saveCfg(); if (key === 'includeDemos') { state.radarAnalysis = analyzeFree(state.ledger, state.radar ? state.radar.ids : null); ui.renderRadar(); } if (key === 'region') { state.radarAnalysis = analyzeFree(state.ledger, state.radar ? state.radar.ids : null); ui.renderRadar(); } } async function runRadar(silent) { if (state.radarBusy) return null; state.radarBusy = true; ui.renderRadar(); const at = Date.now(); try { const lines = []; const scan = await scanFreeCatalog(CFG.region, function (text, kind) { lines.push(text); console.log(LOG_PREFIX, text, kind || ''); }); // 账本按扫描结果合并,再计算 isNew / fresh const merged = mergeFreeLedger(state.ledger, scan, at); state.ledger = merged; setStored(LEDGER_KEY, state.ledger); const ids = scan.items.map(function (x) { return x.id; }); state.radar = { at: at, ids: ids, region: CFG.region, stoppedEarly: scan.stoppedEarly }; setStored(RADAR_KEY, state.radar); const analysis = analyzeFree(state.ledger, ids); state.radarAnalysis = analysis; if (!silent) { const msg = '扫描完成:0 元商品 ' + analysis.totals.active + ' 个' + (merged.newIds.length ? ',新增 ' + merged.newIds.length : ''); ui.toast(msg, 'ok'); } return analysis; } catch (e) { console.warn(LOG_PREFIX, '免费雷达扫描失败', e); if (!silent) ui.toast('扫描失败:' + ((e && e.message) || e), 'err'); return null; } finally { state.radarBusy = false; ui.renderRadar(); } } async function runExport() { if (state.running) return null; state.running = true; state.startedAt = Date.now(); ui.setExportBusy(true); ui.clearLog(); ui.progress(6, '读取库存…'); try { ui.log('→ 读取 GOG 已购游戏', 'ok'); const res = await collectOwnedLibrary(function (text, kind) { ui.log(text, kind); }); ui.progress(72, '聚合分析…'); const games = res.games.slice().sort(function (a, b) { return String(a.title).localeCompare(String(b.title), 'zh-Hans'); }); const result = { schema: 'gog-library.v1', generatedAt: new Date().toISOString(), account: { username: detectUsername() }, summary: { source: 'gog.com /user/data/games + /account/getFilteredProducts', ownedCount: res.ownedCount, gameCount: games.length }, games: games }; result.analysis = analyzeLibrary(games); const prev = loadSnapshots().slice(-1)[0] || null; const snap = makeSnapshot(result); state.diff = diffSnapshots(prev, snap); result.diff = state.diff; state.library = result; ui.progress(100, '完成'); const secs = ((Date.now() - state.startedAt) / 1000).toFixed(1); ui.log('✓ 完成:' + games.length + ' 款,库面值 ' + fmtMoney(result.analysis.totals.shelfValue, result.analysis.totals.currency) + ',' + secs + 's', 'ok'); if (CFG.toast) ui.toast('GOG 库存读取完成:' + games.length + ' 款', 'ok'); return result; } catch (e) { const msg = (e && e.message) || String(e); ui.log('✗ 失败:' + msg, 'err'); ui.progress(0, '失败'); if (CFG.toast) ui.toast('读取失败:' + msg, 'err'); return null; } finally { state.running = false; ui.setExportBusy(false); ui.renderAnalysis(state.library, state.diff); } } function detectUsername() { // GOG 页面把当前用户放在 localStorage 的 ngStorage-user 里 try { const raw = localStorage.getItem('ngStorage-user'); if (raw) { const u = JSON.parse(raw); if (u && u.username) return u.username; } } catch (e) { /* 忽略 */ } try { if (window.profilesData && window.profilesData.profileUser) { if (window.profilesData.profileUser.username) return window.profilesData.profileUser.username; if (window.profilesData.currentUser && window.profilesData.currentUser.username) { return window.profilesData.currentUser.username; } } } catch (e) { /* 忽略 */ } return 'GOG 用户'; } // ==================== 文件导出 ==================== function download(filename, text, mime) { const blob = new Blob([text], { type: mime || 'application/octet-stream' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.style.display = 'none'; document.body.appendChild(a); a.click(); setTimeout(function () { URL.revokeObjectURL(url); if (a.parentNode) a.parentNode.removeChild(a); }, 1200); } function baseName() { const who = (state.library && state.library.account && state.library.account.username) || 'gog'; const day = new Date().toISOString().slice(0, 10); const safe = String(who).replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 40); return 'gog-library-' + safe + '-' + day; } function exportJson() { if (!state.library) return; download(baseName() + '.json', JSON.stringify(state.library, null, 2), 'application/json;charset=utf-8'); pushSnapshot(makeSnapshot(state.library)); ui.toast('JSON 已导出', 'ok'); } function exportCsv() { if (!state.library) return; download(baseName() + '.csv', buildCsv(state.library), 'text/csv;charset=utf-8'); ui.toast('明细 CSV 已导出', 'ok'); } function exportSummaryCsv() { if (!state.library) return; download(baseName() + '-summary.csv', buildSummaryCsv(state.library), 'text/csv;charset=utf-8'); ui.toast('汇总 CSV 已导出', 'ok'); } function exportReport() { if (!state.library) return; const free = state.radarAnalysis || null; download(baseName() + '.md', buildReport(state.library, state.diff, free), 'text/markdown;charset=utf-8'); ui.toast('报告已导出', 'ok'); } async function copyDigest() { if (!state.library) return; const free = state.radarAnalysis || null; const ok = await copyText(buildDigest(state.library, state.diff, free)); ui.toast(ok ? '摘要已复制' : '复制失败,请手动选择文本', ok ? 'ok' : 'err'); } function exportRadarCsv() { const analysis = state.radarAnalysis || analyzeFree(state.ledger, state.radar ? state.radar.ids : null); if (!analysis.rows.length) { ui.toast('还没有雷达记录', 'err'); return; } download('gog-free-' + new Date().toISOString().slice(0, 10) + '.csv', buildFreeCsv(analysis), 'text/csv;charset=utf-8'); ui.toast('免费清单已导出(' + analysis.rows.length + ' 条)', 'ok'); } async function copyRadar() { const analysis = state.radarAnalysis || analyzeFree(state.ledger, state.radar ? state.radar.ids : null); const active = analysis.rows.filter(function (r) { return r.status === 'active'; }); if (!active.length) { ui.toast('当前没有 0 元商品', 'err'); return; } const lines = ['【GOG 免费 ' + active.length + ' 个】']; for (const r of active) { lines.push('· ' + r.title + (r.isDemo ? ' [试玩]' : '') + (r.claimed ? ' [已领]' : '') + ' ' + r.url); } const ok = await copyText(lines.join('\n')); ui.toast(ok ? '清单已复制' : '复制失败,请手动选择文本', ok ? 'ok' : 'err'); } // ==================== 调试/测试出口 ==================== window.__gogEnhancer = { version: VERSION, ui: ui, normalizeProduct: normalizeProduct, scanFreeCatalog: scanFreeCatalog, collectOwnedLibrary: collectOwnedLibrary, collectPublicProfile: collectPublicProfile, normalizePlatforms: normalizePlatforms, releaseYear: releaseYear, demoOf: demoOf, mergeFreeLedger: mergeFreeLedger, analyzeFree: analyzeFree, analyzeLibrary: analyzeLibrary, buildTimeline: buildTimeline, countBy: countBy, ratingBucket: ratingBucket, buildYearChartSvg: buildYearChartSvg, buildCsv: buildCsv, buildSummaryCsv: buildSummaryCsv, buildReport: buildReport, buildDigest: buildDigest, buildFreeCsv: buildFreeCsv, buildFreeMarkdown: buildFreeMarkdown, makeSnapshot: makeSnapshot, diffSnapshots: diffSnapshots, fmtMoney: fmtMoney, fmtRemain: fmtRemain, escapeXml: escapeXml, csvCell: csvCell, // 只给无头预览/调试用:注入假数据后走真实渲染路径,业务代码不要依赖 debug: { setRadar: function (radar, ledger, filter) { state.radar = radar; if (ledger) state.ledger = ledger; state.radarFilter = filter || 'all'; state.radarAnalysis = analyzeFree(state.ledger, radar ? radar.ids : null); ui.renderRadar(); }, setLibrary: function (result, diff) { state.library = result; state.diff = diff || null; ui.setExportBusy(false); ui.renderAnalysis(result, diff || null); } } }; // ==================== 启动 ==================== function registerMenu(label, fn) { try { if (typeof GM_registerMenuCommand === 'function') GM_registerMenuCommand(label, fn); } catch (e) { /* 无 GM 环境忽略 */ } } function boot() { try { ui.mount(); ui.renderSettings(); ui.renderRadar(); ui.setExportBusy(false); ui.renderAnalysis(null, null); registerMenu('GOG 助手:打开面板', function () { ui.open('free'); }); registerMenu('GOG 助手:扫描免费商品', function () { ui.open('free'); runRadar(false); }); registerMenu('GOG 助手:读取库存并导出 JSON', function () { ui.open('export'); runExport().then(function (r) { if (r) exportJson(); }); }); if (CFG.autoRadar) { setTimeout(function () { runRadar(true); }, 1500); } } catch (e) { console.error(LOG_PREFIX, '初始化失败', e); } } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot, { once: true }); } else { boot(); } })();