-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeed_common.py
More file actions
617 lines (450 loc) · 18.2 KB
/
Copy pathfeed_common.py
File metadata and controls
617 lines (450 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
"""Shared helpers for free/paid chapter feed generators.
This module is intentionally limited to generator-level rules:
- source-mode/scope detection from mappings
- completion-state gating for novel-scoped fetches
- shared NSFW marker detection
- shared item sorting
It does not write RSS XML and does not build free/paid RSS items, so the XML
shape stays owned by free_feed_generator.py and paid_feed_generator.py.
"""
from __future__ import annotations
import datetime
import json
import os
import re
import feedparser
from pathlib import Path
from typing import Any
from urllib.request import Request, urlopen
from novel_mappings import HOSTING_SITE_DATA
from config_loader import get_integration_raw_url, get_runtime_fetch_config, get_source_mode_value
NSFW_PAREN_RE = re.compile(r"\([^)]*\b(?:nsfw|r-?18|18\+|h{1,3})\b[^)]*\)", re.I)
FEED_URL_KEYS = {
"free": "free_feed_url",
"paid": "paid_feed_url",
}
SOURCE_MODE_KEYS = {
"free": "free_chapters_source",
"paid": "paid_chapters_source",
}
def has_nsfw_marker(*texts: str) -> bool:
for text in texts:
if text and NSFW_PAREN_RE.search(str(text)):
return True
return False
def truthy(value: Any) -> bool:
if isinstance(value, bool):
return value
if value is None:
return False
text = str(value).strip().casefold()
return text in {"1", "true", "yes", "y", "on"}
def normalize_title_key(title: str) -> str:
return re.sub(r"\s+", " ", str(title or "")).strip().casefold()
def _parsed_time_to_utc(tt: Any) -> datetime.datetime | None:
if not tt:
return None
try:
return datetime.datetime(*tt[:6], tzinfo=datetime.timezone.utc)
except Exception:
return None
def parsed_entry_pub_date(entry: Any) -> datetime.datetime | None:
tt = getattr(entry, "published_parsed", None) or getattr(entry, "updated_parsed", None)
if not tt and isinstance(entry, dict):
tt = entry.get("published_parsed") or entry.get("updated_parsed")
return _parsed_time_to_utc(tt)
def parsed_feed_build_date(parsed_feed: Any) -> datetime.datetime | None:
feed = getattr(parsed_feed, "feed", None) or {}
for key in ("updated_parsed", "published_parsed", "created_parsed"):
tt = getattr(feed, key, None)
if not tt and isinstance(feed, dict):
tt = feed.get(key)
dt = _parsed_time_to_utc(tt)
if dt is not None:
return dt
return None
def feed_looks_capped_at_current_batch(parsed_feed: Any) -> bool:
"""Return True when a 100-row host feed may be hiding same-time leftovers.
Mistmint's public feed shows 100 items. If the oldest visible item still has
the same timestamp as the channel build time or newest entry, there may be
more same-timestamp rows beyond the cap.
"""
entries = list(getattr(parsed_feed, "entries", []) or [])
if len(entries) < 100:
return False
oldest_dt = parsed_entry_pub_date(entries[-1])
if oldest_dt is None:
return False
build_dt = parsed_feed_build_date(parsed_feed)
if build_dt is not None and oldest_dt == build_dt:
return True
newest_dt = parsed_entry_pub_date(entries[0])
return newest_dt is not None and oldest_dt == newest_dt
def entry_matches_chapter_type(utils: dict[str, Any], entry: Any, chapter_type: str) -> bool:
"""Return whether one source entry belongs in this generated feed.
Default is True to preserve old behavior. Hosts with mixed free/paid RSS
feeds can expose one of these hooks in their utils dict:
- entry_matches_chapter_type(entry, "free"/"paid")
- is_free_entry(entry) / is_paid_entry(entry)
- entry_is_free(entry) / entry_is_paid(entry)
"""
chapter_type = str(chapter_type or "").strip().casefold()
utils = utils or {}
checker = utils.get("entry_matches_chapter_type")
if callable(checker):
try:
return bool(checker(entry, chapter_type))
except TypeError:
return bool(checker(entry))
except Exception as exc:
print(f"Warning: entry_matches_chapter_type failed for {chapter_type}: {exc}")
return True
for name in (f"is_{chapter_type}_entry", f"entry_is_{chapter_type}"):
checker = utils.get(name)
if callable(checker):
try:
return bool(checker(entry))
except Exception as exc:
print(f"Warning: {name} failed: {exc}")
return True
return True
# ---------------- Fetch/Concurrency Helpers ----------------
def _safe_int(value: Any, default: int | None = None) -> int | None:
try:
return int(str(value).strip())
except Exception:
return default
def _first_runtime_int(fetch_cfg: dict[str, Any], keys: tuple[str, ...]) -> int | None:
for key in keys:
if key in fetch_cfg and str(fetch_cfg.get(key, "")).strip() != "":
value = _safe_int(fetch_cfg.get(key))
if value is not None:
return value
return None
def chapter_fetch_concurrency(
chapter_type: str = "",
default: int = 6,
*,
max_value: int | None = None,
) -> int:
"""Return the concurrency limit for novel-scoped chapter fetches.
Priority:
1. FREE_FETCH_CONCURRENCY / PAID_FETCH_CONCURRENCY env
2. CHAPTER_FETCH_CONCURRENCY env
3. config/runtime.json free_fetch_concurrency / paid_fetch_concurrency
4. config/runtime.json chapter_fetch_concurrency
5. default
"""
chapter_type_upper = str(chapter_type or "").strip().upper()
chapter_type_lower = str(chapter_type or "").strip().casefold()
env_keys: list[str] = []
if chapter_type_upper:
env_keys.append(f"{chapter_type_upper}_FETCH_CONCURRENCY")
env_keys.append("CHAPTER_FETCH_CONCURRENCY")
value: int | None = None
for key in env_keys:
raw = str(os.getenv(key, "") or "").strip()
if raw:
value = _safe_int(raw)
if value is not None:
break
fetch_cfg = get_runtime_fetch_config()
if value is None:
config_keys: list[str] = []
if chapter_type_lower:
config_keys.append(f"{chapter_type_lower}_fetch_concurrency")
config_keys.append("chapter_fetch_concurrency")
value = _first_runtime_int(fetch_cfg, tuple(config_keys))
if value is None:
value = default
value = max(1, int(value))
config_max = _first_runtime_int(
fetch_cfg,
tuple(
key
for key in (
f"max_{chapter_type_lower}_fetch_concurrency" if chapter_type_lower else "",
"max_chapter_fetch_concurrency",
)
if key
),
)
limits = [candidate for candidate in (max_value, config_max) if candidate is not None]
if limits:
value = min(value, max(1, min(int(candidate) for candidate in limits)))
return value
async def fetch_parsed_feed_async(session: Any, feed_url: str, *, semaphore: Any, label: str = "Feed"):
"""Fetch one RSS/Atom feed with aiohttp and return a feedparser result."""
async with semaphore:
try:
async with session.get(feed_url, timeout=30) as resp:
if resp.status >= 400:
print(f"{label} fetch failed: {feed_url} → HTTP {resp.status}")
return feedparser.parse("")
text = await resp.text()
except Exception as exc:
print(f"{label} fetch failed: {feed_url} → {exc}")
return feedparser.parse("")
return feedparser.parse(text)
# ---------------- Source Scope Helpers ----------------
def host_data_for(host: str) -> dict[str, Any]:
return HOSTING_SITE_DATA.get(host, {}) or {}
def novels_for_host(host: str) -> dict[str, dict[str, Any]]:
return host_data_for(host).get("novels", {}) or {}
def normalize_chapter_source_mode(value: Any) -> str:
"""Normalize chapter source mode names used in host TOML/env/config.
Supported canonical modes:
- feed: use only RSS/feed-style source
- api: use only chapter API/data source
- feed_api: use feed first, then API only when the feed looks capped
"""
raw = str(value or "").strip().casefold().replace("-", "_").replace("+", "_")
raw = re.sub(r"\s+", "_", raw)
aliases = {
"feed": "feed",
"rss": "feed",
"api": "api",
"feed_api": "feed_api",
"api_feed": "feed_api",
"feed_with_api": "feed_api",
"feed_with_api_fallback": "feed_api",
"feed_api_fallback": "feed_api",
"hybrid": "feed_api",
}
return aliases.get(raw, "")
def chapter_source_mode(host: str, chapter_type: str) -> str:
"""Return host source mode for this chapter type.
Modes:
- feed: use the feed/RSS-style source only
- api: use the chapter API/data source only
- feed_api: use feed, then API only when the feed looks capped
If the host TOML does not say explicitly:
- free defaults to feed, unless there is no free_feed_url but there is a chapters_api_url
- paid defaults to feed when paid_feed_url exists, otherwise api
"""
chapter_type = str(chapter_type or "").strip().casefold()
host_data = host_data_for(host)
key = SOURCE_MODE_KEYS.get(chapter_type, "")
raw = get_source_mode_value(host, key, host_data.get(key, ""))
mode = normalize_chapter_source_mode(raw)
if mode:
return mode
if chapter_type == "free":
return "api" if host_data.get("chapters_api_url") and not host_data.get("free_feed_url") else "feed"
if chapter_type == "paid":
return "feed" if host_data.get("paid_feed_url") else "api"
return "feed"
def chapter_source_uses_feed(mode: str) -> bool:
return normalize_chapter_source_mode(mode) in {"feed", "feed_api"}
def chapter_source_uses_api(mode: str) -> bool:
return normalize_chapter_source_mode(mode) in {"api", "feed_api"}
def host_level_feed_url(host: str, chapter_type: str) -> str:
"""Return only the host-level feed URL, without novel fallback."""
key = FEED_URL_KEYS.get(str(chapter_type or "").strip().casefold(), "")
if not key:
return ""
return str(host_data_for(host).get(key, "") or "").strip()
def slug_from_url(url: str) -> str:
value = str(url or "").strip().rstrip("/")
if not value:
return ""
return value.split("/")[-1]
def fill_novel_template(template: str, novel_title: str, details: dict[str, Any]) -> str:
value = str(template or "")
novel_url = str(details.get("novel_url") or "").strip()
slug = str(details.get("slug") or slug_from_url(novel_url) or "").strip()
novel_id = str(details.get("novel_id") or details.get("id") or "").strip()
short_code = str(details.get("short_code") or "").strip()
replacements = {
"{slug}": slug,
"{novel_slug}": slug,
"{novel_url_slug}": slug,
"{novel_id}": novel_id,
"{id}": novel_id,
"{novel_url}": novel_url,
"{title}": novel_title,
"{short_code}": short_code,
}
for key, replacement in replacements.items():
value = value.replace(key, replacement)
return value.strip()
def resolved_novel_feed_url(host: str, novel_title: str, details: dict[str, Any], chapter_type: str) -> str:
raw = novel_level_feed_url(details, chapter_type) or host_level_feed_url(host, chapter_type)
return fill_novel_template(raw, novel_title, details)
def novel_level_feed_url(details: dict[str, Any], chapter_type: str) -> str:
"""Return only the novel-level feed URL, without host fallback."""
key = FEED_URL_KEYS.get(str(chapter_type or "").strip().casefold(), "")
if not key:
return ""
return str((details or {}).get(key, "") or "").strip()
def chapters_api_template(host: str, details: dict[str, Any] | None = None) -> str:
details = details or {}
return str(details.get("chapters_api_url") or host_data_for(host).get("chapters_api_url") or "").strip()
NOVEL_URL_MARKERS = (
"{slug}",
"{novel_slug}",
"{novel_url_slug}",
"{novel_id}",
"{id}",
"{novel_url}",
"{title}",
"{short_code}",
)
def needs_novel_value(template: str) -> bool:
lowered = str(template or "").casefold()
return any(marker in lowered for marker in NOVEL_URL_MARKERS)
def api_source_scope(host: str, details: dict[str, Any] | None = None) -> str:
"""Return "novel" or "host" for a chapters API template.
A host-level template can still be novel-scoped if it needs a novel slug/id/url.
Example: chapters_api_url = ".../slug/{slug}/chapters" is novel-scoped.
"""
template = chapters_api_template(host, details)
if not template:
return ""
if needs_novel_value(template):
return "novel"
# If the API URL is defined directly on one novel, treat it as novel-scoped.
if details and details.get("chapters_api_url"):
return "novel"
return "host"
def source_scope_for(host: str, novel_title: str, details: dict[str, Any], chapter_type: str) -> str:
"""Return one of host_feed, novel_feed, host_api, novel_api, or "".
This reads the mapping shape instead of using novel→host fallback getters,
so the generator can tell where a source lives.
"""
mode = chapter_source_mode(host, chapter_type)
if chapter_source_uses_feed(mode):
novel_feed = novel_level_feed_url(details, chapter_type)
if novel_feed:
return "novel_feed"
host_feed = host_level_feed_url(host, chapter_type)
if host_feed:
return "novel_feed" if needs_novel_value(host_feed) else "host_feed"
if chapter_source_uses_api(mode):
scope = api_source_scope(host, details)
if scope == "novel":
return "novel_api"
if scope == "host":
return "host_api"
return ""
return ""
# ---------------- Completion State Gate ----------------
def completion_state_url() -> str:
env_url = str(os.getenv("COMPLETION_STATE_URL") or "").strip()
if env_url:
return env_url
integration = os.getenv("DISCORD_INTEGRATION", "discord_webhook").strip() or "discord_webhook"
return get_integration_raw_url(integration, "state", "state.json")
def completion_state_path() -> str:
return str(
os.getenv("COMPLETION_STATE_PATH")
or os.getenv("DISCORD_WEBHOOK_STATE_PATH")
or ""
).strip()
def _load_json_path(path: str) -> dict[str, Any]:
p = Path(path)
if not p.exists():
print(f"Warning: completion state path does not exist: {path}")
return {}
try:
data = json.loads(p.read_text(encoding="utf-8"))
except Exception as e:
print(f"Warning: could not read completion state path {path}: {e}")
return {}
if not isinstance(data, dict):
print(f"Warning: completion state is not a JSON object: {path}")
return {}
return data
def _load_json_url(url: str) -> dict[str, Any]:
if not url:
return {}
try:
req = Request(url, headers={"User-Agent": "rss-feed-generator/1.0"})
with urlopen(req, timeout=20) as resp:
status = getattr(resp, "status", 200)
if status != 200:
print(f"Warning: completion state returned HTTP {status}: {url}")
return {}
data = json.loads(resp.read().decode("utf-8"))
except Exception as e:
print(f"Warning: could not fetch completion state {url}: {e}")
return {}
if not isinstance(data, dict):
print(f"Warning: completion state is not a JSON object: {url}")
return {}
return data
def load_completion_state() -> dict[str, Any]:
"""Load canonical discord-webhook/state.json.
Path env wins for local testing; otherwise use integrations.json URL.
Missing/unreadable state returns {}, which means "do not skip anything".
"""
path = completion_state_path()
if path:
return _load_json_path(path)
return _load_json_url(completion_state_url())
def completion_key_for(chapter_type: str, novel_details: dict[str, Any]) -> str:
chapter_type = str(chapter_type or "").strip().casefold()
if chapter_type == "paid":
return "paid_completion"
if chapter_type == "free":
return "free_completion" if (novel_details or {}).get("paid_feed") else "only_free_completion"
return ""
def completion_announced(
novel_title: str,
chapter_type: str,
novel_details: dict[str, Any],
*,
state: dict[str, Any] | None = None,
) -> bool:
state = state if isinstance(state, dict) else {}
key = completion_key_for(chapter_type, novel_details)
if not key:
return False
wanted = normalize_title_key(novel_title)
for title, record in state.items():
if normalize_title_key(title) != wanted:
continue
return isinstance(record, dict) and bool(record.get(key))
return False
def should_skip_completed(
novel_title: str,
chapter_type: str,
novel_details: dict[str, Any],
*,
state: dict[str, Any] | None = None,
force: bool = False,
) -> bool:
if force:
return False
return completion_announced(novel_title, chapter_type, novel_details, state=state)
# ---------------- Shared Feed Sorting ----------------
def _normalized_pubdate(item):
dt = getattr(item, "pubDate", None)
if not isinstance(dt, datetime.datetime):
return datetime.datetime.min.replace(tzinfo=datetime.timezone.utc)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=datetime.timezone.utc)
return dt.astimezone(datetime.timezone.utc).replace(microsecond=0)
def _novel_alpha_sort_key(item):
return (
getattr(item, "host", "").casefold(),
getattr(item, "title", "").casefold(),
)
def _chapter_sort_key(item):
from host_utils import get_host_utils
return get_host_utils(getattr(item, "host", "")).get(
"chapter_num", lambda s: (0,)
)(getattr(item, "chapter", ""))
def sort_feed_items(items):
"""
Sort newest pubDate first.
Tie-breakers:
1. host/title alphabetical
2. chapter number newest first within the same novel/date
"""
# weakest tie-breaker first
items.sort(key=_chapter_sort_key, reverse=True)
# then alphabetical novel tie-breaker
items.sort(key=_novel_alpha_sort_key)
# strongest sort last
items.sort(key=_normalized_pubdate, reverse=True)