Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
210 changes: 151 additions & 59 deletions plugins/english/ao3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = {
fandoms: 'fandom',
Expand All @@ -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 };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Server errors become blank chapters

classifyPage accepts HTTP failures such as 500 and 502 as ok when their bodies lack the listed markers. fetchApi does not reject HTTP errors, so a plain “Bad Gateway” page reaches the parsers. parseChapter returns an empty string, while a failed chapter index makes parseNovel replace the chapter list with one fallback entry.

The previous checkResponse rejected these responses. Keep the specific classifications, then reject any remaining response where res.ok is false.

}

async function fetchPage(url: string): Promise<Ao3Page> {
const res = await fetchApi(url, { headers: REQUEST_HEADERS });
return classifyPage(res, await res.text());
}

function pageError(
page: Exclude<Ao3Page, { kind: 'ok' }>,
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/';

Expand Down Expand Up @@ -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<Plugin.SourceNovel> {
Expand All @@ -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,
Expand All @@ -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(',');
Expand All @@ -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[] = [];
Expand Down Expand Up @@ -256,13 +352,12 @@ class ArchiveOfOurOwn implements Plugin.PluginBase {
async parseChapter(chapterUrl: string): Promise<string> {
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);
Expand Down Expand Up @@ -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(
Expand All @@ -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 {
Expand Down
30 changes: 30 additions & 0 deletions scripts/fixtures/ao3/README.md
Original file line number Diff line number Diff line change
@@ -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.

`<style>` and `<script>` blocks are removed after capture: they are ~80% of the
bytes (mostly workskin CSS) and no parser selector reads them. Everything the
plugin queries — byline, `dl.stats`, `.summary`, `#chapters`, `ol.index`, the
login page and the adult interstitial — is untouched.

| File | Request | Covers |
|---|---|---|
| `chapter-10057010.html` | `/works/10057010/chapters/22409387?view_adult=true` | 58 `a[rel="author"]` links (byline + translations), stats, summary plus a note blockquote |
| `navigate-10057010.html` | `/works/10057010/navigate?view_adult=true` | 188 chapter rows |
| `work-97039671.html` | `/works/97039671/chapters/259407686?view_adult=true` | co-written, two creators |
| `work-97088591.html` | `/works/97088591/chapters/259545856?view_adult=true` | anonymous (`Anonymous`, zero author links) |
| `work-97099316.html` | `/works/97099316?view_adult=true` | one-shot: no `dt.status`, no chapter index |
| `restricted-29870862.html` | `/works/29870862?view_adult=true` | guest login page, `restricted=true`, no `#chapters` |
| `adult-gate-10057010.html` | `/works/10057010` | adult interstitial, `HTTP 200`, no `#chapters` |

The chapter pages are used where a work page would be: AO3 redirects
`/works/{id}?view_adult=true` to `/works/{id}/chapters/{first}` **without the
query string**, which drops the gate bypass and serves the interstitial. The
plugin only avoids this because it also sends `Cookie: view_adult=true`.
Capturing the chapter URL keeps the fixture on the content page.

Regenerate with a guest browser: `fetch(url, { credentials: 'omit' })`, then
save the response body as the file name above.
Loading
Loading