ao3fetch 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ao3fetch/__init__.py +211 -0
- ao3fetch/downloads.py +455 -0
- ao3fetch/entities.py +481 -0
- ao3fetch/fetcher.py +256 -0
- ao3fetch/languages.py +176 -0
- ao3fetch/markdown.py +200 -0
- ao3fetch/pageLoaders.py +109 -0
- ao3fetch/pagination.py +28 -0
- ao3fetch/py.typed +0 -0
- ao3fetch/series.py +82 -0
- ao3fetch/t.py +36 -0
- ao3fetch/tags.py +231 -0
- ao3fetch/urls.py +282 -0
- ao3fetch/users.py +135 -0
- ao3fetch/utils.py +139 -0
- ao3fetch/works.py +609 -0
- ao3fetch-0.1.0.dist-info/METADATA +123 -0
- ao3fetch-0.1.0.dist-info/RECORD +21 -0
- ao3fetch-0.1.0.dist-info/WHEEL +5 -0
- ao3fetch-0.1.0.dist-info/licenses/LICENSE.md +10 -0
- ao3fetch-0.1.0.dist-info/top_level.txt +1 -0
ao3fetch/__init__.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""Python library for scraping AO3 and AO3-compatible archives, ported from FujoWebDev/AO3.js."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from . import urls as urls
|
|
6
|
+
from .downloads import parseEpubWork as parseEpubWork
|
|
7
|
+
from .entities import (
|
|
8
|
+
ArchiveId as ArchiveId,
|
|
9
|
+
Author as Author,
|
|
10
|
+
BasicSeries as BasicSeries,
|
|
11
|
+
Chapter as Chapter,
|
|
12
|
+
ChapterText as ChapterText,
|
|
13
|
+
ChildTag as ChildTag,
|
|
14
|
+
ContentNotes as ContentNotes,
|
|
15
|
+
DownloadedFileInfo as DownloadedFileInfo,
|
|
16
|
+
DownloadedWork as DownloadedWork,
|
|
17
|
+
LockedWorkSummary as LockedWorkSummary,
|
|
18
|
+
PageInfo as PageInfo,
|
|
19
|
+
Series as Series,
|
|
20
|
+
SortDirection as SortDirection,
|
|
21
|
+
SubTag as SubTag,
|
|
22
|
+
Tag as Tag,
|
|
23
|
+
TagCategory as TagCategory,
|
|
24
|
+
TagSearchFilters as TagSearchFilters,
|
|
25
|
+
TagSearchResult as TagSearchResult,
|
|
26
|
+
TagSearchResultSummary as TagSearchResultSummary,
|
|
27
|
+
TagSearchResultType as TagSearchResultType,
|
|
28
|
+
TagSearchSortColumn as TagSearchSortColumn,
|
|
29
|
+
TagSearchType as TagSearchType,
|
|
30
|
+
TagWranglingStatus as TagWranglingStatus,
|
|
31
|
+
User as User,
|
|
32
|
+
UserWorks as UserWorks,
|
|
33
|
+
UserWorksFilters as UserWorksFilters,
|
|
34
|
+
UserWorksSortColumn as UserWorksSortColumn,
|
|
35
|
+
WorkBlurbStats as WorkBlurbStats,
|
|
36
|
+
WorkBlurbSummary as WorkBlurbSummary,
|
|
37
|
+
WorkBlurbTags as WorkBlurbTags,
|
|
38
|
+
WorkCategory as WorkCategory,
|
|
39
|
+
WorkChaptersCount as WorkChaptersCount,
|
|
40
|
+
WorkRatings as WorkRatings,
|
|
41
|
+
WorkStats as WorkStats,
|
|
42
|
+
WorkSummary as WorkSummary,
|
|
43
|
+
WorkTags as WorkTags,
|
|
44
|
+
WorkText as WorkText,
|
|
45
|
+
WorkWarnings as WorkWarnings,
|
|
46
|
+
WorkWarningStatus as WorkWarningStatus,
|
|
47
|
+
WorkWithChapters as WorkWithChapters,
|
|
48
|
+
WorkWithText as WorkWithText,
|
|
49
|
+
)
|
|
50
|
+
from .fetcher import (
|
|
51
|
+
Fetcher as Fetcher,
|
|
52
|
+
FetchResponse as FetchResponse,
|
|
53
|
+
OnRetryCallback as OnRetryCallback,
|
|
54
|
+
RetryEvent as RetryEvent,
|
|
55
|
+
defaultFetch as defaultFetch,
|
|
56
|
+
getFetcher as getFetcher,
|
|
57
|
+
getRetryAfterSeconds as getRetryAfterSeconds,
|
|
58
|
+
resetFetcher as resetFetcher,
|
|
59
|
+
setFetcher as setFetcher,
|
|
60
|
+
withCache as withCache,
|
|
61
|
+
withRetry as withRetry,
|
|
62
|
+
)
|
|
63
|
+
from .languages import AO3_LANGUAGES as AO3_LANGUAGES
|
|
64
|
+
from .markdown import toMarkdown as toMarkdown
|
|
65
|
+
from .pagination import (
|
|
66
|
+
PagedResult as PagedResult,
|
|
67
|
+
collectAllPages as collectAllPages,
|
|
68
|
+
getAllPages as getAllPages,
|
|
69
|
+
)
|
|
70
|
+
from .series import getSeries as getSeries
|
|
71
|
+
from .tags import (
|
|
72
|
+
getTag as getTag,
|
|
73
|
+
getTagNameById as getTagNameById,
|
|
74
|
+
searchTags as searchTags,
|
|
75
|
+
)
|
|
76
|
+
from .urls import (
|
|
77
|
+
DEFAULT_BASE_URL as DEFAULT_BASE_URL,
|
|
78
|
+
ParsedUserUrl as ParsedUserUrl,
|
|
79
|
+
ParsedWorkUrl as ParsedWorkUrl,
|
|
80
|
+
getArchiveBaseUrl as getArchiveBaseUrl,
|
|
81
|
+
getAsShortUrl as getAsShortUrl,
|
|
82
|
+
getAuthorFromUrl as getAuthorFromUrl,
|
|
83
|
+
getDownloadUrls as getDownloadUrls,
|
|
84
|
+
getSearchUrlFromTagFilters as getSearchUrlFromTagFilters,
|
|
85
|
+
getSeriesUrl as getSeriesUrl,
|
|
86
|
+
getTagUrl as getTagUrl,
|
|
87
|
+
getTagWorksFeedAtomUrl as getTagWorksFeedAtomUrl,
|
|
88
|
+
getTagWorksFeedUrl as getTagWorksFeedUrl,
|
|
89
|
+
getUserDetailsFromUrl as getUserDetailsFromUrl,
|
|
90
|
+
getUserProfileUrl as getUserProfileUrl,
|
|
91
|
+
getUserWorksUrl as getUserWorksUrl,
|
|
92
|
+
getWorkDetailsFromUrl as getWorkDetailsFromUrl,
|
|
93
|
+
getWorkIndexUrl as getWorkIndexUrl,
|
|
94
|
+
getWorkUrl as getWorkUrl,
|
|
95
|
+
resetArchiveBaseUrl as resetArchiveBaseUrl,
|
|
96
|
+
setArchiveBaseUrl as setArchiveBaseUrl,
|
|
97
|
+
)
|
|
98
|
+
from .users import (
|
|
99
|
+
getUser as getUser,
|
|
100
|
+
getUserWorks as getUserWorks,
|
|
101
|
+
)
|
|
102
|
+
from .utils import (
|
|
103
|
+
ArchivePageRequestError as ArchivePageRequestError,
|
|
104
|
+
InvalidIDError as InvalidIDError,
|
|
105
|
+
isValidArchiveId as isValidArchiveId,
|
|
106
|
+
parseArchiveId as parseArchiveId,
|
|
107
|
+
toPlainText as toPlainText,
|
|
108
|
+
)
|
|
109
|
+
from .works import (
|
|
110
|
+
getWork as getWork,
|
|
111
|
+
getWorkContent as getWorkContent,
|
|
112
|
+
getWorkWithChapters as getWorkWithChapters,
|
|
113
|
+
parseWorkBlurb as parseWorkBlurb,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
__all__ = [
|
|
117
|
+
"AO3_LANGUAGES",
|
|
118
|
+
"DEFAULT_BASE_URL",
|
|
119
|
+
"ArchiveId",
|
|
120
|
+
"ArchivePageRequestError",
|
|
121
|
+
"Author",
|
|
122
|
+
"BasicSeries",
|
|
123
|
+
"Chapter",
|
|
124
|
+
"ChapterText",
|
|
125
|
+
"ChildTag",
|
|
126
|
+
"ContentNotes",
|
|
127
|
+
"DownloadedFileInfo",
|
|
128
|
+
"DownloadedWork",
|
|
129
|
+
"FetchResponse",
|
|
130
|
+
"Fetcher",
|
|
131
|
+
"InvalidIDError",
|
|
132
|
+
"LockedWorkSummary",
|
|
133
|
+
"OnRetryCallback",
|
|
134
|
+
"PageInfo",
|
|
135
|
+
"PagedResult",
|
|
136
|
+
"ParsedUserUrl",
|
|
137
|
+
"ParsedWorkUrl",
|
|
138
|
+
"RetryEvent",
|
|
139
|
+
"Series",
|
|
140
|
+
"SortDirection",
|
|
141
|
+
"SubTag",
|
|
142
|
+
"Tag",
|
|
143
|
+
"TagCategory",
|
|
144
|
+
"TagSearchFilters",
|
|
145
|
+
"TagSearchResult",
|
|
146
|
+
"TagSearchResultSummary",
|
|
147
|
+
"TagSearchResultType",
|
|
148
|
+
"TagSearchSortColumn",
|
|
149
|
+
"TagSearchType",
|
|
150
|
+
"TagWranglingStatus",
|
|
151
|
+
"User",
|
|
152
|
+
"UserWorks",
|
|
153
|
+
"UserWorksFilters",
|
|
154
|
+
"UserWorksSortColumn",
|
|
155
|
+
"WorkBlurbStats",
|
|
156
|
+
"WorkBlurbSummary",
|
|
157
|
+
"WorkBlurbTags",
|
|
158
|
+
"WorkCategory",
|
|
159
|
+
"WorkChaptersCount",
|
|
160
|
+
"WorkRatings",
|
|
161
|
+
"WorkStats",
|
|
162
|
+
"WorkSummary",
|
|
163
|
+
"WorkTags",
|
|
164
|
+
"WorkText",
|
|
165
|
+
"WorkWarningStatus",
|
|
166
|
+
"WorkWarnings",
|
|
167
|
+
"WorkWithChapters",
|
|
168
|
+
"WorkWithText",
|
|
169
|
+
"collectAllPages",
|
|
170
|
+
"defaultFetch",
|
|
171
|
+
"getAllPages",
|
|
172
|
+
"getArchiveBaseUrl",
|
|
173
|
+
"getAsShortUrl",
|
|
174
|
+
"getAuthorFromUrl",
|
|
175
|
+
"getDownloadUrls",
|
|
176
|
+
"getFetcher",
|
|
177
|
+
"getRetryAfterSeconds",
|
|
178
|
+
"getSearchUrlFromTagFilters",
|
|
179
|
+
"getSeries",
|
|
180
|
+
"getSeriesUrl",
|
|
181
|
+
"getTag",
|
|
182
|
+
"getTagNameById",
|
|
183
|
+
"getTagUrl",
|
|
184
|
+
"getTagWorksFeedAtomUrl",
|
|
185
|
+
"getTagWorksFeedUrl",
|
|
186
|
+
"getUser",
|
|
187
|
+
"getUserDetailsFromUrl",
|
|
188
|
+
"getUserProfileUrl",
|
|
189
|
+
"getUserWorks",
|
|
190
|
+
"getUserWorksUrl",
|
|
191
|
+
"getWork",
|
|
192
|
+
"getWorkContent",
|
|
193
|
+
"getWorkDetailsFromUrl",
|
|
194
|
+
"getWorkIndexUrl",
|
|
195
|
+
"getWorkUrl",
|
|
196
|
+
"getWorkWithChapters",
|
|
197
|
+
"isValidArchiveId",
|
|
198
|
+
"parseArchiveId",
|
|
199
|
+
"parseEpubWork",
|
|
200
|
+
"parseWorkBlurb",
|
|
201
|
+
"resetArchiveBaseUrl",
|
|
202
|
+
"resetFetcher",
|
|
203
|
+
"searchTags",
|
|
204
|
+
"setArchiveBaseUrl",
|
|
205
|
+
"setFetcher",
|
|
206
|
+
"toMarkdown",
|
|
207
|
+
"toPlainText",
|
|
208
|
+
"urls",
|
|
209
|
+
"withCache",
|
|
210
|
+
"withRetry",
|
|
211
|
+
]
|
ao3fetch/downloads.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
"""AO3 EPUB download parser ported from FujoWebDev/AO3.js."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import io
|
|
7
|
+
import re
|
|
8
|
+
import warnings
|
|
9
|
+
import zipfile
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from urllib.parse import unquote, urlparse
|
|
12
|
+
|
|
13
|
+
from bs4 import BeautifulSoup, NavigableString, Tag, XMLParsedAsHTMLWarning
|
|
14
|
+
|
|
15
|
+
from . import t
|
|
16
|
+
from .entities import (
|
|
17
|
+
Author,
|
|
18
|
+
ChapterText,
|
|
19
|
+
ContentNotes,
|
|
20
|
+
DownloadedFileInfo,
|
|
21
|
+
DownloadedWork,
|
|
22
|
+
WorkCategory,
|
|
23
|
+
WorkChaptersCount,
|
|
24
|
+
WorkRatings,
|
|
25
|
+
WorkTags,
|
|
26
|
+
WorkText,
|
|
27
|
+
WorkWarnings,
|
|
28
|
+
)
|
|
29
|
+
from .languages import AO3_LANGUAGES
|
|
30
|
+
from .urls import getAsShortUrl, getAuthorFromUrl, getWorkDetailsFromUrl, getWorkUrl
|
|
31
|
+
from .utils import cleanText, innerHtml
|
|
32
|
+
from .works import (
|
|
33
|
+
ANONYMOUS_AUTHOR,
|
|
34
|
+
isAdultRating,
|
|
35
|
+
isDefaultChapterTitle,
|
|
36
|
+
isWorkCategory,
|
|
37
|
+
isWorkRating,
|
|
38
|
+
isWorkWarning,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
_SAFE_LINK_RE: t.Final[re.Pattern[str]] = re.compile(r"^(?:https?:|mailto:)", re.IGNORECASE)
|
|
42
|
+
_PUBLISHED_RE: t.Final[re.Pattern[str]] = re.compile(r"Published:\s*(\S+)")
|
|
43
|
+
_UPDATED_RE: t.Final[re.Pattern[str]] = re.compile(r"(?:Completed|Updated):\s*(\S+)")
|
|
44
|
+
_WORDS_RE: t.Final[re.Pattern[str]] = re.compile(r"Words:\s*([\d,]+)")
|
|
45
|
+
_CHAPTERS_RE: t.Final[re.Pattern[str]] = re.compile(r"Chapters:\s*(\d+)/(\d+|\?)")
|
|
46
|
+
_AUTHOR_PARENS_RE: t.Final[re.Pattern[str]] = re.compile(r"^(.+?)\s+\((.+)\)$")
|
|
47
|
+
|
|
48
|
+
_PREFACE_LABELS: t.Final[dict[str, tuple[str, ...]]] = {
|
|
49
|
+
"rating": ("Rating",),
|
|
50
|
+
"warnings": ("Archive Warning", "Archive Warnings"),
|
|
51
|
+
"categories": ("Category", "Categories"),
|
|
52
|
+
"fandoms": ("Fandom", "Fandoms"),
|
|
53
|
+
"relationships": ("Relationship", "Relationships"),
|
|
54
|
+
"characters": ("Character", "Characters"),
|
|
55
|
+
"additional": ("Additional Tag", "Additional Tags"),
|
|
56
|
+
"language": ("Language",),
|
|
57
|
+
"stats": ("Stats",),
|
|
58
|
+
}
|
|
59
|
+
_RENAMED_WARNINGS: t.Final[dict[str, WorkWarnings]] = {
|
|
60
|
+
"Choose Not To Use Archive Warnings": WorkWarnings.CHOOSE_NOT_TO_WARN,
|
|
61
|
+
}
|
|
62
|
+
_LANGUAGE_NAMES: t.Final[frozenset[str]] = frozenset(AO3_LANGUAGES.values())
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(slots=True)
|
|
66
|
+
class _ParsedStats:
|
|
67
|
+
publishedAt: str
|
|
68
|
+
updatedAt: str | None
|
|
69
|
+
words: int
|
|
70
|
+
chapters: WorkChaptersCount | None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(slots=True)
|
|
74
|
+
class _RawChapter:
|
|
75
|
+
heading: str
|
|
76
|
+
summary: str | None
|
|
77
|
+
notes: ContentNotes
|
|
78
|
+
html: str
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _resolveZipPath(fromFile: str, href: str) -> str:
|
|
82
|
+
segments = fromFile.split("/")[:-1]
|
|
83
|
+
for segment in unquote(href).split("/"):
|
|
84
|
+
if segment == "..":
|
|
85
|
+
if segments:
|
|
86
|
+
segments.pop()
|
|
87
|
+
elif segment not in {".", ""}:
|
|
88
|
+
segments.append(segment)
|
|
89
|
+
return "/".join(segments)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _readZipBytes(zf: zipfile.ZipFile, fromFile: str, href: str) -> tuple[str, bytes]:
|
|
93
|
+
filePath = _resolveZipPath(fromFile, href)
|
|
94
|
+
try:
|
|
95
|
+
return (filePath, zf.read(filePath))
|
|
96
|
+
except KeyError as exc:
|
|
97
|
+
msg = f"The EPUB doesn't have the file {filePath}"
|
|
98
|
+
raise ValueError(msg) from exc
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _extractEpubBody(epub: bytes) -> tuple[BeautifulSoup, str]:
|
|
102
|
+
"""Combine all EPUB spine XHTML files into one BeautifulSoup document."""
|
|
103
|
+
try:
|
|
104
|
+
zf = zipfile.ZipFile(io.BytesIO(epub))
|
|
105
|
+
except zipfile.BadZipFile as exc:
|
|
106
|
+
msg = "Couldn't open the file as an EPUB"
|
|
107
|
+
raise ValueError(msg) from exc
|
|
108
|
+
|
|
109
|
+
with zf, warnings.catch_warnings():
|
|
110
|
+
warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning)
|
|
111
|
+
_, containerBytes = _readZipBytes(zf, "", "META-INF/container.xml")
|
|
112
|
+
containerSoup = BeautifulSoup(containerBytes.decode("utf-8", errors="replace"), "html.parser")
|
|
113
|
+
rootfile = containerSoup.find("rootfile")
|
|
114
|
+
packagePath = rootfile.get("full-path") if isinstance(rootfile, Tag) else None
|
|
115
|
+
if not isinstance(packagePath, str) or not packagePath:
|
|
116
|
+
msg = "The EPUB doesn't say where its package file is"
|
|
117
|
+
raise ValueError(msg)
|
|
118
|
+
|
|
119
|
+
_, pkgBytes = _readZipBytes(zf, "", packagePath)
|
|
120
|
+
pkgSoup = BeautifulSoup(pkgBytes.decode("utf-8", errors="replace"), "html.parser")
|
|
121
|
+
|
|
122
|
+
items: dict[str, tuple[str, str]] = {}
|
|
123
|
+
mediaTypes: dict[str, str] = {}
|
|
124
|
+
for item in pkgSoup.select("manifest > item"):
|
|
125
|
+
itemId = item.get("id")
|
|
126
|
+
href = item.get("href")
|
|
127
|
+
mediaType = item.get("media-type")
|
|
128
|
+
if isinstance(itemId, str) and isinstance(href, str):
|
|
129
|
+
resolvedMedia = mediaType if isinstance(mediaType, str) else "image/jpeg"
|
|
130
|
+
items[itemId] = (href, resolvedMedia)
|
|
131
|
+
mediaTypes[_resolveZipPath(packagePath, href)] = resolvedMedia
|
|
132
|
+
|
|
133
|
+
spinePaths: list[str] = []
|
|
134
|
+
for itemref in pkgSoup.select("spine > itemref"):
|
|
135
|
+
idref = itemref.get("idref")
|
|
136
|
+
if not isinstance(idref, str) or idref not in items:
|
|
137
|
+
msg = "The EPUB's reading order lists a file it doesn't have"
|
|
138
|
+
raise ValueError(msg)
|
|
139
|
+
href, _ = items[idref]
|
|
140
|
+
filePath, _ = _readZipBytes(zf, packagePath, href)
|
|
141
|
+
spinePaths.append(filePath)
|
|
142
|
+
|
|
143
|
+
langEl = pkgSoup.find("dc:language")
|
|
144
|
+
languageCode = langEl.get_text().strip() if isinstance(langEl, Tag) else ""
|
|
145
|
+
|
|
146
|
+
bodies: list[str] = []
|
|
147
|
+
for filePath in spinePaths:
|
|
148
|
+
docSoup = BeautifulSoup(zf.read(filePath).decode("utf-8", errors="replace"), "html.parser")
|
|
149
|
+
for img in docSoup.select("img"):
|
|
150
|
+
src = img.get("src")
|
|
151
|
+
if not isinstance(src, str) or not src:
|
|
152
|
+
continue
|
|
153
|
+
parsed = urlparse(src)
|
|
154
|
+
if parsed.scheme:
|
|
155
|
+
continue
|
|
156
|
+
imgPath, imgBytes = _readZipBytes(zf, filePath, src)
|
|
157
|
+
mtype = mediaTypes.get(imgPath, "image/jpeg")
|
|
158
|
+
encoded = base64.b64encode(imgBytes).decode("ascii")
|
|
159
|
+
img["src"] = f"data:{mtype};base64,{encoded}"
|
|
160
|
+
bodyEl = docSoup.find("body")
|
|
161
|
+
bodies.append(innerHtml(bodyEl) if isinstance(bodyEl, Tag) else "")
|
|
162
|
+
|
|
163
|
+
return (BeautifulSoup("\n".join(bodies), "html.parser"), languageCode)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _sanitizeNodes(nodes: list[Tag | NavigableString]) -> str:
|
|
167
|
+
"""Clean EPUB HTML fragments (strip styling/classes, drop endnote links, keep safe links)."""
|
|
168
|
+
rawHtml = "".join(str(node) for node in nodes)
|
|
169
|
+
soup = BeautifulSoup(f"<div>{rawHtml}</div>", "html.parser")
|
|
170
|
+
wrapper = soup.find("div")
|
|
171
|
+
if not isinstance(wrapper, Tag):
|
|
172
|
+
return ""
|
|
173
|
+
for endnoteLink in wrapper.select(".endnote-link"):
|
|
174
|
+
endnoteLink.decompose()
|
|
175
|
+
for element in list(wrapper.find_all(True)):
|
|
176
|
+
if not isinstance(element, Tag):
|
|
177
|
+
continue
|
|
178
|
+
href = element.get("href")
|
|
179
|
+
src = element.get("src")
|
|
180
|
+
alt = element.get("alt")
|
|
181
|
+
element.attrs = {}
|
|
182
|
+
if element.name == "a":
|
|
183
|
+
if isinstance(href, str) and _SAFE_LINK_RE.match(href):
|
|
184
|
+
element["href"] = href
|
|
185
|
+
else:
|
|
186
|
+
element.unwrap()
|
|
187
|
+
elif element.name == "img" and isinstance(src, str) and src:
|
|
188
|
+
element["src"] = src
|
|
189
|
+
if isinstance(alt, str):
|
|
190
|
+
element["alt"] = alt
|
|
191
|
+
elif element.name == "iframe" and isinstance(src, str) and src.startswith("https:"):
|
|
192
|
+
element["src"] = src
|
|
193
|
+
return innerHtml(wrapper).strip()
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _getNotesAfter(scopeNodes: list[Tag], label: str) -> str | None:
|
|
197
|
+
for scope in scopeNodes:
|
|
198
|
+
for para in scope.find_all("p"):
|
|
199
|
+
if not isinstance(para, Tag):
|
|
200
|
+
continue
|
|
201
|
+
if cleanText(para.get_text()) != label:
|
|
202
|
+
continue
|
|
203
|
+
if para.find_parent("blockquote") is not None:
|
|
204
|
+
continue
|
|
205
|
+
bq = para.find_next_sibling("blockquote")
|
|
206
|
+
if isinstance(bq, Tag):
|
|
207
|
+
contents = [c for c in bq.contents if isinstance(c, (Tag, NavigableString))]
|
|
208
|
+
return _sanitizeNodes(contents)
|
|
209
|
+
return None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _extractPrefaceTags(soup: BeautifulSoup) -> dict[str, list[str]]:
|
|
213
|
+
rawTags: dict[str, list[str]] = {}
|
|
214
|
+
for term in soup.select("#preface dl.tags dt"):
|
|
215
|
+
label = cleanText(term.get_text()).rstrip(":")
|
|
216
|
+
dd = term.find_next_sibling("dd")
|
|
217
|
+
if not isinstance(dd, Tag):
|
|
218
|
+
continue
|
|
219
|
+
links = dd.find_all("a")
|
|
220
|
+
if links:
|
|
221
|
+
rawTags[label] = [cleanText(link.get_text()) for link in links]
|
|
222
|
+
else:
|
|
223
|
+
rawTags[label] = [cleanText(dd.get_text())]
|
|
224
|
+
return rawTags
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _lookupPreface(tagsMap: dict[str, list[str]], fieldName: str) -> list[str] | None:
|
|
228
|
+
for label in _PREFACE_LABELS[fieldName]:
|
|
229
|
+
if label in tagsMap:
|
|
230
|
+
return tagsMap[label]
|
|
231
|
+
return None
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _parseStats(statsText: str) -> _ParsedStats | None:
|
|
235
|
+
pubMatch = _PUBLISHED_RE.search(statsText)
|
|
236
|
+
wordsMatch = _WORDS_RE.search(statsText)
|
|
237
|
+
if pubMatch is None or wordsMatch is None:
|
|
238
|
+
return None
|
|
239
|
+
updMatch = _UPDATED_RE.search(statsText)
|
|
240
|
+
chMatch = _CHAPTERS_RE.search(statsText)
|
|
241
|
+
chaptersCount = (
|
|
242
|
+
WorkChaptersCount(
|
|
243
|
+
published=int(chMatch.group(1)),
|
|
244
|
+
total=None if chMatch.group(2) == "?" else int(chMatch.group(2)),
|
|
245
|
+
)
|
|
246
|
+
if chMatch is not None
|
|
247
|
+
else None
|
|
248
|
+
)
|
|
249
|
+
return _ParsedStats(
|
|
250
|
+
publishedAt=pubMatch.group(1),
|
|
251
|
+
updatedAt=updMatch.group(1) if updMatch is not None else None,
|
|
252
|
+
words=int(wordsMatch.group(1).replace(",", "")),
|
|
253
|
+
chapters=chaptersCount,
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _extractEpubChapters(soup: BeautifulSoup) -> list[_RawChapter]:
|
|
258
|
+
chaptersRoot = soup.select_one("#chapters")
|
|
259
|
+
if chaptersRoot is None:
|
|
260
|
+
return []
|
|
261
|
+
grouped: list[tuple[str, list[Tag], list[Tag | NavigableString], list[Tag]]] = []
|
|
262
|
+
for part in chaptersRoot.find_all(recursive=False):
|
|
263
|
+
if not isinstance(part, Tag):
|
|
264
|
+
continue
|
|
265
|
+
headingEl = part if part.name == "h2" else part.find("h2")
|
|
266
|
+
partId = part.get("id")
|
|
267
|
+
if isinstance(headingEl, Tag):
|
|
268
|
+
grouped.append((cleanText(headingEl.get_text()), [part], [], []))
|
|
269
|
+
elif isinstance(partId, str) and partId.startswith("endnotes"):
|
|
270
|
+
if grouped:
|
|
271
|
+
grouped[-1][3].append(part)
|
|
272
|
+
elif grouped:
|
|
273
|
+
for child in part.contents:
|
|
274
|
+
if isinstance(child, (Tag, NavigableString)):
|
|
275
|
+
grouped[-1][2].append(child)
|
|
276
|
+
|
|
277
|
+
return [
|
|
278
|
+
_RawChapter(
|
|
279
|
+
heading=heading,
|
|
280
|
+
summary=_getNotesAfter(meta, "Chapter Summary"),
|
|
281
|
+
notes=ContentNotes(
|
|
282
|
+
start=_getNotesAfter(meta, "Chapter Notes"),
|
|
283
|
+
end=_getNotesAfter(endNotes, "Chapter End Notes"),
|
|
284
|
+
),
|
|
285
|
+
html=_sanitizeNodes(textNodes),
|
|
286
|
+
)
|
|
287
|
+
for heading, meta, textNodes, endNotes in grouped
|
|
288
|
+
]
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _resolveAuthors(byline: str, authorUrls: list[str], problems: list[str]) -> tuple[Author, ...] | None:
|
|
292
|
+
if not authorUrls:
|
|
293
|
+
if byline == "Anonymous":
|
|
294
|
+
return (ANONYMOUS_AUTHOR,)
|
|
295
|
+
authors: list[Author] = []
|
|
296
|
+
for rawPart in byline.split(","):
|
|
297
|
+
part = rawPart.strip()
|
|
298
|
+
if not part:
|
|
299
|
+
continue
|
|
300
|
+
match = _AUTHOR_PARENS_RE.match(part)
|
|
301
|
+
if match is not None:
|
|
302
|
+
authors.append(Author(username=match.group(2), pseud=match.group(1), anonymous=False))
|
|
303
|
+
else:
|
|
304
|
+
authors.append(Author(username=part, pseud=part, anonymous=False))
|
|
305
|
+
return tuple(authors)
|
|
306
|
+
try:
|
|
307
|
+
return tuple(getAuthorFromUrl(url) for url in authorUrls)
|
|
308
|
+
except ValueError as exc:
|
|
309
|
+
problems.append(str(exc))
|
|
310
|
+
return None
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def parseEpubWork(epub: bytes, *, filePath: str | None = None) -> DownloadedWork:
|
|
314
|
+
"""Parse an AO3 EPUB download into a DownloadedWork with full metadata and chapters."""
|
|
315
|
+
soup, languageCode = _extractEpubBody(epub)
|
|
316
|
+
tagsMap = _extractPrefaceTags(soup)
|
|
317
|
+
prefaceNodes = [el for el in soup.select("#preface") if isinstance(el, Tag)]
|
|
318
|
+
afterwordNodes = [el for el in soup.select("#afterword") if isinstance(el, Tag)]
|
|
319
|
+
|
|
320
|
+
workUrls = [href for link in soup.select("#preface .message a") if isinstance((href := link.get("href")), str)]
|
|
321
|
+
workUrl = next((u for u in workUrls if "/works/" in u), None)
|
|
322
|
+
if workUrl is None:
|
|
323
|
+
msg = "The EPUB doesn't look like a work downloaded from AO3"
|
|
324
|
+
raise ValueError(msg)
|
|
325
|
+
workId = getWorkDetailsFromUrl(workUrl).workId
|
|
326
|
+
|
|
327
|
+
titleEl = soup.select_one("#preface h1")
|
|
328
|
+
title = cleanText(titleEl.get_text()) if titleEl is not None else ""
|
|
329
|
+
bylineEl = soup.select_one("#preface .byline")
|
|
330
|
+
byline = re.sub(r"^by\s+", "", cleanText(bylineEl.get_text())) if bylineEl is not None else ""
|
|
331
|
+
authorUrls = [
|
|
332
|
+
href for link in soup.select("#preface .byline a[rel='author']") if isinstance((href := link.get("href")), str)
|
|
333
|
+
]
|
|
334
|
+
|
|
335
|
+
problems: list[str] = []
|
|
336
|
+
|
|
337
|
+
rawStatsList = _lookupPreface(tagsMap, "stats")
|
|
338
|
+
rawStats = rawStatsList[0] if rawStatsList else None
|
|
339
|
+
stats = _parseStats(rawStats) if rawStats is not None else None
|
|
340
|
+
if stats is None:
|
|
341
|
+
problems.append(f'Couldn\'t read the "Stats:" list: {rawStats or "(missing)"}')
|
|
342
|
+
|
|
343
|
+
rawRatingList = _lookupPreface(tagsMap, "rating")
|
|
344
|
+
rawRating = rawRatingList[0] if rawRatingList else None
|
|
345
|
+
rating: WorkRatings | None = None
|
|
346
|
+
if rawRating is not None and isWorkRating(rawRating):
|
|
347
|
+
rating = WorkRatings(rawRating)
|
|
348
|
+
else:
|
|
349
|
+
problems.append(f"Unknown rating: {rawRating or '(missing)'}")
|
|
350
|
+
|
|
351
|
+
rawCategories = _lookupPreface(tagsMap, "categories")
|
|
352
|
+
categories: tuple[WorkCategory, ...] | None = None
|
|
353
|
+
if rawCategories is not None:
|
|
354
|
+
parsedCats: list[WorkCategory] = []
|
|
355
|
+
for item in rawCategories:
|
|
356
|
+
if isWorkCategory(item):
|
|
357
|
+
parsedCats.append(WorkCategory(item))
|
|
358
|
+
else:
|
|
359
|
+
problems.append(f"Unknown category: {item}")
|
|
360
|
+
categories = tuple(parsedCats)
|
|
361
|
+
|
|
362
|
+
parsedWarnings: list[WorkWarnings] = []
|
|
363
|
+
for rawWarn in _lookupPreface(tagsMap, "warnings") or []:
|
|
364
|
+
mapped = _RENAMED_WARNINGS.get(rawWarn, rawWarn)
|
|
365
|
+
if isWorkWarning(mapped):
|
|
366
|
+
parsedWarnings.append(WorkWarnings(mapped))
|
|
367
|
+
else:
|
|
368
|
+
problems.append(f"Unknown warning: {rawWarn}")
|
|
369
|
+
|
|
370
|
+
rawLangList = _lookupPreface(tagsMap, "language")
|
|
371
|
+
languageName = rawLangList[0] if rawLangList else None
|
|
372
|
+
language: str | None = None
|
|
373
|
+
if languageName is not None:
|
|
374
|
+
if languageName in _LANGUAGE_NAMES:
|
|
375
|
+
language = languageName
|
|
376
|
+
else:
|
|
377
|
+
problems.append(f"Unknown language: {languageName}")
|
|
378
|
+
elif languageCode:
|
|
379
|
+
if languageCode in AO3_LANGUAGES:
|
|
380
|
+
language = AO3_LANGUAGES[languageCode]
|
|
381
|
+
else:
|
|
382
|
+
problems.append(f"Unknown language code: {languageCode}")
|
|
383
|
+
else:
|
|
384
|
+
problems.append("Missing language")
|
|
385
|
+
|
|
386
|
+
authors = _resolveAuthors(byline, authorUrls, problems)
|
|
387
|
+
fandoms = tuple(_lookupPreface(tagsMap, "fandoms") or [])
|
|
388
|
+
rawChapters = _extractEpubChapters(soup)
|
|
389
|
+
|
|
390
|
+
if not title:
|
|
391
|
+
problems.append("Missing title")
|
|
392
|
+
if not fandoms:
|
|
393
|
+
problems.append("Missing fandoms")
|
|
394
|
+
if authors is not None and not authors:
|
|
395
|
+
problems.append("Missing authors")
|
|
396
|
+
if not rawChapters:
|
|
397
|
+
problems.append("Missing chapters")
|
|
398
|
+
|
|
399
|
+
if stats is None or rating is None or authors is None or language is None or not rawChapters or problems:
|
|
400
|
+
msg = "The EPUB isn't a valid AO3 download:\n- " + "\n- ".join(problems)
|
|
401
|
+
raise ValueError(msg)
|
|
402
|
+
|
|
403
|
+
isMulti = stats.chapters is not None
|
|
404
|
+
chaptersTuple = tuple(
|
|
405
|
+
ChapterText(
|
|
406
|
+
id=None,
|
|
407
|
+
url=None,
|
|
408
|
+
shortUrl=None,
|
|
409
|
+
index=idx + 1,
|
|
410
|
+
title=None if (not isMulti or isDefaultChapterTitle(ch.heading, idx + 1)) else ch.heading,
|
|
411
|
+
summary=ch.summary,
|
|
412
|
+
notes=ch.notes,
|
|
413
|
+
html=ch.html,
|
|
414
|
+
)
|
|
415
|
+
for idx, ch in enumerate(rawChapters)
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
canonicalUrl = getWorkUrl(workId)
|
|
419
|
+
chaptersInfo = stats.chapters or WorkChaptersCount(published=len(chaptersTuple), total=len(chaptersTuple))
|
|
420
|
+
|
|
421
|
+
return DownloadedWork(
|
|
422
|
+
id=workId,
|
|
423
|
+
source="file",
|
|
424
|
+
file=DownloadedFileInfo(format="epub", filePath=filePath),
|
|
425
|
+
host=urlparse(canonicalUrl).hostname or "",
|
|
426
|
+
url=canonicalUrl,
|
|
427
|
+
shortUrl=getAsShortUrl(canonicalUrl),
|
|
428
|
+
title=title,
|
|
429
|
+
authors=authors,
|
|
430
|
+
rating=rating,
|
|
431
|
+
adult=isAdultRating(rating),
|
|
432
|
+
category=categories,
|
|
433
|
+
fandoms=fandoms,
|
|
434
|
+
tags=WorkTags(
|
|
435
|
+
warnings=tuple(parsedWarnings),
|
|
436
|
+
relationships=tuple(_lookupPreface(tagsMap, "relationships") or []),
|
|
437
|
+
characters=tuple(_lookupPreface(tagsMap, "characters") or []),
|
|
438
|
+
additional=tuple(_lookupPreface(tagsMap, "additional") or []),
|
|
439
|
+
),
|
|
440
|
+
language=language,
|
|
441
|
+
summary=_getNotesAfter(prefaceNodes, "Summary"),
|
|
442
|
+
publishedAt=stats.publishedAt,
|
|
443
|
+
updatedAt=stats.updatedAt,
|
|
444
|
+
words=stats.words,
|
|
445
|
+
chapters=chaptersInfo,
|
|
446
|
+
complete=chaptersInfo.published == chaptersInfo.total,
|
|
447
|
+
stats=None,
|
|
448
|
+
content=WorkText(
|
|
449
|
+
notes=ContentNotes(
|
|
450
|
+
start=_getNotesAfter(prefaceNodes, "Notes"),
|
|
451
|
+
end=_getNotesAfter(afterwordNodes, "End Notes"),
|
|
452
|
+
),
|
|
453
|
+
chapters=chaptersTuple,
|
|
454
|
+
),
|
|
455
|
+
)
|