// ==UserScript== // @name Ubisoft 平台增强 // @name:en Ubisoft Platform Enhancer // @namespace ubisoft-platform-enhancer // @version 1.0.0 // @description Ubisoft Connect 库分析:平台覆盖、可用性、授权级别与 IP 系列聚类,自动排重与数据审计,一键导出 JSON / CSV / Markdown 报告 // @description:en Ubisoft Connect library analytics: platform coverage, availability, licence level and franchise clustering with de-duplication and audit, exporting JSON / CSV / Markdown reports. // @author SmallRob // @match https://connect.ubisoft.com/* // @match https://*.ubisoft.com/* // @match https://ubisoft.com/* // @match https://*.ubisoft.com.cn/* // @match https://ubisoft.com.cn/* // @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-ubi'%20x1='0'%20y1='0'%20x2='1'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%23021628'/%3E%3Cstop%20offset='100%25'%20stop-color='%230b0e14'/%3E%3C/linearGradient%3E%3ClinearGradient%20id='ubi-blue'%20x1='0'%20y1='0'%20x2='1'%20y2='1'%3E%3Cstop%20offset='0%25'%20stop-color='%234dd0ff'/%3E%3Cstop%20offset='60%25'%20stop-color='%2300b0e0'/%3E%3Cstop%20offset='100%25'%20stop-color='%230077a8'/%3E%3C/linearGradient%3E%3ClinearGradient%20id='ubi-ring'%20x1='0'%20y1='0'%20x2='1'%20y2='0'%3E%3Cstop%20offset='0%25'%20stop-color='%23ffffff'/%3E%3Cstop%20offset='100%25'%20stop-color='%234dd0ff'/%3E%3C/linearGradient%3E%3Cfilter%20id='glow-ubi'%20x='-30%25'%20y='-30%25'%20width='160%25'%20height='160%25'%3E%3CfeGaussianBlur%20stdDeviation='1.8'%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-ubi)'/%3E%3CradialGradient%20id='halo'%20cx='50%25'%20cy='45%25'%20r='50%25'%3E%3Cstop%20offset='0%25'%20stop-color='%2300b0e0'%20stop-opacity='0.25'/%3E%3Cstop%20offset='100%25'%20stop-color='%2300b0e0'%20stop-opacity='0'/%3E%3C/radialGradient%3E%3Crect%20width='64'%20height='64'%20rx='14'%20fill='url(%23halo)'/%3E%3Cg%20transform='translate(12,%2012)'%20filter='url(%23glow-ubi)'%3E%3Ccircle%20cx='20'%20cy='20'%20r='18'%20fill='none'%20stroke='url(%23ubi-blue)'%20stroke-width='3.5'/%3E%3Cpath%20d='M%2020%208%20A%2012%2012%200%200%201%2032%2020'%20fill='none'%20stroke='%23ffffff'%20stroke-width='3.5'%20stroke-linecap='round'/%3E%3Ccircle%20cx='14'%20cy='22'%20r='2.8'%20fill='%234dd0ff'/%3E%3Ccircle%20cx='23'%20cy='16'%20r='2.8'%20fill='%23ffffff'/%3E%3Ccircle%20cx='26'%20cy='26'%20r='2.8'%20fill='%234dd0ff'/%3E%3C/g%3E%3Cg%20transform='translate(44,%2044)'%20stroke='%234dd0ff'%20stroke-width='2'%20stroke-linecap='round'%20opacity='0.7'%3E%3Cline%20x1='0'%20y1='10'%20x2='0'%20y2='0'/%3E%3Cline%20x1='0'%20y1='4'%20x2='-6'%20y2='0'/%3E%3Cline%20x1='0'%20y1='4'%20x2='6'%20y2='0'/%3E%3C/g%3E%3Ccircle%20cx='10'%20cy='12'%20r='1.2'%20fill='%23ffffff'%20opacity='0.6'/%3E%3C/svg%3E // ==/UserScript== (function () { 'use strict'; // ==================== 配置 ==================== // Ubisoft Connect 桌面客户端的公开 App ID(GOG Galaxy 插件、ubi-docs 等公开项目用的同一组, // 不是私人密钥)。网页登录写进 localStorage 的票属于「登录 appId」,API 侧会拒, // 所以读票后先换一次票(profiles/sessions)再读库存 —— 实测换票后 200。 const APP_ID = 'f68a4bb5-608a-4ff2-8123-be8ef797e0a6'; const LOGIN_APP_ID = '1068ef52-dfd2-4e62-8ac9-37a47e6c0b78'; const LOGIN_URL = 'https://connect.ubisoft.com/login?appId=' + LOGIN_APP_ID; const ENT_URL = 'https://api-ubiservices.ubi.com/v1/profiles/me/global/ubiconnect/entitlement/api/entitlements'; const SESSION_URL = 'https://public-ubiservices.ubi.com/v2/profiles/sessions'; const GRAPHQL_URL = 'https://public-ubiservices.ubi.com/v1/profiles/me/uplay/graphql'; // localStorage 里会话的落点按域不同:connect 域给平铺对象,区域站给 payload 包装 + overlay 键。 const SESSION_KEYS = ['PRODloginData', 'loginData', 'PRODOverlayConnectLoginData']; const VERSION = '1.0.0'; const LOG_PREFIX = '[Ubisoft 助手]'; const SCHEMA_VERSION = 1; const TITLE_CHUNK = 120; const SNAPSHOT_MAX = 20; const JSON_LANG = 'en-US'; const LS_CFG = 'ubie.cfg.v1'; const LS_SNAP = 'ubie.snapshots.v1'; const CFG_DEFAULTS = { includeNonOwned: false, // 是否把 accessLevel 非 owned 的权益也算进库存(默认只算真拥有) sortBy: 'name' // 游戏库列表排序:name | platform }; 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.includeNonOwned !== 'boolean') CFG.includeNonOwned = CFG_DEFAULTS.includeNonOwned; if (['name', 'platform'].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 lower(v) { return String(v === undefined || v === null ? '' : v).toLowerCase(); } function pad2(n) { return n < 10 ? '0' + n : String(n); } 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()); } // 过期时间统一成毫秒:connect 域给数字毫秒,区域站给 ISO 串。 function toMillis(raw) { if (raw === null || raw === undefined || raw === '') return null; const ms = Number(raw); if (isFinite(ms) && ms > 0) return ms; const parsed = Date.parse(String(raw)); return isFinite(parsed) && parsed > 0 ? parsed : null; } function errorCodeOf(err) { if (!err) return 'UNKNOWN'; if (err.status) return 'HTTP_' + err.status; if (err.name === 'TypeError') return 'NETWORK_ERROR'; return 'UNKNOWN'; } // ==================== 网络层 ==================== async function httpJson(url, opts, what) { const started = Date.now(); state.requests += 1; let res; try { res = await fetch(url, opts); } catch (err) { const msg = (err && err.message) ? err.message : String(err); const e = new Error(what + ' 请求失败(网络层):' + msg); // fetch 抛错 = 请求没发出去(浏览器本地拦了),和「服务端回 401」是两回事 e.networkProblem = true; throw e; } const text = await res.text(); let json = null; if (text) { try { json = JSON.parse(text); } catch (e) { const err = new Error(what + ' 返回非 JSON(HTTP ' + res.status + '):' + text.slice(0, 200)); err.status = res.status; throw err; } } if (!res.ok) { const err = new Error(what + ' 失败:HTTP ' + res.status + ' ' + text.slice(0, 200)); err.status = res.status; err.body = json; throw err; } return { json: json, ms: Date.now() - started, status: res.status }; } // ==================== 会话 ==================== function readStoredSession() { const empty = { key: null, ticket: null, sessionId: null, userId: null, nameOnPlatform: null, email: null, expirationDate: null }; const candidates = []; for (const key of SESSION_KEYS) { let raw = null; try { raw = localStorage.getItem(key); } catch (e) { raw = null; } if (!raw) continue; let parsed = null; try { parsed = JSON.parse(raw); } catch (e) { parsed = null; } if (!parsed || typeof parsed !== 'object') continue; // 区域站的 PRODloginData 把真正内容套在 payload 里 const src = (parsed.payload && typeof parsed.payload === 'object') ? parsed.payload : parsed; const ticket = src.ticket || null; const sessionId = src.sessionId || null; if (!ticket || !sessionId) continue; candidates.push({ key: key, ticket: ticket, sessionId: sessionId, userId: src.userId || src.user_id || src.profileId || null, nameOnPlatform: src.nameOnPlatform || src.username || null, email: src.email || src.emailAddress || null, expirationDate: toMillis(src.expirationDate) || toMillis(src.expiration) }); } if (!candidates.length) return empty; // 同一域里可能有两份票,优先没用过期的那张;全过期就返回第一张交给上层报错 for (const c of candidates) if (!isSessionExpired(c)) return c; return candidates[0]; } // 缺失或非法过期时间不做断言,交给服务端 401 判定 function isSessionExpired(session) { const ms = toMillis(session && session.expirationDate); if (ms === null) return false; return ms <= Date.now(); } function authHeaders(session) { return { 'Authorization': 'Ubi_v1 t=' + session.ticket, 'Ubi-SessionId': session.sessionId, 'Ubi-AppId': APP_ID, 'Ubi-LocaleCode': JSON_LANG, 'Content-Type': 'application/json' }; } async function refreshSession(session) { const r = await httpJson(SESSION_URL, { method: 'POST', headers: authHeaders(session), body: '{}' }, '换票(profiles/sessions)'); const j = r.json || {}; if (j.ticket) session.ticket = j.ticket; if (j.sessionId) session.sessionId = j.sessionId; if (j.userId) session.userId = j.userId; if (j.nameOnPlatform) session.nameOnPlatform = j.nameOnPlatform; const exp = toMillis(j.expirationDate) || toMillis(j.expiration); if (exp) session.expirationDate = exp; if (!j.ticket) throw new Error('换票没有返回 ticket,无法继续'); return r; } // 任何一次调用 401/403 就换票重试一次;再失败就明确报「登录过期」 async function withAuthRetry(session, fn) { try { return await fn(); } catch (err) { if (err && (err.status === 401 || err.status === 403)) { await refreshSession(session); return await fn(); } throw err; } } // ==================== 数据整形(纯函数) ==================== // 权益载荷有三种形态:裸数组 / {entitlements:[…]} / {entitlements:{nodes:[…]}} function pickEntitlements(payload) { if (Array.isArray(payload)) return payload; if (!payload || typeof payload !== 'object') return []; const e = payload.entitlements; if (Array.isArray(e)) return e; if (e && Array.isArray(e.nodes)) return e.nodes; if (Array.isArray(payload.nodes)) return payload.nodes; return []; } // 只留「是游戏 / 是本体」的权益,并记下每类排除多少条。 // includeNonOwned=false 时连 accessLevel 非 owned 的一起排除。 function classifyEntitlements(list, includeNonOwned) { const stats = { total: list.length, kept: 0, notOwned: 0, notGame: 0, expired: 0, malformed: 0 }; const kept = []; for (const item of list) { if (!item || typeof item !== 'object') { stats.malformed += 1; continue; } const accessLevel = lower(item.accessLevel); const type = lower(item.type); const availability = lower(item.availability); if (accessLevel && accessLevel !== 'owned' && !includeNonOwned) { stats.notOwned += 1; continue; } if (type && type !== 'game') { stats.notGame += 1; continue; } if (availability === 'expired') { stats.expired += 1; continue; } stats.kept += 1; kept.push(item); } return { stats: stats, kept: kept }; } // 同一个 spaceId 可能有多条权益(不同 productId / 平台),按 spaceId 收敛成一条 function collapseBySpaceId(items) { const bySpace = new Map(); let duplicates = 0; for (const item of items) { const spaceId = String(item.spaceId || '').trim(); if (!spaceId) continue; if (bySpace.has(spaceId)) { duplicates += 1; const prev = bySpace.get(spaceId); if (!prev.productId && item.productId) prev.productId = item.productId; if (!prev.availability && item.availability) prev.availability = item.availability; if (!prev.accessLevel && item.accessLevel) prev.accessLevel = item.accessLevel; continue; } bySpace.set(spaceId, { spaceId: spaceId, productId: item.productId || null, accessLevel: item.accessLevel || null, availability: item.availability || null }); } return { items: Array.from(bySpace.values()), duplicates: duplicates }; } // GraphQL 的 Platform 片段有四处来源,取并集去重 function collectPlatforms(node) { const out = []; function push(p) { if (!p) return; if (typeof p === 'string') { push({ name: p }); return; } const name = p.name || p.platformName || p.type || p.id; if (name && out.indexOf(String(name)) === -1) out.push(String(name)); } push(node.platform); const groups = node.availablePlatformGroups; if (Array.isArray(groups)) groups.forEach(push); const avail = node.availablePlatforms; if (avail && Array.isArray(avail.nodes)) avail.nodes.forEach(push); const meta = node.viewer && node.viewer.meta; if (meta && meta.ownedCrossplayPlatforms && Array.isArray(meta.ownedCrossplayPlatforms.nodes)) { meta.ownedCrossplayPlatforms.nodes.forEach(push); } return out; } // 系列聚类:Ubisoft 的库天然按 IP 成簇,权益接口又没有入库时间, // 所以「系列分布」是这套数据里信息量最大的一维。规则表按名字前缀匹配, // 匹配不上就返回 null(不硬凑),只在命中 ≥2 款时进统计。 const SERIES_RULES = [ [/^assassin[’']?s creed/i, "Assassin's Creed"], [/^far cry/i, 'Far Cry'], [/^watch dogs/i, 'Watch Dogs'], [/^(tom clancy[’']?s )?rainbow six/i, 'Rainbow Six'], [/^(tom clancy[’']?s )?ghost recon/i, 'Ghost Recon'], [/^(tom clancy[’']?s )?(the )?division/i, 'The Division'], [/^(tom clancy[’']?s )?splinter cell/i, 'Splinter Cell'], [/^(tom clancy[’']?s )?the hunt for red october/i, 'Tom Clancy'], [/^prince of persia/i, 'Prince of Persia'], [/^rayman/i, 'Rayman'], [/^anno\b/i, 'Anno'], [/^the settlers/i, 'The Settlers'], [/^just dance/i, 'Just Dance'], [/^the crew/i, 'The Crew'], [/^for honor/i, 'For Honor'], [/^trackmania/i, 'Trackmania'], [/^trials\b/i, 'Trials'], [/^might & magic|^heroes of might/i, 'Might & Magic'], [/^mighty quest/i, 'The Mighty Quest'], [/^child of light/i, 'Child of Light'], [/^beyond good (and|&) evil/i, 'Beyond Good & Evil'], [/^valiant hearts/i, 'Valiant Hearts'], [/^(uno|monopoly|scrabble|trivial pursuit)\b/i, 'Ubisoft 桌游'], [/^rocksmith/i, 'Rocksmith'], [/^starlink/i, 'Starlink'], [/^(the )?smurfs/i, 'Smurfs'], [/^south park/i, 'South Park'], [/^immortals fenyx rising/i, 'Immortals Fenyx Rising'] ]; function seriesKey(name) { const value = String(name || '').trim(); if (!value) return null; for (const rule of SERIES_RULES) { if (rule[0].test(value)) return rule[1]; } return null; } // ==================== 育碧接口 ==================== async function fetchEntitlements(session, onNote) { const r = await withAuthRetry(session, function () { return httpJson(ENT_URL, { method: 'GET', headers: authHeaders(session) }, '读取权益(entitlements)'); }); const list = pickEntitlements(r.json); const c = classifyEntitlements(list, !!CFG.includeNonOwned); const collapsed = collapseBySpaceId(c.kept); if (onNote) { onNote('权益 ' + c.stats.total + ' 条:保留 ' + c.stats.kept + ',排除非游戏 ' + c.stats.notGame + ' / 未拥有 ' + c.stats.notOwned + ' / 已过期 ' + c.stats.expired + ',合并重复 ' + collapsed.duplicates); } return { stats: c.stats, duplicates: collapsed.duplicates, games: collapsed.items, ms: r.ms }; } async function fetchTitles(session, spaceIds, onProgress) { const titles = new Map(); const chunks = []; for (let i = 0; i < spaceIds.length; i += TITLE_CHUNK) chunks.push(spaceIds.slice(i, i + TITLE_CHUNK)); for (let i = 0; i < chunks.length; i += 1) { const payload = { operationName: 'GetOwnedGames', variables: { spaceIds: chunks[i] }, query: 'query GetOwnedGames($spaceIds: [String!]) {' + ' games(spaceIds: $spaceIds) {' + ' id spaceId name' + ' platform { id name type applicationId }' + ' availablePlatformGroups { id name type }' + ' availablePlatforms { nodes { id name type } }' + ' }' + '}' }; const r = await withAuthRetry(session, function () { return httpJson(GRAPHQL_URL, { method: 'POST', headers: authHeaders(session), body: JSON.stringify(payload) }, '读取标题(graphql)'); }); const data = (r.json && r.json.data) || {}; const nodes = Array.isArray(data.games) ? data.games : []; for (const node of nodes) { const spaceId = String(node.spaceId || '').trim(); if (!spaceId) continue; titles.set(spaceId, { name: node.name || null, platforms: collectPlatforms(node) }); } if (onProgress) onProgress(i + 1, chunks.length, titles.size); } return titles; } // ==================== 数据聚合分析(纯函数) ==================== 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'); }); } 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, spaceIds: pair[1].map(function (g) { return g.spaceId; }) }); } return out.sort(function (a, b) { return b.count - a.count; }); } function analyzeLibrary(games) { const list = Array.isArray(games) ? games : []; const platformFlat = []; let noPlatform = 0; for (const g of list) { const ps = (g.platforms && g.platforms.length) ? g.platforms : ['未标注']; if (!g.platforms || !g.platforms.length) noPlatform += 1; for (const p of ps) platformFlat.push({ p: p }); } const seriesFlat = []; for (const g of list) { const s = g.series || seriesKey(g.name); if (s) seriesFlat.push({ s: s }); } // 只有 ≥2 款的系列才算「系列」,单款命中只说明名字长得像 const series = countBy(seriesFlat, function (x) { return x.s; }) .filter(function (d) { return d.count >= 2; }); const resolved = list.filter(function (g) { return g.resolved; }).length; return { totals: { games: list.length, resolved: resolved, unresolved: list.length - resolved, resolutionRate: list.length ? Math.round(resolved / list.length * 1000) / 10 : 0, seriesGames: seriesFlat.length, seriesCount: series.length, platformCoverage: countBy(platformFlat, function (x) { return x.p; }).length }, platforms: countBy(platformFlat, function (x) { return x.p; }), platformMissing: noPlatform, availability: countBy(list, function (g) { return g.availability || '未标注'; }), accessLevel: countBy(list, function (g) { return g.accessLevel || '未标注'; }), series: series, duplicates: findDuplicateNames(list) }; } // ==================== 快照与差异 ==================== function makeSnapshot(result) { const games = (result && result.games) || []; const items = {}; for (const g of games) { const id = String(g.spaceId || 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 buildCsv(result) { const head = ['游戏名', 'spaceId', '产品ID', 'accessLevel', 'availability', '平台', '系列']; const rows = ((result && result.games) || []).map(function (g) { return [ g.name, g.spaceId, g.productId, g.accessLevel, g.availability, (g.platforms || []).join(' / '), g.series || seriesKey(g.name) || '' ]; }); return toCsv(head, rows); } function buildSummaryCsv(result) { const a = (result && result.analysis) || analyzeLibrary((result && result.games) || []); const total = a.totals.games || 0; const pct = function (n) { return total ? Math.round(n / total * 1000) / 10 + '%' : ''; }; const rows = []; 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.availability) rows.push([d.key, d.count, pct(d.count)]); rows.push([]); rows.push(['授权级别', '数量', '占比']); for (const d of a.accessLevel) rows.push([d.key, d.count, pct(d.count)]); rows.push([]); rows.push(['系列', '数量', '占比']); for (const d of a.series) 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('# Ubisoft 库存分析报告'); lines.push(''); lines.push('- 账号:' + (acc.nameOnPlatform || acc.userId || '未知')); lines.push('- 生成时间:' + ((result && result.generatedAt) || new Date().toISOString())); lines.push('- 口径:Ubisoft Connect 权益接口,按 spaceId 收敛' + (sum.includeNonOwned ? '(含非 owned 授权)' : '(仅 owned)')); lines.push('- 注意:权益接口不提供入库/购买时间,因此没有年度时间线,分析以平台 / 授权 / 系列为主。'); lines.push(''); lines.push('## 概览'); lines.push(''); lines.push('| 指标 | 数值 |'); lines.push('| --- | --- |'); lines.push('| 游戏数 | ' + a.totals.games + ' |'); lines.push('| 覆盖平台数 | ' + a.totals.platformCoverage + ' |'); lines.push('| 系列数(≥2 款) | ' + a.totals.seriesCount + '(' + a.totals.seriesGames + ' 款落入系列) |'); lines.push('| 标题解析率 | ' + a.totals.resolutionRate + '% |'); lines.push('| 原始权益条数 | ' + (sum.entitlementCount || '—') + ' |'); lines.push('| 同 spaceId 重复合并 | ' + (sum.duplicateSpaceIds || 0) + ' |'); lines.push(''); lines.push('## 平台分布'); lines.push(''); lines.push('| 平台 | 数量 | 占比 |'); lines.push('| --- | --- | --- |'); for (const d of a.platforms) lines.push('| ' + d.key + ' | ' + d.count + ' | ' + pct(d.count) + ' |'); lines.push(''); lines.push('## 可用性'); lines.push(''); lines.push('| 可用性 | 数量 |'); lines.push('| --- | --- |'); for (const d of a.availability) lines.push('| ' + d.key + ' | ' + d.count + ' |'); lines.push(''); lines.push('## 系列分布'); lines.push(''); if (a.series.length) { lines.push('| 系列 | 数量 |'); lines.push('| --- | --- |'); for (const d of a.series) lines.push('| ' + d.key + ' | ' + d.count + ' |'); } else { lines.push('(没有命中系列规则,或每个系列都只有 1 款)'); } lines.push(''); if (a.duplicates.length) { lines.push('## 疑似重复条目'); lines.push(''); lines.push('| 游戏名 | 条目数 | spaceId |'); lines.push('| --- | --- | --- |'); for (const d of a.duplicates.slice(0, 30)) { lines.push('| ' + d.name + ' | ' + d.count + ' | ' + d.spaceIds.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('> 数据由 Ubisoft 平台增强脚本在本机生成,未上传任何服务器。'); 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('Ubisoft 库存(' + (acc.nameOnPlatform || acc.userId || '未知账号') + '):' + a.totals.games + ' 款'); if (a.platforms.length) { parts.push('平台 ' + a.platforms.slice(0, 3).map(function (d) { return d.key + ' ' + d.count; }).join(' / ')); } if (a.series.length) { parts.push('系列 ' + a.series.slice(0, 3).map(function (d) { return d.key + ' ' + d.count; }).join('、')); } parts.push('标题解析率 ' + a.totals.resolutionRate + '%'); 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() { if (state.running) return null; 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 { const session = readStoredSession(); if (!session.ticket || !session.sessionId) { throw new Error('没有找到登录会话。请先在 ' + LOGIN_URL + ' 登录,登录完成后回到本页再读取'); } if (isSessionExpired(session)) { throw new Error('登录会话已过期(' + new Date(session.expirationDate).toISOString() + ')。请重新登录 ' + LOGIN_URL); } ui.progress(6, '读取权益'); ui.log('会话来源:localStorage["' + session.key + '"] @ ' + location.host + ',用户 ' + (session.nameOnPlatform || session.userId || '未知')); const ent = await fetchEntitlements(session, function (line) { ui.log(' ' + line); }); ui.setAccount(session.nameOnPlatform || session.userId || 'Ubisoft 账号'); lap('权益 ' + ent.games.length + ' 款'); const spaceIds = ent.games.map(function (g) { return g.spaceId; }); let titles = new Map(); let titleErrorCode = null; if (spaceIds.length) { ui.progress(45, '读取标题'); try { titles = await fetchTitles(session, spaceIds, function (done, total) { ui.progress(45 + Math.round(45 * done / total), '标题 ' + done + '/' + total); }); } catch (err) { // 标题拿不到不该让整次导出失败:spaceId 本身仍是稳定主键 titleErrorCode = errorCodeOf(err); ui.log(' ! 标题读取失败,将只输出 spaceId:' + ((err && err.message) || err), 'warn'); } lap('标题 ' + titles.size + ' 条'); } const games = ent.games.map(function (g) { const title = titles.get(g.spaceId) || null; const name = title && title.name ? title.name : null; return { name: name, spaceId: g.spaceId, productId: g.productId || null, platforms: title && Array.isArray(title.platforms) ? title.platforms : [], accessLevel: g.accessLevel || null, availability: g.availability || null, series: seriesKey(name), resolved: !!name }; }); games.sort(function (a, b) { return String(a.name || a.spaceId).localeCompare(String(b.name || b.spaceId), 'en-US'); }); const unresolved = games.filter(function (g) { return !g.resolved; }).length; state.result = { schemaVersion: SCHEMA_VERSION, source: 'ubisoft-platform-enhancer', generatedAt: new Date().toISOString(), account: { userId: session.userId || null, nameOnPlatform: session.nameOnPlatform || null, email: session.email || null }, summary: { gameCount: games.length, entitlementCount: ent.stats.total, ownedGameEntitlementCount: ent.stats.kept, duplicateSpaceIds: ent.duplicates, excludedNotGame: ent.stats.notGame, excludedNotOwned: ent.stats.notOwned, excludedExpired: ent.stats.expired, includeNonOwned: !!CFG.includeNonOwned, unresolvedCount: unresolved, titleError: titleErrorCode }, 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 + ' 款 · 系列 ' + state.result.analysis.totals.seriesCount); ui.log('✓ 完成:' + games.length + ' 款(系列 ' + state.result.analysis.totals.seriesCount + '),共 ' + totalSec + 's / ' + state.requests + ' 次请求', 'ok'); if (unresolved) ui.log(' ⚠ ' + unresolved + ' 款缺标题(spaceId 仍可用)', 'warn'); ui.toast('Ubisoft 库存读取完成:' + 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.networkProblem) { ui.log(' 网络层错误:请求在本地就被拦下了。检查广告拦截器 / 是否处在区域站', 'err'); } if (err && (err.status === 401 || err.status === 403)) { ui.log(' 票据被拒:多半是读到了别的域留下的旧票,重新登录后再试', 'err'); } ui.toast('读取失败:' + msg, 'err'); console.warn(LOG_PREFIX, err); return null; } finally { state.running = false; stopTicker(); ui.setBusy(false); } } // 环境自检:把「localStorage 里有没有票 / 票能不能换 / 能不能读库」三件事分开说清楚 async function runEnvCheck() { const lines = []; lines.push('── Ubisoft 环境自检 ──'); lines.push('当前域:' + ((typeof location !== 'undefined' && location) ? location.origin : '未知')); for (const key of SESSION_KEYS) { let raw = null; try { raw = localStorage.getItem(key); } catch (e) { raw = null; } if (!raw) { lines.push(key + ':✗ 没有'); continue; } let parsed = null; try { parsed = JSON.parse(raw); } catch (e) { parsed = null; } if (!parsed || typeof parsed !== 'object') { lines.push(key + ':⚠ 有值但不是 JSON'); continue; } const src = (parsed.payload && typeof parsed.payload === 'object') ? parsed.payload : parsed; if (src.ticket && src.sessionId) { const exp = toMillis(src.expirationDate) || toMillis(src.expiration); lines.push(key + ':✓ 有票据' + (exp ? '(到期 ' + fmtDateTime(new Date(exp).toISOString()) + ')' : '')); } else { lines.push(key + ':⚠ 有值但缺 ticket/sessionId'); } } const session = readStoredSession(); if (!session.ticket) { lines.push('结论:没有可用会话,请先登录 ' + LOGIN_URL); ui.logBlock(lines); return { ok: false, lines: lines }; } try { const r = await refreshSession(session); lines.push('换票:✓ ' + (r.ms || 0) + 'ms'); } catch (err) { lines.push('换票:✗ ' + ((err && err.message) || err)); ui.logBlock(lines); return { ok: false, lines: lines }; } try { const ent = await fetchEntitlements(session, null); lines.push('权益接口:✓ ' + ent.games.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.nameOnPlatform || r.account.userId)) ? (r.account.nameOnPlatform || r.account.userId) : 'ubisoft'; const day = new Date().toISOString().slice(0, 10); const safe = String(who).replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 40); return 'ubisoft-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 = 'ubie-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.anaPlatforms = root.getElementById('anaPlatforms'); refs.anaSeries = root.getElementById('anaSeries'); refs.anaAvail = root.getElementById('anaAvail'); 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.setNonOwned = root.getElementById('setNonOwned'); refs.setSort = root.getElementById('setSort'); refs.toasts = root.getElementById('toasts'); root.getElementById('ver').textContent = 'Ubisoft 平台增强 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.setNonOwned.addEventListener('change', function () { CFG.includeNonOwned = refs.setNonOwned.checked; saveCfg(); toast(CFG.includeNonOwned ? '下次读取将包含非 owned 授权' : '下次读取仅统计 owned 权益', '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('就绪。登录 Ubisoft 账号后点「读取库存」。'); 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.setNonOwned) return; refs.setNonOwned.checked = !!CFG.includeNonOwned; 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 max = items.reduce(function (m, d) { return Math.max(m, d.count); }, 1); for (const d of items) { 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 = 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.anaPlatforms.textContent = ''; refs.anaSeries.textContent = ''; refs.anaAvail.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.nameOnPlatform || acc.userId || '账号') + ' · ' + a.totals.games + ' 款 · ' + fmtDateTime(result.generatedAt); kpi(refs.anaKpis, [ { label: '游戏数', value: String(a.totals.games) }, { label: '覆盖平台', value: String(a.totals.platformCoverage) }, { label: '系列数(≥2 款)', value: String(a.totals.seriesCount) }, { label: '标题解析率', value: a.totals.resolutionRate + '%' } ]); hbars(refs.anaPlatforms, a.platforms); hbars(refs.anaSeries, a.series.slice(0, 12), { emptyText: '没有命中系列规则(或每个系列都只有 1 款)' }); hbars(refs.anaAvail, a.availability); const audit = []; audit.push('原始权益 ' + ((result.summary && result.summary.entitlementCount) || '—') + ' 条 → 收敛 ' + a.totals.games + ' 款'); if (result.summary) { const s = result.summary; if (s.excludedNotGame || s.excludedNotOwned || s.excludedExpired) { audit.push('已排除 非游戏 ' + s.excludedNotGame + ' / 未拥有 ' + s.excludedNotOwned + ' / 过期 ' + s.excludedExpired + ',同 spaceId 合并 ' + s.duplicateSpaceIds); } if (s.titleError) audit.push('标题接口异常:' + s.titleError + '(只剩 spaceId)'); } if (a.totals.unresolved) audit.push('未解析标题 ' + a.totals.unresolved + ' 款'); if (a.platformMissing) audit.push('平台未标注 ' + a.platformMissing + ' 款'); if (a.duplicates.length) { audit.push('疑似重复 ' + a.duplicates.length + ' 组:' + a.duplicates.slice(0, 3).map(function (d) { return d.name + ' ×' + d.count; }).join('、')); } audit.push('权益接口不提供入库时间,因此不生成年度时间线'); 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.spaceId).indexOf(q) !== -1; }); } const sortBy = CFG.sortBy; games.sort(function (a, b) { if (sortBy === 'platform') { const pa = (a.platforms && a.platforms[0]) || '~'; const pb = (b.platforms && b.platforms[0]) || '~'; return String(pa).localeCompare(String(pb), 'en') || String(a.name || '').localeCompare(String(b.name || ''), 'en'); } return String(a.name || a.spaceId).localeCompare(String(b.name || b.spaceId), '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.spaceId; nm.title = nm.textContent; row.appendChild(nm); const series = g.series || seriesKey(g.name); if (series) { const tag = document.createElement('span'); tag.className = 'tag'; tag.textContent = series; row.appendChild(tag); } const mt = document.createElement('span'); mt.className = 'mt'; const bits = []; if ((g.platforms || []).length) bits.push(g.platforms.join('/')); if (g.availability) bits.push(g.availability); 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 }; })(); // ==================== 启动 ==================== let hotkeyBound = false; function boot() { if (document.getElementById('ubie-root')) return; if (!document.body) return; ui.mount(); ui.progress(0, '就绪'); } function bootSafely() { try { boot(); } catch (err) { console.error(LOG_PREFIX, '界面挂载失败', err); } } function bindHotkey() { if (hotkeyBound) return; hotkeyBound = true; document.addEventListener('keydown', function (e) { if (e.altKey && !e.ctrlKey && !e.metaKey && (e.key === 'u' || e.key === 'U')) { e.preventDefault(); ui.toggle(); } }); } // 自测句柄:纯函数 + 采集入口,方便无头环境验证 try { window.__ubiEnhancer = { version: VERSION, ui: ui, // 供无头预览/调试调用(open/renderAnalysis),不影响脚本行为 pickEntitlements: pickEntitlements, classifyEntitlements: classifyEntitlements, collapseBySpaceId: collapseBySpaceId, collectPlatforms: collectPlatforms, seriesKey: seriesKey, toMillis: toMillis, isSessionExpired: isSessionExpired, analyzeLibrary: analyzeLibrary, buildCsv: buildCsv, buildSummaryCsv: buildSummaryCsv, buildReport: buildReport, buildDigest: buildDigest, makeSnapshot: makeSnapshot, diffSnapshots: diffSnapshots }; } catch (e) { /* 某些沙箱没有 window */ } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { bootSafely(); bindHotkey(); }, { once: true }); } else { bootSafely(); bindHotkey(); } })();