// ==UserScript== // @name AO3 阅读历史增强导出器(提速 + 评论修复版) // @namespace https://github.com/KWzhabing/ao3-reading-exporter // @version 2.1 // @description 一键导出 AO3 阅读历史为 JSON,支持快速/完整模式。现已修复评论检测不准问题,并大幅提速。 // @author KWzhabing (优化 by Qwen) // @match https://archiveofourown.org/users/*/readings* // @icon https://archiveofourown.org/favicon.ico // @grant none // @license MIT // ==/UserScript== (function () { 'use strict'; const username = window.location.pathname.split('/')[2]; if (!username) return; // 创建按钮容器 const container = document.createElement('div'); container.style.margin = '1rem 0'; container.innerHTML = ` `; const readingsList = document.querySelector('#main > dl, #main > ul, .reading-list'); if (readingsList) { readingsList.parentNode.insertBefore(container, readingsList); } else { document.querySelector('#main')?.prepend(container); } // ========== 工具函数:提取 work_id ========== function extractWorkIdFromUrl(url) { const match = url.match(/\/works\/(\d+)/); return match ? match[1] : null; } // ========== 工具函数:获取完整评论并检测是否评论过 ========== async function fetchAllCommentsHtml(workId, username) { if (!workId) return false; try { const commentUrl = `https://archiveofourown.org/comments/show_comments?work_id=${workId}`; const res = await fetch(commentUrl, { credentials: 'include' }); if (!res.ok) return false; const html = await res.text(); // 检查用户名是否出现在评论中(覆盖 a 标签、文本等) const lowerHtml = html.toLowerCase(); const lowerUser = username.toLowerCase(); return lowerHtml.includes(`>${lowerUser}<`) || lowerHtml.includes(`by ${lowerUser}`) || lowerHtml.includes(`comment by ${lowerUser}`); } catch (err) { console.warn('获取评论失败 (work_id=' + workId + '):', err.message); return false; } } // ========== 快速导出 ========== async function exportBasicReadingHistory(btnEl) { const originalText = btnEl.textContent; btnEl.disabled = true; btnEl.textContent = '导出中...'; try { const baseUrl = `https://archiveofourown.org/users/${username}/readings`; const parser = new DOMParser(); let allReadings = []; let page = 1; while (true) { const url = page === 1 ? baseUrl : `${baseUrl}?page=${page}`; const res = await fetch(url, { credentials: 'include' }); if (!res.ok) throw new Error(`列表页请求失败: ${res.status}`); const text = await res.text(); const doc = parser.parseFromString(text, 'text/html'); const readings = Array.from(doc.querySelectorAll('li.reading')).map(item => { const titleEl = item.querySelector('h4 a'); const authorEl = item.querySelector('.byline a'); const dateEl = item.querySelector('.datetime'); if (!titleEl || !dateEl) return null; return { title: titleEl.textContent.trim(), url: 'https://archiveofourown.org' + titleEl.getAttribute('href'), authors: authorEl ? authorEl.textContent.trim() : '', date: dateEl.title || dateEl.textContent.trim() }; }).filter(Boolean); if (readings.length === 0) break; allReadings.push(...readings); page++; // ⚡ 无延迟翻页 } downloadJson(allReadings, 'ao3_reading_history_basic'); } catch (err) { console.error(err); alert('快速导出失败:' + err.message); } finally { btnEl.disabled = false; btnEl.textContent = originalText; } } // ========== 完整导出 ========== async function exportFullReadingHistory(btnEl) { const originalText = btnEl.textContent; btnEl.disabled = true; btnEl.textContent = '准备中...'; try { const baseUrl = `https://archiveofourown.org/users/${username}/readings`; const parser = new DOMParser(); let allReadings = []; let page = 1; while (true) { const url = page === 1 ? baseUrl : `${baseUrl}?page=${page}`; const res = await fetch(url, { credentials: 'include' }); if (!res.ok) throw new Error(`列表页请求失败: ${res.status}`); const text = await res.text(); const doc = parser.parseFromString(text, 'text/html'); const readings = Array.from(doc.querySelectorAll('li.reading')).map(item => { const titleEl = item.querySelector('h4 a'); const authorEl = item.querySelector('.byline a'); const dateEl = item.querySelector('.datetime'); if (!titleEl || !dateEl) return null; return { title: titleEl.textContent.trim(), url: 'https://archiveofourown.org' + titleEl.getAttribute('href'), authors: authorEl ? authorEl.textContent.trim() : '', date: dateEl.title || dateEl.textContent.trim() }; }).filter(Boolean); if (readings.length === 0) break; allReadings.push(...readings); page++; } if (allReadings.length === 0) { alert('未找到任何阅读记录'); return; } // ⚡ 提速参数 const MAX_CONCURRENT = 6; // 平衡速度与稳定性(AO3 对 /comments 接口较敏感) const DELAY_PER_BATCH = 600; // 略微保守,避免 429 const total = allReadings.length; let completed = 0; const updateProgress = () => { const percent = Math.min(100, Math.round((completed / total) * 100)); btnEl.textContent = `导出中... ${percent}% (${completed}/${total})`; }; // ========== 抓取单篇作品详情(含精准评论检测) ========== async function fetchWorkDetails(reading) { try { const workRes = await fetch(reading.url, { credentials: 'include' }); if (!workRes.ok) throw new Error(`HTTP ${workRes.status}`); const workText = await workRes.text(); const workDoc = new DOMParser().parseFromString(workText, 'text/html'); // 字数 let words = null; const wordMeta = workDoc.querySelector('dd.words') || [...workDoc.querySelectorAll('p.meta')].find(p => p.textContent.includes('Words:')); if (wordMeta) { const match = wordMeta.textContent.match(/[\d,]+/); if (match) words = parseInt(match[0].replace(/,/g, ''), 10); } // 标签 const tags = Array.from(workDoc.querySelectorAll('.tag')) .map(el => el.textContent.trim()) .filter(t => t && t !== 'No tags'); // Kudos const kudos_given = !!workDoc.querySelector(`#kudos a[href="/users/${username}"]`); // 🔥【精准评论检测】通过专用评论接口 const workId = extractWorkIdFromUrl(reading.url); const commented = workId ? await fetchAllCommentsHtml(workId, username) : false; return { ...reading, words, tags, kudos_given, commented }; } catch (err) { console.warn(`跳过作品 ${reading.url}:`, err.message); return { ...reading, words: null, tags: [], kudos_given: false, commented: false }; } finally { completed++; updateProgress(); } } // 并发抓取 const queue = [...allReadings]; const results = []; while (queue.length > 0) { const batch = queue.splice(0, MAX_CONCURRENT); const promises = batch.map(fetchWorkDetails); const batchResults = await Promise.all(promises); results.push(...batchResults); if (queue.length > 0) { await new Promise(r => setTimeout(r, DELAY_PER_BATCH)); } } downloadJson(results, 'ao3_reading_history_enhanced'); } catch (err) { console.error(err); alert('完整导出失败:' + err.message); } finally { btnEl.disabled = false; btnEl.textContent = originalText; } } // ========== 事件绑定 ========== document.getElementById('ao3-export-basic').addEventListener('click', function () { exportBasicReadingHistory(this); }); document.getElementById('ao3-export-full').addEventListener('click', function () { exportFullReadingHistory(this); }); // ========== 安全下载函数(兼容性更强) ========== function downloadJson(data, prefix) { const jsonStr = JSON.stringify(data, null, 2); const blob = new Blob([jsonStr], { type: 'application/json;charset=utf-8' }); const url = URL.createObjectURL(blob); const filename = `${prefix}_${new Date().toISOString().slice(0, 10)}.json`; // 尝试自动下载 const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); // 备用:显示手动下载链接(防止被拦截) const fallbackLink = document.createElement('a'); fallbackLink.href = url; fallbackLink.download = filename; fallbackLink.textContent = `⬇️ 如果未自动下载,请点此保存:${filename}`; fallbackLink.style.cssText = ` position: fixed; bottom: 20px; left: 20px; padding: 10px 16px; background: #ff9800; color: white; border-radius: 4px; z-index: 10000; text-decoration: none; font-family: sans-serif; box-shadow: 0 2px 8px rgba(0,0,0,0.3); `; document.body.appendChild(fallbackLink); // 5秒后自动清理 setTimeout(() => { if (fallbackLink.parentNode) fallbackLink.parentNode.removeChild(fallbackLink); URL.revokeObjectURL(url); }, 5000); } })();