eaf-base-api 4.2.6__tar.gz → 4.3.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: eaf_base_api
3
- Version: 4.2.6
3
+ Version: 4.3.1
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)
@@ -0,0 +1,438 @@
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
+ visited, signatures, seen_items = set(), set(), set()
266
+ summary.status = "running"
267
+ can_end_on_error = verify_first and start_page > 1
268
+ try:
269
+ if verify_first and start_page > 1:
270
+ first = await core.fetch_text(
271
+ page_url(1), method=config._page_request_method
272
+ )
273
+ _check_listing_response(first, page_url(1))
274
+ first_rows = tuple(item_extractor(first))
275
+ first_info = (
276
+ page_info(first, 1, first_rows)
277
+ if page_info
278
+ else PageInfo(terminal=not first_rows)
279
+ )
280
+ if (
281
+ first_info.total_pages is not None
282
+ and start_page > first_info.total_pages
283
+ ) or (first_info.total_pages is None and first_info.terminal is True):
284
+ summary.status = "exhausted"
285
+ return
286
+ first_signature = _page_signature(first_rows)
287
+ if first_signature:
288
+ signatures.add(first_signature)
289
+ # First-page navigation can resolve a canonical listing URL.
290
+ current = page_url(number)
291
+ while True:
292
+ key = _identity(current)
293
+ if key in visited:
294
+ raise ValueError("Pagination repeated a request")
295
+ visited.add(key)
296
+ captured = {}
297
+
298
+ def extract(content):
299
+ _check_listing_response(content, current)
300
+ rows = tuple(item_extractor(content))
301
+ info = (
302
+ page_info(content, number, rows)
303
+ if page_info
304
+ else PageInfo(terminal=not rows)
305
+ )
306
+ if not isinstance(info, PageInfo):
307
+ raise TypeError("page_info must return PageInfo")
308
+ if info.terminal is not None and type(info.terminal) is not bool:
309
+ raise ValueError("Invalid terminal-page signal")
310
+ if type(info.next_is_probe) is not bool:
311
+ raise ValueError("Invalid next-page probe signal")
312
+ if info.next_url is not None and (
313
+ not isinstance(info.next_url, str) or not info.next_url.strip()
314
+ ):
315
+ raise ValueError("Invalid next-page URL")
316
+ if info.current_page is not None and (
317
+ type(info.current_page) is not int
318
+ or info.current_page != number
319
+ ):
320
+ raise ValueError("Server returned a different listing page")
321
+ if info.total_pages is not None:
322
+ if type(info.total_pages) is not int or info.total_pages < 0:
323
+ raise ValueError("Invalid total page count")
324
+ if number > info.total_pages:
325
+ if rows:
326
+ raise ValueError(
327
+ "Server returned items beyond its total pages"
328
+ )
329
+ info = replace(info, terminal=True)
330
+ elif number == info.total_pages:
331
+ info = replace(info, terminal=True)
332
+ else:
333
+ # An empty/filtered source page can precede later
334
+ # items. A trusted indexed bound takes precedence.
335
+ info = replace(info, terminal=False)
336
+ signature = _page_signature(rows)
337
+ # A source can place the same cards on two distinct indexed
338
+ # pages. Require an independently parsed current-page signal
339
+ # before accepting that; URL generation alone proves nothing.
340
+ if (
341
+ signature
342
+ and signature in signatures
343
+ and info.current_page is None
344
+ ):
345
+ raise ValueError("Server repeated a complete listing page")
346
+ captured.update(info=info, signature=signature)
347
+ return rows
348
+
349
+ stream = Helper(core=core, constructor=constructor).iterator(
350
+ [current], extract, iterator_config=config
351
+ )
352
+ try:
353
+ async with stream:
354
+ async for result in stream:
355
+ if result.error is not None:
356
+ if (
357
+ can_end_on_error
358
+ and terminal_error
359
+ and terminal_error(result.error, number)
360
+ ):
361
+ summary.status = (
362
+ "exhausted"
363
+ if not summary.errors
364
+ else "incomplete"
365
+ )
366
+ return
367
+ summary.errors += 1
368
+ elif deduplicate:
369
+ identity = (
370
+ item_identity(result.item)
371
+ if item_identity
372
+ else result.url
373
+ )
374
+ if identity in seen_items:
375
+ summary.duplicates += 1
376
+ continue
377
+ seen_items.add(identity)
378
+ yield replace(result, page_index=number - start_page)
379
+ except Exception as error:
380
+ if (
381
+ can_end_on_error
382
+ and terminal_error
383
+ and terminal_error(error, number)
384
+ ):
385
+ summary.status = (
386
+ "exhausted" if not summary.errors else "incomplete"
387
+ )
388
+ return
389
+ raise
390
+ if not captured:
391
+ summary.status = "incomplete"
392
+ return
393
+ signatures.add(captured["signature"])
394
+ summary.pages += 1
395
+ summary.last_page = number
396
+ info = captured["info"]
397
+ if info.terminal is True:
398
+ summary.status = "exhausted" if not summary.errors else "incomplete"
399
+ return
400
+ if pages != "all" and summary.pages >= pages:
401
+ summary.status = (
402
+ "limit_reached" if not summary.errors else "incomplete"
403
+ )
404
+ return
405
+ if info.next_url is None and info.terminal is None:
406
+ raise ValueError(
407
+ "Provider cannot establish the next page or exhaustion"
408
+ )
409
+ number += 1
410
+ current = info.next_url or page_url(number)
411
+ # A 404 after an advertised next link is a hole, not exhaustion.
412
+ # Only an explicitly speculative boundary probe may end on it.
413
+ can_end_on_error = info.next_is_probe
414
+ except (GeneratorExit, asyncio.CancelledError):
415
+ summary.status = "cancelled"
416
+ raise
417
+ except BaseException:
418
+ summary.errors += 1
419
+ summary.status = "failed"
420
+ raise
421
+ finally:
422
+ if summary.status == "running":
423
+ summary.status = "cancelled"
424
+
425
+ return PaginatedStream(generate(), summary)
426
+
427
+
428
+ def http_status_is(error, status):
429
+ """Inspect translated provider/Helper errors without losing HTTP semantics."""
430
+ from base_api.modules.errors import HTTPStatusError
431
+
432
+ seen = set()
433
+ while error is not None and id(error) not in seen:
434
+ seen.add(id(error))
435
+ if isinstance(error, HTTPStatusError):
436
+ return error.status_code == status
437
+ error = error.__cause__ or error.__context__
438
+ 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
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "eaf_base_api"
7
- version = "4.2.6"
7
+ version = "4.3.1"
8
8
  description = "A base API for EchterAlsFake's Porn APIs"
9
9
  requires-python = ">=3.12"
10
10
  license = "AGPL-3.0-or-later"
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "eaf_base_api"
7
- version = "4.2.6"
7
+ version = "4.3.1"
8
8
  description = "A base API for EchterAlsFake's Porn APIs"
9
9
  readme = { file = "README.md", content-type = "text/markdown" }
10
10
  requires-python = ">=3.12"
File without changes