// ==UserScript== // @name O站 世界线记录导出 // @namespace https://userscripts.local/omnimundia-export // @version 1.1.1 // @description 在 O站剧本页左侧添加“导出记录”,导出当前世界线的剧情正文、已选行动和当前实体状态,支持 Markdown 与 JSON。 // @author fenglaosir // @icon https://omnimundia.cn/logo.svg // @license MIT // @homepage https://gitee.com/feng-lao-sir/omnimundia-export // @supportURL https://gitee.com/feng-lao-sir/omnimundia-export/issues // @match https://omnimundia.cn/* // @run-at document-idle // @noframes // @grant GM_addStyle // ==/UserScript== /* * O站 世界线记录导出 * Copyright (c) 2026 fenglaosir * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * 以上为 MIT 许可证正文,与仓库 LICENSE 文件一致。 */ (() => { 'use strict'; const EXPORTER_NAME = 'O站 世界线记录导出'; const EXPORTER_VERSION = '1.1.1'; const SIDEBAR_SELECTOR = '.sidebar-content'; const STORY_SELECTOR = '.story-panel'; const ROOT_ATTRIBUTE = 'data-ome-export-root'; const BUTTON_ATTRIBUTE = 'data-ome-export-button'; const FORMAT_ATTRIBUTE = 'data-ome-format'; const MAX_TURNS = 1000; const POLL_INTERVAL = 50; const TURN_STABLE_MS = 180; const TURN_TIMEOUT_MS = 15000; const API_PREFIX = '/api'; const API_CONCURRENCY = 5; const API_TIMEOUT_MS = 20000; const API_RETRIES = 2; const styles = ` .ome-export-button .ome-export-icon { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; } .ome-export-button .ome-export-icon svg { display: block; } .ome-export-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .ome-export-overlay { position: fixed; inset: 0; z-index: 2147483000; box-sizing: border-box; display: flex; align-items: center; justify-content: center; padding: 16px; background: rgba(0, 0, 0, 0.62); backdrop-filter: blur(2px); } .ome-export-overlay[hidden] { display: none !important; } .ome-export-dialog { box-sizing: border-box; width: min(430px, calc(100vw - 32px)); max-height: calc(100vh - 32px); overflow-y: auto; padding: 20px; border: 1px solid var(--el-border-color, rgba(127, 127, 127, 0.4)); border-radius: 12px; background: var(--el-bg-color-overlay, var(--el-bg-color, #202124)); color: var(--el-text-color-primary, inherit); box-shadow: 0 24px 64px rgba(0, 0, 0, 0.42); font-family: inherit; line-height: 1.5; } .ome-export-dialog-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; } .ome-export-dialog-heading { min-width: 0; } .ome-export-dialog-title { margin: 0; color: inherit; font-size: 18px; font-weight: 650; line-height: 1.35; } .ome-export-dialog-description { margin: 6px 0 0; color: var(--el-text-color-secondary, inherit); font-size: 13px; line-height: 1.55; opacity: 0.78; } .ome-export-close { flex: 0 0 auto; width: 30px; height: 30px; padding: 0; border: 0; border-radius: 7px; background: transparent; color: inherit; font: inherit; font-size: 20px; line-height: 1; cursor: pointer; } .ome-export-close:hover, .ome-export-close:focus-visible { outline: none; background: var(--el-fill-color-light, rgba(127, 127, 127, 0.16)); } .ome-export-options { display: grid; gap: 10px; margin-top: 18px; } .ome-export-option { box-sizing: border-box; display: grid; width: 100%; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 14px; padding: 13px 15px; border: 1px solid var(--el-border-color, rgba(127, 127, 127, 0.35)); border-radius: 9px; background: var(--el-fill-color-blank, transparent); color: inherit; font: inherit; text-align: left; cursor: pointer; } .ome-export-option:hover, .ome-export-option:focus-visible { border-color: var(--el-color-primary, #409eff); outline: none; background: var(--el-fill-color-light, rgba(127, 127, 127, 0.12)); } .ome-export-option-main { display: flex; min-width: 0; flex-direction: column; gap: 3px; } .ome-export-option-title { font-size: 14px; font-weight: 650; } .ome-export-option-description { color: var(--el-text-color-secondary, inherit); font-size: 12px; line-height: 1.5; opacity: 0.76; } .ome-export-option-ext { color: var(--el-text-color-secondary, inherit); font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: 12px; opacity: 0.7; } .ome-export-dialog-footer { display: flex; justify-content: flex-end; margin-top: 14px; } .ome-export-cancel { padding: 7px 14px; border: 1px solid var(--el-border-color, rgba(127, 127, 127, 0.35)); border-radius: 7px; background: transparent; color: inherit; font: inherit; font-size: 13px; cursor: pointer; } .ome-export-cancel:hover, .ome-export-cancel:focus-visible { outline: none; background: var(--el-fill-color-light, rgba(127, 127, 127, 0.14)); } html.ome-exporting .story-panel .pagination, html.ome-exporting .story-panel .input-area, html.ome-exporting .story-panel .options-container, html.ome-exporting .sidebar-content > .sidebar-action-button:not(.ome-export-button) { pointer-events: none !important; } `; if (typeof GM_addStyle === 'function') { GM_addStyle(styles); } else { const style = document.createElement('style'); style.textContent = styles; (document.head || document.documentElement).append(style); } let root = null; let exportButton = null; let exportLabel = null; let formatDialog = null; let dialogLastFocus = null; let busy = false; let syncScheduled = false; let flashTimer = 0; const wait = milliseconds => new Promise(resolve => { window.setTimeout(resolve, milliseconds); }); function directChildrenByClass(parent, className) { if (!parent) return []; return Array.from(parent.children).filter(child => child.classList.contains(className)); } function firstDirectChildByClass(parent, className) { return directChildrenByClass(parent, className)[0] || null; } function cleanInline(value) { return String(value ?? '').replace(/\s+/g, ' ').trim(); } function cleanMultiline(value) { return String(value ?? '') .replace(/\r\n?/g, '\n') .replace(/\u00a0/g, ' ') .trim(); } function escapeMarkdownInline(value) { return cleanInline(value).replace(/([\\`*_[\]<>#|])/g, '\\$1'); } function setButtonLabel(text) { if (exportLabel) exportLabel.textContent = text; } function setButtonDisabled(disabled) { if (!exportButton) return; exportButton.disabled = disabled; exportButton.setAttribute('aria-disabled', disabled ? 'true' : 'false'); } function closeDialog() { if (!formatDialog) return; formatDialog.hidden = true; exportButton?.setAttribute('aria-expanded', 'false'); const previous = dialogLastFocus; dialogLastFocus = null; if (previous instanceof HTMLElement && previous.isConnected) { previous.focus(); } } function ensureFormatDialog() { if (formatDialog?.isConnected) return formatDialog; formatDialog?.remove(); const overlay = document.createElement('div'); overlay.id = 'ome-export-format-dialog'; overlay.className = 'ome-export-overlay'; overlay.hidden = true; const dialog = document.createElement('div'); dialog.className = 'ome-export-dialog'; dialog.setAttribute('role', 'dialog'); dialog.setAttribute('aria-modal', 'true'); dialog.setAttribute('aria-labelledby', 'ome-export-dialog-title'); const header = document.createElement('div'); header.className = 'ome-export-dialog-header'; const heading = document.createElement('div'); heading.className = 'ome-export-dialog-heading'; const title = document.createElement('h2'); title.id = 'ome-export-dialog-title'; title.className = 'ome-export-dialog-title'; title.textContent = '导出当前世界线'; const description = document.createElement('p'); description.className = 'ome-export-dialog-description'; description.textContent = '读取当前世界线的剧情、已选行动和当前实体状态。请选择文件格式。'; heading.append(title, description); const close = document.createElement('button'); close.type = 'button'; close.className = 'ome-export-close'; close.setAttribute('data-ome-close', ''); close.setAttribute('aria-label', '关闭导出格式选择'); close.textContent = '×'; header.append(heading, close); const options = document.createElement('div'); options.className = 'ome-export-options'; for (const item of [ { format: 'markdown', title: 'Markdown 记录', description: '适合阅读、搜索和长期归档,保留原始正文。', ext: '.md' }, { format: 'json', title: 'JSON 数据', description: '保留剧情、行动和实体字段的结构,便于后续处理。', ext: '.json' } ]) { const option = document.createElement('button'); option.type = 'button'; option.className = 'ome-export-option'; option.setAttribute(FORMAT_ATTRIBUTE, item.format); const main = document.createElement('span'); main.className = 'ome-export-option-main'; const optionTitle = document.createElement('span'); optionTitle.className = 'ome-export-option-title'; optionTitle.textContent = item.title; const optionDescription = document.createElement('span'); optionDescription.className = 'ome-export-option-description'; optionDescription.textContent = item.description; const ext = document.createElement('span'); ext.className = 'ome-export-option-ext'; ext.textContent = item.ext; main.append(optionTitle, optionDescription); option.append(main, ext); options.append(option); } const footer = document.createElement('div'); footer.className = 'ome-export-dialog-footer'; const cancel = document.createElement('button'); cancel.type = 'button'; cancel.className = 'ome-export-cancel'; cancel.setAttribute('data-ome-close', ''); cancel.textContent = '取消'; footer.append(cancel); dialog.append(header, options, footer); overlay.append(dialog); overlay.addEventListener('click', event => { if (event.target === overlay) { closeDialog(); return; } const closeTarget = event.target instanceof Element ? event.target.closest('[data-ome-close]') : null; if (closeTarget) { event.preventDefault(); closeDialog(); return; } const formatTarget = event.target instanceof Element ? event.target.closest(`[${FORMAT_ATTRIBUTE}]`) : null; if (!formatTarget) return; const format = formatTarget.getAttribute(FORMAT_ATTRIBUTE); if (format !== 'markdown' && format !== 'json') return; event.preventDefault(); closeDialog(); void runExport(format); }); document.body.append(overlay); formatDialog = overlay; return overlay; } function openDialog() { if (busy || !exportButton) return; const overlay = ensureFormatDialog(); dialogLastFocus = document.activeElement instanceof HTMLElement ? document.activeElement : exportButton; overlay.hidden = false; exportButton.setAttribute('aria-expanded', 'true'); window.requestAnimationFrame(() => { overlay.querySelector(`[${FORMAT_ATTRIBUTE}]`)?.focus(); }); } function flashButton(text) { window.clearTimeout(flashTimer); setButtonLabel(text); flashTimer = window.setTimeout(() => { flashTimer = 0; if (!busy) setButtonLabel('导出记录'); }, 2200); } function findButtonTemplate(sidebar) { if (!sidebar) return null; const buttons = Array.from(sidebar.querySelectorAll(':scope > button.sidebar-action-button')) .filter(button => !button.hasAttribute(ROOT_ATTRIBUTE)); return buttons.find(button => button.querySelector('i.app-line-icon')) || buttons.find(button => !button.classList.contains('el-button--primary')) || buttons[0] || null; } function buildUi() { const sidebar = document.querySelector(SIDEBAR_SELECTOR); const template = findButtonTemplate(sidebar); const button = template ? template.cloneNode(true) : document.createElement('button'); for (const node of [button, ...button.querySelectorAll('[id]')]) { node.removeAttribute('id'); } button.className = 'el-button sidebar-action-button ome-export-button'; button.type = 'button'; button.removeAttribute('disabled'); button.removeAttribute('aria-disabled'); button.removeAttribute('aria-controls'); button.removeAttribute('aria-expanded'); button.removeAttribute('title'); button.setAttribute(ROOT_ATTRIBUTE, ''); button.setAttribute(BUTTON_ATTRIBUTE, ''); button.setAttribute('aria-haspopup', 'dialog'); button.setAttribute('aria-expanded', 'false'); button.setAttribute('aria-controls', 'ome-export-format-dialog'); button.title = '导出当前世界线的剧情、已选行动和当前实体状态'; let content = button.querySelector('.sidebar-action-content'); if (!content) { const outer = document.createElement('span'); content = document.createElement('span'); content.className = 'sidebar-action-content'; outer.append(content); button.replaceChildren(outer); } let icon = content.querySelector('i'); if (!icon) { icon = document.createElement('i'); icon.className = 'el-icon app-line-icon sidebar-action-icon'; content.prepend(icon); } icon.classList.add('ome-export-icon'); icon.setAttribute('aria-hidden', 'true'); const oldSvg = icon.querySelector('svg'); const oldPath = oldSvg?.querySelector('path'); const lineIcon = icon.classList.contains('app-line-icon'); const svgNamespace = 'http://www.w3.org/2000/svg'; const svg = document.createElementNS(svgNamespace, 'svg'); for (const attribute of oldSvg?.attributes || []) { if (attribute.name.startsWith('data-v-')) { svg.setAttribute(attribute.name, attribute.value); } } svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('width', '1em'); svg.setAttribute('height', '1em'); svg.setAttribute('aria-hidden', 'true'); const shapeData = lineIcon ? [ ['M12 4v10', true], ['m7.5 9.5 4.5 4.5 4.5-4.5', true], ['M5 15.5V19h14v-3.5', true] ] : [ ['M11 3h2v9.17l3.09-3.08 1.41 1.41L12 16l-5.5-5.5 1.41-1.41L11 12.17V3Zm-6 14h14v2H5v-2Z', false] ]; for (const [d, stroke] of shapeData) { const path = document.createElementNS(svgNamespace, 'path'); for (const attribute of oldPath?.attributes || []) { if (attribute.name.startsWith('data-v-')) { path.setAttribute(attribute.name, attribute.value); } } if (stroke) { path.setAttribute('class', 'app-line-icon-stroke'); } else { path.setAttribute('fill', 'currentColor'); } path.setAttribute('d', d); svg.append(path); } icon.replaceChildren(svg); let label = content.lastElementChild; if (!label || label === icon) { label = document.createElement('span'); content.append(label); } label.className = 'ome-export-label'; label.textContent = '导出记录'; button.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); if (busy) return; openDialog(); }); exportButton = button; exportLabel = label; return button; } function isGamePage() { const panel = document.querySelector(STORY_SELECTOR); return Boolean( panel && panel.querySelector('.scene-content') && panel.querySelector('.pagination .page-status') ); } function syncUi() { const sidebar = document.querySelector(SIDEBAR_SELECTOR); if (!sidebar || !isGamePage()) { closeDialog(); if (root) root.remove(); root = null; exportButton = null; exportLabel = null; return; } if (!root || !root.isConnected) { const existing = Array.from(sidebar.children) .find(child => child.hasAttribute(ROOT_ATTRIBUTE)); root = existing || buildUi(); } if (root.parentElement !== sidebar) { sidebar.append(root); } for (const duplicate of sidebar.querySelectorAll(`:scope > [${ROOT_ATTRIBUTE}]`)) { if (duplicate !== root) duplicate.remove(); } if (!busy && !flashTimer) setButtonLabel('导出记录'); } function scheduleSync() { if (syncScheduled) return; syncScheduled = true; window.requestAnimationFrame(() => { syncScheduled = false; syncUi(); }); } function getStoryPanel() { const panel = document.querySelector(STORY_SELECTOR); if (!panel) throw new Error('未找到剧本页面,请先打开当前世界线。'); return panel; } function readStoryTitle() { const title = document.querySelector(`${STORY_SELECTOR} .script-title`) || document.querySelector('.script-title'); return cleanInline(title?.textContent) || 'O站世界线'; } function readPageInfo(panel = getStoryPanel()) { const status = panel.querySelector('.pagination .page-status'); if (!status) throw new Error('未找到回合导航,页面结构可能已变化。'); const text = cleanInline(status.textContent); const match = /第\s*(\d+)\s*\/\s*(\d+)\s*回合/.exec(text); if (!match) throw new Error('无法读取当前回合编号。'); const current = Number(match[1]); const total = Number(match[2]); if (!Number.isInteger(current) || !Number.isInteger(total) || current < 1 || total < current) { throw new Error('回合编号无效。'); } return { current, total }; } function getSceneContent(panel = getStoryPanel()) { const content = firstDirectChildByClass(panel, 'scene-content'); if (!content) throw new Error('未找到剧情正文容器。'); return content; } function getSceneSource(content) { return firstDirectChildByClass(content, 'scene'); } function getPageButton(direction, panel = getStoryPanel()) { const nav = panel.querySelector('.pagination .page-nav'); if (!nav) return null; const label = direction === 'next' ? '下一页' : '上一页'; return Array.from(nav.querySelectorAll('button')).find(button => ( cleanInline(button.textContent).includes(label) )) || null; } function isButtonDisabled(button) { return Boolean( !button || button.disabled || button.classList.contains('is-disabled') || button.getAttribute('aria-disabled') === 'true' ); } function readTurnSignature(content) { const source = getSceneSource(content); const action = firstDirectChildByClass(content, 'thought-bubble'); const options = firstDirectChildByClass(content, 'options-container'); const optionText = options ? Array.from(options.querySelectorAll('.option-button')) .map(button => cleanInline(button.textContent)) .join('\u0001') : ''; return [ source?.textContent?.length ?? -1, source?.textContent?.slice(0, 120) ?? '', source?.textContent?.slice(-120) ?? '', action?.textContent ?? '', optionText ].join('\u0000'); } async function waitForStableTurn(target, total, expectedTitle) { const startedAt = performance.now(); let lastSignature = ''; let stableSince = 0; while (performance.now() - startedAt < TURN_TIMEOUT_MS) { const panel = document.querySelector(STORY_SELECTOR); if (!panel) throw new Error('导出期间剧本页面已关闭或被替换。'); if (readStoryTitle() !== expectedTitle) { throw new Error('导出期间切换了剧本,已停止以避免混合不同世界线。'); } const info = readPageInfo(panel); if (info.total !== total) { throw new Error('导出期间总回合数发生变化,请等待世界线稳定后重试。'); } if (info.current === target) { const content = getSceneContent(panel); const source = getSceneSource(content); if (source) { const signature = readTurnSignature(content); const now = performance.now(); if (signature !== lastSignature) { lastSignature = signature; stableSince = now; } else if (stableSince && now - stableSince >= TURN_STABLE_MS) { return panel; } } } else { lastSignature = ''; stableSince = 0; } await wait(POLL_INTERVAL); } throw new Error(`等待第 ${target} 回合内容稳定超时。`); } async function navigateToTurn(target, total, expectedTitle, onStep) { let guard = 0; while (guard < total * 2 + 20) { guard += 1; const panel = getStoryPanel(); const info = readPageInfo(panel); if (info.total !== total) { throw new Error('导出期间总回合数发生变化。'); } if (info.current === target) { await waitForStableTurn(target, total, expectedTitle); onStep?.(target, total); return; } const direction = info.current < target ? 'next' : 'previous'; const button = getPageButton(direction, panel); if (isButtonDisabled(button)) { throw new Error(`无法导航到第 ${target} 回合,翻页按钮不可用。`); } const expectedNext = info.current + (direction === 'next' ? 1 : -1); button.click(); await waitForStableTurn(expectedNext, total, expectedTitle); } throw new Error(`导航到第 ${target} 回合时超过安全翻页次数。`); } function findUnsubmittedDraft(panel) { const fields = panel.querySelectorAll( '.input-area textarea, .input-area input[type="text"], .action-input textarea' ); for (const field of fields) { if (field.disabled || field.readOnly) continue; if (String(field.value ?? '').trim()) return true; } return false; } function looksGenerating(panel) { const controlArea = panel.querySelector('.input-area'); if (!controlArea) return false; const text = cleanInline(controlArea.textContent); return /停止生成|正在生成|生成中/.test(text); } function readTurn(panel, index, warnings) { const content = getSceneContent(panel); const sources = directChildrenByClass(content, 'scene'); const source = sources[0] || null; if (!source) throw new Error(`第 ${index} 回合缺少原始剧情节点。`); if (sources.length > 1) { warnings.push(`第 ${index} 回合存在多个原始剧情节点,已读取第一个。`); } const story = String(source.textContent ?? '') .replace(/^\uFEFF/, '') .replace(/\r\n?/g, '\n'); if (!story.trim()) { warnings.push(`第 ${index} 回合的原始剧情为空。`); } const bubbles = directChildrenByClass(content, 'thought-bubble'); if (bubbles.length > 1) { warnings.push(`第 ${index} 回合存在多个已选行动节点,已读取第一个。`); } const rawAction = cleanMultiline(bubbles[0]?.textContent); let selectedAction = null; if (rawAction) { selectedAction = resolveAction(content, rawAction, index, warnings); } return { index, story, selectedAction }; } function resolveAction(content, rawAction, index, warnings) { const options = firstDirectChildByClass(content, 'options-container'); const byIndex = new Map(); const duplicates = new Set(); for (const button of options?.querySelectorAll('.option-button') || []) { const number = cleanInline(button.querySelector('.option-index-text')?.textContent); const label = cleanMultiline(button.querySelector('.option-label')?.textContent); if (!number) continue; if (byIndex.has(number)) { duplicates.add(number); } else { byIndex.set(number, label); } } return resolveActionFromOptions(byIndex, duplicates, rawAction, index, warnings); } function apiUnavailable(message) { const error = new Error(message); error.apiUnavailable = true; return error; } function readAccessToken() { try { return localStorage.getItem('access_token') || ''; } catch { return ''; } } function findConversationIds() { const ids = []; try { const entries = performance.getEntriesByType('resource'); for (let index = entries.length - 1; index >= 0; index -= 1) { const match = /\/api\/games\/([^/?#]+)\/(?:turns\/\d+|world-state)(?:[?#]|$)/.exec(entries[index].name); if (!match) continue; const id = decodeURIComponent(match[1]); if (id && !ids.includes(id)) ids.push(id); } } catch { // 资源计时不可用时交给 DOM 模式。 } return ids; } function normalizeForCompare(text) { return String(text ?? '').replace(/\s+/g, '').trim(); } async function resolveConversationId(initialTurn) { const ids = findConversationIds(); if (!ids.length) { throw apiUnavailable('未能从浏览器记录中识别当前世界线'); } const panel = getStoryPanel(); const source = getSceneSource(getSceneContent(panel)); const domText = normalizeForCompare(source?.textContent); if (!domText) { throw apiUnavailable('当前回合内容为空,无法校验接口数据'); } for (const id of ids) { try { const proof = await fetchTurnFromApi(id, initialTurn, 1); const apiText = normalizeForCompare(proof?.ai_message?.content); if ( apiText && ( domText.startsWith(apiText.slice(0, 40)) || apiText.startsWith(domText.slice(0, 40)) ) ) { return id; } } catch (error) { if (error?.apiUnavailable && /登录令牌/.test(error.message)) throw error; } } throw apiUnavailable('接口返回内容与当前页面不一致'); } let cachedClientVersion = null; async function readClientVersion() { if (cachedClientVersion !== null) return cachedClientVersion; cachedClientVersion = ''; const sources = Array.from(document.scripts) .map(script => script.src) .filter(src => src && src.includes('/assets/')); for (const source of sources.reverse()) { try { const response = await fetch(source, { credentials: 'same-origin' }); if (!response.ok) continue; const text = await response.text(); const match = /"X-Client-Version"\s*:\s*"([^"]+)"/.exec(text) || /client-refresh-attempt:([^"]+)"/.exec(text); if (match) { cachedClientVersion = match[1]; return cachedClientVersion; } } catch { // 取不到版本号时不发送该请求头,仍可尝试接口。 } } return cachedClientVersion; } async function apiGet(path) { const token = readAccessToken(); if (!token) throw apiUnavailable('未找到当前登录令牌'); const clientVersion = await readClientVersion(); const controller = new AbortController(); const timer = window.setTimeout(() => controller.abort(), API_TIMEOUT_MS); try { const headers = { Authorization: `Bearer ${token}` }; if (clientVersion) headers['X-Client-Version'] = clientVersion; const response = await fetch(`${API_PREFIX}${path}`, { method: 'GET', headers, credentials: 'same-origin', signal: controller.signal }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const body = await response.json(); if ( body && typeof body === 'object' && 'data' in body && Array.isArray(body.errors) && body.meta && typeof body.meta === 'object' ) { return body.data; } return body; } catch (error) { if (error?.name === 'AbortError') throw new Error('请求超时'); throw error; } finally { window.clearTimeout(timer); } } async function fetchTurnFromApi(conversationId, turn, retries = API_RETRIES) { let lastError = null; for (let attempt = 0; attempt <= retries; attempt += 1) { try { return await apiGet( `/games/${encodeURIComponent(conversationId)}/turns/${turn}` ); } catch (error) { lastError = error; if (error?.apiUnavailable) throw error; if (attempt < retries) await wait(250 * (attempt + 1)); } } throw apiUnavailable( `第 ${turn} 回合接口请求失败:${lastError?.message || String(lastError)}` ); } async function mapConcurrent(items, limit, worker) { const results = new Array(items.length); let cursor = 0; const runners = Array.from( { length: Math.min(limit, items.length) }, async () => { while (cursor < items.length) { const index = cursor; cursor += 1; results[index] = await worker(items[index], index); } } ); await Promise.all(runners); return results; } function readApiTurn(data, index, total, warnings) { if (!data || typeof data !== 'object') { throw apiUnavailable(`第 ${index} 回合接口返回为空`); } if (Number(data.turn) !== index) { throw apiUnavailable(`第 ${index} 回合接口返回的回合号不一致`); } if (Number(data.total_turns) !== total) { throw apiUnavailable('接口返回的总回合数与页面不一致'); } const aiMessage = data.ai_message || {}; const story = String(aiMessage.content ?? '') .replace(/^\uFEFF/, '') .replace(/\r\n?/g, '\n'); if (!story.trim()) { warnings.push(`第 ${index} 回合的剧情为空。`); } const rawAction = cleanMultiline(data.player_message?.content); let selectedAction = null; if (rawAction) { const byIndex = new Map(); const duplicates = new Set(); const options = Array.isArray(aiMessage.options) ? aiMessage.options : []; options.forEach((label, optionIndex) => { byIndex.set(String(optionIndex + 1), cleanMultiline(label)); }); selectedAction = resolveActionFromOptions( byIndex, duplicates, rawAction, index, warnings ); } return { index, story, selectedAction }; } async function collectRecordViaApi({ title, initialTurn, total, entitySnapshot, warnings, onProgress }) { if (!readAccessToken()) { throw apiUnavailable('未找到当前登录令牌'); } const conversationId = await resolveConversationId(initialTurn); const indices = Array.from({ length: total }, (_, index) => index + 1); let completed = 0; const rawTurns = await mapConcurrent(indices, API_CONCURRENCY, async index => { const data = await fetchTurnFromApi(conversationId, index); completed += 1; onProgress?.(completed, total); return data; }); const turns = rawTurns.map((data, index) => ( readApiTurn(data, index + 1, total, warnings) )); return buildRecord({ title, initialTurn, total, turns, entitySnapshot, warnings, exportMode: 'api' }); } function resolveActionFromOptions(byIndex, duplicates, rawAction, index, warnings) { if (/^\d+$/.test(rawAction)) { if (duplicates.has(rawAction) || !byIndex.has(rawAction)) { warnings.push( `第 ${index} 回合的已选行动为数字 ${rawAction},但无法在同回合候选中唯一匹配。` ); return { raw: rawAction, text: null, resolution: 'unresolved-number' }; } const text = byIndex.get(rawAction); if (!text) { warnings.push(`第 ${index} 回合的第 ${rawAction} 个选项文本为空。`); return { raw: rawAction, text: null, resolution: 'unresolved-number' }; } return { raw: rawAction, text, resolution: 'same-turn-option-index' }; } return { raw: rawAction, text: rawAction, resolution: 'direct-text' }; } function readTabGroups(tabs) { const header = firstDirectChildByClass(tabs, 'el-tabs__header'); const content = firstDirectChildByClass(tabs, 'el-tabs__content'); if (!header || !content) return []; const panes = Array.from(content.children) .filter(child => child.classList.contains('el-tab-pane')); return Array.from(header.querySelectorAll('.el-tabs__item')) .map(tab => { const paneId = tab.getAttribute('aria-controls'); return { name: cleanInline(tab.textContent), pane: panes.find(pane => pane.id === paneId) || null }; }) .filter(group => group.name && group.pane); } function readSections(container) { const sections = []; for (const collapse of container.querySelectorAll('.world-state-collapse')) { for (const item of Array.from(collapse.children)) { if (!item.classList.contains('el-collapse-item')) continue; const title = cleanInline( item.querySelector('.el-collapse-item__header .el-collapse-item__title')?.textContent ); const fields = []; for (const field of item.querySelectorAll('.item-title')) { const name = cleanInline(field.querySelector('.item-name')?.textContent); if (!name) continue; fields.push({ name, value: cleanMultiline(field.querySelector('.item-value')?.textContent) }); } if (title || fields.length) { sections.push({ title, fields }); } } } return sections; } function readPanelText(pane) { return cleanMultiline(pane.textContent); } function readEntityGroups(entityTabs) { return readTabGroups(entityTabs).map(group => { const sections = readSections(group.pane); const text = sections.length ? '' : readPanelText(group.pane); return { name: group.name, sections, ...(text ? { text } : {}) }; }); } function findStateTabs() { return Array.from(document.querySelectorAll('.el-tabs.custom-tabs')) .find(tabs => ( tabs.querySelector('.entity-tabs') || tabs.querySelector('.player-attributes-collapse') )) || null; } function readEntitySnapshot(sourceTurn, warnings) { const snapshot = { available: false, capturedAt: new Date().toISOString(), sourceTurn, player: null, groups: [], otherPanels: [] }; const tabs = findStateTabs(); if (!tabs) { warnings.push('未找到当前实体状态面板,导出文件不包含实体快照。'); return snapshot; } for (const category of readTabGroups(tabs)) { const pane = category.pane; const entityTabs = pane.querySelector('.entity-tabs'); if (entityTabs) { snapshot.groups.push({ name: category.name, entities: readEntityGroups(entityTabs) }); continue; } const isPlayer = Boolean( pane.querySelector('.player-attributes-collapse') || pane.querySelector('.player-name') ); if (isPlayer && !snapshot.player) { snapshot.player = { name: cleanInline(pane.querySelector('.player-name')?.textContent), sections: readSections(pane) }; continue; } const sections = readSections(pane); const text = sections.length ? '' : readPanelText(pane); snapshot.otherPanels.push({ name: category.name, sections, ...(text ? { text } : {}) }); } snapshot.available = Boolean( snapshot.player || snapshot.groups.length || snapshot.otherPanels.some(panel => panel.sections.length || panel.text) ); if (!snapshot.available) { warnings.push('实体状态面板存在,但未读取到可导出的字段。'); } return snapshot; } function countUnresolvedActions(turns) { return turns.filter(turn => ( turn.selectedAction?.resolution === 'unresolved-number' )).length; } function buildRecord({ title, initialTurn, total, turns, entitySnapshot, warnings, exportMode = 'dom' }) { const unresolvedActions = countUnresolvedActions(turns); return { schemaVersion: 1, type: 'omnimundia-worldline-record', exportMode, exporter: { name: EXPORTER_NAME, version: EXPORTER_VERSION }, exportedAt: new Date().toISOString(), storyTitle: title, turnRange: { start: 1, end: total, initialTurn }, turns, entitySnapshot, completeness: { allTurnsCollected: turns.length === total && turns.every(turn => turn.index >= 1), selectedActionsFullyResolved: unresolvedActions === 0, currentEntitySnapshotIncluded: entitySnapshot.available, historicalEntityChangesIncluded: false, unselectedOptionsIncluded: false }, warnings, notes: [ exportMode === 'api' ? '记录通过站点回合接口并发读取,未使用页面翻页。' : '记录来自当前世界线通过回合导航可访问的剧情。', '未导出未被选择的候选行动。', '实体状态是导出时的当前快照,不包含每轮历史变化。', '数字行动优先按同回合选项序号还原;未匹配时保留原数字并标记。' ] }; } function formatField(name, value) { const safeName = escapeMarkdownInline(name); const lines = cleanMultiline(value).split('\n'); if (lines.length === 1) { return `- **${safeName}**:${lines[0] || '(空)'}`; } return [ `- **${safeName}**:`, ...lines.map(line => ` ${line}`) ].join('\n'); } function renderSections(sections, level = 4) { const output = []; const heading = '#'.repeat(Math.min(level, 6)); for (const section of sections) { if (section.title) { output.push(`${heading} ${escapeMarkdownInline(section.title)}`); output.push(''); } if (section.fields.length) { output.push(...section.fields.map(field => formatField(field.name, field.value))); output.push(''); } } return output; } function renderSelectedAction(action) { if (!action) return []; const output = ['### 已选行动', '']; if (action.resolution === 'unresolved-number') { output.push(action.raw); output.push(''); output.push('> ⚠ 此回合只保留了数字行动,未能确认同回合对应选项。'); output.push(''); return output; } output.push( ...String(action.text ?? action.raw) .split('\n') .map(line => `> ${line}`) ); output.push(''); if (action.resolution === 'same-turn-option-index') { output.push(`> 原始记录为数字 ${action.raw},按同回合第 ${action.raw} 个选项匹配。`); output.push(''); } return output; } function renderEntitySnapshot(snapshot) { const output = [ '## 当前实体状态(导出时快照)', '', `> 快照对应导出时所在的第 ${snapshot.sourceTurn} 回合,不包含每轮实体变化。`, '' ]; if (!snapshot.available) { output.push('_未读取到当前实体状态。_', ''); return output; } if (snapshot.player) { output.push('### 玩家', ''); if (snapshot.player.name) { output.push(`**名称**:${escapeMarkdownInline(snapshot.player.name)}`, ''); } output.push(...renderSections(snapshot.player.sections, 4)); } for (const group of snapshot.groups) { output.push(`### ${escapeMarkdownInline(group.name)}`, ''); for (const entity of group.entities) { output.push(`#### ${escapeMarkdownInline(entity.name)}`, ''); if (entity.sections.length) { output.push(...renderSections(entity.sections, 5)); } else if (entity.text) { output.push(entity.text, ''); } } } for (const panel of snapshot.otherPanels) { output.push(`### ${escapeMarkdownInline(panel.name)}`, ''); if (panel.sections.length) { output.push(...renderSections(panel.sections, 4)); } else if (panel.text) { output.push(panel.text, ''); } } return output; } function buildMarkdown(record) { const localTime = new Date(record.exportedAt).toLocaleString('zh-CN', { hour12: false }); const output = [ `# ${escapeMarkdownInline(record.storyTitle)} — 世界线记录`, '', `- 导出时间:${localTime}`, `- 记录范围:第 1 至 ${record.turnRange.end} 回合`, `- 导出脚本:${EXPORTER_NAME} ${EXPORTER_VERSION}`, `- 未选择候选:不导出`, '' ]; if (record.warnings.length) { output.push('## 导出提醒', ''); output.push(...record.warnings.map(warning => `- ${warning}`)); output.push(''); } for (const turn of record.turns) { output.push('---', '', `## 第 ${turn.index} 回合`, '', '### 剧情', ''); output.push(turn.story.trimEnd(), ''); output.push(...renderSelectedAction(turn.selectedAction)); } output.push('---', ''); output.push(...renderEntitySnapshot(record.entitySnapshot)); output.push('## 导出说明', ''); output.push(...record.notes.map(note => `- ${note}`)); output.push(''); return output.join('\n'); } function localTimestamp(date = new Date()) { const pad = value => String(value).padStart(2, '0'); return [ date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate()), '-', pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds()) ].join(''); } function makeFilename(title, format) { const safeTitle = String(title ?? '') .replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_') .replace(/\s+/g, ' ') .trim() .slice(0, 80) || 'O站世界线'; const extension = format === 'json' ? 'json' : 'md'; return `${safeTitle}_世界线记录_${localTimestamp()}.${extension}`; } function downloadText(text, filename, mimeType) { const blob = new Blob([text], { type: mimeType }); const url = URL.createObjectURL(blob); const anchor = document.createElement('a'); anchor.href = url; anchor.download = filename; anchor.style.display = 'none'; document.body.append(anchor); anchor.click(); anchor.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000); } function showWarnings(warnings) { if (!warnings.length) return; const shown = warnings.slice(0, 8).map(item => `• ${item}`).join('\n'); const extra = warnings.length > 8 ? `\n• 另有 ${warnings.length - 8} 条提醒,请查看导出文件。` : ''; window.alert(`导出已完成,但有以下提醒:\n\n${shown}${extra}`); } async function runExport(format) { if (busy) return; busy = true; window.clearTimeout(flashTimer); flashTimer = 0; closeDialog(); setButtonDisabled(true); setButtonLabel('准备导出…'); document.documentElement.classList.add('ome-exporting'); let initialTurn = null; let total = null; let expectedTitle = ''; let record = null; let failure = ''; let restoreFailed = false; let navigated = false; try { const panel = getStoryPanel(); const info = readPageInfo(panel); initialTurn = info.current; total = info.total; expectedTitle = readStoryTitle(); if (total > MAX_TURNS) { throw new Error(`世界线共有 ${total} 回合,超过 ${MAX_TURNS} 回合的安全上限。`); } if (looksGenerating(panel)) { throw new Error('当前回合仍在生成,请等待生成结束后再导出。'); } if (findUnsubmittedDraft(panel)) { throw new Error('检测到尚未提交的自定义行动,请先提交或清空输入框。'); } const warnings = []; const entitySnapshot = readEntitySnapshot(initialTurn, warnings); try { setButtonLabel(`快速读取 0/${total}`); record = await collectRecordViaApi({ title: expectedTitle, initialTurn, total, entitySnapshot, warnings, onProgress: (done, count) => setButtonLabel(`快速读取 ${done}/${count}`) }); } catch (error) { if (!error?.apiUnavailable) throw error; warnings.push(`快速模式不可用(${error.message}),已改用逐回合读取。`); console.warn(`[O站 导出] 快速模式不可用,回退逐回合读取:${error.message}`); setButtonLabel(`读取 1/${total}`); navigated = true; await navigateToTurn(1, total, expectedTitle, (turn, count) => { setButtonLabel(`读取 ${turn}/${count}`); }); const turns = []; for (let index = 1; index <= total; index += 1) { const stablePanel = await waitForStableTurn(index, total, expectedTitle); turns.push(readTurn(stablePanel, index, warnings)); setButtonLabel(`读取 ${index}/${total}`); if (index < total) { await navigateToTurn(index + 1, total, expectedTitle, (turn, count) => { setButtonLabel(`读取 ${turn}/${count}`); }); } } record = buildRecord({ title: expectedTitle, initialTurn, total, turns, entitySnapshot, warnings }); } } catch (error) { failure = error instanceof Error ? error.message : String(error); console.error(`[O站 导出] ${failure}`, error); } finally { if (navigated && initialTurn && total) { try { setButtonLabel('恢复原回合…'); await navigateToTurn(initialTurn, total, expectedTitle, (turn, count) => { setButtonLabel(`恢复 ${turn}/${count}`); }); } catch (error) { restoreFailed = true; console.warn('[O站 导出] 未能恢复导出前的回合:', error); } } document.documentElement.classList.remove('ome-exporting'); busy = false; setButtonDisabled(false); setButtonLabel('导出记录'); } if (failure) { window.alert( `导出失败:${failure}` + (restoreFailed ? '\n\n同时未能自动恢复导出前的回合,请手动翻页。' : '') ); return; } if (restoreFailed) { record.warnings.push('导出后未能自动恢复原来的回合,请手动翻页。'); } let text; let mimeType; if (format === 'json') { text = `${JSON.stringify(record, null, 2)}\n`; mimeType = 'application/json;charset=utf-8'; } else { text = buildMarkdown(record); mimeType = 'text/markdown;charset=utf-8'; } try { downloadText( text, makeFilename(record.storyTitle, format), mimeType ); } catch (error) { console.error('[O站 导出] 下载失败:', error); window.alert(`文件生成成功,但浏览器未能开始下载:${error instanceof Error ? error.message : String(error)}`); return; } showWarnings(record.warnings); flashButton('已导出'); console.info( `[O站 导出] ${record.storyTitle}:${record.turns.length}/${record.turnRange.end} 回合,` + `提醒 ${record.warnings.length} 条。` ); } document.addEventListener('keydown', event => { if (event.key === 'Escape') { closeDialog(); return; } if (event.key !== 'Tab' || !formatDialog || formatDialog.hidden) return; const focusable = Array.from(formatDialog.querySelectorAll('button:not([disabled])')); if (!focusable.length) return; const first = focusable[0]; const last = focusable[focusable.length - 1]; if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } }); const observer = new MutationObserver(scheduleSync); observer.observe(document.documentElement, { childList: true, subtree: true }); syncUi(); console.info(`[O站 导出] 已启用:${EXPORTER_NAME} ${EXPORTER_VERSION}`); })();