eaf-base-api 4.2.5__tar.gz → 4.3.0__tar.gz
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.
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/PKG-INFO +28 -1
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/README.md +27 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/__init__.py +11 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/base.py +5 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/ffmpeg.py +12 -2
- eaf_base_api-4.3.0/base_api/modules/pagination.py +437 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/provider.py +8 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/urls.py +3 -1
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/pyproject.toml +1 -1
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/pyproject.toml.orig +1 -1
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/LICENSE +0 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/__init__.py +0 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/config.py +0 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/errors.py +0 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/logger.py +0 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/progress_bars.py +0 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/raw_download.py +0 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/static_functions.py +0 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/modules/type_hints.py +0 -0
- {eaf_base_api-4.2.5 → eaf_base_api-4.3.0}/base_api/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: eaf_base_api
|
|
3
|
-
Version: 4.
|
|
3
|
+
Version: 4.3.0
|
|
4
4
|
Summary: A base API for EchterAlsFake's Porn APIs
|
|
5
5
|
Author: Johannes Habel
|
|
6
6
|
Author-email: Johannes Habel <EchterAlsFake@proton.me>
|
|
@@ -287,3 +287,30 @@ optimized. If you just use mine, you need to consume less caffeine and brain cel
|
|
|
287
287
|
# License
|
|
288
288
|
Licensed under The [AGPLv3](https://opensource.org/license/agpl-3-0) license.
|
|
289
289
|
<br>Copyright (C) 2024-2026 Johannes Habel
|
|
290
|
+
|
|
291
|
+
## Shared pagination (4.3.0)
|
|
292
|
+
|
|
293
|
+
`paginated_stream` uses the existing `Helper` item pipeline while discovering
|
|
294
|
+
one source page at a time. Providers supply a page URL factory, an extractor,
|
|
295
|
+
and a `PageInfo` callback based on that same response. `pages` accepts a positive
|
|
296
|
+
integer or `"all"`; `start_page` is always a positive one-based index. A finite
|
|
297
|
+
page limit does not establish exhaustion. Explicit source page bounds continue
|
|
298
|
+
through empty intermediate pages.
|
|
299
|
+
|
|
300
|
+
The returned `PaginatedStream.summary` distinguishes `limit_reached`,
|
|
301
|
+
`exhausted`, `incomplete`, `failed`, and `cancelled`. Page/item errors stay visible:
|
|
302
|
+
`SKIP` becomes `YIELD` during pagination, including custom skip handlers. Default
|
|
303
|
+
errors raise. Error results must be inspected or unwrapped before calling a scan
|
|
304
|
+
successful. Closing a partially consumed stream cancels it and releases its
|
|
305
|
+
iterator. Use `aclosing(stream)` or `async with stream`.
|
|
306
|
+
|
|
307
|
+
Repeated request URLs and unconfirmed repeated page payloads raise. An explicit
|
|
308
|
+
source `current_page` must match the requested page; this allows sites whose
|
|
309
|
+
confirmed distinct pages happen to contain duplicate cards. Optional
|
|
310
|
+
`deduplicate=True` uses item URLs (or `item_identity`) and records duplicates.
|
|
311
|
+
Ordering and bounded item loading remain controlled by `IteratorConfig`.
|
|
312
|
+
|
|
313
|
+
`PageInfo.next_is_probe=True` identifies an inferred boundary request. A
|
|
314
|
+
provider's terminal-error callback may accept a 404 there, or for an independently
|
|
315
|
+
validated initial offset; a 404 after an advertised next link remains an error.
|
|
316
|
+
Repeat detection retains one digest per page, rather than all item URLs.
|
|
@@ -268,3 +268,30 @@ optimized. If you just use mine, you need to consume less caffeine and brain cel
|
|
|
268
268
|
# License
|
|
269
269
|
Licensed under The [AGPLv3](https://opensource.org/license/agpl-3-0) license.
|
|
270
270
|
<br>Copyright (C) 2024-2026 Johannes Habel
|
|
271
|
+
|
|
272
|
+
## Shared pagination (4.3.0)
|
|
273
|
+
|
|
274
|
+
`paginated_stream` uses the existing `Helper` item pipeline while discovering
|
|
275
|
+
one source page at a time. Providers supply a page URL factory, an extractor,
|
|
276
|
+
and a `PageInfo` callback based on that same response. `pages` accepts a positive
|
|
277
|
+
integer or `"all"`; `start_page` is always a positive one-based index. A finite
|
|
278
|
+
page limit does not establish exhaustion. Explicit source page bounds continue
|
|
279
|
+
through empty intermediate pages.
|
|
280
|
+
|
|
281
|
+
The returned `PaginatedStream.summary` distinguishes `limit_reached`,
|
|
282
|
+
`exhausted`, `incomplete`, `failed`, and `cancelled`. Page/item errors stay visible:
|
|
283
|
+
`SKIP` becomes `YIELD` during pagination, including custom skip handlers. Default
|
|
284
|
+
errors raise. Error results must be inspected or unwrapped before calling a scan
|
|
285
|
+
successful. Closing a partially consumed stream cancels it and releases its
|
|
286
|
+
iterator. Use `aclosing(stream)` or `async with stream`.
|
|
287
|
+
|
|
288
|
+
Repeated request URLs and unconfirmed repeated page payloads raise. An explicit
|
|
289
|
+
source `current_page` must match the requested page; this allows sites whose
|
|
290
|
+
confirmed distinct pages happen to contain duplicate cards. Optional
|
|
291
|
+
`deduplicate=True` uses item URLs (or `item_identity`) and records duplicates.
|
|
292
|
+
Ordering and bounded item loading remain controlled by `IteratorConfig`.
|
|
293
|
+
|
|
294
|
+
`PageInfo.next_is_probe=True` identifies an inferred boundary request. A
|
|
295
|
+
provider's terminal-error callback may accept a 404 there, or for an independently
|
|
296
|
+
validated initial offset; a 404 after an advertised next link remains an error.
|
|
297
|
+
Repeat detection retains one digest per page, rather than all item URLs.
|
|
@@ -149,3 +149,14 @@ from base_api.modules.static_functions import (
|
|
|
149
149
|
get_attr_safe,
|
|
150
150
|
build_m3u8_master,
|
|
151
151
|
)
|
|
152
|
+
|
|
153
|
+
from base_api.modules.pagination import (
|
|
154
|
+
PageCount,
|
|
155
|
+
PageInfo,
|
|
156
|
+
PaginationSummary,
|
|
157
|
+
PaginatedStream,
|
|
158
|
+
paginated_stream,
|
|
159
|
+
validate_pagination,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
__all__ += ["PageCount", "PageInfo", "PaginationSummary", "PaginatedStream", "paginated_stream", "validate_pagination"]
|
|
@@ -2104,6 +2104,11 @@ class BaseCore:
|
|
|
2104
2104
|
content = FetchedText(
|
|
2105
2105
|
self._decode_response(response, url, self.logger),
|
|
2106
2106
|
url=getattr(response, "url", None) or url,
|
|
2107
|
+
headers={
|
|
2108
|
+
k.lower(): v
|
|
2109
|
+
for k, v in getattr(response, "headers", {}).items()
|
|
2110
|
+
if k.lower().startswith("x-pagination-")
|
|
2111
|
+
},
|
|
2107
2112
|
)
|
|
2108
2113
|
if key is not None:
|
|
2109
2114
|
self.cache.set_response(key, content)
|
|
@@ -233,6 +233,7 @@ def remux_ts_to_mp4(
|
|
|
233
233
|
try:
|
|
234
234
|
cmd = [
|
|
235
235
|
str(ffmpeg),
|
|
236
|
+
"-nostdin",
|
|
236
237
|
"-y",
|
|
237
238
|
"-v", "error",
|
|
238
239
|
"-i", str(in_p),
|
|
@@ -263,7 +264,12 @@ def remux_ts_to_mp4(
|
|
|
263
264
|
str(out_p),
|
|
264
265
|
])
|
|
265
266
|
|
|
266
|
-
|
|
267
|
+
# GUI launches on Windows may have an invalid inherited console input
|
|
268
|
+
# handle. Supply all streams explicitly and keep FFmpeg windowless.
|
|
269
|
+
proc = subprocess.run(
|
|
270
|
+
cmd, stdin=subprocess.DEVNULL, capture_output=True, text=True,
|
|
271
|
+
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,
|
|
272
|
+
)
|
|
267
273
|
if proc.returncode != 0:
|
|
268
274
|
raise RuntimeError(f"FFmpeg stream-copy remux failed: {proc.stderr.strip()}")
|
|
269
275
|
|
|
@@ -304,6 +310,7 @@ def write_metadata_tags(
|
|
|
304
310
|
try:
|
|
305
311
|
cmd = [
|
|
306
312
|
str(ffmpeg),
|
|
313
|
+
"-nostdin",
|
|
307
314
|
"-y",
|
|
308
315
|
"-v", "error",
|
|
309
316
|
"-i", str(target_path),
|
|
@@ -334,7 +341,10 @@ def write_metadata_tags(
|
|
|
334
341
|
|
|
335
342
|
cmd.extend(["-movflags", "+faststart", str(temporary_output)])
|
|
336
343
|
|
|
337
|
-
proc = subprocess.run(
|
|
344
|
+
proc = subprocess.run(
|
|
345
|
+
cmd, stdin=subprocess.DEVNULL, capture_output=True, text=True,
|
|
346
|
+
creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,
|
|
347
|
+
)
|
|
338
348
|
if proc.returncode != 0:
|
|
339
349
|
raise MetadataWriteError(f"FFmpeg tagging failed: {proc.stderr.strip()}")
|
|
340
350
|
|
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
"""Validated, lazy pagination using the existing Helper request/item pipeline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, replace
|
|
6
|
+
import asyncio
|
|
7
|
+
from hashlib import sha256
|
|
8
|
+
from html.parser import HTMLParser
|
|
9
|
+
from inspect import isawaitable
|
|
10
|
+
from typing import Callable, Literal
|
|
11
|
+
from urllib.parse import parse_qsl, urljoin, urlsplit, urlunsplit
|
|
12
|
+
from base_api.modules.urls import same_site_url
|
|
13
|
+
|
|
14
|
+
from base_api.base import Helper, ScrapeStream
|
|
15
|
+
from base_api.modules.config import make_iterator_config
|
|
16
|
+
from base_api.modules.type_hints import ErrorAction, ErrorMode
|
|
17
|
+
|
|
18
|
+
PageCount = int | Literal["all"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def validate_pagination(pages: PageCount, start_page: int = 1) -> None:
|
|
22
|
+
if isinstance(pages, bool) or (
|
|
23
|
+
pages != "all" and (not isinstance(pages, int) or pages < 1)
|
|
24
|
+
):
|
|
25
|
+
raise ValueError("pages must be a positive integer or 'all'")
|
|
26
|
+
if (
|
|
27
|
+
isinstance(start_page, bool)
|
|
28
|
+
or not isinstance(start_page, int)
|
|
29
|
+
or start_page < 1
|
|
30
|
+
):
|
|
31
|
+
raise ValueError("start_page must be a positive integer")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class PageInfo:
|
|
36
|
+
"""Provider-confirmed navigation. None means the terminal state is unknown."""
|
|
37
|
+
|
|
38
|
+
terminal: bool | None = None
|
|
39
|
+
next_url: str | None = None
|
|
40
|
+
total_pages: int | None = None
|
|
41
|
+
current_page: int | None = None
|
|
42
|
+
next_is_probe: bool = False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class PaginationSummary:
|
|
47
|
+
status: str = "pending"
|
|
48
|
+
pages: int = 0
|
|
49
|
+
last_page: int | None = None
|
|
50
|
+
errors: int = 0
|
|
51
|
+
duplicates: int = 0
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def exhausted(self) -> bool:
|
|
55
|
+
return self.status == "exhausted"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _identity(url):
|
|
59
|
+
p = urlsplit(url)
|
|
60
|
+
return (
|
|
61
|
+
p.scheme,
|
|
62
|
+
p.netloc,
|
|
63
|
+
p.path.rstrip("/"),
|
|
64
|
+
tuple(sorted(parse_qsl(p.query, keep_blank_values=True))),
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _page_signature(rows):
|
|
69
|
+
if not rows:
|
|
70
|
+
return None
|
|
71
|
+
digest = sha256()
|
|
72
|
+
for row in rows:
|
|
73
|
+
value = str(row.get("url") or row.get("video_id") or row).encode()
|
|
74
|
+
digest.update(len(value).to_bytes(8, "big"))
|
|
75
|
+
digest.update(value)
|
|
76
|
+
return digest.digest()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _check_listing_response(content, requested):
|
|
80
|
+
resolved = getattr(content, "url", None)
|
|
81
|
+
if not isinstance(resolved, str):
|
|
82
|
+
return
|
|
83
|
+
before = urlsplit(requested).path.rstrip("/")
|
|
84
|
+
after = urlsplit(resolved).path.rstrip("/")
|
|
85
|
+
if before and not after:
|
|
86
|
+
raise ValueError("Listing redirected to the site homepage")
|
|
87
|
+
if (
|
|
88
|
+
after in {"/login", "/signin", "/register", "/registerstep1", "/user/login"}
|
|
89
|
+
and after != before
|
|
90
|
+
):
|
|
91
|
+
raise ValueError("Listing redirected to an account access page")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class _Links(HTMLParser):
|
|
95
|
+
def __init__(self):
|
|
96
|
+
super().__init__()
|
|
97
|
+
self.hrefs = []
|
|
98
|
+
self.next_hrefs = []
|
|
99
|
+
self.stack = []
|
|
100
|
+
|
|
101
|
+
def handle_starttag(self, tag, attrs):
|
|
102
|
+
attrs = dict(attrs)
|
|
103
|
+
classes = attrs.get("class", "").casefold().split()
|
|
104
|
+
next_marker = "next" in attrs.get("rel", "").casefold().split() or any(
|
|
105
|
+
token in {"next", "next-page", "next_page", "nmnext", "pagination-next"}
|
|
106
|
+
or token.endswith(("--next", "-next", "_next"))
|
|
107
|
+
for token in classes
|
|
108
|
+
)
|
|
109
|
+
inherited = next_marker or any(n for _, n in self.stack)
|
|
110
|
+
if tag == "a" and attrs.get("href"):
|
|
111
|
+
self.hrefs.append(attrs["href"])
|
|
112
|
+
if inherited:
|
|
113
|
+
self.next_hrefs.append(attrs["href"])
|
|
114
|
+
if tag not in {
|
|
115
|
+
"area",
|
|
116
|
+
"base",
|
|
117
|
+
"br",
|
|
118
|
+
"col",
|
|
119
|
+
"embed",
|
|
120
|
+
"hr",
|
|
121
|
+
"img",
|
|
122
|
+
"input",
|
|
123
|
+
"link",
|
|
124
|
+
"meta",
|
|
125
|
+
"param",
|
|
126
|
+
"source",
|
|
127
|
+
"track",
|
|
128
|
+
"wbr",
|
|
129
|
+
}:
|
|
130
|
+
self.stack.append((tag, inherited))
|
|
131
|
+
|
|
132
|
+
def handle_endtag(self, tag):
|
|
133
|
+
for index in range(len(self.stack) - 1, -1, -1):
|
|
134
|
+
if self.stack[index][0] == tag:
|
|
135
|
+
del self.stack[index:]
|
|
136
|
+
break
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def linked_page(
|
|
140
|
+
content, page: int, rows, *, page_url: Callable[[int], str]
|
|
141
|
+
) -> PageInfo:
|
|
142
|
+
"""For HTML endpoints whose numbered anchors describe the complete navigation.
|
|
143
|
+
|
|
144
|
+
Match the actual next request rather than translated link labels or broad
|
|
145
|
+
class-name matches that can accidentally select video cards/recommendations.
|
|
146
|
+
Providers with AJAX blocks or unreliable navigation must supply another parser.
|
|
147
|
+
"""
|
|
148
|
+
parser = _Links()
|
|
149
|
+
parser.feed(str(content))
|
|
150
|
+
expected = page_url(page + 1)
|
|
151
|
+
base = getattr(content, "url", None) or page_url(page)
|
|
152
|
+
if same_site_url(expected, base):
|
|
153
|
+
parts = urlsplit(expected)
|
|
154
|
+
actual = urlsplit(base)
|
|
155
|
+
expected = urlunsplit(
|
|
156
|
+
parts._replace(scheme=actual.scheme, netloc=actual.netloc)
|
|
157
|
+
)
|
|
158
|
+
following = next(
|
|
159
|
+
(
|
|
160
|
+
urljoin(base, h)
|
|
161
|
+
for h in parser.hrefs
|
|
162
|
+
if _identity(urljoin(base, h)) == _identity(expected)
|
|
163
|
+
),
|
|
164
|
+
None,
|
|
165
|
+
)
|
|
166
|
+
if following is None:
|
|
167
|
+
# Sites often omit default sort/filter values in an explicit next link.
|
|
168
|
+
# Trust that control only within the expected listing route and host.
|
|
169
|
+
target = urlsplit(expected)
|
|
170
|
+
for href in parser.next_hrefs:
|
|
171
|
+
candidate = urljoin(base, href)
|
|
172
|
+
parts = urlsplit(candidate)
|
|
173
|
+
if (parts.scheme, parts.netloc, parts.path.rstrip("/")) != (
|
|
174
|
+
target.scheme,
|
|
175
|
+
target.netloc,
|
|
176
|
+
target.path.rstrip("/"),
|
|
177
|
+
):
|
|
178
|
+
continue
|
|
179
|
+
wanted = dict(parse_qsl(target.query))
|
|
180
|
+
received = dict(parse_qsl(parts.query))
|
|
181
|
+
if any(
|
|
182
|
+
key in wanted and received.get(key) != wanted[key]
|
|
183
|
+
for key in ("page", "p", "pg", "from")
|
|
184
|
+
):
|
|
185
|
+
continue
|
|
186
|
+
following = candidate
|
|
187
|
+
break
|
|
188
|
+
return PageInfo(terminal=following is None, next_url=following)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class PaginatedStream(ScrapeStream):
|
|
192
|
+
def __init__(self, generator, summary):
|
|
193
|
+
super().__init__(generator)
|
|
194
|
+
self.summary = summary
|
|
195
|
+
|
|
196
|
+
async def aclose(self):
|
|
197
|
+
try:
|
|
198
|
+
await super().aclose()
|
|
199
|
+
finally:
|
|
200
|
+
if self.summary.status in {"pending", "running"}:
|
|
201
|
+
self.summary.status = "cancelled"
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def paginated_stream(
|
|
205
|
+
*,
|
|
206
|
+
core,
|
|
207
|
+
constructor,
|
|
208
|
+
page_url,
|
|
209
|
+
item_extractor,
|
|
210
|
+
pages: PageCount = 1,
|
|
211
|
+
start_page: int = 1,
|
|
212
|
+
page_info=None,
|
|
213
|
+
iterator_config=None,
|
|
214
|
+
terminal_error=None,
|
|
215
|
+
verify_first=False,
|
|
216
|
+
deduplicate=False,
|
|
217
|
+
item_identity=None,
|
|
218
|
+
):
|
|
219
|
+
"""Discover one source page at a time; Helper retains bounded item concurrency.
|
|
220
|
+
|
|
221
|
+
The extractor runs once per response. Discovery captures that same response,
|
|
222
|
+
so it never issues a second preflight request. No URL array is materialized.
|
|
223
|
+
Page failures always remain visible, even if a caller selected SKIP: a missing
|
|
224
|
+
page cannot be interpreted as successful exhaustion. Item loading follows the
|
|
225
|
+
caller's configuration. Explicit source ordering remains available there.
|
|
226
|
+
"""
|
|
227
|
+
validate_pagination(pages, start_page)
|
|
228
|
+
config = iterator_config or make_iterator_config(
|
|
229
|
+
page_error_mode=ErrorMode.RAISE, item_error_mode=ErrorMode.RAISE
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
# A skipped page would conceal a hole in a complete scan.
|
|
233
|
+
def visible_mode(mode):
|
|
234
|
+
value = ErrorMode(mode)
|
|
235
|
+
return ErrorMode.YIELD if value is ErrorMode.SKIP else value
|
|
236
|
+
|
|
237
|
+
config = replace(
|
|
238
|
+
config,
|
|
239
|
+
page_error_mode=visible_mode(config.page_error_mode),
|
|
240
|
+
item_error_mode=visible_mode(config.item_error_mode),
|
|
241
|
+
)
|
|
242
|
+
summary = PaginationSummary()
|
|
243
|
+
|
|
244
|
+
def visible_errors(handler):
|
|
245
|
+
if handler is None:
|
|
246
|
+
return None
|
|
247
|
+
|
|
248
|
+
async def handle(context):
|
|
249
|
+
action = handler(context)
|
|
250
|
+
if isawaitable(action):
|
|
251
|
+
action = await action
|
|
252
|
+
# A custom SKIP cannot conceal a hole in a pagination scan.
|
|
253
|
+
return ErrorAction.YIELD if action is ErrorAction.SKIP else action
|
|
254
|
+
|
|
255
|
+
return handle
|
|
256
|
+
|
|
257
|
+
config = replace(
|
|
258
|
+
config,
|
|
259
|
+
page_error_handler=visible_errors(config.page_error_handler),
|
|
260
|
+
item_error_handler=visible_errors(config.item_error_handler),
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
async def generate():
|
|
264
|
+
number = start_page
|
|
265
|
+
current = page_url(number)
|
|
266
|
+
visited, signatures, seen_items = set(), set(), set()
|
|
267
|
+
summary.status = "running"
|
|
268
|
+
can_end_on_error = verify_first and start_page > 1
|
|
269
|
+
try:
|
|
270
|
+
if verify_first and start_page > 1:
|
|
271
|
+
first = await core.fetch_text(
|
|
272
|
+
page_url(1), method=config._page_request_method
|
|
273
|
+
)
|
|
274
|
+
_check_listing_response(first, page_url(1))
|
|
275
|
+
first_rows = tuple(item_extractor(first))
|
|
276
|
+
first_info = (
|
|
277
|
+
page_info(first, 1, first_rows)
|
|
278
|
+
if page_info
|
|
279
|
+
else PageInfo(terminal=not first_rows)
|
|
280
|
+
)
|
|
281
|
+
if (
|
|
282
|
+
first_info.total_pages is not None
|
|
283
|
+
and start_page > first_info.total_pages
|
|
284
|
+
) or (first_info.total_pages is None and first_info.terminal is True):
|
|
285
|
+
summary.status = "exhausted"
|
|
286
|
+
return
|
|
287
|
+
first_signature = _page_signature(first_rows)
|
|
288
|
+
if first_signature:
|
|
289
|
+
signatures.add(first_signature)
|
|
290
|
+
while True:
|
|
291
|
+
key = _identity(current)
|
|
292
|
+
if key in visited:
|
|
293
|
+
raise ValueError("Pagination repeated a request")
|
|
294
|
+
visited.add(key)
|
|
295
|
+
captured = {}
|
|
296
|
+
|
|
297
|
+
def extract(content):
|
|
298
|
+
_check_listing_response(content, current)
|
|
299
|
+
rows = tuple(item_extractor(content))
|
|
300
|
+
info = (
|
|
301
|
+
page_info(content, number, rows)
|
|
302
|
+
if page_info
|
|
303
|
+
else PageInfo(terminal=not rows)
|
|
304
|
+
)
|
|
305
|
+
if not isinstance(info, PageInfo):
|
|
306
|
+
raise TypeError("page_info must return PageInfo")
|
|
307
|
+
if info.terminal is not None and type(info.terminal) is not bool:
|
|
308
|
+
raise ValueError("Invalid terminal-page signal")
|
|
309
|
+
if type(info.next_is_probe) is not bool:
|
|
310
|
+
raise ValueError("Invalid next-page probe signal")
|
|
311
|
+
if info.next_url is not None and (
|
|
312
|
+
not isinstance(info.next_url, str) or not info.next_url.strip()
|
|
313
|
+
):
|
|
314
|
+
raise ValueError("Invalid next-page URL")
|
|
315
|
+
if info.current_page is not None and (
|
|
316
|
+
type(info.current_page) is not int
|
|
317
|
+
or info.current_page != number
|
|
318
|
+
):
|
|
319
|
+
raise ValueError("Server returned a different listing page")
|
|
320
|
+
if info.total_pages is not None:
|
|
321
|
+
if type(info.total_pages) is not int or info.total_pages < 0:
|
|
322
|
+
raise ValueError("Invalid total page count")
|
|
323
|
+
if number > info.total_pages:
|
|
324
|
+
if rows:
|
|
325
|
+
raise ValueError(
|
|
326
|
+
"Server returned items beyond its total pages"
|
|
327
|
+
)
|
|
328
|
+
info = replace(info, terminal=True)
|
|
329
|
+
elif number == info.total_pages:
|
|
330
|
+
info = replace(info, terminal=True)
|
|
331
|
+
else:
|
|
332
|
+
# An empty/filtered source page can precede later
|
|
333
|
+
# items. A trusted indexed bound takes precedence.
|
|
334
|
+
info = replace(info, terminal=False)
|
|
335
|
+
signature = _page_signature(rows)
|
|
336
|
+
# A source can place the same cards on two distinct indexed
|
|
337
|
+
# pages. Require an independently parsed current-page signal
|
|
338
|
+
# before accepting that; URL generation alone proves nothing.
|
|
339
|
+
if (
|
|
340
|
+
signature
|
|
341
|
+
and signature in signatures
|
|
342
|
+
and info.current_page is None
|
|
343
|
+
):
|
|
344
|
+
raise ValueError("Server repeated a complete listing page")
|
|
345
|
+
captured.update(info=info, signature=signature)
|
|
346
|
+
return rows
|
|
347
|
+
|
|
348
|
+
stream = Helper(core=core, constructor=constructor).iterator(
|
|
349
|
+
[current], extract, iterator_config=config
|
|
350
|
+
)
|
|
351
|
+
try:
|
|
352
|
+
async with stream:
|
|
353
|
+
async for result in stream:
|
|
354
|
+
if result.error is not None:
|
|
355
|
+
if (
|
|
356
|
+
can_end_on_error
|
|
357
|
+
and terminal_error
|
|
358
|
+
and terminal_error(result.error, number)
|
|
359
|
+
):
|
|
360
|
+
summary.status = (
|
|
361
|
+
"exhausted"
|
|
362
|
+
if not summary.errors
|
|
363
|
+
else "incomplete"
|
|
364
|
+
)
|
|
365
|
+
return
|
|
366
|
+
summary.errors += 1
|
|
367
|
+
elif deduplicate:
|
|
368
|
+
identity = (
|
|
369
|
+
item_identity(result.item)
|
|
370
|
+
if item_identity
|
|
371
|
+
else result.url
|
|
372
|
+
)
|
|
373
|
+
if identity in seen_items:
|
|
374
|
+
summary.duplicates += 1
|
|
375
|
+
continue
|
|
376
|
+
seen_items.add(identity)
|
|
377
|
+
yield replace(result, page_index=number - start_page)
|
|
378
|
+
except Exception as error:
|
|
379
|
+
if (
|
|
380
|
+
can_end_on_error
|
|
381
|
+
and terminal_error
|
|
382
|
+
and terminal_error(error, number)
|
|
383
|
+
):
|
|
384
|
+
summary.status = (
|
|
385
|
+
"exhausted" if not summary.errors else "incomplete"
|
|
386
|
+
)
|
|
387
|
+
return
|
|
388
|
+
raise
|
|
389
|
+
if not captured:
|
|
390
|
+
summary.status = "incomplete"
|
|
391
|
+
return
|
|
392
|
+
signatures.add(captured["signature"])
|
|
393
|
+
summary.pages += 1
|
|
394
|
+
summary.last_page = number
|
|
395
|
+
info = captured["info"]
|
|
396
|
+
if info.terminal is True:
|
|
397
|
+
summary.status = "exhausted" if not summary.errors else "incomplete"
|
|
398
|
+
return
|
|
399
|
+
if pages != "all" and summary.pages >= pages:
|
|
400
|
+
summary.status = (
|
|
401
|
+
"limit_reached" if not summary.errors else "incomplete"
|
|
402
|
+
)
|
|
403
|
+
return
|
|
404
|
+
if info.next_url is None and info.terminal is None:
|
|
405
|
+
raise ValueError(
|
|
406
|
+
"Provider cannot establish the next page or exhaustion"
|
|
407
|
+
)
|
|
408
|
+
number += 1
|
|
409
|
+
current = info.next_url or page_url(number)
|
|
410
|
+
# A 404 after an advertised next link is a hole, not exhaustion.
|
|
411
|
+
# Only an explicitly speculative boundary probe may end on it.
|
|
412
|
+
can_end_on_error = info.next_is_probe
|
|
413
|
+
except (GeneratorExit, asyncio.CancelledError):
|
|
414
|
+
summary.status = "cancelled"
|
|
415
|
+
raise
|
|
416
|
+
except BaseException:
|
|
417
|
+
summary.errors += 1
|
|
418
|
+
summary.status = "failed"
|
|
419
|
+
raise
|
|
420
|
+
finally:
|
|
421
|
+
if summary.status == "running":
|
|
422
|
+
summary.status = "cancelled"
|
|
423
|
+
|
|
424
|
+
return PaginatedStream(generate(), summary)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def http_status_is(error, status):
|
|
428
|
+
"""Inspect translated provider/Helper errors without losing HTTP semantics."""
|
|
429
|
+
from base_api.modules.errors import HTTPStatusError
|
|
430
|
+
|
|
431
|
+
seen = set()
|
|
432
|
+
while error is not None and id(error) not in seen:
|
|
433
|
+
seen.add(id(error))
|
|
434
|
+
if isinstance(error, HTTPStatusError):
|
|
435
|
+
return error.status_code == status
|
|
436
|
+
error = error.__cause__ or error.__context__
|
|
437
|
+
return False
|
|
@@ -4,6 +4,7 @@ import copy
|
|
|
4
4
|
import json
|
|
5
5
|
import os
|
|
6
6
|
from functools import wraps
|
|
7
|
+
from urllib.parse import urlsplit
|
|
7
8
|
|
|
8
9
|
from base_api.modules import errors
|
|
9
10
|
from base_api.modules.logger import class_name, get_logger, log_context
|
|
@@ -23,6 +24,13 @@ async def fetch_content(core, url: str, *, logger, owner=None, get_json=False,
|
|
|
23
24
|
try:
|
|
24
25
|
content = await core.fetch_text(url)
|
|
25
26
|
resolved = getattr(content, "url", None)
|
|
27
|
+
if (isinstance(resolved, str) and owner is not None
|
|
28
|
+
and getattr(owner, "url", None) == url and same_site_url(url, resolved)):
|
|
29
|
+
before, after = urlsplit(url), urlsplit(resolved)
|
|
30
|
+
if before.path not in {"", "/"} and after.path in {"", "/"}:
|
|
31
|
+
raise error_types.NotFound("Resource redirected to the site homepage", url=url)
|
|
32
|
+
if after.path.rstrip("/") in {"/login", "/signin", "/register", "/registerstep1", "/user/login"}:
|
|
33
|
+
raise errors.AccessDeniedError("Resource redirected to an account access page")
|
|
26
34
|
if (isinstance(resolved, str) and owner is not None
|
|
27
35
|
and getattr(owner, "url", None) == url and same_site_url(url, resolved)):
|
|
28
36
|
owner.resolved_url = resolved
|
|
@@ -44,8 +44,10 @@ class FetchedText(str):
|
|
|
44
44
|
"""A string that retains response identity through text caches and parsers."""
|
|
45
45
|
|
|
46
46
|
url: str
|
|
47
|
+
headers: dict[str, str]
|
|
47
48
|
|
|
48
|
-
def __new__(cls, content: str, *, url: str):
|
|
49
|
+
def __new__(cls, content: str, *, url: str, headers=None):
|
|
49
50
|
value = super().__new__(cls, content)
|
|
50
51
|
value.url = url
|
|
52
|
+
value.headers = dict(headers or {})
|
|
51
53
|
return value
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|