// ==UserScript==
// @name Epic 平台增强
// @name:en Epic Platform Enhancer
// @namespace epic-platform-enhancer
// @version 1.2.0
// @description Epic 会免雷达 + 库存分析:每期价值与倒计时分级、本机领取账本、月度预告、自动提醒与一键打开待领,另有入库时间线分析与 JSON / CSV / Markdown 导出
// @description:en Epic giveaway radar plus library analytics: per-cycle value and countdown buckets, local claim ledger, monthly preview, auto reminders and one-click open, alongside acquisition timeline analysis and JSON / CSV / Markdown export.
// @author SmallRob
// @match https://www.epicgames.com/*
// @match https://store.epicgames.com/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_notification
// @grant GM_openInTab
// @grant GM_setClipboard
// @grant GM_registerMenuCommand
// @grant GM_xmlhttpRequest
// @grant GM.xmlHttpRequest
// @connect store-site-backend-static.ak.epicgames.com
// @connect store-site-backend-static-ipv4.ak.epicgames.com
// @connect www.epicgames.com
// @connect store.epicgames.com
// @connect account-public-service-prod03.ol.epicgames.com
// @connect library-service.live.use1a.on.epicgames.com
// @connect entitlement-public-service-prod08.ol.epicgames.com
// @connect catalog-public-service-prod06.ol.epicgames.com
// @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-epic'%20x1='0'%20y1='0'%20x2='1'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%23001530'/%3E%3Cstop%20offset='100%25'%20stop-color='%23080b12'/%3E%3C/linearGradient%3E%3ClinearGradient%20id='epic-shield'%20x1='0.1'%20y1='0'%20x2='0.9'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%234fb0ff'/%3E%3Cstop%20offset='45%25'%20stop-color='%230074e4'/%3E%3Cstop%20offset='100%25'%20stop-color='%230a3f8f'/%3E%3C/linearGradient%3E%3ClinearGradient%20id='epic-white'%20x1='0'%20y1='0'%20x2='0'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%23ffffff'/%3E%3Cstop%20offset='100%25'%20stop-color='%23cfe6ff'/%3E%3C/linearGradient%3E%3ClinearGradient%20id='countdown'%20x1='0'%20y1='0'%20x2='1'%20y2='0'%3E%3Cstop%20offset='0%25'%20stop-color='%23ff5a5a'/%3E%3Cstop%20offset='100%25'%20stop-color='%23f5a623'/%3E%3C/linearGradient%3E%3Cfilter%20id='glow-epic'%20x='-30%25'%20y='-30%25'%20width='160%25'%20height='160%25'%3E%3CfeGaussianBlur%20stdDeviation='1.6'%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-epic)'/%3E%3Cellipse%20cx='32'%20cy='10'%20rx='22'%20ry='7'%20fill='%230074e4'%20opacity='0.22'/%3E%3Cg%20filter='url(%23glow-epic)'%3E%3Cpath%20d='M%2032%207%20L%2051%2014.5%20V%2032%20C%2051%2043.5%2042.5%2051%2032%2056.5%20C%2021.5%2051%2013%2043.5%2013%2032%20V%2014.5%20Z'%20fill='url(%23epic-shield)'/%3E%3Cpath%20d='M%2032%207%20L%2051%2014.5%20V%2032%20C%2051%2043.5%2042.5%2051%2032%2056.5%20C%2021.5%2051%2013%2043.5%2013%2032%20V%2014.5%20Z'%20fill='none'%20stroke='%23ffffff'%20stroke-opacity='0.35'%20stroke-width='1.2'/%3E%3Crect%20x='24'%20y='20.5'%20width='5'%20height='24'%20rx='1.5'%20fill='url(%23epic-white)'/%3E%3Crect%20x='24'%20y='20.5'%20width='17'%20height='5'%20rx='1.5'%20fill='url(%23epic-white)'/%3E%3Crect%20x='24'%20y='30'%20width='13.5'%20height='4.5'%20rx='1.5'%20fill='url(%23epic-white)'%20opacity='0.92'/%3E%3Crect%20x='24'%20y='39.5'%20width='16'%20height='5'%20rx='1.5'%20fill='url(%23epic-white)'%20opacity='0.86'/%3E%3C/g%3E%3Cg%20transform='translate(48,%2016)'%3E%3Ccircle%20r='10.5'%20fill='%23080b12'/%3E%3Ccircle%20r='8.4'%20fill='url(%23countdown)'/%3E%3Cline%20x1='0'%20y1='0'%20x2='0'%20y2='-5'%20stroke='%23ffffff'%20stroke-width='1.8'%20stroke-linecap='round'/%3E%3Cline%20x1='0'%20y1='0'%20x2='4'%20y2='0.5'%20stroke='%23ffffff'%20stroke-width='1.4'%20stroke-linecap='round'/%3E%3Ccircle%20r='1.3'%20fill='%23ffffff'/%3E%3C/g%3E%3Ccircle%20cx='10'%20cy='53'%20r='3.4'%20fill='none'%20stroke='%234fb0ff'%20stroke-width='1.6'%20opacity='0.85'/%3E%3Cpath%20d='M%208.2%2053%20L%209.6%2054.6%20L%2012%2051.6'%20fill='none'%20stroke='%234fb0ff'%20stroke-width='1.6'%20stroke-linecap='round'%20stroke-linejoin='round'/%3E%3C/svg%3E
// ==/UserScript==
(function () {
'use strict';
const VERSION = '1.2.0';
const LOG_PREFIX = '[Epic 助手]';
const STORE = 'https://store.epicgames.com';
// 公开的 EGS 启动器客户端凭据(legendary / Heroic 等项目使用的同一组,不是私人密钥)
const CLIENT_ID = '34a02cf8f4414e29b15921876da36f9a';
const CLIENT_SECRET = 'daafbccc737745039dffe53d94fc76cf';
const OAUTH_HOST = 'https://account-public-service-prod03.ol.epicgames.com';
const LIBRARY_HOST = 'https://library-service.live.use1a.on.epicgames.com';
const ENTITLEMENT_HOST = 'https://entitlement-public-service-prod08.ol.epicgames.com';
const CATALOG_HOST = 'https://catalog-public-service-prod06.ol.epicgames.com';
const SCHEMA_VERSION = 1;
// 会免账本:按「商品 id + 本期开始时间」归档,跨刷新累积,登录后不清空
const LEDGER_KEY = 'epe.freeLedger';
const LEDGER_MAX = 400;
const LOCALES = { CN: 'zh-CN', US: 'en-US', JP: 'ja-JP', GB: 'en-GB', DE: 'de-DE' };
const CFG_DEFAULTS = {
autoCheck: true, // 打开 Epic 页面时自动检查
intervalMin: 60, // 自动检查间隔(分钟)
desktopNotify: true, // 系统通知
toast: true, // 页面内提醒
background: true, // 一键领取时在后台标签页打开
country: 'CN' // 商店区域,决定币种与语言
};
// ==================== 存储 ====================
function getStored(key, fallback) {
try {
if (typeof GM_getValue !== 'function') return fallback;
const raw = GM_getValue(key, '');
if (raw === '' || raw === undefined || raw === null) return fallback;
if (typeof raw === 'string') {
try { return JSON.parse(raw); } catch (e) { return fallback; }
}
return raw;
} catch (e) { return fallback; }
}
function setStored(key, value) {
try {
if (typeof GM_setValue === 'function') GM_setValue(key, JSON.stringify(value));
} catch (e) { /* 存储不可用时只影响持久化,不影响本次使用 */ }
}
const CFG = Object.assign({}, CFG_DEFAULTS, getStored('epe.cfg', {}));
if (!LOCALES[CFG.country]) CFG.country = 'CN';
CFG.intervalMin = Math.max(5, Number(CFG.intervalMin) || 60);
['autoCheck', 'desktopNotify', 'toast', 'background'].forEach(function (k) {
if (typeof CFG[k] !== 'boolean') CFG[k] = CFG_DEFAULTS[k];
});
const state = {
cfg: CFG,
free: { at: 0, country: '', current: [], upcoming: [], stale: false },
ledger: { version: 1, items: {} },
freeFilter: 'all',
notified: {},
checking: false,
running: false,
result: null,
diff: null,
timer: null,
startedAt: 0,
ticker: null
};
(function restoreCache() {
const cached = getStored('epe.free', null);
if (cached && typeof cached === 'object') {
state.free = {
at: Number(cached.at) || 0,
country: cached.country || '',
current: Array.isArray(cached.current) ? cached.current : [],
upcoming: Array.isArray(cached.upcoming) ? cached.upcoming : [],
stale: !!cached.stale
};
}
const notified = getStored('epe.notified', null);
if (notified && typeof notified === 'object' && !Array.isArray(notified)) {
state.notified = notified;
}
const ledger = getStored(LEDGER_KEY, null);
if (ledger && ledger.items && typeof ledger.items === 'object') {
state.ledger = { version: 1, items: ledger.items };
}
})();
function saveCfg() {
setStored('epe.cfg', CFG);
}
// ==================== 通用工具 ====================
function sleep(ms) {
return new Promise(function (r) { setTimeout(r, ms); });
}
function shortUrl(u) {
return String(u).replace(/^https?:\/\//, '').slice(0, 60);
}
function pad2(n) {
return n < 10 ? '0' + n : String(n);
}
function parseJson(text, what) {
try { return JSON.parse(text); }
catch (e) { throw new Error(what + ' 返回非 JSON(可能被拦截,请刷新页面重试)'); }
}
function fmtAgo(ts) {
if (!ts) return '';
const diff = Date.now() - ts;
if (diff < 60000) return '刚刚';
const m = Math.floor(diff / 60000);
if (m < 60) return m + ' 分钟前';
const h = Math.floor(m / 60);
if (h < 24) return h + ' 小时前';
return Math.floor(h / 24) + ' 天前';
}
function fmtStart(iso) {
if (!iso) return '开始时间待定';
const d = new Date(iso);
if (!isFinite(d.getTime())) return '开始时间待定';
const now = new Date();
const head = d.getFullYear() !== now.getFullYear() ? d.getFullYear() + '年' : '';
return head + (d.getMonth() + 1) + '月' + d.getDate() + '日 '
+ pad2(d.getHours()) + ':' + pad2(d.getMinutes()) + ' 开始';
}
function fmtRemain(iso) {
if (!iso) return '限时免费';
const end = new Date(iso).getTime();
if (!isFinite(end)) return '限时免费';
const ms = end - Date.now();
if (ms <= 0) return '已结束';
const m = Math.floor(ms / 60000);
const h = Math.floor(m / 60);
const d = Math.floor(h / 24);
if (d > 0) return '剩 ' + d + ' 天 ' + (h % 24) + ' 小时';
if (h > 0) return '剩 ' + h + ' 小时 ' + (m % 60) + ' 分';
return '剩 ' + Math.max(1, m) + ' 分钟';
}
// ==================== 网络层 ====================
// 同时兼容 GM4 / 旧版 GM_xmlhttpRequest。XMonkey 等实现里 GM.xmlHttpRequest
// 可能「存在、可调用、但 Promise 解出来是 undefined」,所以两条通道都挂回调,
// 并用一次真实失败记住 GM4 不可用,后续直接走旧接口。
function okStatus(st) {
return typeof st === 'number' && st >= 200 && st < 300;
}
function networkError(what, url) {
const err = new Error(what + ' · ' + shortUrl(url));
err.status = undefined;
return err;
}
function httpFailure(res, url) {
const st = res && res.status;
if (typeof st === 'number' && st >= 100 && st <= 599) {
const err = new Error('HTTP ' + st + ' · ' + shortUrl(url));
err.status = st;
return err;
}
if (typeof st === 'number' && st <= 0) {
return networkError('网络请求失败(status ' + st + ')', url);
}
const err = new Error('没拿到 HTTP 响应(响应对象里没有 status)· ' + shortUrl(url)
+ ' · 请确认脚本由 Tampermonkey 运行');
err.envProblem = true;
return err;
}
let gm4Broken = false;
function hasGm4() {
try {
return typeof GM !== 'undefined' && !!GM && typeof GM.xmlHttpRequest === 'function';
} catch (e) { return false; }
}
function hasLegacy() {
return typeof GM_xmlhttpRequest === 'function';
}
function gm4Request(cfg, url) {
return new Promise(function (resolve, reject) {
let settled = false;
let graceTimer = null;
let finalTimer = null;
function clearTimers() {
if (graceTimer) { clearTimeout(graceTimer); graceTimer = null; }
if (finalTimer) { clearTimeout(finalTimer); finalTimer = null; }
}
function finish(fn, v) {
if (settled) return;
settled = true;
clearTimers();
fn(v);
}
function settle(r) {
if (!okStatus(r && r.status)) return finish(reject, httpFailure(r, url));
finish(resolve, r.responseText);
}
const timeoutMs = cfg.timeout || 20000;
finalTimer = setTimeout(function () {
finish(reject, networkError('请求超时', url));
}, timeoutMs + 1000);
let p;
try {
p = GM.xmlHttpRequest(Object.assign({}, cfg, {
onload: function (r) { settle(r); },
onerror: function () { finish(reject, networkError('网络错误', url)); },
ontimeout: function () { finish(reject, networkError('请求超时', url)); }
}));
} catch (e) {
finish(reject, e);
return;
}
if (p && typeof p.then === 'function') {
p.then(function (r) {
if (okStatus(r && r.status)) return finish(resolve, r.responseText);
if (settled) return;
// Promise 已 resolve 却没有 status:给回调一个很短的宽限,等不到就判环境问题
graceTimer = setTimeout(function () { settle(r); }, 500);
}, function (e) { finish(reject, e); });
}
});
}
function legacyRequest(cfg, url) {
return new Promise(function (resolve, reject) {
GM_xmlhttpRequest(Object.assign({}, cfg, {
onload: function (r) {
if (okStatus(r && r.status)) return resolve(r.responseText);
reject(httpFailure(r, url));
},
onerror: function () { reject(networkError('网络错误', url)); },
ontimeout: function () { reject(networkError('请求超时', url)); }
}));
});
}
function httpOnce(cfg, url) {
const canGm4 = hasGm4() && !gm4Broken;
const canLegacy = hasLegacy();
if (canGm4) {
let p;
try {
p = gm4Request(cfg, url);
} catch (e) {
if (!canLegacy) throw e;
p = Promise.reject(e);
}
if (!canLegacy) return p;
return p.catch(function (e) {
if (!(e && e.envProblem)) throw e;
gm4Broken = true;
return legacyRequest(cfg, url);
});
}
if (canLegacy) return legacyRequest(cfg, url);
const err = new Error('未检测到 GM 请求接口,请确认脚本由 Tampermonkey 运行');
err.envProblem = true;
throw err;
}
async function httpText(url, opts) {
const RETRIES = (opts && opts.retries !== undefined) ? opts.retries : 2;
const cfg = Object.assign({ method: 'GET', timeout: 25000, url: url }, opts || {});
delete cfg.retries;
let lastErr;
for (let attempt = 0; attempt <= RETRIES; attempt++) {
try {
return await httpOnce(cfg, url);
} catch (e) {
lastErr = e;
const st = e && e.status;
const retryable = !(e && e.envProblem) && (st === 429 || st === 500 || st === 502 ||
st === 503 || st === 504 || st === undefined);
if (attempt === RETRIES || !retryable) break;
const backoff = (st === 429 ? 1200 : 300) * Math.pow(2, attempt);
await sleep(backoff + Math.random() * 150);
}
}
throw lastErr;
}
async function pool(items, limit, worker) {
let idx = 0;
const runners = [];
const n = Math.min(limit, items.length);
for (let k = 0; k < n; k++) {
runners.push((async function () {
while (true) {
const i = idx++;
if (i >= items.length) return;
await worker(items[i], i);
}
})());
}
await Promise.all(runners);
}
// ==================== 限免数据 ====================
function freeApiUrls(country) {
const c = LOCALES[country] ? country : 'CN';
const loc = LOCALES[c];
const q = 'locale=' + loc + '&country=' + c + '&allowCountries=' + c;
return [
'https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?' + q,
'https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions?' + q
];
}
function pickImage(game) {
const imgs = (game && game.keyImages) || [];
const prefer = ['OfferImageWide', 'DieselStoreFrontWide', 'Thumbnail', 'OfferImageTall'];
for (const type of prefer) {
const hit = imgs.find(function (img) { return img && img.type === type && img.url; });
if (hit) return hit.url;
}
const any = imgs.find(function (img) { return img && img.url; });
return any ? any.url : '';
}
function gameLink(game) {
const maps = (game && game.catalogNs && game.catalogNs.mappings) || [];
const offers = (game && game.catalogNs && game.catalogNs.offerMappings) || [];
const home = maps.find(function (m) { return m && m.pageType === 'productHome'; });
const chosen = home || offers[0] || maps[0] || null;
let slug = (chosen && chosen.pageSlug) || (game && game.productSlug) || (game && game.urlSlug) || '';
slug = String(slug).replace(/\/home\/?$/i, '').replace(/^\/+/, '').trim();
if (!slug) return STORE + '/free-games';
const type = String((chosen && chosen.pageType) || '');
const prefix = /bundle/i.test(type) ? '/bundles/' : '/p/';
return STORE + prefix + encodeURI(slug);
}
function isPriceFree(game) {
const tp = game && game.price && game.price.totalPrice;
if (!tp) return false;
return typeof tp.originalPrice === 'number' && typeof tp.discountPrice === 'number'
&& tp.originalPrice > 0 && tp.discountPrice === 0;
}
function originalPriceText(game) {
const tp = game && game.price && game.price.totalPrice;
if (!tp) return '';
const fmt = tp.fmtPrice;
if (fmt && typeof fmt.originalPrice === 'string') {
const s = fmt.originalPrice.trim();
if (s && !/^0([.,]0+)?$/.test(s) && !/^(免费|free)$/i.test(s)) return s;
}
if (typeof tp.originalPrice === 'number' && tp.originalPrice > 0) {
return (tp.originalPrice / 100).toFixed(2);
}
return '';
}
// 0% 折扣窗口:promotionalOffers 与 upcomingPromotionalOffers 的结构相同,
// 用 start/end 与当前时间的关系区分「正在免费」和「即将免费」。
function collectFreeWindows(game, now) {
const out = { current: null, upcoming: [] };
const promos = game && game.promotions;
if (!promos) return out;
const groups = (promos.promotionalOffers || []).concat(promos.upcomingPromotionalOffers || []);
for (const group of groups) {
const offers = (group && group.promotionalOffers) || [];
for (const offer of offers) {
const pct = offer && offer.discountSetting && offer.discountSetting.discountPercentage;
if (pct !== 0) continue;
const s = Date.parse(offer.startDate);
const e = Date.parse(offer.endDate);
if (!isFinite(s) || !isFinite(e) || e <= now) continue;
if (s <= now) {
if (!out.current || e > out.current.endMs) {
out.current = { start: offer.startDate, end: offer.endDate, startMs: s, endMs: e };
}
} else {
out.upcoming.push({ start: offer.startDate, end: offer.endDate, startMs: s, endMs: e });
}
}
}
out.upcoming.sort(function (a, b) { return a.startMs - b.startMs; });
return out;
}
function parseFreeElements(elements, now) {
const at = now || Date.now();
const cur = new Map();
const up = new Map();
for (const game of elements || []) {
if (!game || !game.id) continue;
if (game.status && game.status !== 'ACTIVE') continue;
const win = collectFreeWindows(game, at);
let current = win.current;
// 兜底:促销字段缺失,但价格确实是「原价 > 0,现价 0」
if (!current && isPriceFree(game)) current = { start: null, end: null };
const base = {
id: String(game.id),
title: game.title || '未知游戏',
description: game.description || '',
cover: pickImage(game),
url: gameLink(game),
originalPrice: originalPriceText(game)
};
if (current) {
cur.set(base.id, Object.assign(base, {
kind: 'current',
start: current.start || null,
end: current.end || null
}));
} else if (win.upcoming.length) {
const first = win.upcoming[0];
if (!up.has(base.id)) {
up.set(base.id, Object.assign(base, {
kind: 'upcoming',
start: first.start || null,
end: first.end || null
}));
}
}
}
for (const id of cur.keys()) up.delete(id);
const current = Array.from(cur.values()).sort(function (a, b) {
const ae = a.end ? Date.parse(a.end) : Infinity;
const be = b.end ? Date.parse(b.end) : Infinity;
return ae - be;
});
const upcoming = Array.from(up.values()).sort(function (a, b) {
return Date.parse(a.start || 0) - Date.parse(b.start || 0);
});
return { current: current, upcoming: upcoming };
}
// ==================== 会免账本与领取分析 ====================
// 倒计时分级:3 天内 / 7 天内 / 还早 / 无截止(长期免费)/ 已过期
const FREE_BUCKETS = [
{ key: 'urgent', label: '3 天内', days: 3 },
{ key: 'soon', label: '7 天内', days: 7 },
{ key: 'later', label: '还早', days: Infinity },
{ key: 'open', label: '无截止', days: Infinity },
{ key: 'expired', label: '已过期', days: 0 }
];
const CURRENCY_SYMBOL = { CNY: '¥', USD: '$', EUR: '€', GBP: '£', JPY: '¥', KRW: '₩', RUB: '₽' };
function bucketLabel(key) {
const hit = FREE_BUCKETS.find(function (b) { return b.key === key; });
return hit ? hit.label : key;
}
// 原价统一折成「元」:Epic 给的是最小货币单位(分),fmtPrice 是本地化字符串
function parsePriceValue(game) {
const tp = game && game.price && game.price.totalPrice;
if (!tp) return { value: 0, currency: '' };
const currency = tp.currencyCode || '';
if (typeof tp.originalPrice === 'number' && tp.originalPrice > 0) {
return { value: tp.originalPrice / 100, currency: currency };
}
return { value: 0, currency: currency };
}
function freeBucket(endIso, now) {
if (!endIso) return 'open';
const end = Date.parse(endIso);
if (!isFinite(end)) return 'open';
const left = end - (now || Date.now());
if (left <= 0) return 'expired';
if (left <= FREE_BUCKETS[0].days * 86400000) return 'urgent';
if (left <= FREE_BUCKETS[1].days * 86400000) return 'soon';
return 'later';
}
function ledgerKey(item) {
return String(item && item.id) + '@' + String((item && item.start) || '');
}
// 会免卡片的日期要按本地时区显示(Epic 给的是带 Z 的 ISO)
function dayOfIso(iso, withTime) {
if (!iso) return '—';
const d = new Date(iso);
if (!isFinite(d.getTime())) return String(iso).slice(0, 10);
const p = function (n) { return n < 10 ? '0' + n : String(n); };
const day = d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate());
return withTime ? day + ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) : day;
}
// Markdown 表格单元格:竖线与换行会把表格撑破
function mdCell(text) {
return String(text === null || text === undefined ? '' : text)
.replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
}
// 快照 → 账本:同一期(key 相同)保留首次发现时间与已领标记,只刷新可变字段
function mergeLedger(ledger, snap, now) {
const at = now || Date.now();
const out = {};
const base = (ledger && ledger.items) ? ledger.items : {};
for (const k of Object.keys(base)) out[k] = base[k];
const list = ((snap && snap.current) || []).concat((snap && snap.upcoming) || []);
for (const g of list) {
if (!g || !g.id) continue;
const key = ledgerKey(g);
const prev = out[key] || null;
const price = parsePriceValue(g);
out[key] = {
key: key,
id: String(g.id),
title: g.title || '未知游戏',
cover: g.cover || '',
url: g.url || '',
originalPrice: g.originalPrice || '',
value: price.value,
currency: price.currency,
start: g.start || null,
end: g.end || null,
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 };
}
function dominantCurrency(items) {
const map = {};
for (const it of items) {
const c = it.currency || 'UNKNOWN';
map[c] = (map[c] || 0) + 1;
}
let best = '';
let max = 0;
for (const c of Object.keys(map)) {
if (map[c] > max) { max = map[c]; best = c; }
}
return best;
}
function formatMoney(value, currency) {
if (!value) return '¥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 analyzeFree(ledger, snap, now) {
const at = now || Date.now();
const items = Object.keys((ledger && ledger.items) || {}).map(function (k) {
return ledger.items[k];
});
const activeKeys = {};
for (const g of (snap && snap.current) || []) activeKeys[ledgerKey(g)] = true;
const upcomingKeys = {};
for (const g of (snap && snap.upcoming) || []) upcomingKeys[ledgerKey(g)] = true;
const currency = dominantCurrency(items);
const buckets = { urgent: 0, soon: 0, later: 0, open: 0, expired: 0 };
const rows = [];
let valueSum = 0;
let activeValue = 0;
let claimedValue = 0;
let unclaimedValue = 0;
let claimed = 0;
let active = 0;
let upcoming = 0;
let foreignCurrency = 0;
for (const it of items) {
const b = freeBucket(it.end, at);
const isActive = !!activeKeys[it.key] && b !== 'expired';
const isUpcoming = !!upcomingKeys[it.key] && b !== 'expired';
const status = isActive ? 'active' : (isUpcoming ? 'upcoming' : 'expired');
buckets[b] += 1;
if (status === 'active') active += 1;
if (status === 'upcoming') upcoming += 1;
if (it.claimedAt && it.claimedAt > 0) claimed += 1;
// 价值只统计主币种,混币种单独计数,避免 ¥ + $ 相加的假总额
const sameCurrency = (it.currency || '') === (currency || '');
if (!sameCurrency && it.value) foreignCurrency += 1;
if (sameCurrency) {
valueSum += it.value || 0;
if (status === 'active') activeValue += it.value || 0;
if (it.claimedAt) claimedValue += it.value || 0;
else unclaimedValue += it.value || 0;
}
rows.push({
key: it.key,
id: it.id,
title: it.title,
cover: it.cover || '',
url: it.url || '',
originalPrice: it.originalPrice || '',
value: it.value || 0,
currency: it.currency || '',
start: it.start || null,
end: it.end || null,
bucket: b,
status: status,
claimed: !!it.claimedAt,
claimedAt: it.claimedAt || null,
firstSeenAt: it.firstSeenAt || null,
leftMs: it.end ? (Date.parse(it.end) - at) : null
});
}
rows.sort(function (a, b) {
const rank = { active: 0, upcoming: 1, expired: 2 };
if (rank[a.status] !== rank[b.status]) return rank[a.status] - rank[b.status];
const ae = a.end ? Date.parse(a.end) : Infinity;
const be = b.end ? Date.parse(b.end) : Infinity;
if (ae !== be) return ae - be;
return String(a.title).localeCompare(String(b.title), 'zh-Hans');
});
// 月度预告:即将上线按开始月份分组,供「官方月度预告」式时间线使用
const byMonth = [];
const monthIndex = {};
for (const r of rows) {
if (r.status !== 'upcoming' || !r.start) continue;
const m = monthOf(r.start);
if (!m) continue;
if (!monthIndex[m]) {
monthIndex[m] = { month: m, items: [] };
byMonth.push(monthIndex[m]);
}
monthIndex[m].items.push(r);
}
byMonth.sort(function (a, b) { return a.month < b.month ? -1 : (a.month > b.month ? 1 : 0); });
for (const m of byMonth) {
m.items.sort(function (a, b) { return String(a.start) < String(b.start) ? -1 : 1; });
}
const tracked = rows.length;
return {
at: at,
currency: currency,
totals: {
tracked: tracked,
active: active,
upcoming: upcoming,
claimed: claimed,
unclaimed: Math.max(0, tracked - claimed),
claimRate: tracked ? Math.round(claimed / tracked * 1000) / 10 : 0,
valueSum: Math.round(valueSum * 100) / 100,
activeValue: Math.round(activeValue * 100) / 100,
claimedValue: Math.round(claimedValue * 100) / 100,
unclaimedValue: Math.round(unclaimedValue * 100) / 100,
foreignCurrency: foreignCurrency
},
buckets: buckets,
rows: rows,
byMonth: byMonth
};
}
function filterFreeItems(analysis, filter) {
const rows = (analysis && analysis.rows) || [];
if (!filter || filter === 'all') return rows;
if (filter === 'active') return rows.filter(function (r) { return r.status === 'active'; });
if (filter === 'urgent') return rows.filter(function (r) { return r.status === 'active' && (r.bucket === 'urgent' || r.bucket === 'soon'); });
if (filter === 'claimed') return rows.filter(function (r) { return r.claimed; });
if (filter === 'expired') return rows.filter(function (r) { return r.status === 'expired'; });
return rows;
}
function buildFreeCsv(analysis) {
const head = ['游戏', '状态', '领取状态', '倒计时分级', '原价', '币种', '开始', '截止', '剩余小时', '首次发现', '已领时间', '链接'];
const statusText = { active: '可领取', upcoming: '即将开始', expired: '已过期' };
const lines = [head.map(csvCell).join(',')];
for (const r of (analysis && analysis.rows) || []) {
lines.push([
r.title,
statusText[r.status] || r.status,
r.claimed ? '已领' : '未领',
bucketLabel(r.bucket),
r.value ? r.value.toFixed(2) : '',
r.currency || '',
r.start ? r.start.slice(0, 10) : '',
r.end ? r.end.slice(0, 10) : '',
r.leftMs === null || r.leftMs === undefined ? '' : Math.max(0, Math.round(r.leftMs / 3600000)),
r.firstSeenAt ? new Date(r.firstSeenAt).toISOString().slice(0, 10) : '',
r.claimedAt ? new Date(r.claimedAt).toISOString().slice(0, 10) : '',
r.url
].map(csvCell).join(','));
}
return '\uFEFF' + lines.join('\r\n') + '\r\n';
}
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('| 当前可领 | ' + t.active + ' |');
lines.push('| 3 天内截止 | ' + analysis.buckets.urgent + ' |');
lines.push('| 已标记领取 | ' + t.claimed + '(' + t.claimRate + '%) |');
lines.push('| 累计价值 | ' + formatMoney(t.valueSum, analysis.currency)
+ '(已领 ' + formatMoney(t.claimedValue, analysis.currency) + ') |');
lines.push('');
const activeRows = analysis.rows.filter(function (r) { return r.status === 'active' || r.status === 'upcoming'; });
if (activeRows.length) {
lines.push('| 游戏 | 状态 | 原价 | 开始 | 截止 | 已领 |');
lines.push('| --- | --- | --- | --- | --- | --- |');
for (const r of activeRows.slice(0, 40)) {
lines.push('| ' + mdCell(r.title) + ' | ' + (r.status === 'active' ? '可领取' : '即将开始')
+ ' | ' + (r.value ? formatMoney(r.value, r.currency) : '—')
+ ' | ' + (r.start ? r.start.slice(0, 10) : '—')
+ ' | ' + (r.end ? r.end.slice(0, 10) : '长期')
+ ' | ' + (r.claimed ? '是' : '否') + ' |');
}
lines.push('');
}
if (analysis.byMonth.length) {
lines.push('### 即将开始的月份分布');
lines.push('');
for (const m of analysis.byMonth) {
lines.push('- ' + m.month + ':' + m.items.map(function (r) { return r.title; }).join('、'));
}
lines.push('');
}
return lines.join('\n');
}
async function fetchFreeSnapshot(country) {
let lastErr = null;
// 当前区域没数据时再试一次美区,避免区域过滤导致「什么都没有」
const order = country === 'US' ? ['US'] : [country, 'US'];
for (const c of order) {
for (const url of freeApiUrls(c)) {
try {
const text = await httpText(url, {
headers: { Accept: 'application/json' },
timeout: 20000,
retries: 1
});
const json = parseJson(text, '限免接口');
const elements = json && json.data && json.data.Catalog
&& json.data.Catalog.searchStore && json.data.Catalog.searchStore.elements;
if (!Array.isArray(elements)) throw new Error('限免接口返回结构异常');
const parsed = parseFreeElements(elements, Date.now());
if (!parsed.current.length && !parsed.upcoming.length && c !== order[order.length - 1]) {
continue;
}
return {
country: c,
current: parsed.current,
upcoming: parsed.upcoming
};
} catch (e) {
lastErr = e;
console.warn(LOG_PREFIX, '限免接口失败', url, e);
}
}
}
throw lastErr || new Error('限免接口全部不可用');
}
// ==================== 提醒 ====================
function pruneNotified(map) {
const keys = Object.keys(map);
if (keys.length <= 80) return map;
keys.sort(function (a, b) { return (map[b].at || 0) - (map[a].at || 0); });
keys.slice(80).forEach(function (k) { delete map[k]; });
return map;
}
function notifyFree(current) {
if (!current || !current.length) return;
const seen = state.notified || {};
const now = Date.now();
const fresh = current.filter(function (g) {
const rec = seen[g.id];
return !rec || rec.end !== (g.end || '');
});
// 同一促销期只提醒一次;换了结束时间 = 新一期,会再次提醒
for (const g of current) {
seen[g.id] = { end: g.end || '', at: now };
}
state.notified = pruneNotified(seen);
setStored('epe.notified', state.notified);
if (!fresh.length) return;
const names = fresh.map(function (g) { return g.title; }).join('、');
const text = names.length > 160 ? names.slice(0, 157) + '…' : names;
if (CFG.desktopNotify) {
try {
if (typeof GM_notification === 'function') {
GM_notification({
title: 'Epic 限时免费',
text: text,
image: fresh[0].cover || undefined,
timeout: 15000,
onclick: function () { openAll(fresh); }
});
}
} catch (e) { console.warn(LOG_PREFIX, '桌面通知失败', e); }
}
if (CFG.toast) {
ui.toast('Epic 限免:' + text, 'gift', function () { openAll(fresh); });
}
}
function openGame(game) {
const url = (game && game.url) || (STORE + '/free-games');
if (typeof GM_openInTab === 'function') {
try {
GM_openInTab(url, { active: !CFG.background, insert: true });
return;
} catch (e) { /* 落到 window.open */ }
}
window.open(url, '_blank', 'noopener');
}
function openAll(list) {
(list || []).forEach(openGame);
}
async function copyText(text) {
if (typeof GM_setClipboard === 'function') {
try { GM_setClipboard(text, 'text'); return true; } catch (e) { /* 继续 */ }
}
try {
await navigator.clipboard.writeText(text);
return true;
} catch (e) { return false; }
}
// ==================== 界面 ====================
const ui = (function () {
let shadow = null;
const refs = {};
let currentTab = 'free';
function mount() {
const host = document.createElement('div');
host.id = 'epe-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 = `
尚未检查
读取账号真实库存(含从未产生订单的入库记录),在本机生成 JSON / CSV,不上传任何数据。需先登录 Epic 官网。
就绪
未读取账号
尚无数据
年度入库分布
平台分布
数据审计
与上次导出对比
`;
(document.body || document.documentElement).appendChild(host);
shadow = root;
refs.panel = root.getElementById('panel');
refs.fab = root.getElementById('fab');
refs.badge = root.getElementById('badge');
refs.freeStatus = root.getElementById('freeStatus');
refs.freeList = root.getElementById('freeList');
refs.freeKpis = root.getElementById('freeKpis');
refs.freeChips = root.getElementById('freeChips');
refs.refresh = root.getElementById('btnRefresh');
refs.claimAll = root.getElementById('btnClaimAll');
refs.copy = root.getElementById('btnCopy');
refs.btnFreeCsv = root.getElementById('btnFreeCsv');
refs.btnFreeMd = root.getElementById('btnFreeMd');
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.anaState = root.getElementById('anaState');
refs.anaKpis = root.getElementById('anaKpis');
refs.anaYears = root.getElementById('anaYears');
refs.anaPlatforms = root.getElementById('anaPlatforms');
refs.anaAudit = root.getElementById('anaAudit');
refs.anaDiff = root.getElementById('anaDiff');
refs.anaDiffTitle = root.getElementById('anaDiffTitle');
refs.setAuto = root.getElementById('setAuto');
refs.setInterval = root.getElementById('setInterval');
refs.setNotify = root.getElementById('setNotify');
refs.setToast = root.getElementById('setToast');
refs.setBackground = root.getElementById('setBackground');
refs.setCountry = root.getElementById('setCountry');
refs.toasts = root.getElementById('toasts');
root.getElementById('ver').textContent = 'Epic 助手 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.refresh.addEventListener('click', function () { checkFree(false); });
refs.claimAll.addEventListener('click', function () {
const analysis = state.freeAnalysis || analyzeFree(state.ledger, state.free);
const todo = analysis.rows.filter(function (r) {
return r.status === 'active' && !r.claimed;
});
openAll(todo);
});
refs.copy.addEventListener('click', function () { copyList(); });
refs.btnFreeCsv.addEventListener('click', function () { exportFreeCsv(); });
refs.btnFreeMd.addEventListener('click', function () { exportFreeMd(); });
refs.btnFetch.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.btnAnaFetch.addEventListener('click', function () { runExport(); });
refs.setAuto.addEventListener('change', function () {
updateCfg('autoCheck', refs.setAuto.checked);
});
refs.setInterval.addEventListener('change', function () {
updateCfg('intervalMin', Math.max(5, Number(refs.setInterval.value) || 60));
});
refs.setNotify.addEventListener('change', function () {
updateCfg('desktopNotify', refs.setNotify.checked);
});
refs.setToast.addEventListener('change', function () {
updateCfg('toast', refs.setToast.checked);
});
refs.setBackground.addEventListener('change', function () {
updateCfg('background', refs.setBackground.checked);
});
refs.setCountry.addEventListener('change', function () {
updateCfg('country', refs.setCountry.value);
});
root.getElementById('btnCheckNow').addEventListener('click', function () { checkFree(false); });
root.getElementById('btnClearCache').addEventListener('click', function () {
state.free = { at: 0, country: '', current: [], upcoming: [], stale: false };
setStored('epe.free', null);
renderFree();
toast('限免缓存已清除', 'ok');
});
root.getElementById('btnResetNotify').addEventListener('click', function () {
state.notified = {};
setStored('epe.notified', {});
toast('提醒记录已重置,下次检查会重新提醒', 'ok');
});
log('就绪。确认已在 Epic 官网登录后点「读取库存」。');
}
function open(tab) {
if (!refs.panel) return;
refs.panel.hidden = false;
if (tab) switchTab(tab);
else renderFree();
}
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') renderFree();
if (currentTab === 'analysis') renderAnalysis(state.result, state.diff);
if (currentTab === 'settings') renderSettings();
}
function renderSettings() {
if (!refs.setAuto) return;
refs.setAuto.checked = !!CFG.autoCheck;
refs.setInterval.value = String(CFG.intervalMin);
if (!refs.setInterval.value) {
// 自定义间隔(例如手工改过存储)不在下拉项里时补一个临时项
const opt = document.createElement('option');
opt.value = String(CFG.intervalMin);
opt.textContent = CFG.intervalMin + ' 分钟';
refs.setInterval.appendChild(opt);
refs.setInterval.value = String(CFG.intervalMin);
}
refs.setNotify.checked = !!CFG.desktopNotify;
refs.setToast.checked = !!CFG.toast;
refs.setBackground.checked = !!CFG.background;
refs.setCountry.value = CFG.country;
}
function badge(n) {
if (!refs.badge) return;
refs.badge.textContent = n > 99 ? '99+' : String(n);
refs.badge.classList.toggle('show', n > 0);
}
function empty(text) {
const el = document.createElement('div');
el.className = 'empty';
el.textContent = text;
return el;
}
function section(title, rows, note) {
if (!rows.length) return;
const h = document.createElement('div');
h.className = 'sec';
h.textContent = title + ' · ' + rows.length + (note ? '(' + note + ')' : '');
refs.freeList.appendChild(h);
rows.forEach(function (r) { refs.freeList.appendChild(card(r)); });
}
// 倒计时分级 → 标签样式:3 天内红色、7 天内橙色、其余灰色
function bucketClass(bucket) {
if (bucket === 'urgent') return 'hot';
if (bucket === 'soon') return 'warn';
if (bucket === 'open') return 'ok';
return 'mute';
}
function card(row) {
const item = document.createElement('div');
item.className = 'card' + (row.status === 'expired' ? ' dim' : '');
if (row.cover) {
const img = document.createElement('img');
img.className = 'thumb';
img.src = row.cover;
img.alt = '';
img.loading = 'lazy';
img.referrerPolicy = 'no-referrer';
img.addEventListener('error', function () {
const ph = document.createElement('div');
ph.className = 'ph';
ph.textContent = (row.title || 'E').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 = (row.title || 'E').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 = row.title;
name.title = row.title;
meta.appendChild(name);
const price = document.createElement('div');
price.className = 'price';
if (row.value) {
const s = document.createElement('s');
s.textContent = row.originalPrice || formatMoney(row.value, row.currency);
price.appendChild(s);
}
const free = document.createElement('span');
free.className = row.status === 'upcoming' ? 'up' : 'free';
free.textContent = row.status === 'upcoming' ? '即将免费' : '免费';
price.appendChild(free);
if (row.status === 'active' && !row.claimed) {
const tag = document.createElement('span');
tag.className = 'tag ' + bucketClass(row.bucket);
tag.textContent = bucketLabel(row.bucket);
price.appendChild(tag);
}
if (row.claimed) {
const tag = document.createElement('span');
tag.className = 'tag ok';
tag.textContent = '已领';
price.appendChild(tag);
}
meta.appendChild(price);
const time = document.createElement('div');
time.className = 'time';
if (row.status === 'active') {
time.textContent = row.end ? fmtRemain(row.end) : '长期免费';
if (row.bucket === 'urgent') time.classList.add('urgent');
} else if (row.status === 'upcoming') {
time.textContent = fmtStart(row.start);
} else {
time.textContent = row.end ? '已结束 · ' + dayOfIso(row.end) : '已结束';
}
meta.appendChild(time);
const sub = document.createElement('div');
sub.className = 'sub';
const bits = [];
if (row.end) bits.push('截止 ' + dayOfIso(row.end, true));
if (!row.value && row.originalPrice) bits.push('原价 ' + row.originalPrice);
if (row.firstSeenAt) bits.push('首次发现 ' + dayOfIso(new Date(row.firstSeenAt).toISOString()));
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' + (row.status === 'active' ? '' : ' alt');
btn.textContent = row.status === 'active' ? '领取' : '查看';
btn.addEventListener('click', function () { openGame(row); });
ops.appendChild(btn);
// 只在「正在免费」时给「标记已领」:没开始的期数还没法领,过期了也领不到
if (row.status === 'active') {
const mark = document.createElement('button');
mark.className = 'mark' + (row.claimed ? ' on' : '');
mark.textContent = row.claimed ? '✓ 已领' : '标记已领';
mark.title = row.claimed ? '点击取消标记' : '记录到本地账本(不会真的去 Epic 领取)';
mark.addEventListener('click', function () { toggleClaimed(row.key); });
ops.appendChild(mark);
}
item.appendChild(ops);
return item;
}
function renderFree() {
if (!refs.freeList) return;
const snap = state.free;
const analysis = analyzeFree(state.ledger, snap);
state.freeAnalysis = analysis;
const t = analysis.totals;
// 红点只算「当前能领且没标记已领」的,才是真正待办
const todo = analysis.rows.filter(function (r) { return r.status === 'active' && !r.claimed; });
badge(todo.length);
refs.claimAll.disabled = todo.length === 0;
refs.claimAll.textContent = todo.length ? '一键打开待领(' + todo.length + ')' : '一键打开待领';
refs.copy.disabled = analysis.rows.length === 0;
refs.refresh.disabled = state.checking;
refs.refresh.textContent = state.checking ? '检查中…' : '刷新';
if (state.checking) {
refs.freeStatus.textContent = '正在检查限免…';
} else if (!snap.at) {
refs.freeStatus.textContent = '尚未检查';
} else {
let text = fmtAgo(snap.at) + '更新 · 本档 ' + (snap.current || []).length + ' 款';
if ((snap.upcoming || []).length) text += ' · 预告 ' + snap.upcoming.length + ' 款';
if (snap.country && snap.country !== CFG.country) text += ' · ' + snap.country + ' 区数据';
if (snap.stale) text += ' · 上次检查失败';
refs.freeStatus.textContent = text;
}
kpi(refs.freeKpis, [
{ label: '可领取', value: String(t.active) },
{ label: '3 天内截止', value: String(analysis.buckets.urgent) },
{ label: '已标记领取', value: t.claimed + (t.tracked ? ' · ' + t.claimRate + '%' : '') },
{ label: t.active ? '本期价值' : '累计价值',
value: formatMoney(t.active ? t.activeValue : t.valueSum, analysis.currency) }
]);
// 筛选芯片带上数量,避免点了才发现是空的
const chips = [
{ key: 'all', text: '全部', n: analysis.rows.length },
{ key: 'active', text: '可领取', n: t.active },
{ key: 'urgent', text: '7 天内', n: analysis.buckets.urgent + analysis.buckets.soon },
{ key: 'claimed', text: '已领', n: t.claimed },
{ key: 'expired', text: '已过期', n: analysis.buckets.expired }
];
if (refs.freeChips) {
refs.freeChips.textContent = '';
for (const c of chips) {
const b = document.createElement('button');
b.className = 'chip' + (state.freeFilter === c.key ? ' on' : '');
b.textContent = c.text + ' ' + c.n;
b.disabled = c.n === 0 && c.key !== 'all';
b.addEventListener('click', function () {
state.freeFilter = c.key;
renderFree();
});
refs.freeChips.appendChild(b);
}
}
refs.freeList.textContent = '';
if (!analysis.rows.length) {
refs.freeList.appendChild(empty(state.checking
? '正在向 Epic 查询限免信息…'
: '当前没有可用的限免数据。\n点右上角「刷新」重试,或在设置里切换商店区域。'));
if (refs.btnFreeCsv) refs.btnFreeCsv.disabled = true;
if (refs.btnFreeMd) refs.btnFreeMd.disabled = true;
return;
}
if (refs.btnFreeCsv) refs.btnFreeCsv.disabled = false;
if (refs.btnFreeMd) refs.btnFreeMd.disabled = false;
const filter = state.freeFilter || 'all';
if (filter === 'all' || filter === 'active' || filter === 'urgent') {
const act = filterFreeItems(analysis, filter).filter(function (r) { return r.status === 'active'; });
const up = filter === 'all' || filter === 'active' || filter === 'urgent'
? analysis.rows.filter(function (r) { return r.status === 'upcoming'; })
: [];
if (!act.length && filter !== 'all') {
refs.freeList.appendChild(empty('这个筛选下没有条目。'));
}
section('当前可领', act);
if (up.length) section('即将开始', up);
if (filter === 'all' && analysis.byMonth.length) {
refs.freeList.appendChild(monthPreview(analysis.byMonth));
}
if (filter === 'all' && analysis.buckets.expired) {
const hint = document.createElement('div');
hint.className = 'hint';
hint.textContent = '账本里还有 ' + analysis.buckets.expired + ' 期已结束的会免,点上面「已过期」查看或导出 CSV。';
refs.freeList.appendChild(hint);
}
} else {
const rows = filterFreeItems(analysis, filter);
section(filter === 'claimed' ? '已标记领取' : '已过期', rows);
if (!rows.length) refs.freeList.appendChild(empty('这个筛选下没有条目。'));
}
}
// 参考「官方月度预告」:按开始月份分组,一行一款,带日期与名称
function monthPreview(byMonth) {
const box = document.createElement('div');
box.className = 'tl';
for (const m of byMonth) {
const h = document.createElement('div');
h.className = 'tl-h';
h.textContent = m.month;
box.appendChild(h);
for (const r of m.items) {
const row = document.createElement('div');
row.className = 'tl-row';
const d = document.createElement('span');
d.className = 'tl-d';
d.textContent = r.start ? r.start.slice(5, 10).replace('-', '/') : '—';
const t = document.createElement('span');
t.className = 'tl-t';
t.textContent = r.title;
t.title = r.title;
row.appendChild(d);
row.appendChild(t);
if (r.value) {
const v = document.createElement('span');
v.className = 'tl-v';
v.textContent = formatMoney(r.value, r.currency);
row.appendChild(v);
}
box.appendChild(row);
}
}
return box;
}
function toggleClaimed(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);
renderFree();
}
// ---- 分析视图 ----
function esc(text) {
return String(text === null || text === undefined ? '' : text)
.replace(/&/g, '&').replace(//g, '>')
.replace(/"/g, '"');
}
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, total) {
if (!container) return;
container.textContent = '';
if (!items.length) {
container.appendChild(empty('暂无数据'));
return;
}
const max = items.reduce(function (m, d) { return Math.max(m, d.count); }, 1);
for (const d of items.slice(0, 8)) {
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 = total ? d.count + ' · ' + Math.round(d.count / total * 100) + '%' : String(d.count);
row.appendChild(lb);
row.appendChild(tr);
row.appendChild(vl);
container.appendChild(row);
}
}
// 年度柱状图:纯 SVG 字符串,不引任何图表库(用户脚本环境没有 bundle 加载器)
function yearChart(container, byYear) {
if (!container) return;
container.textContent = '';
if (!byYear || !byYear.length) {
container.appendChild(empty('还没有带入库时间的记录'));
return;
}
container.innerHTML = buildYearChartSvg(byYear);
}
function renderAnalysis(result, diff) {
if (!refs.anaKpis) return;
if (!result || !result.analysis) {
refs.anaState.textContent = '尚无数据';
refs.anaKpis.textContent = '';
refs.anaYears.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.accountId || '账号')
+ ' · ' + a.totals.games + ' 款 · ' + String(result.generatedAt || '').replace('T', ' ').slice(0, 16);
const spanYears = a.timeline.first && a.timeline.last
? Math.max(1, Math.round(a.timeline.spanDays / 365 * 10) / 10)
: 0;
kpi(refs.anaKpis, [
{ label: '游戏数', value: String(a.totals.games) },
{ label: '入库记录', value: String((result.summary && result.summary.recordCount) || '—') },
{ label: '时间跨度', value: spanYears ? spanYears + ' 年' : '—' },
{ label: '年均入库', value: a.timeline.avgPerYear ? String(a.timeline.avgPerYear) : '—' },
{ label: '峰值年', value: a.timeline.peakYear ? a.timeline.peakYear.year + ' · ' + a.timeline.peakYear.count : '—' },
{ label: '标题解析率', value: a.totals.resolutionRate + '%' }
]);
yearChart(refs.anaYears, a.timeline.byYear);
hbars(refs.anaPlatforms, a.platforms, a.totals.games);
const audit = [];
audit.push('已授权 ' + a.totals.entitled + ' 款 / 未授权 ' + a.totals.notEntitled
+ ' 款 / 未知 ' + a.totals.entitlementUnknown + ' 款');
if (a.totals.unresolved) audit.push('未解析标题 ' + a.totals.unresolved + ' 款(用沙盒名占位)');
if (a.timeline.undated) audit.push('无入库时间 ' + a.timeline.undated + ' 款');
if (a.platformMissing) audit.push('平台未标注 ' + a.platformMissing + ' 款');
if (a.duplicates.length) {
const head = a.duplicates.slice(0, 3).map(function (d) { return d.name + ' ×' + d.count; });
audit.push('疑似重复 ' + a.duplicates.length + ' 组:' + head.join('、')
+ (a.duplicates.length > 3 ? ' …' : ''));
}
if (a.timeline.maxGap && a.timeline.maxGap.days > 0) {
audit.push('最长空档 ' + a.timeline.maxGap.days + ' 天('
+ a.timeline.maxGap.from + ' → ' + a.timeline.maxGap.to + ')');
}
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 line1 = document.createElement('div');
line1.textContent = '较上次(' + String(diff.prevAt).slice(0, 10) + ','
+ diff.prevCount + ' 款)';
const line2 = 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 + ' 移除';
del.style.marginLeft = '8px';
line2.appendChild(add);
line2.appendChild(del);
refs.anaDiff.appendChild(line1);
refs.anaDiff.appendChild(line2);
const names = diff.added.slice(0, 6).map(function (x) { return x.name || x.id; });
if (names.length) {
const line3 = document.createElement('div');
line3.textContent = '新增:' + names.join('、') + (diff.added.length > 6 ? ' …' : '');
refs.anaDiff.appendChild(line3);
}
} else {
refs.anaDiffTitle.hidden = true;
refs.anaDiff.hidden = true;
}
}
function toast(msg, kind, onClick) {
if (!refs.toasts) return;
const el = document.createElement('div');
el.className = 'toast' + (kind ? ' ' + kind : '');
el.textContent = msg;
if (typeof onClick === 'function') {
el.style.cursor = 'pointer';
el.addEventListener('click', function () {
onClick();
el.remove();
});
}
refs.toasts.appendChild(el);
setTimeout(function () {
el.classList.add('out');
setTimeout(function () { el.remove(); }, 320);
}, 12000);
}
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 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 setExportBusy(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;
if (refs.btnAnaFetch) {
refs.btnAnaFetch.disabled = !!on;
refs.btnAnaFetch.textContent = 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,
renderFree: renderFree,
toast: toast,
log: log,
progress: progress,
elapsed: elapsed,
setExportBusy: setExportBusy,
setAccount: setAccount,
setStats: setStats,
resetExportView: resetExportView,
renderAnalysis: renderAnalysis
};
})();
// ==================== 设置 / 调度 ====================
function updateCfg(key, value) {
CFG[key] = value;
saveCfg();
ui.renderSettings();
if (key === 'autoCheck' || key === 'intervalMin') scheduleTimer();
if (key === 'country') checkFree(false);
}
function scheduleTimer() {
if (state.timer) {
clearInterval(state.timer);
state.timer = null;
}
if (!CFG.autoCheck) return;
const ms = Math.max(5, Number(CFG.intervalMin) || 60) * 60000;
state.timer = setInterval(function () {
if (document.visibilityState === 'visible') checkFree(true);
}, ms);
}
async function checkFree(silent) {
if (state.checking) return;
state.checking = true;
ui.renderFree();
try {
const snap = await fetchFreeSnapshot(CFG.country);
state.free = {
at: Date.now(),
country: snap.country,
current: snap.current,
upcoming: snap.upcoming,
stale: false
};
setStored('epe.free', state.free);
// 账本随每次刷新累积:既保留历史期数,也让「首次发现」时间成为真实观测值
state.ledger = mergeLedger(state.ledger, state.free, Date.now());
setStored(LEDGER_KEY, state.ledger);
notifyFree(state.free.current);
if (!silent) {
const n = state.free.current.length;
ui.toast(n ? '检查完成:当前有 ' + n + ' 款限免游戏' : '检查完成:当前没有限免游戏', 'ok');
}
} catch (e) {
state.free.stale = true;
console.warn(LOG_PREFIX, '限免检查失败', e);
if (!silent) {
ui.toast('限免检查失败:' + ((e && e.message) || e), 'err');
}
} finally {
state.checking = false;
ui.renderFree();
}
}
function copyList() {
const analysis = state.freeAnalysis || analyzeFree(state.ledger, state.free);
const act = analysis.rows.filter(function (r) { return r.status === 'active'; });
const up = analysis.rows.filter(function (r) { return r.status === 'upcoming'; });
const lines = [];
if (act.length) {
lines.push('【可领取 ' + act.length + ' 款 · 合计 ' + formatMoney(analysis.totals.valueSum, analysis.currency) + '】');
act.forEach(function (r) {
lines.push('· ' + r.title
+ (r.value ? '(' + formatMoney(r.value, r.currency) + ')' : '')
+ (r.end ? ' 截止 ' + r.end.slice(0, 10) : ' 长期')
+ (r.claimed ? ' [已领]' : '')
+ ' ' + r.url);
});
}
if (up.length) {
lines.push('【即将开始 ' + up.length + ' 款】');
up.forEach(function (r) {
lines.push('· ' + r.title + (r.start ? '(' + r.start.slice(0, 10) + ' 开始)' : '') + ' ' + r.url);
});
}
if (!lines.length) {
ui.toast('目前没有可复制的限免清单', 'err');
return;
}
copyText(lines.join('\n')).then(function (ok) {
ui.toast(ok ? '限免清单已复制' : '复制失败,请手动选择文本', ok ? 'ok' : 'err');
});
}
// ==================== 库存导出 ====================
// 第 1 步:取一次性授权码。站在 www.epicgames.com 上时同源 fetch 最省事,
// 其他子域只能走 GM 并携带目标域 cookie。
async function fetchAuthCode() {
const url = 'https://www.epicgames.com/id/api/redirect'
+ '?clientId=' + CLIENT_ID
+ '&responseType=code';
let text;
if (location.hostname === 'www.epicgames.com') {
try {
const res = await fetch(url, { credentials: 'include', cache: 'no-store' });
if (!res.ok) throw new Error('取授权码失败 HTTP ' + res.status);
text = await res.text();
} catch (e) {
if (/^取授权码失败 HTTP /.test((e && e.message) || '')) throw e;
text = await httpText(url, {
headers: { Accept: 'application/json' },
anonymous: false
});
}
} else {
text = await httpText(url, {
headers: { Accept: 'application/json' },
anonymous: false
});
}
const data = parseJson(text, '授权码接口');
if (!data.authorizationCode) {
throw new Error('未登录。请先在 Epic 官网登录,再回到本页重试');
}
return data.authorizationCode;
}
// 第 2 步:授权码换访问令牌(授权码一次性,每次导出都重新取)
async function exchangeToken(code) {
const body = 'grant_type=authorization_code'
+ '&code=' + encodeURIComponent(code)
+ '&token_type=eg1';
const text = await httpText(OAUTH_HOST + '/account/api/oauth/token', {
method: 'POST',
headers: {
'Authorization': 'basic ' + btoa(CLIENT_ID + ':' + CLIENT_SECRET),
'Content-Type': 'application/x-www-form-urlencoded'
},
data: body
});
const json = parseJson(text, '令牌接口');
if (!json.access_token) throw new Error('换取令牌失败:' + (json.errorCode || '未知原因'));
return json;
}
// 第 3 步(快路径):商城同源 GraphQL,一次请求取回多页库记录与标题。
// 分页 cursor 就是 base64 的 {"offset":N},每页 100 条;需要更多页时再发下一波。
async function fetchLibraryGraphql(onProgress) {
const PAGE = 100;
const WAVE = 8;
const records = [];
const titles = new Map();
for (let wave = 0; wave < 20; wave++) {
const aliases = [];
for (let i = 0; i < WAVE; i++) {
const offset = (wave * WAVE + i) * PAGE;
aliases.push('p' + i + ': libraryItems(cursor: "' + btoa(String(offset)) + '")'
+ ' { records { namespace catalogItemId productId appName sandboxName sandboxType'
+ ' acquisitionDate recordType'
+ ' catalogItem(locale: "en-US") { title releaseInfo { platform } } } }');
}
const query = 'query Q { Library { ' + aliases.join(' ') + ' } }';
const res = await fetch('/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ query: query })
});
if (!res.ok) throw new Error('GraphQL HTTP ' + res.status);
const json = await res.json();
if (json && json.errors && json.errors.length) {
throw new Error(json.errors[0].message || 'GraphQL 返回错误');
}
const lib = json && json.data && json.data.Library;
if (!lib) throw new Error('GraphQL 响应里没有 Library');
let got = 0;
for (let i = 0; i < WAVE; i++) {
const page = lib['p' + i];
const rows = (page && page.records) || [];
got += rows.length;
for (const r of rows) {
const item = r.catalogItem || null;
const platforms = new Set();
if (item && item.releaseInfo) {
for (const rel of item.releaseInfo) {
for (const p of (rel.platform || [])) platforms.add(p);
}
}
if (r.catalogItemId && item && item.title) {
titles.set(r.catalogItemId, item.title);
}
records.push({
namespace: r.namespace,
catalogItemId: r.catalogItemId,
productId: r.productId,
appName: r.appName,
sandboxName: r.sandboxName,
sandboxType: r.sandboxType,
acquisitionDate: r.acquisitionDate,
recordType: r.recordType,
platform: Array.from(platforms)
});
}
}
if (onProgress) onProgress(records.length);
if (got < WAVE * PAGE) break;
}
if (!records.length) throw new Error('GraphQL 返回 0 条库记录');
return { records: records, titles: titles };
}
// 第 3 步(兜底):REST 库接口,按 nextCursor 串行翻页。
// 慢一些,但语义清楚、不会丢页;只有在 GraphQL 不可用时才走这里。
async function fetchLibraryRest(token, onProgress) {
const records = [];
let cursor = null;
for (let page = 0; page < 200; page++) {
let url = LIBRARY_HOST + '/library/api/public/items?includeMetadata=true';
if (cursor) url += '&cursor=' + encodeURIComponent(cursor);
const json = parseJson(await httpText(url, {
headers: { Authorization: 'bearer ' + token }
}), '游戏库接口');
const batch = json.records || [];
records.push.apply(records, batch);
if (onProgress) onProgress(records.length);
const next = json.responseMetadata && json.responseMetadata.nextCursor;
if (!next || !batch.length) break;
cursor = next;
}
return records;
}
// 第 4 步:权益记录(确认条目确实在账号里且为 ACTIVE)
async function fetchEntitlements(token, accountId) {
if (!accountId) throw new Error('令牌响应里没有 account_id');
const out = [];
const PAGE = 100;
const WAVE = 6;
for (let wave = 0; wave < 60; wave++) {
const starts = [];
for (let k = 0; k < WAVE; k++) starts.push((wave * WAVE + k) * PAGE);
const got = [];
await pool(starts, WAVE, async function (start) {
const url = ENTITLEMENT_HOST + '/entitlement/api/account/'
+ encodeURIComponent(accountId)
+ '/entitlements?start=' + start + '&count=' + PAGE;
const json = parseJson(await httpText(url, {
headers: { Authorization: 'bearer ' + token }
}), '权益接口');
got.push({ start: start, batch: Array.isArray(json) ? json : [] });
});
got.sort(function (a, b) { return a.start - b.start; });
for (const r of got) out.push.apply(out, r.batch);
if (got.some(function (r) { return r.batch.length < PAGE; })) break;
}
return out;
}
// 第 5 步(补标题):GraphQL 不可用或部分条目缺标题时,批量查目录。
async function fetchCatalogTitles(token, ids, onProgress) {
const titles = new Map();
let failedBatches = 0;
const BATCH = 30;
const WAVE = 6;
if (!ids.length) return { titles: titles, failedBatches: 0, totalBatches: 0 };
const chunks = [];
for (let i = 0; i < ids.length; i += BATCH) chunks.push(ids.slice(i, i + BATCH));
let done = 0;
for (let i = 0; i < chunks.length; i += WAVE) {
const wave = chunks.slice(i, i + WAVE);
await pool(wave, WAVE, async function (chunk) {
const q = chunk.map(function (id) { return 'id=' + encodeURIComponent(id); }).join('&');
const url = CATALOG_HOST + '/catalog/api/shared/bulk/items?' + q
+ '&country=US&locale=en-US';
let json = null;
try {
json = parseJson(await httpText(url, {
headers: { Authorization: 'bearer ' + token }
}), '目录接口');
} catch (e) {
failedBatches++;
}
if (json) {
for (const id of chunk) {
const item = json[id];
if (!item) continue;
const title = item.title || (item.mainGameItem && item.mainGameItem.title) || null;
if (title) titles.set(id, title);
}
}
done += chunk.length;
if (onProgress) onProgress(done, ids.length);
});
}
return { titles: titles, failedBatches: failedBatches, totalBatches: chunks.length };
}
// Epic 中文目录会给一部分游戏名套《》,按名字对账的第三方工具会被这层噪音干扰
function stripBookTitle(value) {
if (typeof value !== 'string') return value;
if (value.indexOf('\u300A') === -1 && value.indexOf('\u300B') === -1) return value;
const spaced = value.replace(/\u300B/g, ' ').replace(/\u300A/g, ' ').replace(/\s+/g, ' ').trim();
const bare = value.replace(/[\u300A\u300B]/g, '').replace(/\s+/g, ' ').trim();
const wrapped = /^\s*\u300A/.test(value);
return (wrapped ? spaced : bare) || bare || value;
}
function assembleLibrary(lib, ents, entOk, titles) {
const groups = new Map();
for (const r of lib) {
if (!r || !r.namespace) continue;
if (!groups.has(r.namespace)) groups.set(r.namespace, []);
groups.get(r.namespace).push(r);
}
const entByNs = new Set();
if (entOk) {
for (const e of ents) {
if (e && e.namespace) entByNs.add(e.namespace);
}
}
const games = [];
for (const pair of groups) {
const ns = pair[0];
const rows = pair[1];
const first = rows[0] || {};
const cidRow = rows.find(function (r) { return r.catalogItemId; });
const cid = cidRow ? cidRow.catalogItemId : null;
const title = cid ? titles.get(cid) : null;
const dates = rows.map(function (r) { return r.acquisitionDate; })
.filter(Boolean).sort();
const platforms = new Set();
for (const r of rows) {
for (const p of (r.platform || [])) platforms.add(p);
}
const types = new Set();
for (const r of rows) {
if (r.recordType) types.add(r.recordType);
}
games.push({
name: stripBookTitle(title) || first.sandboxName || ns,
namespace: ns,
catalogItemId: cid,
productId: first.productId || null,
sandboxName: first.sandboxName || null,
platforms: Array.from(platforms).sort(),
acquiredAt: dates[0] || null,
recordCount: rows.length,
recordTypes: Array.from(types).sort(),
entitled: entOk ? entByNs.has(ns) : null,
resolved: !!title
});
}
games.sort(function (a, b) {
return String(a.name).localeCompare(String(b.name), 'en');
});
return games;
}
// ==================== 数据聚合分析 ====================
// 纯函数区:只吃 games / 快照,不碰网络与 DOM,方便无头环境逐条断言。
const SNAPSHOT_KEY = 'epe.snapshots';
const SNAPSHOT_MAX = 20;
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 monthOf(iso) {
const d = dayOf(iso);
return d ? d.slice(0, 7) : null;
}
function yearOf(iso) {
const d = dayOf(iso);
return d ? d.slice(0, 4) : null;
}
// 按 keyFn 分组计数,按数量降序、同数量按名称升序(稳定,便于快照对比与测试)
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');
});
}
// 时间线:年度/月度分布、跨度、峰值年、年均、最大空档。
// 没有任何入库时间的条目单独计入 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 });
const m0 = Number(first.slice(5, 7));
let y = y0;
let m = m0;
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;
const monthsActive = byMonth.filter(function (d) { return d.count > 0; }).length;
const avgPerYear = byYear.length
? Math.round(stamps.length / byYear.length * 10) / 10
: 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: monthsActive,
avgPerYear: avgPerYear,
maxGap: maxGap
};
}
// 同名不同命名空间 = 同一款游戏的重复入库条目(Epic 常见:本体 + 不同 sandbox 授权)
function findDuplicateNames(games) {
const seen = new Map();
for (const g of games) {
const key = String(g.name || '').trim().toLowerCase();
if (!key) continue;
if (!seen.has(key)) seen.set(key, []);
seen.get(key).push(g);
}
const out = [];
for (const pair of seen) {
if (pair[1].length < 2) continue;
out.push({
name: pair[1][0].name,
count: pair[1].length,
namespaces: pair[1].map(function (g) { return g.namespace; })
});
}
return out.sort(function (a, b) { return b.count - a.count; });
}
function analyzeLibrary(games) {
const list = Array.isArray(games) ? games : [];
const resolved = list.filter(function (g) { return g.resolved; }).length;
const entYes = list.filter(function (g) { return g.entitled === true; }).length;
const entNo = list.filter(function (g) { return g.entitled === false; }).length;
const entUnknown = list.filter(function (g) { return g.entitled === null || g.entitled === undefined; }).length;
// 平台是多值字段:分别按「任意平台」和「平台组合」两种口径统计
const platformFlat = [];
let platformMissing = 0;
for (const g of list) {
const ps = (g.platforms && g.platforms.length) ? g.platforms : ['未标注'];
if (!g.platforms || !g.platforms.length) platformMissing += 1;
for (const p of ps) platformFlat.push({ p: p });
}
const platformCounts = countBy(platformFlat, function (x) { return x.p; });
const combos = countBy(list, function (g) {
const ps = (g.platforms || []).slice().sort();
return ps.length ? ps.join(' + ') : '未标注';
});
const recordTypes = countBy(
list.reduce(function (acc, g) {
for (const t of (g.recordTypes || [])) acc.push({ t: t });
return acc;
}, []),
function (x) { return x.t; }
);
return {
totals: {
games: list.length,
resolved: resolved,
unresolved: list.length - resolved,
resolutionRate: list.length ? Math.round(resolved / list.length * 1000) / 10 : 0,
entitled: entYes,
notEntitled: entNo,
entitlementUnknown: entUnknown
},
timeline: buildTimeline(list),
platforms: platformCounts,
platformCombos: combos,
platformMissing: platformMissing,
recordTypes: recordTypes,
duplicates: findDuplicateNames(list)
};
}
// ==================== 快照与差异 ====================
function makeSnapshot(result) {
const games = (result && result.games) || [];
const items = {};
for (const g of games) {
const id = String(g.namespace || 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.accountId) || null,
gameCount: games.length,
items: items
};
}
// 上一份快照 vs 本次结果:按 namespace 做集合差。没有上一份时返回 null,
// 不要造一个「全部都是新增」的假 diff。
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 = getStored(SNAPSHOT_KEY, []);
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();
setStored(SNAPSHOT_KEY, list);
return diff;
}
// ==================== 导出:CSV / Markdown / 摘要 ====================
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, '"');
}
// 年度柱状图(纯字符串):面板里直接喂给 innerHTML,无图表库依赖。
// 空年份保留 0 高柱位,否则时间轴会「塌缩」成连续年份,读起来像没有空档。
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('');
return parts.join('');
}
function toCsv(head, rows) {
const lines = [head.map(csvCell).join(',')];
for (const row of rows) lines.push(row.map(csvCell).join(','));
// 带 BOM,Excel 直接打开不会乱码
return '\uFEFF' + lines.join('\r\n') + '\r\n';
}
function buildCsv(result) {
const head = ['游戏名', '命名空间', '目录ID', '商品ID', '沙盒名', '平台',
'获得时间', '入库记录数', '已授权'];
const rows = ((result && result.games) || []).map(function (g) {
return [
g.name,
g.namespace,
g.catalogItemId,
g.productId,
g.sandboxName,
(g.platforms || []).join(' / '),
g.acquiredAt,
g.recordCount,
g.entitled === null || g.entitled === undefined ? '' : (g.entitled ? '是' : '否')
];
});
return toCsv(head, rows);
}
// 汇总表:年度 / 平台 / 记录类型 三段拼一张长表,方便直接透视
function buildSummaryCsv(result) {
const a = (result && result.analysis) || analyzeLibrary((result && result.games) || []);
const rows = [];
rows.push(['年度', '入库数量', '占比']);
const total = a.totals.games || 0;
for (const d of a.timeline.byYear) {
rows.push([d.key, d.count, total ? Math.round(d.count / total * 1000) / 10 + '%' : '']);
}
rows.push([]);
rows.push(['平台', '数量', '占比']);
for (const d of a.platforms) {
rows.push([d.key, d.count, total ? Math.round(d.count / total * 1000) / 10 + '%' : '']);
}
rows.push([]);
rows.push(['入库记录类型', '条数', '']);
for (const d of a.recordTypes) rows.push([d.key, d.count, '']);
return toCsv(['维度', '数量', '占比'], rows);
}
function fmtIsoDay(iso) {
return iso || '—';
}
function buildReport(result, diff, freeAnalysis) {
const a = (result && result.analysis) || analyzeLibrary((result && result.games) || []);
const acc = (result && result.account) || {};
const lines = [];
lines.push('# Epic 库存分析报告');
lines.push('');
lines.push('- 账号:' + (acc.displayName || acc.accountId || '未知'));
lines.push('- 生成时间:' + ((result && result.generatedAt) || new Date().toISOString()));
lines.push('- 口径:Epic 库存接口全量入库记录(含从未产生订单的条目),按命名空间收敛');
lines.push('');
lines.push('## 概览');
lines.push('');
lines.push('| 指标 | 数值 |');
lines.push('| --- | --- |');
lines.push('| 游戏数 | ' + a.totals.games + ' |');
lines.push('| 入库记录数 | ' + ((result && result.summary && result.summary.recordCount) || '—') + ' |');
lines.push('| 标题解析率 | ' + a.totals.resolutionRate + '% |');
lines.push('| 首次入库 | ' + fmtIsoDay(a.timeline.first) + ' |');
lines.push('| 最近入库 | ' + fmtIsoDay(a.timeline.last) + ' |');
lines.push('| 跨度 | ' + a.timeline.spanDays + ' 天 |');
lines.push('| 峰值年 | ' + (a.timeline.peakYear ? a.timeline.peakYear.year + ' 年(' + a.timeline.peakYear.count + ' 款)' : '—') + ' |');
lines.push('| 有入库时间的月份 | ' + a.timeline.monthsActive + ' 个 |');
lines.push('| 年均入库 | ' + a.timeline.avgPerYear + ' 款 |');
if (a.timeline.maxGap && a.timeline.maxGap.days) {
lines.push('| 最长空档 | ' + a.timeline.maxGap.days + ' 天(' + a.timeline.maxGap.from + ' → ' + a.timeline.maxGap.to + ') |');
}
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.platforms) lines.push('| ' + d.key + ' | ' + d.count + ' |');
lines.push('');
if (a.duplicates.length) {
lines.push('## 疑似重复条目');
lines.push('');
lines.push('| 游戏名 | 条目数 | 命名空间 |');
lines.push('| --- | --- | --- |');
for (const d of a.duplicates.slice(0, 30)) {
lines.push('| ' + d.name + ' | ' + d.count + ' | ' + d.namespaces.join('、') + ' |');
}
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('> 数据由 Epic 平台增强脚本在本机生成,未上传任何服务器。');
if (freeAnalysis && freeAnalysis.rows && freeAnalysis.rows.length) {
lines.push('');
lines.push(buildFreeMarkdown(freeAnalysis));
}
return lines.join('\n');
}
function buildDigest(result, diff, freeAnalysis) {
const a = (result && result.analysis) || analyzeLibrary((result && result.games) || []);
const acc = (result && result.account) || {};
const parts = [];
parts.push('Epic 库存(' + (acc.displayName || acc.accountId || '未知账号') + '):' + a.totals.games + ' 款');
if (a.timeline.first) parts.push('跨度 ' + a.timeline.first + ' → ' + a.timeline.last);
if (a.timeline.peakYear) parts.push('峰值 ' + a.timeline.peakYear.year + ' 年 ' + a.timeline.peakYear.count + ' 款');
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) {
const ft = freeAnalysis.totals;
parts.push('会免 可领 ' + ft.active + ' / 3天内 ' + freeAnalysis.buckets.urgent
+ ' / 已领 ' + ft.claimed + ' / 价值 ' + formatMoney(ft.valueSum, freeAnalysis.currency));
}
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() {
if (state.running) return null;
state.running = true;
state.result = null;
ui.resetExportView();
ui.setExportBusy(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(2, '获取授权码');
ui.log('获取授权码…');
const code = await fetchAuthCode();
lap('授权码');
ui.progress(6, '换取令牌');
ui.log('换取访问令牌…');
const tok = await exchangeToken(code);
const token = tok.access_token;
lap('令牌');
const who = tok.displayName || tok.account_id || 'Epic 账号';
ui.setAccount(who);
let lib = null;
let titles = new Map();
// GraphQL 只在商城同源可用;站在 www.epicgames.com 时直接走 REST 兜底
if (location.hostname === 'store.epicgames.com') {
ui.progress(10, '读取游戏库');
ui.log('读取游戏库(GraphQL)…');
try {
const g = await fetchLibraryGraphql(function (n) {
ui.progress(10, '读取游戏库 ' + n + ' 条');
});
lib = g.records;
titles = g.titles;
lap('游戏库 ' + lib.length + ' 条');
} catch (e) {
ui.log(' · GraphQL 不可用(' + ((e && e.message) || e) + '),改用库接口', 'warn');
}
}
if (!lib) {
ui.progress(12, '读取游戏库');
ui.log('读取游戏库(REST)…');
lib = await fetchLibraryRest(token, function (n) {
ui.progress(12, '读取游戏库 ' + n + ' 条');
});
lap('游戏库 ' + lib.length + ' 条');
}
ui.progress(18, '读取权益');
ui.log('读取权益…');
let ents = [];
let entOk = true;
try {
ents = await fetchEntitlements(token, tok.account_id);
lap('权益 ' + ents.length + ' 条');
} catch (e) {
entOk = false;
ui.log(' ⚠ 权益读取失败(' + ((e && e.message) || e) + '),导出继续,entitled 字段置空', 'warn');
}
ui.progress(24, '解析游戏名');
ui.log('归档游戏…');
const games = assembleLibrary(lib, ents, entOk, titles);
const missing = games.filter(function (g) { return !g.resolved && g.catalogItemId; })
.map(function (g) { return g.catalogItemId; });
if (missing.length) {
ui.log('补全 ' + missing.length + ' 个缺失标题…');
const extra = await fetchCatalogTitles(token, missing, function (done, total) {
ui.progress(24 + Math.round(done / total * 70), '解析游戏名 ' + done + '/' + total);
});
for (const g of games) {
if (!g.resolved && g.catalogItemId && extra.titles.has(g.catalogItemId)) {
g.name = stripBookTitle(extra.titles.get(g.catalogItemId));
g.resolved = true;
}
}
if (extra.failedBatches) {
ui.log(' ⚠ ' + extra.failedBatches + ' / ' + extra.totalBatches
+ ' 批目录请求失败,对应游戏回退为沙盒名', 'warn');
}
lap('补全标题');
}
games.sort(function (a, b) {
return String(a.name).localeCompare(String(b.name), 'en');
});
const stamps = games.map(function (g) { return g.acquiredAt; }).filter(Boolean).sort();
const unresolved = games.filter(function (g) { return !g.resolved; }).length;
state.result = {
schemaVersion: SCHEMA_VERSION,
source: 'epic-platform-enhancer',
generatedAt: new Date().toISOString(),
account: {
accountId: tok.account_id || null,
displayName: tok.displayName || null
},
summary: {
gameCount: games.length,
recordCount: lib.length,
entitlementCount: entOk ? ents.length : null,
unresolvedCount: unresolved,
firstAcquiredAt: stamps[0] || null,
lastAcquiredAt: stamps[stamps.length - 1] || null
},
games: games
};
// 聚合分析 + 快照差异:分析结果随结果一起带走(JSON 里也有),
// 快照按账号无关的 namespace 集合存储,最多留 SNAPSHOT_MAX 份。
state.result.analysis = analyzeLibrary(games);
state.diff = pushSnapshot(makeSnapshot(state.result));
ui.renderAnalysis(state.result, state.diff);
const totalSec = ((Date.now() - state.startedAt) / 1000).toFixed(1);
stopTicker();
ui.elapsed(Number(totalSec));
ui.progress(100, '完成');
ui.setStats(games.length + ' 款 · ' + lib.length + ' 条记录');
ui.log('✓ 导出完成:' + games.length + ' 款游戏,共 ' + totalSec + 's', 'ok');
if (unresolved) {
ui.log(' ⚠ ' + unresolved + ' 款未能解析标题,已用沙盒名代替', 'warn');
}
ui.setExportBusy(false);
ui.toast('库存读取完成:' + 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.envProblem) {
ui.log(' 当前脚本管理器的请求接口没有返回 HTTP 状态,建议换用 Tampermonkey。', 'err');
}
ui.toast('库存读取失败:' + msg, 'err');
console.warn(LOG_PREFIX, err);
return null;
} finally {
state.running = false;
stopTicker();
ui.setExportBusy(false);
}
}
// ==================== 输出 ====================
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.displayName
: (r && r.account && r.account.accountId) || 'epic';
const day = new Date().toISOString().slice(0, 10);
const safe = String(who).replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 40);
return 'epic-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 freeBaseName() {
return 'epic-giveaways-' + new Date().toISOString().slice(0, 10);
}
function exportFreeCsv() {
const analysis = state.freeAnalysis || analyzeFree(state.ledger, state.free);
if (!analysis.rows.length) {
ui.toast('还没有会免记录,先刷新一次', 'err');
return;
}
download(freeBaseName() + '.csv', buildFreeCsv(analysis), 'text/csv;charset=utf-8');
ui.toast('会免记录已导出(' + analysis.rows.length + ' 期)', 'ok');
}
function exportFreeMd() {
const analysis = state.freeAnalysis || analyzeFree(state.ledger, state.free);
if (!analysis.rows.length) {
ui.toast('还没有会免记录,先刷新一次', 'err');
return;
}
const head = '# Epic 会免领取报告\n\n- 生成时间:' + new Date().toISOString()
+ '\n- 数据区域:' + (state.free.country || CFG.country)
+ '\n- 说明:账本为本机累积观测,标记已领只是本地记录\n\n';
download(freeBaseName() + '.md', head + buildFreeMarkdown(analysis), 'text/markdown;charset=utf-8');
ui.toast('会免报告已导出', 'ok');
}
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 copyDigest() {
if (!state.result) return;
const text = buildDigest(state.result, state.diff);
await copyText(text);
ui.toast('摘要已复制', 'ok');
}
// ==================== 启动 ====================
function registerMenu(label, fn) {
try {
if (typeof GM_registerMenuCommand === 'function') GM_registerMenuCommand(label, fn);
} catch (e) { /* 管理器不支持菜单命令时静默跳过 */ }
}
function maybeAutoCheck() {
if (!CFG.autoCheck) return;
const age = Date.now() - (state.free.at || 0);
const interval = Math.max(5, Number(CFG.intervalMin) || 60) * 60000;
if (age > interval) checkFree(true);
}
function boot() {
if (!document.body) {
setTimeout(boot, 50);
return;
}
if (document.getElementById('epe-root')) return;
ui.mount();
ui.renderSettings();
ui.renderFree();
ui.renderAnalysis(null, null);
ui.setExportBusy(false);
scheduleTimer();
registerMenu('Epic 助手:打开面板', function () { ui.open('free'); });
registerMenu('Epic 限免:立即检查', function () {
ui.open('free');
checkFree(false);
});
registerMenu('Epic 库存:读取并导出 JSON', function () {
ui.open('export');
runExport().then(function (result) {
if (result) exportJson();
});
});
registerMenu('Epic 库存:打开分析视图', function () { ui.open('analysis'); });
registerMenu('Epic 库存:导出 Markdown 报告', function () {
ui.open('analysis');
if (state.result) { exportReport(); return; }
runExport().then(function (result) { if (result) exportReport(); });
});
document.addEventListener('visibilitychange', function () {
if (document.visibilityState !== 'visible') return;
const age = Date.now() - (state.free.at || 0);
if (CFG.autoCheck && age > Math.max(5, Number(CFG.intervalMin) || 60) * 60000) {
checkFree(true);
}
});
setTimeout(maybeAutoCheck, 1200);
}
// 自测句柄:只读纯函数,方便在无头环境里验证解析逻辑,不改变脚本行为
try {
window.__epicEnhancer = {
version: VERSION,
ui: ui, // 供无头预览/调试调用(open/renderAnalysis),不影响脚本行为
parseFreeElements: parseFreeElements,
collectFreeWindows: collectFreeWindows,
gameLink: gameLink,
isPriceFree: isPriceFree,
fmtRemain: fmtRemain,
buildCsv: buildCsv,
buildSummaryCsv: buildSummaryCsv,
buildReport: buildReport,
buildDigest: buildDigest,
analyzeLibrary: analyzeLibrary,
buildTimeline: buildTimeline,
parsePriceValue: parsePriceValue,
freeBucket: freeBucket,
ledgerKey: ledgerKey,
mergeLedger: mergeLedger,
analyzeFree: analyzeFree,
filterFreeItems: filterFreeItems,
buildFreeCsv: buildFreeCsv,
buildFreeMarkdown: buildFreeMarkdown,
formatMoney: formatMoney,
buildYearChartSvg: buildYearChartSvg,
escapeXml: escapeXml,
diffSnapshots: diffSnapshots,
makeSnapshot: makeSnapshot,
okStatus: okStatus,
// 只给无头预览/调试用:注入假快照后走真实渲染路径,业务代码不要依赖
debug: {
setFree: function (free, ledger, filter) {
state.free = free;
if (ledger) state.ledger = ledger;
state.freeFilter = filter || 'all';
ui.renderFree();
}
}
};
} catch (e) { /* 某些沙箱没有 window */ }
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', boot, { once: true });
} else {
boot();
}
})();