diff --git a/readme.md b/readme.md index 41d06d1..ea62ffc 100644 --- a/readme.md +++ b/readme.md @@ -12,3 +12,51 @@ Une fois vos modifications effectuées, envoyez-moi un MP pour que je mette la v Si ces instructions ne sont pas suffisemment claires (et je doute qu'elles le soient), s'il vous plaît dites-le moi que je les mette à jour avec ce qui manque. — Vicky. + +## Ajouter ou déplacer un jeu en ligne de commande + +Le script utilise uniquement Python 3, sans dépendance à installer (ni besoin de +`uv`). Depuis la racine du dépôt : + +1. Ajouter un jeu dans les nouveautés à partir de son lien Steam, de son identifiant + ou de son nom exact : + + ```sh + python3 scripts/games.py add "https://store.steampowered.com/app/620/Portal_2/" --owners "Dandaedre, Vky" + # Variante par nom (à utiliser à la place de la commande précédente) : + python3 scripts/games.py add "Portal 2" --owners "Dandaedre, Vky" + ``` + + Le script récupère la description anglaise, les genres Steam et l'image dans + `src/images/`. Les possesseurs sont obligatoires. En cas de recherche ambiguë, + il affiche des liens candidats : relancer avec le bon lien ou identifiant. + Une entrée existante n'est pas ajoutée une deuxième fois. + +2. Choisir éventuellement la catégorie dès l'ajout avec `--category action`, et + remplacer les genres Steam par des tags personnalisés avec + `--tags "Puzzle, Co-op, Sci-fi"`. Sans `--category`, l'entrée va dans `news`. + Les genres automatiques sont plus généraux que les tags communautaires Steam. + +3. Déplacer une entrée existante en donnant son titre complet et la destination : + + ```sh + python3 scripts/games.py move "Portal 2" action + python3 scripts/games.py move "Sworn" action --from aventure + ``` + + `--from` sert à préciser la source si le même titre figure dans plusieurs + catégories. Tout le bloc est conservé, + y compris les avis et les tags ; l'image reste au même endroit. Déplacer un jeu + ne nécessite pas de connexion Internet. + +Ajouter `--dry-run` à l'une des commandes pour prévisualiser sans écrire. +Les catégories disponibles viennent de `src/SUMMARY.md` et sont listées par +`python3 scripts/games.py add --help` ou `python3 scripts/games.py move --help`. +Vérifier ensuite les modifications avec `git diff` avant de les publier. +L'ajout nécessite Internet et dépend des endpoints publics du magasin Steam. + +Pour lancer les vérifications hors ligne : + +```sh +python3 -m unittest discover -s scripts -p 'test_*.py' +``` diff --git a/scripts/games.py b/scripts/games.py new file mode 100644 index 0000000..9334ab2 --- /dev/null +++ b/scripts/games.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Add Steam games and move Markdown entries. Python standard library only.""" + +import argparse +import html +import json +import re +import unicodedata +from pathlib import Path +from urllib.error import URLError +from urllib.parse import urlencode, urlparse +from urllib.request import Request, urlopen + + +SRC = Path(__file__).resolve().parent.parent / "src" +HEADING = re.compile(r"^[ \t]*###[ \t]+(.+?)[ \t]*$", re.MULTILINE) + + +def categories(): + summary = re.sub(r"", "", (SRC / "SUMMARY.md").read_text(encoding="utf-8"), flags=re.S) + return { + Path(file).stem: SRC / file + for file in re.findall(r"^\s*-\s+\[[^\]]+\]\(\.?/?([^\s)]+\.md)\)", summary, re.M) + } + + +def entries(path): + text = path.read_text(encoding="utf-8") + headings = list(HEADING.finditer(text)) + return text, [ + (match[1], match.start(), headings[i + 1].start() if i + 1 < len(headings) else len(text)) + for i, match in enumerate(headings) + ] + + +def matching(title, paths): + matches = [] + for path in paths: + text, blocks = entries(path) + for name, start, end in blocks: + if name.casefold() == title.casefold(): + matches.append((path, text, start, end)) + return matches + + +def append(text, block): + # Preserve existing contents, including manually written notes and spacing. + separator = "" if not text or text.endswith("\n\n") else "\n" if text.endswith("\n") else "\n\n" + return text + separator + block + + +def fetch(url): + request = Request(url, headers={"User-Agent": "crayon-eaters/1.0"}) + with urlopen(request, timeout=20) as response: + return response.read() + + +def api(endpoint, **params): + return json.loads(fetch("https://store.steampowered.com/api/" + endpoint + "?" + urlencode(params))) + + +def app_id(value): + if value.isascii() and value.isdigit(): + return value + url = urlparse(value) + if url.scheme or value.startswith("store.steampowered.com/"): + url = urlparse(value if url.scheme else "https://" + value) + match = re.match(r"/app/(\d+)(?:/|$)", url.path) + if url.scheme not in ("http", "https") or url.hostname != "store.steampowered.com" or not match: + raise ValueError("Use a Steam /app/ URL, an app ID, or a game name.") + return match[1] + items = api("storesearch/", term=value, l="english", cc="us").get("items", []) + exact = [item for item in items if item["name"].casefold() == value.casefold()] + if len(exact) == 1: + return str(exact[0]["id"]) + choices = "\n".join(f" {item['name']}: https://store.steampowered.com/app/{item['id']}/" for item in items[:10]) + raise ValueError("No unique exact name match. Retry with a Steam URL or ID." + ("\n" + choices if choices else "")) + + +def plain(value): + return " ".join(html.unescape(re.sub(r"<[^>]*>", " ", value)).split()) + + +def markdown(value): + return re.sub(r"([\\`*_\[\]<>])", r"\\\1", plain(value)) + + +def add(args, paths): + ident = app_id(args.game) + result = api("appdetails", appids=ident, l="english", cc="us").get(ident, {}) + if not result.get("success"): + raise ValueError(f"Steam has no available details for app {ident}.") + data = result["data"] + title = markdown(data["name"]) + duplicates = matching(title, paths.values()) + if duplicates: + raise ValueError("Entry already exists in: " + ", ".join(item[0].stem for item in duplicates)) + slug = unicodedata.normalize("NFKD", data["name"]).encode("ascii", "ignore").decode().lower() + slug = re.sub(r"[^a-z0-9]+", "_", slug).strip("_") or "game" + image = SRC / "images" / f"{slug}_{ident}.jpg" + if image.exists(): + raise ValueError(f"Image already exists: {image}") + # Steam's structured genres are a starting point; custom tags can override them. + tags = args.tags if args.tags is not None else ", ".join(g["description"] for g in data.get("genres", [])[:10]) + block = ( + f"### {title}\n![{title}](images/{image.name})\n" + f" * **Possesseur**: {markdown(args.owners)}\n" + f" * **Description**: {markdown(data['short_description'])}\n" + f" * **Catégories**: {markdown(tags)}\n" + ) + destination = paths[args.category] + updated = append(destination.read_text(encoding="utf-8"), block) + if args.dry_run: + print(f"Would add to {destination}:\n\n{block}") + return + picture = fetch(data["header_image"]) + if not picture.startswith(b"\xff\xd8\xff"): + raise ValueError("Steam header image is not a JPEG; no entry was written.") + image.parent.mkdir(exist_ok=True) + with image.open("xb") as output: + output.write(picture) + try: + destination.write_text(updated, encoding="utf-8") + except OSError: + # A failed Markdown write must not leave a misleading image behind. + if image.exists(): + image.unlink() + raise + print(f"Added {data['name']} to {destination.stem}.") + + +def move(args, paths): + sources = [paths[args.source]] if args.source else paths.values() + found = matching(args.game, sources) + if not found: + raise ValueError(f"No entry named {args.game!r}. Use its full Markdown heading (case insensitive).") + if len(found) > 1: + raise ValueError("Entry appears in multiple categories; choose --from: " + ", ".join(item[0].stem for item in found)) + source, original, start, end = found[0] + destination = paths[args.category] + if source == destination: + raise ValueError("Entry is already in that category.") + if matching(args.game, [destination]): + raise ValueError("Destination already contains that entry.") + target = destination.read_text(encoding="utf-8") + if args.dry_run: + print(f"Would move {args.game} from {source.stem} to {destination.stem}.") + return + # Write the destination first so a failed write cannot lose the source entry. + destination.write_text(append(target, original[start:end]), encoding="utf-8") + source.write_text(original[:start] + original[end:], encoding="utf-8") + print(f"Moved {args.game} from {source.stem} to {destination.stem}.") + + +def main(): + paths = categories() + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + create = commands.add_parser("add", help="Create an entry from a Steam URL, app ID, or exact name") + create.add_argument("game") + create.add_argument("--category", choices=paths, default="news") + create.add_argument("--owners", required=True, help='For example: "Dandaedre, Vky"') + create.add_argument("--tags", help="Comma-separated tags; defaults to Steam genres") + create.add_argument("--dry-run", action="store_true", help="Preview without writing files") + transfer = commands.add_parser("move", help="Move a complete entry into another category") + transfer.add_argument("game", help="Full entry heading, case insensitive") + transfer.add_argument("category", choices=paths) + transfer.add_argument("--from", dest="source", choices=paths, help="Resolve entries present in multiple categories") + transfer.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + try: + (add if args.command == "add" else move)(args, paths) + except (OSError, URLError, ValueError, KeyError) as error: + parser.exit(1, f"Error: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/test_games.py b/scripts/test_games.py new file mode 100644 index 0000000..1f14dc8 --- /dev/null +++ b/scripts/test_games.py @@ -0,0 +1,93 @@ +"""Offline checks using temporary category files; run with unittest discovery.""" + +import argparse +import contextlib +import io +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import games + + +class GamesTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + override = patch.object(games, "SRC", self.root) + override.start() + self.addCleanup(override.stop) + self.paths = {name: self.root / f"{name}.md" for name in ("news", "action")} + for name, path in self.paths.items(): + path.write_text(f"# {name}\n", encoding="utf-8") + self.block = " ### Test Game\n ![Game](images/game.jpg)\n * **Avis**: Très bien !\n\n" + self.paths["news"].write_text("# News\nIntro\n\n" + self.block + "### Other\nNotes\n", encoding="utf-8") + self.silence = contextlib.redirect_stdout(io.StringIO()) + self.silence.__enter__() + self.addCleanup(self.silence.__exit__, None, None, None) + + def move_args(self, **overrides): + return argparse.Namespace(**dict(dict(game="test game", category="action", source=None, dry_run=False), **overrides)) + + def test_move_preserves_block_neighbors_and_intro(self): + games.move(self.move_args(), self.paths) + self.assertEqual(self.paths["action"].read_text(), "# action\n\n" + self.block) + self.assertEqual(self.paths["news"].read_text(), "# News\nIntro\n\n### Other\nNotes\n") + + def test_duplicate_requires_source_and_refuses_duplicate_destination(self): + self.paths["action"].write_text(self.block) + before = {name: path.read_bytes() for name, path in self.paths.items()} + with self.assertRaisesRegex(ValueError, "multiple categories"): + games.move(self.move_args(), self.paths) + with self.assertRaisesRegex(ValueError, "already contains"): + games.move(self.move_args(source="news"), self.paths) + self.assertEqual(before, {name: path.read_bytes() for name, path in self.paths.items()}) + + def test_move_dry_run_changes_nothing(self): + before = {name: path.read_bytes() for name, path in self.paths.items()} + games.move(self.move_args(dry_run=True), self.paths) + self.assertEqual(before, {name: path.read_bytes() for name, path in self.paths.items()}) + + def test_steam_inputs_and_ambiguous_search(self): + self.assertEqual(games.app_id("https://store.steampowered.com/app/620/Portal_2/?l=french"), "620") + self.assertEqual(games.app_id("620"), "620") + with patch.object(games, "api", return_value={"items": [{"id": 620, "name": "Portal 2"}]}): + self.assertEqual(games.app_id("portal 2"), "620") + with self.assertRaisesRegex(ValueError, "No unique exact name"): + games.app_id("Portal") + with self.assertRaises(ValueError): + games.app_id("https://example.com/app/620") + + def test_add_downloads_image_and_rejects_duplicate(self): + args = argparse.Namespace(game="620", category="news", owners="Dan, Vky", tags=None, dry_run=False) + data = {"620": {"success": True, "data": { + "name": "Portal 2", "short_description": "A test & puzzles.", + "genres": [{"description": "Adventure"}], "header_image": "https://example.com/header.jpg", + }}} + with patch.object(games, "api", return_value=data), patch.object(games, "fetch", return_value=b"\xff\xd8\xffimage") as download: + games.add(args, self.paths) + text = self.paths["news"].read_text() + self.assertIn("### Portal 2\n![Portal 2](images/portal_2_620.jpg)", text) + self.assertIn("**Description**: A test & puzzles.", text) + self.assertEqual((self.root / "images/portal_2_620.jpg").read_bytes(), b"\xff\xd8\xffimage") + with self.assertRaisesRegex(ValueError, "already exists"): + games.add(args, self.paths) + download.assert_called_once() + + def test_download_failure_does_not_change_markdown(self): + args = argparse.Namespace(game="620", category="news", owners="Dan", tags="Puzzle", dry_run=False) + data = {"620": {"success": True, "data": { + "name": "Portal 2", "short_description": "Puzzles", "header_image": "https://example.com/header.jpg", + }}} + before = self.paths["news"].read_bytes() + with patch.object(games, "api", return_value=data), patch.object(games, "fetch", side_effect=OSError("offline")): + with self.assertRaises(OSError): + games.add(args, self.paths) + self.assertEqual(before, self.paths["news"].read_bytes()) + self.assertFalse((self.root / "images").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/images/craftcraft_fantasy_merchant_simulator_2226430.jpg b/src/images/craftcraft_fantasy_merchant_simulator_2226430.jpg new file mode 100644 index 0000000..2ae6a6d Binary files /dev/null and b/src/images/craftcraft_fantasy_merchant_simulator_2226430.jpg differ diff --git a/src/images/death_and_taxes_1166290.jpg b/src/images/death_and_taxes_1166290.jpg new file mode 100644 index 0000000..92a2906 Binary files /dev/null and b/src/images/death_and_taxes_1166290.jpg differ diff --git a/src/images/white_knuckle_3195790.jpg b/src/images/white_knuckle_3195790.jpg new file mode 100644 index 0000000..1eba2c2 Binary files /dev/null and b/src/images/white_knuckle_3195790.jpg differ diff --git a/src/news.md b/src/news.md index 1ecbd32..6c39502 100644 --- a/src/news.md +++ b/src/news.md @@ -37,3 +37,20 @@ Les titres tous juste achetés a peine sortis du four. * **Description**: This is a special strategy game that combines Wargame and Roguelike. As the guider of the former ancestors, you revived and arrived. In the name of Star Envoy, you leave for the Human camp, and lead the warriors of different clans with talents and abilities to find the truth of history and disaster. * **Catégories**: Strategy, RPG, Strategy, Roguelite +### CraftCraft: Fantasy Merchant Simulator +![CraftCraft: Fantasy Merchant Simulator](images/craftcraft_fantasy_merchant_simulator_2226430.jpg) + * **Possesseur**: Dan + * **Description**: CraftCraft is a narrative-heavy RPG sim with hands on forging and jewelry making! Create a pretty tiara for a mermaid or a sword made of dragon blood! Be a Moth or a Cat and express your creativity in your cozy crafting studio and change the lives of locals in the mysterious port town of Windspell. + * **Catégories**: Casual, Indie, RPG, Simulation + +### Death and Taxes +![Death and Taxes](images/death_and_taxes_1166290.jpg) + * **Possesseur**: Dan + * **Description**: In this 2D, short narrative-based game, you assume the role of the Grim Reaper... on an office job. Your job is to decide which people are going to live or die. The consequences of your choices are yours to bear, while the mystery of your incarnation awaits revelation! + * **Catégories**: Adventure, Casual, Indie, Simulation, Strategy + +### White Knuckle +![White Knuckle](images/white_knuckle_3195790.jpg) + * **Possesseur**: Dan + * **Description**: White Knuckle is a first-person roguelite speed-climbing game. Ascend through the guts of SUB-STRUCTURE 17 using precision movement mechanics. Sharp reflexes and resource management will bring you out from under ten thousand meters of concrete and decay. + * **Catégories**: Early Access