Merge pull request #1 from Orionis312050/vibe/scalper-sprint1-db69f7
feat: init Scalper — pipeline légal de scraping + traduction de chapitres manga/webtoon
This commit is contained in:
14 files changed
+344
-40
No files matched your search
@@ -0,0 +1,18 @@
|
||||
## Summary
|
||||
- Décrivez la changement en quelques bullets
|
||||
|
||||
## Ticket Jira (projet SCAL)
|
||||
- Ex. SCAL-2 — lien : https://orionis312050.atlassian.net/browse/SCAL-2
|
||||
|
||||
## Type
|
||||
- [ ] Feature (Story) [ ] Bug [ ] Task / chore
|
||||
|
||||
## Conformité légale (obligatoire)
|
||||
- [ ] Aucune source non autorisée ajoutée (legal-source-check inchangé ou élargi avec licence justifiée)
|
||||
- [ ] robots.txt / rate limiting / pas de contournement respectés
|
||||
- [ ] Pas de secret committé (clés API hors du code)
|
||||
|
||||
## Vérification
|
||||
- [ ] `python -m pytest -q` passe localement
|
||||
- [ ] CI verte sur la PR
|
||||
- [ ] Doc à jour si comportement change
|
||||
@@ -32,7 +32,9 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out
|
||||
| Commande | Description |
|
||||
|---|---|
|
||||
| `scalper check-source <url>` | verdict légal (allowed/blocked + raisons) |
|
||||
| `scalper list-series <source>` / `list-chapters <source> <series>` | catalogage |
|
||||
| `scalper list-series <source>` / `list-chapters <source> <series> [--group Keiyoushi]` | catalogage (filtre par groupe via API MangaDex) |
|
||||
| `scalper list-groups mangadex --query Keiyoushi` | recherche de groupes de scanlation (API officielle) |
|
||||
| `scalper --config sources.toml fetch-url <url>` | lien direct (gate légal : licence déclarée + robots.txt + blocage) |
|
||||
| `scalper fetch <source> <series> <chapitre>` | téléchargement brut + `state.json` (reprise) |
|
||||
| `scalper clean <raw.html> --out chapter.json` | nettoyage/structuration en blocs typés |
|
||||
| `scalper translate <chapter.json> --lang fr [--mock-llm]` | traduction LLM + glossaire |
|
||||
@@ -52,7 +54,11 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out
|
||||
|
||||
## Ajouter une source légale
|
||||
|
||||
Voir [docs/add-a-source.md](docs/add-a-source.md) et la politique des sources légales :
|
||||
Voir [docs/add-a-source.md](docs/add-a-source.md) : registre déclaratif `sources.toml`
|
||||
(licence obligatoire par domaine) ou lien direct `fetch-url`, plus adaptateur dédié.
|
||||
La liste de blocage (mangas-origines, keiyoushi.github.io…) n'est **pas contournable**.
|
||||
|
||||
## Politique des sources légales
|
||||
[docs/legal-sources.md](docs/legal-sources.md).
|
||||
|
||||
## Tests & CI
|
||||
|
||||
+31
-6
@@ -1,10 +1,32 @@
|
||||
# Ajouter une source légale
|
||||
## Deux façons d'ajouter une source
|
||||
|
||||
1. **Vérification manuelle** : licence (API officielle / CC / domaine public / contenu propre),
|
||||
CGU (pas d'interdiction de scraping), `robots.txt` autorisant les chemins ciblés.
|
||||
2. **Enregistrement** : ajouter le domaine dans `TRUSTED_SOURCES` (`src/scalper/legal.py`)
|
||||
avec sa licence. Sans cet enregistrement, la source est **bloquée** par défaut.
|
||||
3. **Adaptateur** : implémenter le contrat `SourceAdapter` (`src/scalper/sources/base.py`) :
|
||||
### 1. Registre déclaratif (recommandé) — `sources.toml`
|
||||
|
||||
Déclare le domaine avec sa **licence obligatoire** (le pipeline refuse toute source sans licence) :
|
||||
|
||||
```toml
|
||||
[source."exemple-domaine-public.fr"]
|
||||
license = "Domaine public (œuvres tombées dans le domaine public)"
|
||||
kind = "html"
|
||||
```
|
||||
|
||||
Utilisation : `scalper --config sources.toml check-source https://exemple-domaine-public.fr/...`
|
||||
|
||||
Règles inviolables : robots.txt vérifié, liste de blocage prioritaire (aucune config ne peut
|
||||
autoriser mangas-origines.fr / keiyoushi.github.io), aucun contournement de paywall.
|
||||
|
||||
### 2. Lien direct — `fetch-url`
|
||||
|
||||
```bash
|
||||
scalper --config sources.toml fetch-url "https://exemple-domaine-public.fr/manga/x/chapitre-1" --out data
|
||||
```
|
||||
|
||||
Le lien passe par `legal-source-check` (licence déclarée + robots.txt + liste de blocage) :
|
||||
s'il est bloqué, rien n'est téléchargé. Produit `raw.html` + `meta.json` + `chapter.json`.
|
||||
|
||||
## Adaptateur dédié
|
||||
|
||||
Pour une source récurrente, implémenter le contrat `SourceAdapter` (`src/scalper/sources/base.py`) :
|
||||
- `list_series() -> list[Series]`
|
||||
- `list_chapters(series_id) -> list[ChapterRef]`
|
||||
- `fetch_chapter(chapter, dest_dir)` : écrit le brut dans `dest_dir` (raw.html + images + meta.json)
|
||||
@@ -13,4 +35,7 @@
|
||||
5. **Tests** : ajouter un test hors ligne (fixtures mockées, aucun appel réseau en test).
|
||||
6. **PR** : ouvrir une PR liée au ticket Jira correspondant (projet SCAL).
|
||||
|
||||
> ⚠️ Les index d'extensions de scanlation (keiyoushi.github.io) et les sites de scanlation
|
||||
> non autorisés (mangas-origines.fr) sont **bloqués** et ne peuvent pas être autorisés via la config.
|
||||
|
||||
Exemple d'adaptateur légal existant : `src/scalper/sources/mangadex.py` (API officielle).
|
||||
@@ -12,6 +12,10 @@ Scalper ne doit traiter que des contenus pour lesquels une autorisation existe.
|
||||
## Interdit (bloqué par `legal-source-check`)
|
||||
- Sites de scanlation non autorisés hébergeant des mangas commerciaux sans licence
|
||||
(ex. **mangas-origines**) : contrefaçon + violation des CGU.
|
||||
- **keiyoushi.github.io / keiyoushi.com** : index d'extensions de lecteurs pointant vers des
|
||||
sites de scanlation non autorisés — bloqué. Pour suivre un groupe de scanlation (ex.
|
||||
Keiyoushi), utiliser la voie légale : l'API officielle MangaDex avec le filtre par groupe
|
||||
(`scalper list-chapters mangadex <series> --group Keiyoushi`, `scalper list-groups mangadex --query Keiyoushi`).
|
||||
- Toute source dont `robots.txt` interdit le chemin ciblé.
|
||||
- Tout contournement de paywall, captcha, authentification ou DRM.
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# Registre de sources personnalisées pour Scalper.
|
||||
# Chaque domaine DOIT déclarer sa licence (obligatoire) et passe toujours
|
||||
# par robots.txt + liste de blocage (non contournable).
|
||||
#
|
||||
# Exemple :
|
||||
# [source."exemple-domaine-public.fr"]
|
||||
# license = "Domaine public (œuvres tombées dans le domaine public)"
|
||||
# kind = "html"
|
||||
#
|
||||
# [source."api.oeuvres-cc.example"]
|
||||
# license = "API officielle — contenus Creative Commons CC BY 4.0"
|
||||
# kind = "api"
|
||||
|
||||
[source]
|
||||
+66
-6
@@ -1,15 +1,16 @@
|
||||
"""CLI Scalper : check-source, list-series, list-chapters, fetch, clean, translate, qa, export, run."""
|
||||
"""CLI Scalper : check-source, list-series, list-groups, list-chapters, fetch, clean, translate, qa, export, run."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from . import legal, pipeline
|
||||
from .cleaner import clean_chapter
|
||||
from .exporter import export_chapter
|
||||
from .exporter import export_chapter, slugify
|
||||
from .models import Chapter
|
||||
from .qa import qa_chapter
|
||||
from .scraper import RespectfulFetcher, chapter_dir
|
||||
@@ -23,6 +24,7 @@ def _print(data: dict) -> None:
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
p = argparse.ArgumentParser(prog="scalper", description="Pipeline légal de scraping + traduction de chapitres manga/webtoon")
|
||||
p.add_argument("--config", default=None, help="registre de sources personnalisées (TOML, ex. sources.example.toml)")
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
c = sub.add_parser("check-source", help="valide une source (robots.txt, licence, liste de blocage)")
|
||||
@@ -30,10 +32,17 @@ def main(argv: list[str] | None = None) -> int:
|
||||
|
||||
c = sub.add_parser("list-series", help="liste les séries d'une source")
|
||||
c.add_argument("source")
|
||||
c.add_argument("--query", default="")
|
||||
|
||||
c = sub.add_parser("list-chapters", help="liste les chapitres d'une série")
|
||||
c = sub.add_parser("list-groups", help="liste les groupes de scanlation (source mangadex uniquement)")
|
||||
c.add_argument("source")
|
||||
c.add_argument("--query", default="")
|
||||
|
||||
c = sub.add_parser("list-chapters", help="liste les chapitres d'une série (--group pour filtrer par groupe, ex. Keiyoushi)")
|
||||
c.add_argument("source")
|
||||
c.add_argument("series")
|
||||
c.add_argument("--group", default=None, help="nom ou UUID du groupe (mangadex)")
|
||||
c.add_argument("--lang", default="en", help="langue des chapitres (mangadex), '' pour toutes")
|
||||
|
||||
c = sub.add_parser("fetch", help="télécharge un chapitre brut")
|
||||
c.add_argument("source")
|
||||
@@ -64,26 +73,51 @@ def main(argv: list[str] | None = None) -> int:
|
||||
c.add_argument("--format", choices=["md", "json", "html"], required=True)
|
||||
c.add_argument("--out", required=True)
|
||||
|
||||
c = sub.add_parser("fetch-url", help="récupère un lien direct (soumis à legal-source-check : licence déclarée + robots.txt + liste de blocage)")
|
||||
c.add_argument("url")
|
||||
c.add_argument("--out", default="data")
|
||||
|
||||
c = sub.add_parser("run", help="pipeline complet end-to-end")
|
||||
c.add_argument("--source", required=True)
|
||||
c.add_argument("--series", required=True)
|
||||
c.add_argument("--lang", required=True)
|
||||
c.add_argument("--group", default=None, help="filtrer par groupe (mangadex)")
|
||||
c.add_argument("--out", default="out")
|
||||
c.add_argument("--max-chapters", type=int, default=None)
|
||||
c.add_argument("--mock-llm", action="store_true", help="démo hors ligne (LLM factice)")
|
||||
|
||||
args = p.parse_args(argv)
|
||||
|
||||
if getattr(args, "config", None):
|
||||
legal.load_config(args.config)
|
||||
|
||||
if args.cmd == "check-source":
|
||||
_print(legal.check_source(args.source).to_dict())
|
||||
return 0
|
||||
if args.cmd == "list-series":
|
||||
adapter = get_adapter(args.source)
|
||||
series = adapter.list_series() if args.source == "demo" else adapter.list_series(query="")
|
||||
series = adapter.list_series(query=args.query) if args.source == "mangadex" else adapter.list_series()
|
||||
_print([s.to_dict() for s in series])
|
||||
return 0
|
||||
if args.cmd == "list-groups":
|
||||
if args.source != "mangadex":
|
||||
print("list-groups est disponible uniquement pour la source 'mangadex'", file=sys.stderr)
|
||||
return 1
|
||||
from .sources.mangadex import MangaDexAdapter
|
||||
|
||||
_print(MangaDexAdapter(fetcher=RespectfulFetcher()).list_groups(args.query))
|
||||
return 0
|
||||
if args.cmd == "list-chapters":
|
||||
_print([c.to_dict() for c in get_adapter(args.source).list_chapters(args.series)])
|
||||
adapter = get_adapter(args.source)
|
||||
kwargs: dict = {}
|
||||
if args.group:
|
||||
if args.source != "mangadex":
|
||||
print("--group est disponible uniquement pour la source 'mangadex'", file=sys.stderr)
|
||||
return 1
|
||||
kwargs["group"] = args.group
|
||||
if args.source == "mangadex":
|
||||
kwargs["lang"] = args.lang or None
|
||||
_print([c.to_dict() for c in adapter.list_chapters(args.series, **kwargs)])
|
||||
return 0
|
||||
if args.cmd == "fetch":
|
||||
adapter = get_adapter(args.source, fetcher=RespectfulFetcher())
|
||||
@@ -124,8 +158,34 @@ def main(argv: list[str] | None = None) -> int:
|
||||
path = export_chapter(chapter, args.format, Path(args.out))
|
||||
_print({"exported": str(path)})
|
||||
return 0
|
||||
if args.cmd == "fetch-url":
|
||||
verdict = legal.check_source(args.url)
|
||||
if not verdict.allowed:
|
||||
_print({"status": "blocked", "verdict": verdict.to_dict()})
|
||||
return 3
|
||||
fetcher = RespectfulFetcher()
|
||||
html = fetcher.get(args.url).decode("utf-8", errors="replace")
|
||||
domain = legal.domain_of(args.url)
|
||||
dest = Path(args.out) / "raw" / domain / slugify(args.url)
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
(dest / "raw.html").write_text(html, encoding="utf-8")
|
||||
meta = {
|
||||
"source": domain,
|
||||
"license": verdict.license,
|
||||
"url": args.url,
|
||||
"fetched_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
}
|
||||
(dest / "meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
chapter = clean_chapter(html, meta)
|
||||
(dest / "chapter.json").write_text(json.dumps(chapter.to_dict(), ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
_print({"status": "ok", "dest": str(dest), "blocks": len(chapter.blocks), "language": chapter.meta.get("language")})
|
||||
return 0
|
||||
if args.cmd == "run":
|
||||
summary = pipeline.run_pipeline(args.source, args.series, args.lang, out_root=Path(args.out), mock_llm=args.mock_llm, max_chapters=args.max_chapters)
|
||||
summary = pipeline.run_pipeline(
|
||||
args.source, args.series, args.lang,
|
||||
out_root=Path(args.out), mock_llm=args.mock_llm,
|
||||
max_chapters=args.max_chapters, group=args.group,
|
||||
)
|
||||
_print(summary)
|
||||
return 0 if summary.get("status") == "done" else 3
|
||||
return 1
|
||||
|
||||
+32
-4
@@ -19,8 +19,10 @@ USER_AGENT = "Scalper/1.0 (+https://github.com/Orionis312050/Scalper)"
|
||||
|
||||
BLOCKED_DOMAINS: dict[str, str] = {
|
||||
"mangas-origines.fr": "site de scanlation non autorisé (contrefaçon de mangas commerciaux)",
|
||||
"keiyoushi.github.io": "index d'extensions Keiyoushi pointant vers des sites de scanlation non autorisés",
|
||||
"keiyoushi.com": "dépôt d'extensions Keiyoushi pointant vers des sites de scanlation non autorisés",
|
||||
}
|
||||
BLOCKED_SUBSTRINGS = ("mangas-origines",)
|
||||
BLOCKED_SUBSTRINGS = ("mangas-origines", "keiyoushi.github.io", "keiyoushi.com")
|
||||
|
||||
TRUSTED_SOURCES: dict[str, dict[str, str]] = {
|
||||
"api.mangadex.org": {
|
||||
@@ -33,6 +35,32 @@ TRUSTED_SOURCES: dict[str, dict[str, str]] = {
|
||||
},
|
||||
}
|
||||
|
||||
# Sources personnalisées déclarées par l'utilisateur (sources.toml).
|
||||
# La liste de blocage a TOUJOURS priorité sur ce registre : aucune config ne
|
||||
# peut autoriser un domaine bloqué.
|
||||
CUSTOM_SOURCES: dict[str, dict[str, str]] = {}
|
||||
|
||||
|
||||
def register_custom_sources(entries: dict[str, dict]) -> None:
|
||||
"""Enregistre des sources personnalisées. Champ 'license' obligatoire."""
|
||||
for domain, cfg in entries.items():
|
||||
lic = str(cfg.get("license", "")).strip()
|
||||
if not lic:
|
||||
raise ValueError(
|
||||
f"source '{domain}': le champ 'license' est obligatoire "
|
||||
"(API officielle, CC, domaine public ou contenu propre)"
|
||||
)
|
||||
CUSTOM_SOURCES[domain.lower()] = {"license": lic, "kind": str(cfg.get("kind", "html"))}
|
||||
|
||||
|
||||
def load_config(path: str) -> None:
|
||||
"""Charge un registre de sources TOML : [source."domaine"] license = "..." kind = "..."."""
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
data = tomllib.loads(Path(path).read_text(encoding="utf-8"))
|
||||
register_custom_sources(data.get("source", {}))
|
||||
|
||||
|
||||
@dataclass
|
||||
class Verdict:
|
||||
@@ -90,14 +118,14 @@ def check_source(source: str, path: str = "/") -> Verdict:
|
||||
license="",
|
||||
)
|
||||
|
||||
trusted = TRUSTED_SOURCES.get(domain)
|
||||
trusted = TRUSTED_SOURCES.get(domain) or CUSTOM_SOURCES.get(domain)
|
||||
if trusted is None:
|
||||
return Verdict(
|
||||
source=source,
|
||||
verdict="blocked",
|
||||
reasons=[
|
||||
"source non enregistrée : ajoutez-la manuellement dans TRUSTED_SOURCES "
|
||||
"avec sa licence après vérification (robots.txt, CGU, licence CC/domaine public/API officielle)"
|
||||
"source non enregistrée : déclarez-la dans sources.toml (champ 'license' obligatoire) "
|
||||
"après vérification manuelle (robots.txt, CGU, licence CC/domaine public/API officielle)"
|
||||
],
|
||||
license="",
|
||||
)
|
||||
|
||||
@@ -25,6 +25,7 @@ def run_pipeline(
|
||||
mock_llm: bool = False,
|
||||
fetcher: RespectfulFetcher | None = None,
|
||||
max_chapters: int | None = None,
|
||||
group: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
out_root = Path(out_root)
|
||||
verdict = legal.check_source(source_id)
|
||||
@@ -33,7 +34,7 @@ def run_pipeline(
|
||||
|
||||
fetcher = fetcher or RespectfulFetcher(min_delay=1.0)
|
||||
adapter = get_adapter(source_id, fetcher=fetcher)
|
||||
chapters = adapter.list_chapters(series_id)
|
||||
chapters = adapter.list_chapters(series_id, **({"group": group} if group else {}))
|
||||
if max_chapters is not None:
|
||||
chapters = chapters[:max_chapters]
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ class SourceAdapter(Protocol):
|
||||
|
||||
def list_series(self) -> list[Series]: ...
|
||||
|
||||
def list_chapters(self, series_id: str) -> list[ChapterRef]: ...
|
||||
def list_chapters(self, series_id: str, **kwargs) -> list[ChapterRef]: ...
|
||||
|
||||
def fetch_chapter(self, chapter: ChapterRef, dest_dir: Path) -> None:
|
||||
"""Télécharge le chapitre brut (HTML + images) dans dest_dir."""
|
||||
|
||||
@@ -27,7 +27,7 @@ class DemoAdapter:
|
||||
idx = self._index()
|
||||
return [Series(id=s["id"], title=s["title"], url=s["url"], license=self.license) for s in idx["series"]]
|
||||
|
||||
def list_chapters(self, series_id: str) -> list[ChapterRef]:
|
||||
def list_chapters(self, series_id: str, **kwargs) -> list[ChapterRef]:
|
||||
idx = self._index()
|
||||
chapters = idx["chapters"].get(series_id, [])
|
||||
return [
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
"""Adaptateur API officielle MangaDex (https://api.mangadex.org) — source légale.
|
||||
|
||||
L'API publique ne nécessite pas de clé pour la lecture. Rate limiting appliqué.
|
||||
Permet de filtrer les chapitres par groupe de scanlation (ex. Keiyoushi) via le
|
||||
paramètre groups[] — la voie légale pour suivre un groupe donné.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from ..models import ChapterRef, Series
|
||||
from ..scraper import RespectfulFetcher
|
||||
|
||||
API = "https://api.mangadex.org"
|
||||
|
||||
_UUID_RE = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
||||
|
||||
|
||||
class MangaDexAdapter:
|
||||
id = "mangadex"
|
||||
@@ -21,16 +27,14 @@ class MangaDexAdapter:
|
||||
def __init__(self, fetcher: RespectfulFetcher | None = None) -> None:
|
||||
self.fetcher = fetcher or RespectfulFetcher(min_delay=1.0)
|
||||
|
||||
def _get_json(self, path: str, params: dict[str, str] | None = None) -> dict:
|
||||
def _get_json(self, path: str, params: dict[str, object] | None = None) -> dict:
|
||||
url = API + path
|
||||
if params:
|
||||
from urllib.parse import urlencode
|
||||
|
||||
url += "?" + urlencode(params)
|
||||
url += "?" + urlencode(params, doseq=True)
|
||||
return json.loads(self.fetcher.get(url).decode("utf-8"))
|
||||
|
||||
def list_series(self, query: str = "", limit: int = 20) -> list[Series]:
|
||||
params = {"limit": str(limit), "order[relevance]": "desc", "includes[]": "cover_art"}
|
||||
params: dict[str, object] = {"limit": limit, "order[relevance]": "desc", "includes[]": "cover_art"}
|
||||
if query:
|
||||
params["title"] = query
|
||||
data = self._get_json("/manga", params)
|
||||
@@ -44,17 +48,35 @@ class MangaDexAdapter:
|
||||
for m in data.get("data", [])
|
||||
]
|
||||
|
||||
def list_chapters(self, series_id: str, limit: int = 100) -> list[ChapterRef]:
|
||||
data = self._get_json(
|
||||
f"/manga/{series_id}/feed",
|
||||
{
|
||||
"limit": str(limit),
|
||||
"translatedLanguage[]": "en",
|
||||
"order[chapter]": "asc",
|
||||
"contentRating[]": "safe",
|
||||
"contentRating[]": "suggestive",
|
||||
},
|
||||
)
|
||||
def list_groups(self, query: str = "", limit: int = 20) -> list[dict]:
|
||||
"""Recherche des groupes de scanlation par nom (ex. 'Keiyoushi')."""
|
||||
params: dict[str, object] = {"limit": limit, "order[name]": "asc"}
|
||||
if query:
|
||||
params["name"] = query
|
||||
data = self._get_json("/group", params)
|
||||
return [{"id": g["id"], "name": g["attributes"]["name"]} for g in data.get("data", [])]
|
||||
|
||||
def resolve_group(self, name_or_id: str) -> str:
|
||||
if _UUID_RE.match(name_or_id):
|
||||
return name_or_id
|
||||
groups = self.list_groups(name_or_id)
|
||||
if not groups:
|
||||
raise KeyError(f"groupe introuvable sur MangaDex: {name_or_id}")
|
||||
exact = next((g for g in groups if g["name"].lower() == name_or_id.lower()), None)
|
||||
return (exact or groups[0])["id"]
|
||||
|
||||
def list_chapters(self, series_id: str, limit: int = 100, group: str | None = None, lang: str | None = "en") -> list[ChapterRef]:
|
||||
params: dict[str, object] = {
|
||||
"limit": limit,
|
||||
"order[chapter]": "asc",
|
||||
"contentRating[]": ["safe", "suggestive"],
|
||||
"includeFutureUpdates": "0",
|
||||
}
|
||||
if lang:
|
||||
params["translatedLanguage[]"] = [lang]
|
||||
if group:
|
||||
params["groups[]"] = [self.resolve_group(group)]
|
||||
data = self._get_json(f"/manga/{series_id}/feed", params)
|
||||
refs = []
|
||||
for c in data.get("data", []):
|
||||
attrs = c["attributes"]
|
||||
@@ -76,13 +98,12 @@ class MangaDexAdapter:
|
||||
attrs = data["data"]["attributes"]
|
||||
chapter_hash = attrs["hash"]
|
||||
pages = attrs.get("pages", 0)
|
||||
files = attrs.get("data", []) + attrs.get("dataSaver", [])
|
||||
files = attrs.get("data", [])
|
||||
lines = [f"# raw chapter {chapter.id} ({chapter.title})", ""]
|
||||
img_dir = dest_dir / "images"
|
||||
img_dir.mkdir(exist_ok=True)
|
||||
quality = "data-saver" if attrs.get("dataSaver") else "data"
|
||||
for i, fname in enumerate(files, start=1):
|
||||
url = f"{base}/{quality}/{chapter_hash}/{fname}"
|
||||
url = f"{base}/data/{chapter_hash}/{fname}"
|
||||
(img_dir / fname).write_bytes(self.fetcher.get(url))
|
||||
lines.append(f"")
|
||||
(dest_dir / "raw.html").write_text("\n".join(lines), encoding="utf-8")
|
||||
|
||||
@@ -14,6 +14,12 @@ class TestLegal(unittest.TestCase):
|
||||
self.assertFalse(v.allowed, url)
|
||||
self.assertIn("blocage", v.reasons[0])
|
||||
|
||||
def test_keiyoushi_extensions_blocked(self):
|
||||
for url in ("https://keiyoushi.github.io", "https://keiyoushi.github.io/extensions", "keiyoushi.com"):
|
||||
v = legal.check_source(url)
|
||||
self.assertFalse(v.allowed, url)
|
||||
self.assertIn("blocage", v.reasons[0])
|
||||
|
||||
def test_unknown_domain_blocked(self):
|
||||
v = legal.check_source("https://site-inconnu.example/manga")
|
||||
self.assertFalse(v.allowed)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import json
|
||||
import unittest
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
|
||||
from scalper.sources.mangadex import MangaDexAdapter
|
||||
|
||||
GROUP_UUID = "123e4567-e89b-42d3-a456-426614174000"
|
||||
|
||||
|
||||
class StubFetcher:
|
||||
def __init__(self, responses: dict[str, dict]) -> None:
|
||||
self.responses = responses
|
||||
self.urls: list[str] = []
|
||||
|
||||
def get(self, url: str) -> bytes:
|
||||
self.urls.append(url)
|
||||
for key, payload in self.responses.items():
|
||||
if key in url:
|
||||
return json.dumps(payload).encode("utf-8")
|
||||
raise AssertionError(f"URL inattendue: {url}")
|
||||
|
||||
|
||||
def make_adapter() -> tuple[MangaDexAdapter, StubFetcher]:
|
||||
stub = StubFetcher(
|
||||
{
|
||||
"/group": {"data": [{"id": GROUP_UUID, "attributes": {"name": "Keiyoushi"}}]},
|
||||
"/manga/m1/feed": {
|
||||
"data": [
|
||||
{"id": "ch-1", "attributes": {"chapter": "1", "title": "Start"}},
|
||||
{"id": "ch-2", "attributes": {"chapter": "2", "title": None}},
|
||||
]
|
||||
},
|
||||
}
|
||||
)
|
||||
return MangaDexAdapter(fetcher=stub), stub
|
||||
|
||||
|
||||
class TestMangaDexGroupFilter(unittest.TestCase):
|
||||
def test_resolve_group_by_name(self):
|
||||
adapter, stub = make_adapter()
|
||||
self.assertEqual(adapter.resolve_group("Keiyoushi"), GROUP_UUID)
|
||||
self.assertTrue(any("/group?" in u and "name=Keiyoushi" in u for u in stub.urls))
|
||||
|
||||
def test_resolve_group_uuid_passthrough(self):
|
||||
adapter, _ = make_adapter()
|
||||
self.assertEqual(adapter.resolve_group(GROUP_UUID), GROUP_UUID)
|
||||
|
||||
def test_list_chapters_with_group_filter(self):
|
||||
adapter, stub = make_adapter()
|
||||
chapters = adapter.list_chapters("m1", group="Keiyoushi")
|
||||
self.assertEqual([c.number for c in chapters], ["1", "2"])
|
||||
feed_url = next(u for u in stub.urls if "/manga/m1/feed" in u)
|
||||
qs = parse_qs(urlparse(feed_url).query)
|
||||
self.assertEqual(qs.get("groups[]"), [GROUP_UUID])
|
||||
self.assertEqual(qs.get("translatedLanguage[]"), ["en"])
|
||||
|
||||
def test_list_chapters_without_group(self):
|
||||
adapter, stub = make_adapter()
|
||||
adapter.list_chapters("m1", lang=None)
|
||||
feed_url = next(u for u in stub.urls if "/manga/m1/feed" in u)
|
||||
qs = parse_qs(urlparse(feed_url).query)
|
||||
self.assertNotIn("groups[]", qs)
|
||||
self.assertNotIn("translatedLanguage[]", qs)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,54 @@
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from scalper import legal
|
||||
|
||||
ALLOW_ALL = "User-agent: *\nAllow: /\n"
|
||||
|
||||
|
||||
class TestCustomSourceRegistry(unittest.TestCase):
|
||||
def setUp(self):
|
||||
legal.CUSTOM_SOURCES.clear()
|
||||
|
||||
def tearDown(self):
|
||||
legal.CUSTOM_SOURCES.clear()
|
||||
|
||||
def test_custom_source_with_license_allowed(self):
|
||||
with mock.patch.object(legal, "_fetch_robots_txt", return_value=ALLOW_ALL):
|
||||
legal.register_custom_sources({"exemple-cc.fr": {"license": "CC BY 4.0", "kind": "html"}})
|
||||
v = legal.check_source("https://exemple-cc.fr/manga/x")
|
||||
self.assertTrue(v.allowed)
|
||||
self.assertEqual(v.license, "CC BY 4.0")
|
||||
|
||||
def test_custom_source_without_license_rejected(self):
|
||||
with self.assertRaises(ValueError):
|
||||
legal.register_custom_sources({"pirate.example": {"kind": "html"}})
|
||||
self.assertNotIn("pirate.example", legal.CUSTOM_SOURCES)
|
||||
|
||||
def test_blocklist_wins_over_config(self):
|
||||
with mock.patch.object(legal, "_fetch_robots_txt", return_value=ALLOW_ALL):
|
||||
legal.register_custom_sources(
|
||||
{"mangas-origines.fr": {"license": "CC BY 4.0"}, "keiyoushi.github.io": {"license": "CC BY 4.0"}}
|
||||
)
|
||||
for url in ("https://mangas-origines.fr/", "https://keiyoushi.github.io/"):
|
||||
v = legal.check_source(url)
|
||||
self.assertFalse(v.allowed, url)
|
||||
|
||||
def test_unknown_source_still_blocked(self):
|
||||
v = legal.check_source("https://inconnu.example/")
|
||||
self.assertFalse(v.allowed)
|
||||
|
||||
def test_robots_disallow_blocks_custom_source(self):
|
||||
robots = "User-agent: *\nDisallow: /manga/\n"
|
||||
with mock.patch.object(legal, "_fetch_robots_txt", return_value=robots):
|
||||
legal.register_custom_sources({"exemple.fr": {"license": "Domaine public"}})
|
||||
v = legal.check_source("https://exemple.fr/manga/x", path="/manga/x")
|
||||
self.assertFalse(v.allowed)
|
||||
self.assertIn("robots.txt interdit", v.reasons[-1])
|
||||
|
||||
def test_demo_still_allowed(self):
|
||||
self.assertTrue(legal.check_source("demo").allowed)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user