From 041e55b6690a7672dd7491f37c3c3566601dfa21 Mon Sep 17 00:00:00 2001 From: Vibe Date: Mon, 16 Nov 2026 10:09:23 +0000 Subject: [PATCH 1/3] =?UTF-8?q?chore:=20template=20de=20PR=20avec=20lien?= =?UTF-8?q?=20ticket=20Jira=20SCAL=20et=20checklist=20conformit=C3=A9=20l?= =?UTF-8?q?=C3=A9gale?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/PULL_REQUEST_TEMPLATE.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..f0797bc --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -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 From 5177ddedc59850c187de343c3540efc75dae7500 Mon Sep 17 00:00:00 2001 From: Vibe Date: Mon, 16 Nov 2026 10:25:59 +0000 Subject: [PATCH 2/3] =?UTF-8?q?feat:=20filtre=20par=20groupe=20MangaDex=20?= =?UTF-8?q?(ex.=20Keiyoushi)=20+=20keiyoushi.github.io=20bloqu=C3=A9=20(SC?= =?UTF-8?q?AL-13)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - list-groups / --group via API officielle MangaDex (groups[]), résolution nom -> UUID - keiyoushi.github.io et keiyoushi.com ajoutés à la liste de blocage legal-source-check - tests: stub fetcher MangaDex (params groups[]/translatedLanguage[]), blocage keiyoushi --- README.md | 3 +- docs/legal-sources.md | 4 ++ src/scalper/cli.py | 39 ++++++++++++++++--- src/scalper/legal.py | 4 +- src/scalper/pipeline.py | 3 +- src/scalper/sources/base.py | 2 +- src/scalper/sources/demo.py | 2 +- src/scalper/sources/mangadex.py | 59 +++++++++++++++++++---------- tests/test_legal.py | 6 +++ tests/test_mangadex.py | 67 +++++++++++++++++++++++++++++++++ 10 files changed, 160 insertions(+), 29 deletions(-) create mode 100644 tests/test_mangadex.py diff --git a/README.md b/README.md index d388b8e..11d8c0a 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,8 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out | Commande | Description | |---|---| | `scalper check-source ` | verdict légal (allowed/blocked + raisons) | -| `scalper list-series ` / `list-chapters ` | catalogage | +| `scalper list-series ` / `list-chapters [--group Keiyoushi]` | catalogage (filtre par groupe via API MangaDex) | +| `scalper list-groups mangadex --query Keiyoushi` | recherche de groupes de scanlation (API officielle) | | `scalper fetch ` | téléchargement brut + `state.json` (reprise) | | `scalper clean --out chapter.json` | nettoyage/structuration en blocs typés | | `scalper translate --lang fr [--mock-llm]` | traduction LLM + glossaire | diff --git a/docs/legal-sources.md b/docs/legal-sources.md index 5cd406e..ab62237 100644 --- a/docs/legal-sources.md +++ b/docs/legal-sources.md @@ -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 --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. diff --git a/src/scalper/cli.py b/src/scalper/cli.py index da20beb..6c74622 100644 --- a/src/scalper/cli.py +++ b/src/scalper/cli.py @@ -1,4 +1,4 @@ -"""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 @@ -30,10 +30,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") @@ -68,6 +75,7 @@ def main(argv: list[str] | None = None) -> int: 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)") @@ -79,11 +87,28 @@ def main(argv: list[str] | None = None) -> int: 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()) @@ -125,7 +150,11 @@ def main(argv: list[str] | None = None) -> int: _print({"exported": str(path)}) 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 diff --git a/src/scalper/legal.py b/src/scalper/legal.py index 1fc26a3..d881e29 100644 --- a/src/scalper/legal.py +++ b/src/scalper/legal.py @@ -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": { diff --git a/src/scalper/pipeline.py b/src/scalper/pipeline.py index 0bdc95c..3f37da9 100644 --- a/src/scalper/pipeline.py +++ b/src/scalper/pipeline.py @@ -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] diff --git a/src/scalper/sources/base.py b/src/scalper/sources/base.py index 0b2520f..e8fd991 100644 --- a/src/scalper/sources/base.py +++ b/src/scalper/sources/base.py @@ -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.""" diff --git a/src/scalper/sources/demo.py b/src/scalper/sources/demo.py index 9d82ef0..b4c0ba9 100644 --- a/src/scalper/sources/demo.py +++ b/src/scalper/sources/demo.py @@ -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 [ diff --git a/src/scalper/sources/mangadex.py b/src/scalper/sources/mangadex.py index 8f4264c..4f360f4 100644 --- a/src/scalper/sources/mangadex.py +++ b/src/scalper/sources/mangadex.py @@ -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"![page {i}](images/{fname})") (dest_dir / "raw.html").write_text("\n".join(lines), encoding="utf-8") diff --git a/tests/test_legal.py b/tests/test_legal.py index 3976d59..4da848d 100644 --- a/tests/test_legal.py +++ b/tests/test_legal.py @@ -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) diff --git a/tests/test_mangadex.py b/tests/test_mangadex.py new file mode 100644 index 0000000..f80c5fc --- /dev/null +++ b/tests/test_mangadex.py @@ -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() From 876faf3ede0c07aa199aa77b145ee072d9d509b8 Mon Sep 17 00:00:00 2001 From: Vibe Date: Mon, 16 Nov 2026 11:05:11 +0000 Subject: [PATCH 3/3] =?UTF-8?q?feat:=20registre=20de=20sources=20personnal?= =?UTF-8?q?is=C3=A9es=20(sources.toml)=20+=20commande=20fetch-url=20(SCAL-?= =?UTF-8?q?14)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - --config sources.toml: domaine + license OBLIGATOIRE, robots.txt vérifié - liste de blocage inviolable (test: keiyoushi/mangas-origines restent blocked même déclarés) - scalper fetch-url : lien direct soumis au gate légal, produit raw/meta/chapter.json - 33 tests OK --- README.md | 7 +++++- docs/add-a-source.md | 37 ++++++++++++++++++++++++----- sources.example.toml | 14 +++++++++++ src/scalper/cli.py | 33 +++++++++++++++++++++++++- src/scalper/legal.py | 32 ++++++++++++++++++++++--- tests/test_registry.py | 54 ++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 166 insertions(+), 11 deletions(-) create mode 100644 sources.example.toml create mode 100644 tests/test_registry.py diff --git a/README.md b/README.md index 11d8c0a..0ce76eb 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ scalper run --source demo --series demo-1 --lang fr --mock-llm --out out | `scalper check-source ` | verdict légal (allowed/blocked + raisons) | | `scalper list-series ` / `list-chapters [--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 ` | lien direct (gate légal : licence déclarée + robots.txt + blocage) | | `scalper fetch ` | téléchargement brut + `state.json` (reprise) | | `scalper clean --out chapter.json` | nettoyage/structuration en blocs typés | | `scalper translate --lang fr [--mock-llm]` | traduction LLM + glossaire | @@ -53,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 diff --git a/docs/add-a-source.md b/docs/add-a-source.md index 38991d3..513b6a0 100644 --- a/docs/add-a-source.md +++ b/docs/add-a-source.md @@ -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). diff --git a/sources.example.toml b/sources.example.toml new file mode 100644 index 0000000..27fb2ba --- /dev/null +++ b/sources.example.toml @@ -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] diff --git a/src/scalper/cli.py b/src/scalper/cli.py index 6c74622..b892c15 100644 --- a/src/scalper/cli.py +++ b/src/scalper/cli.py @@ -5,11 +5,12 @@ 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)") @@ -71,6 +73,10 @@ 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) @@ -82,6 +88,9 @@ def main(argv: list[str] | None = None) -> int: 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 @@ -149,6 +158,28 @@ 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, diff --git a/src/scalper/legal.py b/src/scalper/legal.py index d881e29..60412ab 100644 --- a/src/scalper/legal.py +++ b/src/scalper/legal.py @@ -35,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: @@ -92,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="", ) diff --git a/tests/test_registry.py b/tests/test_registry.py new file mode 100644 index 0000000..c4f4679 --- /dev/null +++ b/tests/test_registry.py @@ -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()