// ==UserScript==
// @name AO3 阅读历史增强导出器(提速 + 评论修复 + 稳定增强版)
// @namespace https://github.com/KWzhabing/ao3-reading-exporter
// @version 1.8-enhanced
// @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 userLink = document.querySelector(`a[href="/users/${username}"]`);
if (!userLink) {
alert('⚠️ 请先登录 AO3 账号再使用此工具!');
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;
}
// ========== 带重试的 fetch 封装 ==========
async function fetchWithRetry(url, options = {}, maxRetries = 3, baseDelay = 800) {
for (let i = 0; i <= maxRetries; i++) {
try {
const res = await fetch(url, { credentials: 'include', ...options });
if (res.status === 429) {
const retryAfter = parseInt(res.headers.get('Retry-After')) || baseDelay * (i + 1);
console.warn(`⚠️ 429 Too Many Requests. Waiting ${retryAfter}ms...`);
await new Promise(r => setTimeout(r, retryAfter));
continue;
}
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res;
} catch (err) {
if (i === maxRetries) throw err;
const delay = baseDelay * Math.pow(2, i); // 指数退避
console.warn(`🔁 重试 (${i + 1}/${maxRetries}) ${url}: ${err.message}. 等待 ${delay}ms...`);
await new Promise(r => setTimeout(r, delay));
}
}
}
// ========== 获取评论并检测是否评论过(带重试)==========
async function fetchAllCommentsHtml(workId, username) {
if (!workId) return false;
try {
const commentUrl = `https://archiveofourown.org/comments/show_comments?work_id=${workId}`;
const res = await fetchWithRetry(commentUrl, {}, 2, 1000);
const html = await res.text();
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 fetchWithRetry(url);
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 fetchWithRetry(url);
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 seenUrls = new Set();
const uniqueReadings = allReadings.filter(r => {
if (seenUrls.has(r.url)) return false;
seenUrls.add(r.url);
return true;
});
const MAX_CONCURRENT = 5; // 保守并发
const total = uniqueReadings.length;
let completed = 0;
const results = [];
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 fetchWithRetry(reading.url, {}, 2, 1200);
const workText = await workRes.text();
const workDoc = new DOMParser().parseFromString(workText, 'text/html');
// 字数:支持多种格式
let words = null;
const wordEls = [
workDoc.querySelector('dd.words'),
...Array.from(workDoc.querySelectorAll('p.meta')).find(p => p.textContent.includes('Words:'))
].filter(Boolean);
if (wordEls.length) {
const text = wordEls[0].textContent;
const match = text.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:检查是否在 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.error(`❌ 跳过作品 ${reading.title} (${reading.url}):`, err.message);
return { ...reading, words: null, tags: [], kudos_given: false, commented: false };
} finally {
completed++;
updateProgress();
}
}
// 并发处理(带批次延迟)
const queue = [...uniqueReadings];
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, 800)); // 批次间延迟
}
downloadJson(results, 'ao3_reading_history_enhanced');
console.log('✅ 导出完成!共处理', results.length, '篇作品');
} 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);
setTimeout(() => {
if (fallbackLink.parentNode) fallbackLink.parentNode.removeChild(fallbackLink);
URL.revokeObjectURL(url);
}, 5000);
}
})();