// ==UserScript== // @name EA 平台增强 // @name:en EA Platform Enhancer // @namespace ea-platform-enhancer // @version 1.0.0 // @description 看清你的 EA 库:原生/关联入库拆分、游玩时长分布与排行、入库时间线、订阅状态,面板内实时分析,一键导出 JSON / CSV / Markdown 报告 // @description:en See through your EA library: native vs linked split, playtime distribution and ranking, acquisition timeline, subscriptions — live in-page analytics with JSON / CSV / Markdown export. // @author SmallRob // @match https://www.ea.com/* // @run-at document-idle // @noframes // @grant none // @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'%20x1='0'%20y1='0'%20x2='1'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%231a0608'/%3E%3Cstop%20offset='100%25'%20stop-color='%230b0e14'/%3E%3C/linearGradient%3E%3ClinearGradient%20id='ea-red'%20x1='0'%20y1='0'%20x2='1'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%23ff6b6b'/%3E%3Cstop%20offset='60%25'%20stop-color='%23ff4747'/%3E%3Cstop%20offset='100%25'%20stop-color='%23c0392b'/%3E%3C/linearGradient%3E%3ClinearGradient%20id='accent'%20x1='0'%20y1='0'%20x2='0'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%23ffffff'%20stop-opacity='0.9'/%3E%3Cstop%20offset='100%25'%20stop-color='%23ffffff'%20stop-opacity='0.3'/%3E%3C/linearGradient%3E%3Cfilter%20id='glow'%20x='-20%25'%20y='-20%25'%20width='140%25'%20height='140%25'%3E%3CfeGaussianBlur%20stdDeviation='1.5'%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)'/%3E%3Crect%20x='2'%20y='2'%20width='60'%20height='30'%20rx='12'%20fill='url(%23accent)'%20opacity='0.06'/%3E%3Cg%20transform='translate(16,%2012)'%20filter='url(%23glow)'%3E%3Crect%20x='0'%20y='0'%20width='8'%20height='40'%20rx='2'%20fill='url(%23ea-red)'/%3E%3Crect%20x='0'%20y='0'%20width='24'%20height='8'%20rx='2'%20fill='url(%23ea-red)'/%3E%3Crect%20x='0'%20y='16'%20width='18'%20height='7'%20rx='1.5'%20fill='url(%23ea-red)'%20opacity='0.9'/%3E%3Crect%20x='0'%20y='32'%20width='22'%20height='7'%20rx='1.5'%20fill='url(%23ea-red)'%20opacity='0.85'/%3E%3C/g%3E%3Cg%20transform='translate(42,%2038)'%20fill='%23ff6b6b'%20opacity='0.9'%3E%3Crect%20x='0'%20y='6'%20width='3'%20height='8'%20rx='1'/%3E%3Crect%20x='4'%20y='2'%20width='3'%20height='12'%20rx='1'/%3E%3Crect%20x='8'%20y='8'%20width='3'%20height='6'%20rx='1'/%3E%3Crect%20x='12'%20y='0'%20width='3'%20height='14'%20rx='1'/%3E%3C/g%3E%3Ccircle%20cx='12'%20cy='52'%20r='3'%20fill='%232ecc71'/%3E%3Ccircle%20cx='20'%20cy='52'%20r='2'%20fill='%23f1c40f'%20opacity='0.8'/%3E%3Ccircle%20cx='54'%20cy='10'%20r='1.5'%20fill='%23ffffff'%20opacity='0.7'/%3E%3Ccircle%20cx='58'%20cy='18'%20r='1'%20fill='%23ff6b6b'%20opacity='0.6'/%3E%3C/svg%3E // ==/UserScript== (function () { 'use strict'; // ==================== 配置 ==================== // www.ea.com 自身内置的网页端 OAuth 隐式流:隐藏 iframe 静默向 accounts.ea.com 要 // DX_DROP_JS_WEB_APP 令牌,回调同源的 /static-pages/auth.html 后由该页调用 // window.parent.handleToken 把 hash 传回来。 // 该 Bearer Token 可直接调用 service-aggregation-layer GraphQL,且服务端对浏览器端 // 返回 ACAO: *,所以这里用页面内 fetch 就够了(不需要 GM 跨域请求)。 const AUTH_CLIENT_ID = 'DX_DROP_JS_WEB_APP'; const AUTH_REDIRECT_URI = 'https://www.ea.com/static-pages/auth.html'; const SILENT_AUTH_URL = 'https://accounts.ea.com/connect/auth' + '?client_id=' + encodeURIComponent(AUTH_CLIENT_ID) + '&response_type=token' + '&prompt=none' + '&redirect_uri=' + encodeURIComponent(AUTH_REDIRECT_URI); const LOGIN_URL = 'https://accounts.ea.com/connect/auth' + '?response_type=code' + '&client_id=EADOTCOM-WEB-SERVER' + '&display=junoWeb/login' + '&release_type=prod' + '&redirect_uri=' + encodeURIComponent('https://www.ea.com/'); const GRAPHQL_URL = 'https://service-aggregation-layer.juno.ea.com/graphql'; const X_CLIENT_ID = 'EAX-JUNO-CLIENT'; const AUTH_PATH = '/static-pages/auth.html'; const VERSION = '1.0.0'; const LOG_PREFIX = '[EA 助手]'; const SCHEMA_VERSION = 1; const OFFER_BATCH = 25; const PLAYTIME_BATCH = 25; const TOKEN_TIMEOUT_MS = 12000; const SNAPSHOT_MAX = 20; // 存储走同源 localStorage(脚本 @grant none,保持与网页同一个会话环境) const LS_CFG = 'eae.cfg.v1'; const LS_SNAP = 'eae.snapshots.v1'; const CFG_DEFAULTS = { includeLinked: false, // 是否把 Steam/Epic 关联入库的条目算进库存 sortBy: 'playtime' // 游戏库列表排序:playtime | name | acquired }; function lsGet(key, fallback) { try { const raw = localStorage.getItem(key); if (!raw) return fallback; return JSON.parse(raw); } catch (e) { return fallback; } } function lsSet(key, value) { try { localStorage.setItem(key, JSON.stringify(value)); } catch (e) { /* 存储满/被禁用时只影响持久化 */ } } const CFG = Object.assign({}, CFG_DEFAULTS, lsGet(LS_CFG, {})); if (typeof CFG.includeLinked !== 'boolean') CFG.includeLinked = CFG_DEFAULTS.includeLinked; if (['playtime', 'name', 'acquired'].indexOf(CFG.sortBy) === -1) CFG.sortBy = CFG_DEFAULTS.sortBy; const state = { running: false, result: null, diff: null, startedAt: 0, requests: 0, ticker: null, query: '' }; function saveCfg() { lsSet(LS_CFG, CFG); } // ==================== 通用工具 ==================== function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); } function shortUrl(u) { return String(u || '').replace(/^https?:\/\//, '').slice(0, 64); } function lower(v) { return String(v === undefined || v === null ? '' : v).toLowerCase(); } function pad2(n) { return n < 10 ? '0' + n : String(n); } function chunkArray(list, size) { const out = []; for (let i = 0; i < list.length; i += size) out.push(list.slice(i, i + size)); return out; } function errorCodeOf(err) { if (!err) return 'UNKNOWN'; if (err.code) return String(err.code); if (err.status) return 'HTTP_' + err.status; if (err.name === 'TypeError') return 'NETWORK_ERROR'; return 'UNKNOWN'; } // EA 对没记录过的日期回 1970-01-01 哨兵值,统一清洗成 null,否则统计会多出一堆 1970 年 function normalizeIsoDate(ts) { if (!ts || typeof ts !== 'string') return null; const trimmed = ts.trim(); if (!trimmed) return null; const ms = Date.parse(trimmed); if (!Number.isFinite(ms) || ms <= 86400000) return null; return trimmed; } function fmtMinutes(min) { const m = Number(min); if (!Number.isFinite(m) || m <= 0) return '0'; if (m < 60) return m + ' 分'; const h = m / 60; return (h >= 100 ? Math.round(h) : Math.round(h * 10) / 10) + ' 小时'; } function fmtDateTime(iso) { if (!iso) return ''; const d = new Date(iso); if (!isFinite(d.getTime())) return ''; return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()) + ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes()); } // ==================== 鉴权:静默 iframe 拿网页端 Bearer Token ==================== let tokenInFlight = null; function parseAuthHash(hash) { const params = new URLSearchParams(String(hash || '').replace(/^#/, '')); const accessToken = params.get('access_token'); const error = params.get('error') || params.get('error_code'); const errorDesc = params.get('error_description') || ''; const expiresIn = Number(params.get('expires_in')); return { accessToken: accessToken || null, error: error || null, errorDescription: errorDesc, expiresIn: Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : null }; } function fetchAccessToken() { if (tokenInFlight) return tokenInFlight; if (typeof document === 'undefined' || !document.body) { return Promise.reject(new Error('当前不在浏览器页面环境,无法获取网页令牌')); } tokenInFlight = new Promise(function (resolve, reject) { const prevHandleToken = window.handleToken; let settled = false; let iframe = null; function cleanup() { if (window.handleToken === onToken) window.handleToken = prevHandleToken; if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe); } const timer = setTimeout(function () { if (settled) return; settled = true; cleanup(); const err = new Error('静默获取 EA 网页令牌超时(' + Math.round(TOKEN_TIMEOUT_MS / 1000) + 's),请确认能正常访问 accounts.ea.com'); err.code = 'TOKEN_TIMEOUT'; err.networkProblem = true; reject(err); }, TOKEN_TIMEOUT_MS); function onToken(hash) { if (typeof prevHandleToken === 'function') { try { prevHandleToken(hash); } catch (e) { /* 页面原有回调失败不影响我们 */ } } if (settled) return; settled = true; clearTimeout(timer); cleanup(); const parsed = parseAuthHash(hash); if (parsed.accessToken) { resolve({ token: parsed.accessToken, expiresIn: parsed.expiresIn }); return; } if (parsed.error === 'login_required') { const err = new Error('未检测到 EA 登录会话。请先登录 ' + LOGIN_URL + ' 再回到本页'); err.code = 'LOGIN_REQUIRED'; err.loginRequired = true; reject(err); return; } const err = new Error('获取网页令牌失败:' + (parsed.error || '未返回 access_token') + (parsed.errorDescription ? '(' + parsed.errorDescription + ')' : '')); err.code = parsed.error ? String(parsed.error).toUpperCase() : 'TOKEN_ERROR'; reject(err); } window.handleToken = onToken; iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.setAttribute('aria-hidden', 'true'); iframe.src = SILENT_AUTH_URL; document.body.appendChild(iframe); }).finally(function () { tokenInFlight = null; }); return tokenInFlight; } // ==================== 网络层 ==================== async function gqlOnce(token, query, what) { state.requests += 1; const url = GRAPHQL_URL + '?query=' + encodeURIComponent(query); const started = Date.now(); let res; try { res = await fetch(url, { method: 'GET', headers: { 'Authorization': 'Bearer ' + token, 'x-client-id': X_CLIENT_ID, 'Accept': 'application/json' } }); } catch (err) { const msg = (err && err.message) ? err.message : String(err); const wrapped = new Error((what || shortUrl(url)) + ' 网络请求失败:' + msg); wrapped.networkProblem = true; throw wrapped; } const text = await res.text(); let json = null; try { json = text ? JSON.parse(text) : null; } catch (e) { json = null; } if (!res.ok) { const gqlMsg = json && Array.isArray(json.errors) && json.errors[0] && json.errors[0].message; const err = new Error((what || shortUrl(url)) + ' 返回 HTTP ' + res.status + (gqlMsg ? ':' + gqlMsg : '')); err.status = res.status; err.json = json; throw err; } if (!json || typeof json !== 'object') { throw new Error((what || shortUrl(url)) + ' 返回了非 JSON 内容'); } if (Array.isArray(json.errors) && json.errors.length && !json.data) { const err = new Error((what || 'GraphQL') + ' 报错:' + ((json.errors[0] && json.errors[0].message) || '未知错误')); err.gqlErrors = json.errors; throw err; } return { status: res.status, json: json, ms: Date.now() - started }; } // 401/403 换一次令牌;429/5xx/网络错按指数退避重试。令牌是隐式流发的,没有 refresh_token。 async function gqlRequest(authCtx, query, what) { const RETRIES = 2; let refreshed = false; let lastErr = null; for (let attempt = 0; attempt <= RETRIES; attempt += 1) { try { return await gqlOnce(authCtx.token, query, what); } catch (err) { lastErr = err; const st = err && err.status; if ((st === 401 || st === 403) && !refreshed) { refreshed = true; const fresh = await fetchAccessToken(); authCtx.token = fresh.token; continue; } const retryable = st === 429 || st === 500 || st === 502 || st === 503 || st === 504 || !!err.networkProblem; if (attempt === RETRIES || !retryable) break; const backoff = (st === 429 ? 1200 : 350) * Math.pow(2, attempt); await sleep(backoff + Math.random() * 150); } } throw lastErr; } async function pool(items, limit, worker) { const runners = []; let idx = 0; async function run() { while (idx < items.length) { const i = idx++; await worker(items[i], i); } } for (let k = 0; k < Math.min(limit, items.length); k++) runners.push(run()); await Promise.all(runners); } // ==================== 数据整形(纯函数) ==================== function normalizeEaPlatform(raw) { const v = lower(raw).trim(); if (!v) return null; if (v === 'pc' || v === 'pcwin' || v === 'windows' || v === 'win') return 'Windows'; if (v === 'mac' || v === 'macos' || v === 'osx') return 'macOS'; if (v === 'linux') return 'Linux'; return String(raw).trim(); } function collectPlatforms(entitlement, offer) { const out = []; function add(val) { const p = normalizeEaPlatform(val); if (p && out.indexOf(p) === -1) out.push(p); } const product = (entitlement && entitlement.product) || {}; const details = product.gamePlatformDetails; if (Array.isArray(details)) { for (let i = 0; i < details.length; i += 1) add(details[i] && details[i].gamePlatform); } else if (details && typeof details === 'object') { add(details.gamePlatform); } if (offer && typeof offer === 'object') { add(offer.basePlatform); add(offer.softwarePlatform); } if (!out.length) out.push('Windows'); return out; } function isDlcOffer(entitlement, offer) { const displayType = lower(offer && offer.displayType).replace(/[_-]/g, ''); if (displayType === 'addon' || displayType === 'expansion' || displayType === 'dlc') return true; const product = (entitlement && entitlement.product) || {}; const offerProduct = (offer && offer.game_product) || {}; const gameType = lower( (product.baseItem && product.baseItem.gameType) || (offerProduct.baseItem && offerProduct.baseItem.gameType) ); return gameType === 'extra_content' || gameType === 'expansion'; } function isTrialProduct(entitlement) { const product = (entitlement && entitlement.product) || {}; return !!(product.trialDetails && product.trialDetails.trialType); } // ownedGameProducts 有时会给出 product=null(Sims 4 扩展包 / 虚拟货币 / 内购 Offer), // 这时只有 legacyOffers 明确标成本体或能匹配到 game_product 才留下,否则算非游戏条目。 function hasResolvableGameProduct(entitlement, offer) { if (entitlement && entitlement.product && typeof entitlement.product === 'object') return true; if (offer && offer.game_product && typeof offer.game_product === 'object') return true; const dt = lower(offer && offer.displayType).replace(/[_-]/g, ''); return dt === 'fullgame' || dt === 'game' || dt === 'bundle'; } // 所有权方式只有 STEAM / EPIC = 这台机器上没装 EA 版,属于「关联入库」而非 EA 原生 function isLinkedOnlyMethods(methods) { if (!Array.isArray(methods) || !methods.length) return false; for (let i = 0; i < methods.length; i += 1) { const m = String(methods[i] || '').toUpperCase(); if (m !== 'STEAM' && m !== 'EPIC') return false; } return true; } function pickBetterEntitlement(a, b) { const pa = (a && a.product) || {}; const pb = (b && b.product) || {}; const da = pa.downloadable ? 0 : 1; const db = pb.downloadable ? 0 : 1; if (da !== db) return da < db ? a : b; const ta = (pa.gameProductUser && pa.gameProductUser.initialEntitlementDate) || '9999'; const tb = (pb.gameProductUser && pb.gameProductUser.initialEntitlementDate) || '9999'; if (ta !== tb) return ta < tb ? a : b; return String(a.id || '') <= String(b.id || '') ? a : b; } // 同一个 gameSlug 的多条权益(不同 originOfferId / 平台)收敛成一条 function dedupeEntitlements(items) { const bySlug = new Map(); const noSlug = []; const seenIds = new Set(); let duplicates = 0; for (let i = 0; i < items.length; i += 1) { const item = items[i]; if (!item || typeof item !== 'object') continue; const offerId = String(item.id || '').trim(); const slug = String((item.product && item.product.gameSlug) || '').trim(); if (slug) { if (bySlug.has(slug)) { duplicates += 1; bySlug.set(slug, pickBetterEntitlement(bySlug.get(slug), item)); } else { bySlug.set(slug, item); } } else { if (offerId && seenIds.has(offerId)) { duplicates += 1; continue; } if (offerId) seenIds.add(offerId); noSlug.push(item); } } return { items: Array.from(bySlug.values()).concat(noSlug), duplicates: duplicates }; } // ==================== EA GraphQL 查询 ==================== async function fetchIdentity(authCtx) { const r = await gqlRequest(authCtx, 'query{me{player{pd psd displayName}}}', '读取账号身份(player)'); const player = r.json && r.json.data && r.json.data.me && r.json.data.me.player; if (!player || !player.pd) throw new Error('未能解析 EA 账号身份信息'); return { userId: String(player.pd), personaId: player.psd ? String(player.psd) : null, displayName: player.displayName ? String(player.displayName) : null }; } async function fetchEntitlements(authCtx, includeLinked) { const storefronts = includeLinked ? '[EA, STEAM, EPIC]' : '[EA]'; const query = 'query getOwnedGames {' + ' me {' + ' ownedGameProducts(' + ' storefronts: ' + storefronts + ' locale: "DEFAULT"' + ' paging: {limit: 9999, next: null}' + ' orderBy: {field: NAME, direction: ASC}' + ' ) {' + ' items {' + ' id: originOfferId' + ' status' + ' product {' + ' id name downloadable gameSlug' + ' trialDetails { trialType }' + ' baseItem(availabilities: [VISIBLE]) { title id baseGameSlug gameType }' + ' gameProductUser(storefronts: ' + storefronts + ') {' + ' ownershipMethods initialEntitlementDate entitlementId status' + ' }' + ' }' + ' }' + ' }' + ' }' + '}'; const r = await gqlRequest(authCtx, query, '读取拥有游戏库(ownedGameProducts)'); const items = r.json && r.json.data && r.json.data.me && r.json.data.me.ownedGameProducts && r.json.data.me.ownedGameProducts.items; if (!Array.isArray(items)) throw new Error('ownedGameProducts 返回格式异常,未找到 items 数组'); return items; } async function fetchOffersBatch(authCtx, offerIds) { const idsJson = JSON.stringify(offerIds); const query = 'query{' + ' legacyOffers(offerIds:' + idsJson + ',locale:"DEFAULT"){' + ' offerId:id contentId basePlatform primaryMasterTitleId displayName displayType softwarePlatform' + ' }' + ' gameProducts(offerIds:' + idsJson + ',locale:"DEFAULT"){' + ' items{id name originOfferId baseItem{title gameType} gameSlug}' + ' }' + '}'; const r = await gqlRequest(authCtx, query, '读取商品详情(offers)'); const data = (r.json && r.json.data) || {}; const legacyOffers = Array.isArray(data.legacyOffers) ? data.legacyOffers : []; const gameProducts = (data.gameProducts && Array.isArray(data.gameProducts.items)) ? data.gameProducts.items : []; const byOriginOffer = new Map(); const byProductId = new Map(); for (let i = 0; i < gameProducts.length; i += 1) { const p = gameProducts[i]; if (!p || typeof p !== 'object') continue; if (p.originOfferId) byOriginOffer.set(String(p.originOfferId), p); if (p.id) byProductId.set(String(p.id), p); } const result = new Map(); for (let i = 0; i < legacyOffers.length; i += 1) { const lo = legacyOffers[i]; if (!lo || !lo.offerId) continue; const oid = String(lo.offerId); const product = byOriginOffer.get(oid) || (lo.contentId ? byProductId.get(String(lo.contentId)) : null) || byProductId.get(oid) || null; const merged = Object.assign({}, lo); if (!merged.displayName && product && product.name) merged.displayName = product.name; if (product && product.gameSlug) merged.gameSlug = product.gameSlug; if (product) merged.game_product = product; result.set(oid, merged); } return result; } async function fetchAllOffers(authCtx, offerIds, onProgress) { const map = new Map(); const batches = chunkArray(offerIds, OFFER_BATCH); for (let i = 0; i < batches.length; i += 1) { const part = await fetchOffersBatch(authCtx, batches[i]); part.forEach(function (val, key) { map.set(key, val); }); if (onProgress) onProgress(i + 1, batches.length); } return map; } async function fetchPlaytimes(authCtx, gameSlugs, onProgress) { const map = new Map(); const uniqueSlugs = Array.from(new Set(gameSlugs.filter(Boolean))); const batches = chunkArray(uniqueSlugs, PLAYTIME_BATCH); for (let i = 0; i < batches.length; i += 1) { const query = 'query{me{recentGames(gameSlugs:' + JSON.stringify(batches[i]) + '){' + 'items{gameSlug totalPlayTimeSeconds lastSessionEndDate}' + '}}}'; const r = await gqlRequest(authCtx, query, '读取游玩时长(recentGames)'); const items = r.json && r.json.data && r.json.data.me && r.json.data.me.recentGames && r.json.data.me.recentGames.items; if (Array.isArray(items)) { for (let k = 0; k < items.length; k += 1) { const row = items[k]; if (!row || !row.gameSlug) continue; const sec = Number(row.totalPlayTimeSeconds); map.set(String(row.gameSlug), { playtimeMinutes: Number.isFinite(sec) && sec >= 0 ? Math.round(sec / 60) : 0, lastPlayedAt: normalizeIsoDate(row.lastSessionEndDate) }); } } if (onProgress) onProgress(i + 1, batches.length); } return map; } async function fetchSubscriptions(authCtx) { const query = 'query{me{subscriptions{offerId recurring start end level status' + ' offer{offerName duration} platform type acquisitionMethod}}}'; const r = await gqlRequest(authCtx, query, '读取订阅状态(subscriptions)'); const subs = r.json && r.json.data && r.json.data.me && r.json.data.me.subscriptions; return Array.isArray(subs) ? subs : []; } // ==================== 数据聚合分析(纯函数) ==================== function dayOf(iso) { if (!iso) return null; const t = Date.parse(iso); if (!isFinite(t)) return null; return new Date(t).toISOString().slice(0, 10); } function countBy(list, keyFn) { const map = new Map(); for (const item of list) { const key = keyFn(item); if (key === null || key === undefined || key === '') continue; map.set(key, (map.get(key) || 0) + 1); } return Array.from(map.entries()) .map(function (e) { return { key: e[0], count: e[1] }; }) .sort(function (a, b) { return b.count - a.count || String(a.key).localeCompare(String(b.key), 'en'); }); } // 入库时间线:年度/月度分布、跨度、峰值年、年均、最大空档。 // 入库时间是 EA 的 initialEntitlementDate,不是购买时间;无记录的单独计 undated。 function buildTimeline(games) { const stamps = []; let undated = 0; for (const g of games) { const d = dayOf(g.acquiredAt); if (d) stamps.push(d); else undated += 1; } stamps.sort(); const first = stamps[0] || null; const last = stamps[stamps.length - 1] || null; const byYear = []; const byMonth = []; if (first && last) { const y0 = Number(first.slice(0, 4)); const y1 = Number(last.slice(0, 4)); for (let y = y0; y <= y1; y++) byYear.push({ key: String(y), count: 0 }); let y = y0; let m = Number(first.slice(5, 7)); while (y < y1 || (y === y1 && m <= Number(last.slice(5, 7)))) { byMonth.push({ key: y + '-' + pad2(m), count: 0 }); m += 1; if (m > 12) { m = 1; y += 1; } } const yearIdx = new Map(byYear.map(function (d, i) { return [d.key, i]; })); const monthIdx = new Map(byMonth.map(function (d, i) { return [d.key, i]; })); for (const d of stamps) { const yi = yearIdx.get(d.slice(0, 4)); if (yi !== undefined) byYear[yi].count += 1; const mi = monthIdx.get(d.slice(0, 7)); if (mi !== undefined) byMonth[mi].count += 1; } } let peakYear = null; for (const d of byYear) if (!peakYear || d.count > peakYear.count) peakYear = d; const spanDays = (first && last) ? Math.round((Date.parse(last + 'T00:00:00Z') - Date.parse(first + 'T00:00:00Z')) / 86400000) : 0; let maxGap = { days: 0, from: null, to: null }; for (let i = 1; i < stamps.length; i++) { const days = Math.round((Date.parse(stamps[i] + 'T00:00:00Z') - Date.parse(stamps[i - 1] + 'T00:00:00Z')) / 86400000); if (days > maxGap.days) maxGap = { days: days, from: stamps[i - 1], to: stamps[i] }; } return { first: first, last: last, spanDays: spanDays, undated: undated, byYear: byYear, byMonth: byMonth, peakYear: peakYear ? { year: peakYear.key, count: peakYear.count } : null, monthsActive: byMonth.filter(function (d) { return d.count > 0; }).length, avgPerYear: byYear.length ? Math.round(stamps.length / byYear.length * 10) / 10 : 0, maxGap: maxGap }; } // 时长分桶:边界写死成常量,UI / CSV / 报告共用同一份,避免两个页面口径不一致。 // 边界是「分钟区间闭合」语义:1–299 归 < 5h,300 分钟(正好 5 小时)归 5–20h。 const PLAYTIME_BUCKETS = [ { key: '未游玩', min: 0, max: 0 }, { key: '< 5h', min: 1, max: 299 }, { key: '5–20h', min: 300, max: 1200 }, { key: '20–50h', min: 1201, max: 3000 }, { key: '50–100h', min: 3001, max: 6000 }, { key: '100–500h', min: 6001, max: 30000 }, { key: '500h+', min: 30001, max: Infinity } ]; function bucketOf(minutes) { const m = Number(minutes); const v = Number.isFinite(m) && m > 0 ? m : 0; for (const b of PLAYTIME_BUCKETS) { if (v >= b.min && v <= b.max) return b.key; } return '500h+'; } function analyzeLibrary(games) { const list = Array.isArray(games) ? games : []; const platformFlat = []; for (const g of list) { const ps = (g.platforms && g.platforms.length) ? g.platforms : ['未标注']; for (const p of ps) platformFlat.push({ p: p }); } const methodFlat = []; for (const g of list) { const ms = (g.ownershipMethods && g.ownershipMethods.length) ? g.ownershipMethods : ['UNKNOWN']; for (const m of ms) methodFlat.push({ m: m }); } let totalMinutes = 0; let played = 0; let unplayed = 0; let last60 = 0; let last30 = 0; const now = Date.now(); for (const g of list) { const m = Number(g.playtimeMinutes) || 0; if (m > 0) { played += 1; totalMinutes += m; } else { unplayed += 1; } const lp = g.lastPlayedAt ? Date.parse(g.lastPlayedAt) : NaN; if (isFinite(lp)) { if (now - lp <= 60 * 86400000) last60 += 1; if (now - lp <= 30 * 86400000) last30 += 1; } } const top = list.slice() .filter(function (g) { return (Number(g.playtimeMinutes) || 0) > 0; }) .sort(function (a, b) { return Number(b.playtimeMinutes) - Number(a.playtimeMinutes); }) .slice(0, 10) .map(function (g) { return { name: g.name || g.gameSlug || g.originOfferId, minutes: Number(g.playtimeMinutes) || 0 }; }); const buckets = PLAYTIME_BUCKETS.map(function (b) { return { key: b.key, count: 0 }; }); const bucketIdx = new Map(buckets.map(function (b, i) { return [b.key, i]; })); for (const g of list) { const i = bucketIdx.get(bucketOf(g.playtimeMinutes)); if (i !== undefined) buckets[i].count += 1; } const nativeCount = list.filter(function (g) { return !g.linkedOnly; }).length; const linkedCount = list.length - nativeCount; const resolved = list.filter(function (g) { return g.resolved; }).length; return { totals: { games: list.length, native: nativeCount, linked: linkedCount, resolved: resolved, unresolved: list.length - resolved, resolutionRate: list.length ? Math.round(resolved / list.length * 1000) / 10 : 0, played: played, unplayed: unplayed, playedRate: list.length ? Math.round(played / list.length * 1000) / 10 : 0, totalPlaytimeMinutes: totalMinutes, avgPlaytimeMinutes: played ? Math.round(totalMinutes / played) : 0, playedLast30d: last30, playedLast60d: last60 }, timeline: buildTimeline(list), platforms: countBy(platformFlat, function (x) { return x.p; }), ownership: countBy(methodFlat, function (x) { return x.m; }), playtimeBuckets: buckets, topPlaytime: top }; } // ==================== 快照与差异 ==================== function makeSnapshot(result) { const games = (result && result.games) || []; const items = {}; for (const g of games) { const id = String(g.gameSlug || g.originOfferId || g.name || '').trim(); if (!id) continue; items[id] = g.name || null; } return { at: (result && result.generatedAt) || new Date().toISOString(), accountId: (result && result.account && result.account.userId) || null, gameCount: games.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 (!Object.prototype.hasOwnProperty.call(prev.items, id)) added.push({ id: id, name: cur.items[id] }); } for (const id of Object.keys(prev.items)) { if (!Object.prototype.hasOwnProperty.call(cur.items, id)) removed.push({ id: id, name: prev.items[id] }); } const key = function (x) { return String(x.name || x.id); }; added.sort(function (a, b) { return key(a).localeCompare(key(b), 'en'); }); removed.sort(function (a, b) { return key(a).localeCompare(key(b), 'en'); }); return { prevAt: prev.at || null, curAt: cur.at || null, prevCount: prev.gameCount || Object.keys(prev.items).length, curCount: cur.gameCount || Object.keys(cur.items).length, added: added, removed: removed }; } function loadSnapshots() { const raw = lsGet(LS_SNAP, []); return Array.isArray(raw) ? raw : []; } function pushSnapshot(snap) { const list = loadSnapshots(); const prev = list.length ? list[list.length - 1] : null; const diff = prev ? diffSnapshots(prev, snap) : null; list.push(snap); while (list.length > SNAPSHOT_MAX) list.shift(); lsSet(LS_SNAP, list); return diff; } // ==================== 导出:CSV / Markdown / 摘要 ==================== function csvCell(value) { const s = (value === null || value === undefined) ? '' : String(value); return '"' + s.replace(/"/g, '""') + '"'; } 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 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 = 10; const n = byYear.length; const gap = n > 10 ? 2 : 4; const bw = Math.max(2, (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(''); parts.push('' + '' + ''); 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(String(d.key).slice(-2)) + ''); } } parts.push(''); return parts.join(''); } function buildCsv(result) { const head = ['游戏名', 'EA 商品ID', '产品ID', 'gameSlug', '权益ID', '所有权方式', '是否仅关联', '入库时间', '平台', '游玩分钟', '最近游玩', '状态']; const rows = ((result && result.games) || []).map(function (g) { return [ g.name, g.originOfferId, g.productId, g.gameSlug, g.entitlementId, (g.ownershipMethods || []).join(' / '), g.linkedOnly ? '是' : '否', g.acquiredAt, (g.platforms || []).join(' / '), g.playtimeMinutes === undefined ? '' : g.playtimeMinutes, g.lastPlayedAt || '', g.status || '' ]; }); return toCsv(head, rows); } function buildSummaryCsv(result) { const a = (result && result.analysis) || analyzeLibrary((result && result.games) || []); const rows = []; const total = a.totals.games || 0; const pct = function (n) { return total ? Math.round(n / total * 1000) / 10 + '%' : ''; }; rows.push(['年度', '入库数量', '占比']); for (const d of a.timeline.byYear) rows.push([d.key, d.count, pct(d.count)]); rows.push([]); rows.push(['平台', '数量', '占比']); for (const d of a.platforms) rows.push([d.key, d.count, pct(d.count)]); rows.push([]); rows.push(['时长分桶', '数量', '占比']); for (const d of a.playtimeBuckets) rows.push([d.key, d.count, pct(d.count)]); rows.push([]); rows.push(['所有权方式', '数量', '占比']); for (const d of a.ownership) rows.push([d.key, d.count, pct(d.count)]); return toCsv(['维度', '数量', '占比'], rows); } function buildReport(result, diff) { const a = (result && result.analysis) || analyzeLibrary((result && result.games) || []); const acc = (result && result.account) || {}; const sum = (result && result.summary) || {}; const lines = []; const pct = function (n) { return a.totals.games ? Math.round(n / a.totals.games * 1000) / 10 + '%' : ''; }; lines.push('# EA 库存分析报告'); lines.push(''); lines.push('- 账号:' + (acc.displayName || acc.userId || '未知')); lines.push('- 生成时间:' + ((result && result.generatedAt) || new Date().toISOString())); lines.push('- 口径:' + (sum.includeLinked ? 'EA 原生 + Steam/Epic 关联' : '仅 EA 原生') + ',按 gameSlug 收敛'); lines.push(''); lines.push('## 概览'); lines.push(''); lines.push('| 指标 | 数值 |'); lines.push('| --- | --- |'); lines.push('| 游戏数 | ' + a.totals.games + ' |'); lines.push('| 原生 / 关联 | ' + a.totals.native + ' / ' + a.totals.linked + ' |'); lines.push('| 有游玩记录 | ' + a.totals.played + '(' + a.totals.playedRate + '%) |'); lines.push('| 总游玩时长 | ' + fmtMinutes(a.totals.totalPlaytimeMinutes) + ' |'); lines.push('| 平均每款(已玩) | ' + fmtMinutes(a.totals.avgPlaytimeMinutes) + ' |'); lines.push('| 首次入库 | ' + (a.timeline.first || '—') + ' |'); lines.push('| 最近入库 | ' + (a.timeline.last || '—') + ' |'); lines.push('| 峰值年 | ' + (a.timeline.peakYear ? a.timeline.peakYear.year + ' 年(' + a.timeline.peakYear.count + ' 款)' : '—') + ' |'); lines.push('| 最近 30 天玩过 | ' + a.totals.playedLast30d + ' |'); lines.push(''); lines.push('## 年度入库分布'); lines.push(''); lines.push('| 年份 | 数量 |'); lines.push('| --- | --- |'); for (const d of a.timeline.byYear) lines.push('| ' + d.key + ' | ' + d.count + ' |'); if (!a.timeline.byYear.length) lines.push('| (无数据) | 0 |'); lines.push(''); lines.push('## 游玩时长分布'); lines.push(''); lines.push('| 分桶 | 数量 | 占比 |'); lines.push('| --- | --- | --- |'); for (const d of a.playtimeBuckets) lines.push('| ' + d.key + ' | ' + d.count + ' | ' + pct(d.count) + ' |'); lines.push(''); if (a.topPlaytime.length) { lines.push('## 游玩时长 Top 10'); lines.push(''); lines.push('| # | 游戏 | 时长 |'); lines.push('| --- | --- | --- |'); a.topPlaytime.forEach(function (g, i) { lines.push('| ' + (i + 1) + ' | ' + g.name + ' | ' + fmtMinutes(g.minutes) + ' |'); }); lines.push(''); } lines.push('## 平台分布'); lines.push(''); lines.push('| 平台 | 数量 |'); lines.push('| --- | --- |'); for (const d of a.platforms) lines.push('| ' + d.key + ' | ' + d.count + ' |'); lines.push(''); const subs = (result && result.subscriptions) || []; if (subs.length) { lines.push('## 订阅'); lines.push(''); lines.push('| 名称 | 状态 | 平台 | 到期 |'); lines.push('| --- | --- | --- | --- |'); for (const s of subs) { lines.push('| ' + (s.name || s.offerId || '—') + ' | ' + (s.status || '—') + ' | ' + (s.platform || '—') + ' | ' + (s.end || '—') + ' |'); } lines.push(''); } if (diff) { lines.push('## 与上次导出对比'); lines.push(''); lines.push('- 上次:' + diff.prevAt + '(' + diff.prevCount + ' 款)'); lines.push('- 本次:' + diff.curAt + '(' + diff.curCount + ' 款)'); lines.push('- 新增 ' + diff.added.length + ' 款' + (diff.added.length ? ':' + diff.added.map(function (x) { return x.name || x.id; }).join('、') : '')); lines.push('- 移除 ' + diff.removed.length + ' 款' + (diff.removed.length ? ':' + diff.removed.map(function (x) { return x.name || x.id; }).join('、') : '')); lines.push(''); } lines.push('> 数据由 EA 平台增强脚本在本机生成,未上传任何服务器。'); return lines.join('\n'); } function buildDigest(result, diff) { const a = (result && result.analysis) || analyzeLibrary((result && result.games) || []); const acc = (result && result.account) || {}; const parts = []; parts.push('EA 库存(' + (acc.displayName || acc.userId || '未知账号') + '):' + a.totals.games + ' 款'); parts.push('原生 ' + a.totals.native + ' / 关联 ' + a.totals.linked); parts.push('总时长 ' + fmtMinutes(a.totals.totalPlaytimeMinutes)); if (a.topPlaytime.length) parts.push('最久 ' + a.topPlaytime[0].name + ' ' + fmtMinutes(a.topPlaytime[0].minutes)); if (diff) parts.push('较上次 +' + diff.added.length + ' / -' + diff.removed.length); return parts.join('|'); } // ==================== 导出流程 ==================== function startTicker() { stopTicker(); state.startedAt = Date.now(); ui.elapsed(0); state.ticker = setInterval(function () { ui.elapsed((Date.now() - state.startedAt) / 1000); }, 100); } function stopTicker() { if (state.ticker) { clearInterval(state.ticker); state.ticker = null; } } async function runExport(options) { if (state.running) return null; const opts = options || {}; const includeLinked = opts.includeLinked !== undefined ? !!opts.includeLinked : !!CFG.includeLinked; state.running = true; state.result = null; ui.resetExportView(); ui.setBusy(true); ui.progress(0, '准备中'); startTicker(); let lapAt = Date.now(); function lap(name) { const sec = ((Date.now() - lapAt) / 1000).toFixed(1); lapAt = Date.now(); ui.log(' · ' + name + ' ' + sec + 's'); } try { ui.progress(5, '获取网页令牌'); ui.log('获取 EA 网页令牌…'); const tokenInfo = await fetchAccessToken(); const authCtx = { token: tokenInfo.token }; lap('令牌'); ui.progress(12, '读取账号信息'); const account = await fetchIdentity(authCtx); ui.setAccount(account.displayName || account.userId); lap('身份'); ui.progress(20, '读取拥有游戏库'); ui.log('读取拥有游戏库(' + (includeLinked ? 'EA + Steam/Epic 关联' : '仅 EA 原生') + ')…'); const rawItems = await fetchEntitlements(authCtx, includeLinked); ui.log(' 原始权益 ' + rawItems.length + ' 条'); lap('库存'); const offerIds = []; for (const item of rawItems) { const oid = item && item.id; if (oid && offerIds.indexOf(String(oid)) === -1) offerIds.push(String(oid)); } let offers = new Map(); let offersErrorCode = null; if (offerIds.length) { ui.progress(38, '读取商品详情'); try { offers = await fetchAllOffers(authCtx, offerIds, function (done, total) { ui.progress(38 + Math.round(24 * done / total), '详情 ' + done + '/' + total); }); } catch (err) { offersErrorCode = errorCodeOf(err); ui.log(' ! 商品详情读取失败(降级为仅用基础字段):' + ((err && err.message) || err), 'warn'); } lap('详情 ' + offers.size + ' 条'); } let excludedDlc = 0; let excludedTrial = 0; let excludedNonGame = 0; const baseItems = []; for (const item of rawItems) { if (!item || !item.id) continue; const offer = offers.get(String(item.id)) || null; if (isTrialProduct(item)) { excludedTrial += 1; continue; } if (isDlcOffer(item, offer)) { excludedDlc += 1; continue; } if (!hasResolvableGameProduct(item, offer)) { excludedNonGame += 1; continue; } baseItems.push(item); } const deduped = dedupeEntitlements(baseItems); const kept = deduped.items; ui.log(' 过滤 DLC ' + excludedDlc + ' / 试玩 ' + excludedTrial + ' / 非本体 ' + excludedNonGame + ' / 同款去重 ' + deduped.duplicates + ' → ' + kept.length + ' 款'); const slugs = []; for (const item of kept) { const offer = offers.get(String(item.id)) || null; const slug = (item.product && item.product.gameSlug) || (offer && offer.gameSlug); if (slug) slugs.push(String(slug)); } let playtimes = new Map(); let playtimeErrorCode = null; if (slugs.length) { ui.progress(66, '读取游玩时长'); try { playtimes = await fetchPlaytimes(authCtx, slugs, function (done, total) { ui.progress(66 + Math.round(20 * done / total), '时长 ' + done + '/' + total); }); } catch (err) { playtimeErrorCode = errorCodeOf(err); ui.log(' ! 游玩时长读取失败(不影响库存):' + ((err && err.message) || err), 'warn'); } lap('时长 ' + playtimes.size + ' 条'); } ui.progress(88, '读取订阅状态'); let subscriptions = []; try { subscriptions = (await fetchSubscriptions(authCtx)).map(function (s) { return { offerId: s.offerId || null, name: (s.offer && s.offer.offerName) || s.level || null, level: s.level || null, status: s.status || null, platform: s.platform || null, start: normalizeIsoDate(s.start), end: normalizeIsoDate(s.end), recurring: !!s.recurring }; }); } catch (err) { ui.log(' ! 订阅信息读取跳过:' + ((err && err.message) || err), 'warn'); } let nativeCount = 0; let linkedCount = 0; const games = kept.map(function (item) { const offerId = String(item.id); const offer = offers.get(offerId) || null; const product = item.product || (offer && offer.game_product) || {}; const gpu = product.gameProductUser || {}; const slug = product.gameSlug || (offer && offer.gameSlug) || null; const pt = slug ? (playtimes.get(String(slug)) || null) : null; const methods = Array.isArray(gpu.ownershipMethods) ? gpu.ownershipMethods.slice() : []; const linkedOnly = isLinkedOnlyMethods(methods); if (linkedOnly) linkedCount += 1; else nativeCount += 1; const name = (offer && offer.displayName) || (offer && offer.game_product && offer.game_product.name) || product.name || (product.baseItem && product.baseItem.title) || null; const entry = { name: name ? String(name).trim() : null, originOfferId: offerId, productId: product.id ? String(product.id) : null, gameSlug: slug ? String(slug) : null, entitlementId: gpu.entitlementId ? String(gpu.entitlementId) : null, ownershipMethods: methods, linkedOnly: linkedOnly, acquiredAt: normalizeIsoDate(gpu.initialEntitlementDate), platforms: collectPlatforms(item, offer), status: gpu.status || item.status || null, resolved: !!name }; if (pt) { entry.playtimeMinutes = pt.playtimeMinutes; if (pt.lastPlayedAt) entry.lastPlayedAt = pt.lastPlayedAt; } return entry; }); games.sort(function (a, b) { return String(a.name || a.originOfferId).localeCompare(String(b.name || b.originOfferId), 'en-US'); }); let totalPlaytimeMinutes = 0; let playtimeGamesCount = 0; for (const g of games) { if (typeof g.playtimeMinutes === 'number' && g.playtimeMinutes > 0) { playtimeGamesCount += 1; totalPlaytimeMinutes += g.playtimeMinutes; } } const unresolvedCount = games.filter(function (g) { return !g.resolved; }).length; state.result = { schemaVersion: SCHEMA_VERSION, source: 'ea-platform-enhancer', generatedAt: new Date().toISOString(), account: account, subscriptions: subscriptions, summary: { gameCount: games.length, nativeCount: nativeCount, linkedCount: linkedCount, includeLinked: includeLinked, entitlementCount: rawItems.length, duplicateGameSlugs: deduped.duplicates, excludedDlc: excludedDlc, excludedTrial: excludedTrial, excludedNonGame: excludedNonGame, unresolvedCount: unresolvedCount, playtimeGamesCount: playtimeGamesCount, totalPlaytimeMinutes: totalPlaytimeMinutes, offersError: offersErrorCode, playtimeError: playtimeErrorCode }, games: games }; state.result.analysis = analyzeLibrary(games); state.diff = pushSnapshot(makeSnapshot(state.result)); ui.renderAnalysis(state.result, state.diff); ui.renderLibrary(); const totalSec = ((Date.now() - state.startedAt) / 1000).toFixed(1); stopTicker(); ui.elapsed(Number(totalSec)); ui.progress(100, '完成'); ui.setStats(games.length + ' 款 · ' + fmtMinutes(totalPlaytimeMinutes)); ui.log('✓ 完成:' + games.length + ' 款' + (includeLinked ? '(原生 ' + nativeCount + ' / 关联 ' + linkedCount + ')' : '') + ',总时长 ' + fmtMinutes(totalPlaytimeMinutes) + ',共 ' + totalSec + 's / ' + state.requests + ' 次请求', 'ok'); if (unresolvedCount) ui.log(' ⚠ ' + unresolvedCount + ' 款缺标题(保留 offerId 主键)', 'warn'); ui.toast('EA 库存读取完成:' + games.length + ' 款', 'ok'); return state.result; } catch (err) { stopTicker(); const msg = (err && err.message) ? err.message : String(err); ui.progress(0, '失败'); ui.log('✗ 失败:' + msg, 'err'); if (err && err.loginRequired) ui.log(' 请先在 ' + LOGIN_URL + ' 登录,再刷新本页重试', 'err'); if (err && err.networkProblem) { ui.log(' 网络层错误:确认能访问 accounts.ea.com / juno.ea.com,且未被广告拦截器拦下', 'err'); } ui.toast('读取失败:' + msg, 'err'); console.warn(LOG_PREFIX, err); return null; } finally { state.running = false; stopTicker(); ui.setBusy(false); } } // 环境自检:把「没令牌 / 令牌无效 / 查询失败」三种原因分开说清楚 async function runEnvCheck() { const lines = []; lines.push('── EA 环境自检 ──'); lines.push('当前域:' + ((typeof location !== 'undefined' && location) ? location.origin : '未知')); let authCtx = null; try { const t0 = Date.now(); const tok = await fetchAccessToken(); authCtx = { token: tok.token }; lines.push('网页令牌:✓ 成功(' + (Date.now() - t0) + 'ms)'); } catch (err) { lines.push('网页令牌:✗ ' + ((err && err.message) || err)); ui.logBlock(lines); return { ok: false, lines: lines }; } try { const acc = await fetchIdentity(authCtx); lines.push('账号身份:✓ ' + (acc.displayName || acc.userId)); } catch (err) { lines.push('账号身份:✗ ' + ((err && err.message) || err)); } try { const items = await fetchEntitlements(authCtx, CFG.includeLinked); lines.push('库存接口:✓ ' + items.length + ' 条权益'); } catch (err) { lines.push('库存接口:✗ ' + ((err && err.message) || err)); } ui.logBlock(lines); return { ok: true, lines: lines }; } // ==================== 输出 ==================== function download(filename, text, mime) { const blob = new Blob([text], { type: mime }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.style.display = 'none'; (document.body || document.documentElement).appendChild(a); a.click(); a.remove(); setTimeout(function () { URL.revokeObjectURL(url); }, 5000); } function baseName() { const r = state.result; const who = (r && r.account && (r.account.displayName || r.account.userId)) ? (r.account.displayName || r.account.userId) : 'ea'; const day = new Date().toISOString().slice(0, 10); const safe = String(who).replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 40); return 'ea-library-' + safe + '-' + day; } function exportJson() { if (!state.result) return; download(baseName() + '.json', JSON.stringify(state.result, null, 2), 'application/json'); } function exportCsv() { if (!state.result) return; download(baseName() + '.csv', buildCsv(state.result), 'text/csv;charset=utf-8'); } function exportSummaryCsv() { if (!state.result) return; download(baseName() + '-summary.csv', buildSummaryCsv(state.result), 'text/csv;charset=utf-8'); } function exportReport() { if (!state.result) return; download(baseName() + '.md', buildReport(state.result, state.diff), 'text/markdown;charset=utf-8'); } async function copyText(text) { try { if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(text); return true; } } catch (e) { /* 落到下面的兜底 */ } try { const ta = document.createElement('textarea'); ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0'; (document.body || document.documentElement).appendChild(ta); ta.select(); const ok = document.execCommand('copy'); ta.remove(); return ok; } catch (e) { return false; } } async function copyDigest() { if (!state.result) return; await copyText(buildDigest(state.result, state.diff)); ui.toast('摘要已复制', 'ok'); } // ==================== 界面 ==================== const ui = (function () { let shadow = null; const refs = {}; let currentTab = 'overview'; function mount() { const host = document.createElement('div'); host.id = 'eae-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.anaState = root.getElementById('anaState'); refs.anaKpis = root.getElementById('anaKpis'); refs.anaYears = root.getElementById('anaYears'); refs.anaBuckets = root.getElementById('anaBuckets'); refs.anaTop = root.getElementById('anaTop'); refs.anaPlatforms = root.getElementById('anaPlatforms'); refs.anaAudit = root.getElementById('anaAudit'); refs.anaDiff = root.getElementById('anaDiff'); refs.anaDiffTitle = root.getElementById('anaDiffTitle'); refs.libSearch = root.getElementById('libSearch'); refs.libCount = root.getElementById('libCount'); refs.libSort = root.getElementById('libSort'); refs.libList = root.getElementById('libList'); 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.btnAnaFetch = root.getElementById('btnAnaFetch'); refs.setLinked = root.getElementById('setLinked'); refs.setSort = root.getElementById('setSort'); refs.toasts = root.getElementById('toasts'); root.getElementById('ver').textContent = 'EA 平台增强 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.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.libSearch.addEventListener('input', function () { state.query = refs.libSearch.value || ''; renderLibrary(); }); refs.libSort.addEventListener('change', function () { CFG.sortBy = refs.libSort.value; saveCfg(); if (refs.setSort) refs.setSort.value = CFG.sortBy; renderLibrary(); }); refs.setLinked.addEventListener('change', function () { CFG.includeLinked = refs.setLinked.checked; saveCfg(); toast(CFG.includeLinked ? '下次读取将包含 Steam/Epic 关联条目' : '下次读取仅统计 EA 原生库', 'ok'); }); refs.setSort.addEventListener('change', function () { CFG.sortBy = refs.setSort.value; saveCfg(); if (refs.libSort) refs.libSort.value = CFG.sortBy; renderLibrary(); }); root.getElementById('btnEnvCheck').addEventListener('click', function () { runEnvCheck(); }); root.getElementById('btnClearSnap').addEventListener('click', function () { lsSet(LS_SNAP, []); state.diff = null; toast('快照历史已清除', 'ok'); }); root.getElementById('btnLogin').addEventListener('click', function () { window.open(LOGIN_URL, '_blank', 'noopener'); }); log('就绪。登录 EA 账号后点「读取库存」。'); renderSettings(); renderAnalysis(null, null); } function open(tab) { if (!refs.panel) return; refs.panel.hidden = false; if (tab) switchTab(tab); else switchTab(currentTab); } 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 || 'overview'; 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 === 'overview') renderAnalysis(state.result, state.diff); if (currentTab === 'library') renderLibrary(); if (currentTab === 'settings') renderSettings(); } function renderSettings() { if (!refs.setLinked) return; refs.setLinked.checked = !!CFG.includeLinked; refs.setSort.value = CFG.sortBy; if (refs.libSort) refs.libSort.value = CFG.sortBy; } function empty(text) { const el = document.createElement('div'); el.className = 'note'; 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, items, opts) { if (!container) return; container.textContent = ''; if (!items.length) { container.appendChild(empty(opts && opts.emptyText ? opts.emptyText : '暂无数据')); return; } const o = opts || {}; const list = o.slice ? items.slice(0, o.slice) : items; const max = list.reduce(function (m, d) { return Math.max(m, d.count); }, 1); for (const d of list) { 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, Math.round(d.count / max * 100)) + '%'; tr.appendChild(fl); const vl = document.createElement('span'); vl.className = 'vl'; vl.textContent = o.fmt ? o.fmt(d) : String(d.count); row.appendChild(lb); row.appendChild(tr); row.appendChild(vl); container.appendChild(row); } } function renderAnalysis(result, diff) { if (!refs.anaKpis) return; if (!result || !result.analysis) { refs.anaState.textContent = '尚无数据'; refs.anaKpis.textContent = ''; refs.anaYears.textContent = ''; refs.anaBuckets.textContent = ''; refs.anaTop.textContent = ''; refs.anaPlatforms.textContent = ''; refs.anaAudit.textContent = '点右上角「读取库存」后生成分析。'; refs.anaDiff.hidden = true; refs.anaDiffTitle.hidden = true; return; } const a = result.analysis; const acc = result.account || {}; refs.anaState.textContent = (acc.displayName || acc.userId || '账号') + ' · ' + a.totals.games + ' 款 · ' + fmtDateTime(result.generatedAt); kpi(refs.anaKpis, [ { label: '游戏数', value: String(a.totals.games) }, { label: '原生 / 关联', value: a.totals.native + ' / ' + a.totals.linked }, { label: '总游玩', value: fmtMinutes(a.totals.totalPlaytimeMinutes) }, { label: '已玩比例', value: a.totals.playedRate + '%' }, { label: '峰值年', value: a.timeline.peakYear ? a.timeline.peakYear.year + ' · ' + a.timeline.peakYear.count : '—' }, { label: '30 天内玩过', value: String(a.totals.playedLast30d) } ]); if (a.timeline.byYear.length) { refs.anaYears.innerHTML = buildYearChartSvg(a.timeline.byYear); } else { refs.anaYears.textContent = ''; refs.anaYears.appendChild(empty('没有带入库时间的记录')); } hbars(refs.anaBuckets, a.playtimeBuckets, { emptyText: '暂无时长数据' }); hbars(refs.anaTop, a.topPlaytime.map(function (g) { return { key: g.name, count: g.minutes }; }), { slice: 10, emptyText: '还没有游玩记录', fmt: function (d) { return fmtMinutes(d.count); } }); hbars(refs.anaPlatforms, a.platforms); const audit = []; audit.push('权益过滤后保留 ' + a.totals.games + ' 款;标题解析率 ' + a.totals.resolutionRate + '%'); audit.push('已玩 ' + a.totals.played + ' 款 / 未玩 ' + a.totals.unplayed + ' 款,平均每款(已玩)' + fmtMinutes(a.totals.avgPlaytimeMinutes)); if (a.timeline.undated) audit.push('无入库时间 ' + a.timeline.undated + ' 款'); if (a.timeline.first) { audit.push('入库跨度 ' + a.timeline.first + ' → ' + a.timeline.last + '(' + a.timeline.spanDays + ' 天)'); } if (result.summary) { const s = result.summary; if (s.excludedDlc || s.excludedNonGame || s.excludedTrial) { audit.push('已排除 DLC ' + (s.excludedDlc || 0) + ' / 试玩 ' + (s.excludedTrial || 0) + ' / 非本体 ' + (s.excludedNonGame || 0) + ' / 同款去重 ' + (s.duplicateGameSlugs || 0)); } if (s.playtimeError) audit.push('时长接口异常:' + s.playtimeError); if (s.offersError) audit.push('详情接口异常:' + s.offersError); } const subs = (result.subscriptions || []).filter(function (s) { return lower(s.status) !== 'expired'; }); if (subs.length) { audit.push('生效订阅 ' + subs.length + ' 项:' + subs.slice(0, 3).map(function (s) { return s.name || s.level || s.offerId; }).join('、')); } refs.anaAudit.textContent = ''; audit.forEach(function (line) { const div = document.createElement('div'); div.textContent = '· ' + line; refs.anaAudit.appendChild(div); }); if (diff) { refs.anaDiffTitle.hidden = false; refs.anaDiff.hidden = false; refs.anaDiff.textContent = ''; const l1 = document.createElement('div'); l1.textContent = '较上次(' + String(diff.prevAt).slice(0, 10) + ',' + diff.prevCount + ' 款)'; const l2 = document.createElement('div'); const add = document.createElement('span'); add.className = 'add'; add.textContent = '+' + diff.added.length + ' 新增'; const del = document.createElement('span'); del.className = 'del'; del.textContent = ' −' + diff.removed.length + ' 移除'; l2.appendChild(add); l2.appendChild(del); refs.anaDiff.appendChild(l1); refs.anaDiff.appendChild(l2); const names = diff.added.slice(0, 6).map(function (x) { return x.name || x.id; }); if (names.length) { const l3 = document.createElement('div'); l3.textContent = '新增:' + names.join('、') + (diff.added.length > 6 ? ' …' : ''); refs.anaDiff.appendChild(l3); } } else { refs.anaDiffTitle.hidden = true; refs.anaDiff.hidden = true; } } function renderLibrary() { if (!refs.libList) return; refs.libList.textContent = ''; const result = state.result; if (!result) { refs.libCount.textContent = '尚未读取'; refs.libList.appendChild(empty('先到「导出」读取库存。')); return; } const q = String(state.query || '').trim().toLowerCase(); let games = (result.games || []).slice(); if (q) { games = games.filter(function (g) { return lower(g.name).indexOf(q) !== -1 || lower(g.gameSlug).indexOf(q) !== -1; }); } const sortBy = CFG.sortBy; games.sort(function (a, b) { if (sortBy === 'playtime') { return (Number(b.playtimeMinutes) || 0) - (Number(a.playtimeMinutes) || 0) || String(a.name || '').localeCompare(String(b.name || ''), 'en'); } if (sortBy === 'acquired') { return String(b.acquiredAt || '').localeCompare(String(a.acquiredAt || '')) || String(a.name || '').localeCompare(String(b.name || ''), 'en'); } return String(a.name || a.originOfferId).localeCompare(String(b.name || b.originOfferId), 'en'); }); const CAP = 300; const shown = games.slice(0, CAP); refs.libCount.textContent = games.length + ' 款' + (games.length > CAP ? '(显示前 ' + CAP + ')' : ''); for (const g of shown) { const row = document.createElement('div'); row.className = 'gi'; const nm = document.createElement('span'); nm.className = 'nm'; nm.textContent = g.name || g.gameSlug || g.originOfferId; nm.title = nm.textContent; row.appendChild(nm); if (g.linkedOnly) { const tag = document.createElement('span'); tag.className = 'tag'; tag.textContent = '关联'; tag.title = '所有权方式仅 STEAM / EPIC'; row.appendChild(tag); } const mt = document.createElement('span'); mt.className = 'mt'; const bits = []; if (g.playtimeMinutes) bits.push(fmtMinutes(g.playtimeMinutes)); if (g.acquiredAt) bits.push(String(g.acquiredAt).slice(0, 10)); if ((g.platforms || []).length) bits.push(g.platforms.join('/')); mt.textContent = bits.join(' · '); row.appendChild(mt); refs.libList.appendChild(row); } if (!shown.length) refs.libList.appendChild(empty('没有匹配的游戏')); } function toast(msg, kind) { if (!refs.toasts) return; const el = document.createElement('div'); el.className = 'toast' + (kind ? ' ' + kind : ''); el.textContent = msg; refs.toasts.appendChild(el); setTimeout(function () { el.classList.add('out'); setTimeout(function () { el.remove(); }, 320); }, 8000); } function log(line, cls) { if (!refs.expLog) return; const el = document.createElement('div'); if (cls) el.className = cls; el.textContent = line; refs.expLog.appendChild(el); while (refs.expLog.childNodes.length > 300) refs.expLog.removeChild(refs.expLog.firstChild); refs.expLog.scrollTop = refs.expLog.scrollHeight; } function logBlock(lines) { lines.forEach(function (line) { log(line); }); toast('自检完成,详见导出页日志', 'ok'); } function progress(pct, label) { if (refs.expBar) refs.expBar.style.width = Math.max(0, Math.min(100, pct)) + '%'; if (refs.expState && label) refs.expState.textContent = label; } function elapsed(sec) { if (refs.expElapsed) refs.expElapsed.textContent = sec >= 0 ? sec.toFixed(1) + 's' : ''; } function setBusy(on) { if (!refs.btnFetch) return; refs.btnFetch.disabled = !!on; refs.btnFetch.textContent = on ? '读取中…' : '读取库存'; const noResult = !!on || !state.result; refs.btnJson.disabled = noResult; refs.btnCsv.disabled = noResult; refs.btnMd.disabled = noResult; refs.btnSum.disabled = noResult; refs.btnDigest.disabled = noResult; refs.btnAnaFetch.disabled = !!on; } function setAccount(text) { if (refs.expAccount) refs.expAccount.textContent = text || '未读取账号'; } function setStats(text) { if (refs.expStats) refs.expStats.textContent = text || ''; } function resetExportView() { setAccount('未读取账号'); setStats(''); if (refs.expLog) refs.expLog.textContent = ''; } return { mount: mount, open: open, close: close, toggle: toggle, switchTab: switchTab, renderSettings: renderSettings, renderAnalysis: renderAnalysis, renderLibrary: renderLibrary, toast: toast, log: log, logBlock: logBlock, progress: progress, elapsed: elapsed, setBusy: setBusy, setAccount: setAccount, setStats: setStats, resetExportView: resetExportView }; })(); // ==================== 启动 ==================== const REMOUNT_INTERVAL = 1500; let remountTimer = null; let hotkeyBound = false; function boot() { // auth.html 是令牌回调页,不挂面板(挂了会挡住 handleToken 的父页逻辑) if (typeof location !== 'undefined' && location.pathname && location.pathname.indexOf(AUTH_PATH) === 0) return; if (document.getElementById('eae-root')) return; if (!document.body) return; ui.mount(); ui.progress(0, '就绪'); } function bootSafely() { try { boot(); } catch (err) { console.error(LOG_PREFIX, '界面挂载失败', err); } } // www.ea.com 是 Next.js 站,客户端 hydration 有可能把注入的节点清掉,定时自检补挂 function watchForRemoval() { if (remountTimer) return; remountTimer = setInterval(function () { if (!document.getElementById('eae-root')) bootSafely(); }, REMOUNT_INTERVAL); } function bindHotkey() { if (hotkeyBound) return; hotkeyBound = true; document.addEventListener('keydown', function (e) { if (e.altKey && !e.ctrlKey && !e.metaKey && (e.key === 'e' || e.key === 'E')) { e.preventDefault(); ui.toggle(); } }); } // 自测句柄:纯函数 + 采集入口,方便无头环境验证 try { window.__eaEnhancer = { version: VERSION, ui: ui, // 供无头预览/调试调用(open/renderAnalysis),不影响脚本行为 parseAuthHash: parseAuthHash, normalizeIsoDate: normalizeIsoDate, normalizeEaPlatform: normalizeEaPlatform, collectPlatforms: collectPlatforms, isDlcOffer: isDlcOffer, isTrialProduct: isTrialProduct, hasResolvableGameProduct: hasResolvableGameProduct, isLinkedOnlyMethods: isLinkedOnlyMethods, dedupeEntitlements: dedupeEntitlements, bucketOf: bucketOf, analyzeLibrary: analyzeLibrary, buildTimeline: buildTimeline, buildYearChartSvg: buildYearChartSvg, buildCsv: buildCsv, buildSummaryCsv: buildSummaryCsv, buildReport: buildReport, buildDigest: buildDigest, makeSnapshot: makeSnapshot, diffSnapshots: diffSnapshots }; } catch (e) { /* 某些沙箱没有 window */ } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { bootSafely(); watchForRemoval(); bindHotkey(); }, { once: true }); } else { bootSafely(); watchForRemoval(); bindHotkey(); } })();