From f656bfaebd31c759a5bb64281724914fda0809b7 Mon Sep 17 00:00:00 2001 From: JKJapona <239331688+JKJapona@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:31:07 +0800 Subject: [PATCH] fix(english/ao3): scope byline, stats and summary, classify failures - author: read the byline (one author link per creator) and fall back to its text, so translated works no longer show up to 58 names and anonymous works are no longer blank - stats: read dl.stats dt/dd pairs; the old dd.stats li a.tag matches nothing - summary: scope to .summary blockquote.userstuff, not every blockquote - classify responses: a guest login page, the adult interstitial, a Cloudflare challenge and a 429 all arrive as usable-looking responses today, so a restricted work parsed as an Untitled novel with a blank chapter. They now throw the matching PluginError with an actionable message. - add offline fixture tests in scripts/test-ao3.js (pnpm check:plugin cannot reach AO3 from a non-browser TLS stack) version: 1.2.0 --- plugins/english/ao3.ts | 210 ++-- scripts/fixtures/ao3/README.md | 30 + scripts/fixtures/ao3/adult-gate-10057010.html | 350 +++++++ scripts/fixtures/ao3/chapter-10057010.html | 921 ++++++++++++++++++ scripts/fixtures/ao3/navigate-10057010.html | 439 +++++++++ scripts/fixtures/ao3/restricted-29870862.html | 276 ++++++ scripts/fixtures/ao3/work-97039671.html | 542 +++++++++++ scripts/fixtures/ao3/work-97088591.html | 529 ++++++++++ scripts/fixtures/ao3/work-97099316.html | 498 ++++++++++ scripts/test-ao3.js | 293 ++++++ 10 files changed, 4029 insertions(+), 59 deletions(-) create mode 100644 scripts/fixtures/ao3/README.md create mode 100644 scripts/fixtures/ao3/adult-gate-10057010.html create mode 100644 scripts/fixtures/ao3/chapter-10057010.html create mode 100644 scripts/fixtures/ao3/navigate-10057010.html create mode 100644 scripts/fixtures/ao3/restricted-29870862.html create mode 100644 scripts/fixtures/ao3/work-97039671.html create mode 100644 scripts/fixtures/ao3/work-97088591.html create mode 100644 scripts/fixtures/ao3/work-97099316.html create mode 100644 scripts/test-ao3.js diff --git a/plugins/english/ao3.ts b/plugins/english/ao3.ts index 7f2124ab2..cc2510fd0 100644 --- a/plugins/english/ao3.ts +++ b/plugins/english/ao3.ts @@ -2,6 +2,11 @@ import { CheerioAPI, load as parseHTML } from 'cheerio'; import { fetchApi } from '@libs/fetch'; import { Plugin } from '@/types/plugin'; import { FilterOption, Filters, FilterTypes } from '@libs/filterInputs'; +import { + PluginError, + createPluginError, + isChallengeHtml, +} from '@libs/pluginError'; const tagAutocompletePaths: Record = { fandoms: 'fandom', @@ -21,28 +26,103 @@ function setTagNames( } } -function checkResponse(res: Response, body: string, context: string) { - if (!res.ok) { - if (res.status >= 500 || res.status === 429 || res.status === 403) { - throw Object.assign( - new Error(`AO3 request timed out / blocked: HTTP ${res.status}`), - { status: res.status, response: res }, - ); - } - throw new Error(`Failed to ${context}: HTTP ${res.status}`); +const REQUEST_HEADERS = { Cookie: 'view_adult=true' }; + +/** + * AO3 renders most failures with HTTP 200, so the body decides what a response + * actually is. A restricted work, for instance, is a 200 login page with no + * `#chapters`; parsing it silently produces an empty novel instead of an error. + */ +type Ao3Page = + | { kind: 'ok'; html: string } + | { kind: 'adult-gate'; html: string } + | { kind: 'login-required'; html: string } + | { kind: 'challenge'; html: string } + | { kind: 'rate-limited'; html: string } + | { kind: 'not-found'; html: string }; + +type PageContext = 'work' | 'chapter' | 'listing'; + +function classifyPage(res: Response, html: string): Ao3Page { + const url = res.url || ''; + + if (res.status === 404) { + return { kind: 'not-found', html }; } - if (body.includes('Retry later')) { - throw Object.assign( - new Error('AO3 rate limit: request timed out by server (Retry later)'), - { status: 429, response: res }, - ); + if (res.status === 429 || /Retry later/i.test(html)) { + return { kind: 'rate-limited', html }; + } + if ( + res.status === 403 || + res.status === 503 || + isChallengeHtml(html, url, url) + ) { + return { kind: 'challenge', html }; + } + + // Requires both signals: a normal page always has `#chapters`, so a stray + // `restricted=true` link (related works, return_to) cannot reject a work + // that actually loaded. + const hasChapters = html.includes('id="chapters"'); + if ( + !hasChapters && + (/restricted=true/i.test(html) || /\/users\/login/i.test(url)) + ) { + return { kind: 'login-required', html }; + } + if (!hasChapters && html.includes('could have adult content')) { + return { kind: 'adult-gate', html }; + } + + return { kind: 'ok', html }; +} + +async function fetchPage(url: string): Promise { + const res = await fetchApi(url, { headers: REQUEST_HEADERS }); + return classifyPage(res, await res.text()); +} + +function pageError( + page: Exclude, + context: PageContext, +): Error { + switch (page.kind) { + case 'not-found': + return createPluginError( + context === 'listing' + ? PluginError.InvalidResponse + : context === 'chapter' + ? PluginError.ChapterNotFound + : PluginError.NovelNotFound, + { status: 404 }, + ); + case 'login-required': + return createPluginError(PluginError.AuthRequired, { + status: 401, + message: + 'This work is restricted to registered AO3 users. Open it in the WebView, log in to AO3, then try again.', + }); + case 'adult-gate': + return createPluginError(PluginError.InvalidResponse, { + status: 200, + message: + 'AO3 asked for adult-content confirmation. Open this work once in the WebView, then try again.', + }); + case 'challenge': + return createPluginError(PluginError.Captcha, { + status: 403, + message: + 'AO3 is showing a bot check. Open the work in the WebView, then try again.', + }); + case 'rate-limited': + return createPluginError(PluginError.RateLimited, { status: 429 }); } } class ArchiveOfOurOwn implements Plugin.PluginBase { id = 'archiveofourown'; name = 'Archive Of Our Own'; - version = '1.1.0'; + version = '1.2.0'; icon = 'src/en/ao3/icon.png'; site = 'https://archiveofourown.org/'; @@ -147,13 +227,11 @@ class ArchiveOfOurOwn implements Plugin.PluginBase { } const link = `${this.site}works/search?${params.toString()}`; - const res = await fetchApi(link, { - headers: { Cookie: 'view_adult=true' }, - }); - const body = await res.text(); - checkResponse(res, body, 'fetch popular novels'); - const loadedCheerio = parseHTML(body); - return this.parseNovels(loadedCheerio); + const result = await fetchPage(link); + if (result.kind !== 'ok') { + throw pageError(result, 'listing'); + } + return this.parseNovels(parseHTML(result.html)); } async parseNovel(novelUrl: string): Promise { @@ -164,18 +242,18 @@ class ArchiveOfOurOwn implements Plugin.PluginBase { this.site, ); navHttpUrl.searchParams.set('view_adult', 'true'); - const headers = { Cookie: 'view_adult=true' }; - - const [result, chapters] = await Promise.all([ - fetchApi(novelHttpUrl.toString(), { headers }), - fetchApi(navHttpUrl.toString(), { headers }), + const [page, chapterPage] = await Promise.all([ + fetchPage(novelHttpUrl.toString()), + fetchPage(navHttpUrl.toString()), ]); - const body = await result.text(); - const chapterlisttext = await chapters.text(); - checkResponse(result, body, 'fetch novel details'); - checkResponse(chapters, chapterlisttext, 'fetch novel chapters'); - const chapterlistload = parseHTML(chapterlisttext); - const loadedCheerio = parseHTML(body); + if (page.kind !== 'ok') { + throw pageError(page, 'work'); + } + if (chapterPage.kind !== 'ok') { + throw pageError(chapterPage, 'work'); + } + const chapterlistload = parseHTML(chapterPage.html); + const loadedCheerio = parseHTML(page.html); const novel: Plugin.SourceNovel = { path: novelUrl, @@ -186,14 +264,24 @@ class ArchiveOfOurOwn implements Plugin.PluginBase { chapters: [], }; - novel.author = loadedCheerio('a[rel="author"]') - .map((i, el) => loadedCheerio(el).text().trim()) + const byline = loadedCheerio('.byline'); + const authors = byline + .find('a[rel="author"]') + .map((_, el) => loadedCheerio(el).text().trim()) .get() - .join(', '); + .filter(Boolean); + // Unscoped `a[rel="author"]` also matches the translations/related-works + // list in the notes (up to 58 names), so the byline is the only safe scope. + // Anonymous works have no author link at all; their byline text is + // "Anonymous", which is the only thing left to read. + novel.author = + authors.join(', ') || byline.first().text().trim() || undefined; novel.genres = Array.from(loadedCheerio('dd.freeform.tags li a.tag')) .map(el => loadedCheerio(el).text().trim()) .join(','); - const summary = loadedCheerio('blockquote.userstuff').text().trim(); + const summary = loadedCheerio('.summary blockquote.userstuff') + .text() + .trim(); const fandom = Array.from(loadedCheerio('dd.fandom.tags li a.tag')) .map(el => loadedCheerio(el).text().trim()) .join(','); @@ -212,9 +300,17 @@ class ArchiveOfOurOwn implements Plugin.PluginBase { const character = Array.from(loadedCheerio('dd.character.tags li a.tag')) .map(el => loadedCheerio(el).text().trim()) .join(','); - const stats = Array.from(loadedCheerio('dd.stats li a.tag')) - .map(el => loadedCheerio(el).text().trim()) - .join(','); + // Stats are `dt`/`dd` pairs in `dl.stats`; the old `dd.stats li a.tag` + // selector no longer exists anywhere on a work page. + const stats = loadedCheerio('dl.stats dt') + .map((_, dt) => { + const label = loadedCheerio(dt).text().trim(); + const value = loadedCheerio(dt).next('dd').text().trim(); + return value ? `${label} ${value}` : ''; + }) + .get() + .filter(Boolean) + .join(', '); novel.summary = `Fandom:\n${fandom}\n\nRating:\n${rating}\n\nWarning:\n${warning}\n\nSummary:\n${summary}\n\nSeries:\n${series}\n\nRelationships:\n${relation}\n\nCharacters:\n${character}\n\nStats:\n${stats}`; const chapterItems: Plugin.ChapterItem[] = []; @@ -256,13 +352,12 @@ class ArchiveOfOurOwn implements Plugin.PluginBase { async parseChapter(chapterUrl: string): Promise { const chapterHttpUrl = new URL(chapterUrl, this.site); chapterHttpUrl.searchParams.set('view_adult', 'true'); - const result = await fetchApi(chapterHttpUrl.toString(), { - headers: { Cookie: 'view_adult=true' }, - }); - const body = await result.text(); - checkResponse(result, body, 'fetch chapter'); + const page = await fetchPage(chapterHttpUrl.toString()); + if (page.kind !== 'ok') { + throw pageError(page, 'chapter'); + } - const loadedCheerio = parseHTML(body); + const loadedCheerio = parseHTML(page.html); loadedCheerio('h3.title').each((i, el) => { const $h3 = loadedCheerio(el); @@ -298,14 +393,11 @@ class ArchiveOfOurOwn implements Plugin.PluginBase { }); const searchUrl = `${this.site}works/search?${params.toString()}`; - const result = await fetchApi(searchUrl, { - headers: { Cookie: 'view_adult=true' }, - }); - const body = await result.text(); - checkResponse(result, body, 'search novels'); - - const loadedCheerio = parseHTML(body); - return this.parseNovels(loadedCheerio); + const result = await fetchPage(searchUrl); + if (result.kind !== 'ok') { + throw pageError(result, 'listing'); + } + return this.parseNovels(parseHTML(result.html)); } async getFilterSuggestions( @@ -320,11 +412,11 @@ class ArchiveOfOurOwn implements Plugin.PluginBase { const params = new URLSearchParams({ term }); const url = `${this.site}autocomplete/${path}?${params.toString()}`; - const res = await fetchApi(url, { - headers: { Cookie: 'view_adult=true' }, - }); - const body = await res.text(); - checkResponse(res, body, 'fetch filter suggestions'); + const page = await fetchPage(url); + if (page.kind !== 'ok') { + throw pageError(page, 'listing'); + } + const body = page.html; let parsed: unknown; try { diff --git a/scripts/fixtures/ao3/README.md b/scripts/fixtures/ao3/README.md new file mode 100644 index 000000000..c13726afd --- /dev/null +++ b/scripts/fixtures/ao3/README.md @@ -0,0 +1,30 @@ +# AO3 fixtures + +Real pages saved from `archiveofourown.org` on 2026-12-02, used by +`scripts/test-ao3.js`. They are captured **as a guest** (no AO3 session) with +the same request shape the plugin sends, so the parsers are tested against the +page a normal install actually receives. + +`