// ==UserScript==
// @name AO3 阅读历史增强导出器(提速版)
// @namespace https://github.com/KWzhabing/ao3-reading-exporter
// @version 1.6
// @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);
}
// ========== 快速导出 ==========
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++;
// ⚡ 移除原 300ms 延迟以加速翻页
}
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 = 8;
const DELAY_PER_BATCH = 500;
const total = allReadings.length;
let completed = 0;
const updateProgress = () => {
const percent = Math.min(100, Math.round((completed / total) * 100));
btnEl.textContent = `导出中... ${percent}% (${completed}/${total})`;
};
// 🔍 优化:更快的评论检测(只查 .posted 文本)
function isCommentedByUser(workDoc, username) {
const postedElements = workDoc.querySelectorAll('.comment .posted');
for (const el of postedElements) {
if (el.textContent.includes(`by ${username}`)) {
return true;
}
}
return false;
}
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 commented = isCommentedByUser(workDoc, username);
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 a = document.createElement('a');
a.href = url;
a.download = `${prefix}_${new Date().toISOString().slice(0, 10)}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
})();